feat(plugins): New Plugin System with multi-language PDK support (#4833)

* chore(plugins): remove the old plugins system implementation

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement new plugin system with using Extism

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add capability detection for plugins based on exported functions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add auto-reload functionality for plugins with file watcher support

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add auto-reload functionality for plugins with file watcher support

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): standardize variable names and remove superfluous wrapper functions

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): improve error handling and logging in plugin manager

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): implement plugin function call helper and refactor MetadataAgent methods

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): race condition in plugin manager

* tests(plugins): change BeforeEach to BeforeAll in MetadataAgent tests

Signed-off-by: Deluan <deluan@navidrome.org>

* tests(plugins): optimize tests

Signed-off-by: Deluan <deluan@navidrome.org>

* tests(plugins): more optimizations

Signed-off-by: Deluan <deluan@navidrome.org>

* test(plugins): ignore goroutine leaks from notify library in tests

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add Wikimedia plugin for Navidrome to fetch artist metadata

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): enhance plugin logging and set User-Agent header

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement scrobbler plugin with authorization and scrobbling capabilities

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): integrate logs

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): clean up manifest struct and improve plugin loading logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add metadata agent and scrobbler schemas for bootstrapping plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(hostgen): add hostgen tool for generating Extism host function wrappers

- Implemented hostgen tool to generate wrappers from annotated Go interfaces.
- Added command-line flags for input/output directories and package name.
- Introduced parsing and code generation logic for host services.
- Created test data for various service interfaces and expected generated code.
- Added documentation for host services and annotations for code generation.
- Implemented SubsonicAPI service with corresponding generated code.

* feat(subsonicapi): update Call method to return JSON string response

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement SubsonicAPI host function integration with permissions

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(generator): error-only methods in response handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): generate client wrappers for host functions

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(generator): remove error handling for response.Error in client templates

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(scheduler): add Scheduler service interface with host function wrappers for scheduling tasks

* feat(plugins): add WASI build constraints to client wrapper templates, to avoid lint errors

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(scheduler): implement Scheduler service with one-time and recurring scheduling capabilities

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(manifest): remove unused ConfigPermission from permissions schema

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(scheduler): add scheduler callback schema and implementation for plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(scheduler): streamline scheduling logic and remove unused callback tracking

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(scheduler): add Close method for resource cleanup on plugin unload

Signed-off-by: Deluan <deluan@navidrome.org>

* docs(scheduler): clarify SchedulerCallback requirement for scheduling functions

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: update wasm build rule to include all Go files in the directory

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: rewrite the wikimedia plugin using the XTP CLI

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(scheduler): replace uuid with id.NewRandom for schedule ID generation

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: capabilities registration

Signed-off-by: Deluan <deluan@navidrome.org>

* test: add scheduler service isolation test for plugin instances

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: update plugin manager initialization and encapsulate logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add WebSocket service definitions for plugin communication

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement WebSocket service for plugin integration and connection management

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Crypto Ticker example plugin for real-time cryptocurrency price updates via Coinbase WebSocket API

Also add the lifecycle capability

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: use context.Background() in invokeCallback for scheduled tasks

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: rename plugin.create() to plugin.instance()

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: rename pluginInstance to plugin for consistency across the codebase

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: simplify schedule cloning in Close method and enhance plugin cleanup error handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement Artwork service for generating artwork URLs in Navidrome plugins - WIP

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: moved public URL builders to avoid import cycles

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Cache service for in-memory TTL-based caching in plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Discord Rich Presence example plugin for Navidrome integration

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: host function wrappers to use structured request and response types

- Updated the host function signatures in `nd_host_artwork.go`, `nd_host_scheduler.go`, `nd_host_subsonicapi.go`, and `nd_host_websocket.go` to accept a single parameter for JSON requests.
- Introduced structured request and response types for various cache operations in `nd_host_cache.go`.
- Modified cache functions to marshal requests to JSON and unmarshal responses, improving error handling and code clarity.
- Removed redundant memory allocation for string parameters in favor of JSON marshaling.
- Enhanced error handling in WebSocket and cache operations to return structured error responses.

* refactor: error handling in various plugins to convert response.Error to Go errors

- Updated error handling in `nd_host_scheduler.go`, `nd_host_websocket.go`, `nd_host_artwork.go`, `nd_host_cache.go`, and `nd_host_subsonicapi.go` to convert string errors from responses into Go errors.
- Removed redundant error checks in test data plugins for cleaner code.
- Ensured consistent error handling across all plugins to improve reliability and maintainability.

* refactor: rename fake plugins to test plugins for clarity in integration tests

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add help target to Makefile for plugin usage instructions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Cover Art Archive plugin as an example of Python plugin

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update Makefile and README to clarify Go plugin usage

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: include plugin capabilities in loading log message

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add trace logging for plugin availability and error handling in agents

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Now Playing Logger plugin to showcase calling host functions from Python plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: generate Python client wrappers for various host services

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add generated host function wrappers for Scheduler and SubsonicAPI services

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update Python plugin documentation and usage instructions for host function wrappers

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Webhook Scrobbler plugin in Rust to send HTTP notifications on scrobble events

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: enable parallel loading of plugins during startup

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README to include WebSocket callback schema in plugin documentation

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: extend plugin watcher with improved logging and debounce duration adjustment

Signed-off-by: Deluan <deluan@navidrome.org>

* add trace message for plugin recompiles

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement plugin cache purging functionality

Signed-off-by: Deluan <deluan@navidrome.org>

* test: move purgeCacheBySize unit tests

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): add plugin repository and database support

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): add plugin management routes and middleware

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): implement plugin synchronization with database for add, update, and remove actions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): add PluginList and PluginShow components with plugin management functionality

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): optimize plugin change detection

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins UI): improve PluginList structure

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): enhance PluginShow with author, website, and permissions display

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): refactor to use MUI and RA components

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): add error handling for plugin enable/disable actions

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): inject PluginManager into native API

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update GetManager to accept DataStore parameter

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add subsonicRouter to Manager and refactor host service registration

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): enhance debug logging for plugin actions and recompile logic

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): break manager.go into smaller, focused files

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): streamline error handling and improve plugin retrieval logic

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update newWebSocketService to use WebSocketPermission for allowed hosts

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): introduce ToggleEnabledSwitch for managing plugin enable/disable state

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update READMEs

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(library): add Library service for metadata access and filesystem integration

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add Library Inspector plugin for periodic library inspection and file size logging

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README to reflect JSON configuration format for plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(build): update target to wasm32-wasip1 for improved WASI support

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement configuration management UI with key-value pairs support

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(ui): adjust grid layout in InfoRow component for improved responsiveness

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): rename ErrorIndicator to EnabledOrErrorField and enhance error handling logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(i18n): add Portuguese translations for plugin management and notifications

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add support for .ndp plugin packages and update build process

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README for .ndp plugin packaging and installation instructions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement KVStore service for persistent key-value storage

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: enhance README with Extism plugin development resources and recommendations

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): integrate event broker into plugin manager

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): update config handling in PluginShow to track last record state

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add Rust host function library and example implementation of Discord Rich Presence plugin in Rust

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): generate Rust lib.rs file to expose host function wrappers

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update JSON field names to camelCase for consistency

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: reduce cyclomatic complexity by refactoring main function

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): enhance Rust code generation with typed struct support and improved type handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add Go client library with host function wrappers and documentation

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): generate Go client stubs for non-WASM platforms

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): update client template file names for consistency

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add initial implementation of the Navidrome Plugin Development Kit code generator - Pahse 1

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 2

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 2 (2)

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 3

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 4

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 5

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): consistent naming/types across PDK

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): streamline plugin function signatures and error handling

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update scrobbler interface to return errors directly instead of response structs

Signed-off-by: Deluan <deluan@navidrome.org>

* test: make all test plugins use the PDK

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): reorganize and sort type definitions for consistency

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update error handling for methods to return errors directly

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update function signatures to return values directly instead of response structs

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update request/response types to use private naming conventions

Signed-off-by: Deluan <deluan@navidrome.org>

* build: mark .wasm files as intermediate for cleanup after building .ndp

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): consolidate PDK module path and update Go version to 1.25

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement Rust PDK

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): reorganize Rust output structure to follow standard conventions

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update Discord Rich Presence and Library Inspector plugins to use nd-pdk for service calls and implement lifecycle management

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update macro names for websocket and metadata registration to improve clarity and consistency

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): rename scheduler callback methods for consistency and clarity

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update export wrappers to use `//go:wasmexport` for WebAssembly compatibility

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update plugin registration docs

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): generate host wrappers

Signed-off-by: Deluan <deluan@navidrome.org>

* test(plugins): conditionally run goleak checks based on CI environment

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README to reflect changes in plugin import paths

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update plugin instance creation to accept context for cancellation support

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): update return types in metadata interfaces to use pointers

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): enhance type handling for Rust and XTP output in capability generation

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): update IsAuthorized method to return boolean instead of response object

Signed-off-by: Deluan <deluan@navidrome.org>

* test(plugins): add unit tests for rustOutputType and isPrimitiveRustType functions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement XTP JSONSchema validation for generated schemas

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): update response types in testMetadataAgent methods to use pointers

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update Go and Rust plugin developer sections for clarity

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: correct example link for library inspector in README

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: clarify artwork URL generation capabilities in service descriptions

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README to include Rust PDK crate information for plugin developers

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: handle URL parsing errors and use atomic upsert in plugin repository

Added proper error handling for url.Parse calls in PublicURL and AbsoluteURL
functions. When parsing fails, PublicURL now falls back to AbsoluteURL, and
AbsoluteURL logs the error and returns an empty string, preventing malformed
URLs from being generated.

Replaced the non-atomic UPDATE-then-INSERT pattern in plugin repository Put
method with a single atomic INSERT ... ON CONFLICT statement. This eliminates
potential race conditions and improves consistency with the upsert pattern
already used in host_kvstore.go.

* feat: implement mock service instances for non-WASM builds using testify/mock

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: Discord RPC struct to encapsulate WebSocket logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add support for experimental WebAssembly threads

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add PDK abstraction layer with mock support for non-WASM builds

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add unit tests for Discord plugin and RPC functionality

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: update return types in minimalPlugin and wikimediaPlugin methods to use pointers

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: context cancellation and implement WebSocket callback timeout for improved error handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: conditionally include error handling in generated client code templates

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement ConfigService for plugin configuration management

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: enhance plugin manager to support metrics recording

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: make MockPDK private

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: update interface types to use 'any' in plugin repository methods

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: rename List method to Keys for clarity in configuration management

Signed-off-by: Deluan <deluan@navidrome.org>

* test: add ndpgen plugin tests in the pipeline and update Makefile

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add users permission management to plugin system

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: streamline users integration tests and enhance plugin user management

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: remove UserID from scrobbler request structure

Signed-off-by: Deluan <deluan@navidrome.org>

* test: add integration tests for UsersService enable gate behavior

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement user permissions for SubsonicAPI and scrobbler plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: show proper error in the UI when enabling a plugin fails

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add library permission management to plugin system

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add user permission for processing scrobbles in Discord Rich Presence plugin

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: implement dynamic loading for buffered scrobbler plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add GetAdmins method to retrieve admin users from the plugin

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update Portuguese translations for user and library permissions

Signed-off-by: Deluan <deluan@navidrome.org>

* reorder migrations

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: remove unnecessary bulkActionButtons prop from PluginList component

* feat: add manual plugin rescan functionality and corresponding UI action

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement user/library and plugin management integration with cleanup on deletion

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: replace core mock services with test-specific implementations to avoid import cycles

* feat: add ID fields to Artist and Song structs and enhance track loading logic by prioritizing ID matches

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update plugin permissions from allowedHosts to requiredHosts for better clarity and consistency

* feat: refactor plugin host permissions to use RequiredHosts directly for improved clarity

* fix: don't record metrics for plugin calls that aren't implemented at all

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: enhance connection management with improved error handling and cleanup logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: introduce ArtistRef struct for better artist representation and update track metadata handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update user configuration handling to use user key prefix for improved clarity

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: enhance ConfigCard input fields with multiline support and vertical resizing

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: rust plugin compilation error

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement IsOptionPattern method for better return type handling in Rust PDK generation

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: Deluan <deluan@navidrome.org>
This commit is contained in:
Deluan Quintão
2026-01-14 19:22:48 -05:00
committed by GitHub
parent fd4a04339e
commit 03a45753e9
518 changed files with 49456 additions and 34933 deletions
+4
View File
@@ -0,0 +1,4 @@
# Rust build artifacts
# Cargo.lock is not needed for library crates (this is a cdylib)
Cargo.lock
target
+900 -1582
View File
File diff suppressed because it is too large Load Diff
-166
View File
@@ -1,166 +0,0 @@
package plugins
import (
"context"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/plugins/api"
"github.com/tetratelabs/wazero"
)
// NewWasmMediaAgent creates a new adapter for a MetadataAgent plugin
func newWasmMediaAgent(wasmPath, pluginID string, m *managerImpl, runtime api.WazeroNewRuntime, mc wazero.ModuleConfig) WasmPlugin {
loader, err := api.NewMetadataAgentPlugin(context.Background(), api.WazeroRuntime(runtime), api.WazeroModuleConfig(mc))
if err != nil {
log.Error("Error creating media metadata service plugin", "plugin", pluginID, "path", wasmPath, err)
return nil
}
return &wasmMediaAgent{
baseCapability: newBaseCapability[api.MetadataAgent, *api.MetadataAgentPlugin](
wasmPath,
pluginID,
CapabilityMetadataAgent,
m.metrics,
loader,
func(ctx context.Context, l *api.MetadataAgentPlugin, path string) (api.MetadataAgent, error) {
return l.Load(ctx, path)
},
),
}
}
// wasmMediaAgent adapts a MetadataAgent plugin to implement the agents.Interface
type wasmMediaAgent struct {
*baseCapability[api.MetadataAgent, *api.MetadataAgentPlugin]
}
func (w *wasmMediaAgent) AgentName() string {
return w.id
}
func (w *wasmMediaAgent) mapError(err error) error {
if err != nil && (err.Error() == api.ErrNotFound.Error() || err.Error() == api.ErrNotImplemented.Error()) {
return agents.ErrNotFound
}
return err
}
// Album-related methods
func (w *wasmMediaAgent) GetAlbumInfo(ctx context.Context, name, artist, mbid string) (*agents.AlbumInfo, error) {
res, err := callMethod(ctx, w, "GetAlbumInfo", func(inst api.MetadataAgent) (*api.AlbumInfoResponse, error) {
return inst.GetAlbumInfo(ctx, &api.AlbumInfoRequest{Name: name, Artist: artist, Mbid: mbid})
})
if err != nil {
return nil, w.mapError(err)
}
if res == nil || res.Info == nil {
return nil, agents.ErrNotFound
}
info := res.Info
return &agents.AlbumInfo{
Name: info.Name,
MBID: info.Mbid,
Description: info.Description,
URL: info.Url,
}, nil
}
func (w *wasmMediaAgent) GetAlbumImages(ctx context.Context, name, artist, mbid string) ([]agents.ExternalImage, error) {
res, err := callMethod(ctx, w, "GetAlbumImages", func(inst api.MetadataAgent) (*api.AlbumImagesResponse, error) {
return inst.GetAlbumImages(ctx, &api.AlbumImagesRequest{Name: name, Artist: artist, Mbid: mbid})
})
if err != nil {
return nil, w.mapError(err)
}
return convertExternalImages(res.Images), nil
}
// Artist-related methods
func (w *wasmMediaAgent) GetArtistMBID(ctx context.Context, id string, name string) (string, error) {
res, err := callMethod(ctx, w, "GetArtistMBID", func(inst api.MetadataAgent) (*api.ArtistMBIDResponse, error) {
return inst.GetArtistMBID(ctx, &api.ArtistMBIDRequest{Id: id, Name: name})
})
if err != nil {
return "", w.mapError(err)
}
return res.GetMbid(), nil
}
func (w *wasmMediaAgent) GetArtistURL(ctx context.Context, id, name, mbid string) (string, error) {
res, err := callMethod(ctx, w, "GetArtistURL", func(inst api.MetadataAgent) (*api.ArtistURLResponse, error) {
return inst.GetArtistURL(ctx, &api.ArtistURLRequest{Id: id, Name: name, Mbid: mbid})
})
if err != nil {
return "", w.mapError(err)
}
return res.GetUrl(), nil
}
func (w *wasmMediaAgent) GetArtistBiography(ctx context.Context, id, name, mbid string) (string, error) {
res, err := callMethod(ctx, w, "GetArtistBiography", func(inst api.MetadataAgent) (*api.ArtistBiographyResponse, error) {
return inst.GetArtistBiography(ctx, &api.ArtistBiographyRequest{Id: id, Name: name, Mbid: mbid})
})
if err != nil {
return "", w.mapError(err)
}
return res.GetBiography(), nil
}
func (w *wasmMediaAgent) GetSimilarArtists(ctx context.Context, id, name, mbid string, limit int) ([]agents.Artist, error) {
resp, err := callMethod(ctx, w, "GetSimilarArtists", func(inst api.MetadataAgent) (*api.ArtistSimilarResponse, error) {
return inst.GetSimilarArtists(ctx, &api.ArtistSimilarRequest{Id: id, Name: name, Mbid: mbid, Limit: int32(limit)})
})
if err != nil {
return nil, w.mapError(err)
}
artists := make([]agents.Artist, 0, len(resp.GetArtists()))
for _, a := range resp.GetArtists() {
artists = append(artists, agents.Artist{
Name: a.GetName(),
MBID: a.GetMbid(),
})
}
return artists, nil
}
func (w *wasmMediaAgent) GetArtistImages(ctx context.Context, id, name, mbid string) ([]agents.ExternalImage, error) {
resp, err := callMethod(ctx, w, "GetArtistImages", func(inst api.MetadataAgent) (*api.ArtistImageResponse, error) {
return inst.GetArtistImages(ctx, &api.ArtistImageRequest{Id: id, Name: name, Mbid: mbid})
})
if err != nil {
return nil, w.mapError(err)
}
return convertExternalImages(resp.Images), nil
}
func (w *wasmMediaAgent) GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]agents.Song, error) {
resp, err := callMethod(ctx, w, "GetArtistTopSongs", func(inst api.MetadataAgent) (*api.ArtistTopSongsResponse, error) {
return inst.GetArtistTopSongs(ctx, &api.ArtistTopSongsRequest{Id: id, ArtistName: artistName, Mbid: mbid, Count: int32(count)})
})
if err != nil {
return nil, w.mapError(err)
}
songs := make([]agents.Song, 0, len(resp.GetSongs()))
for _, s := range resp.GetSongs() {
songs = append(songs, agents.Song{
Name: s.GetName(),
MBID: s.GetMbid(),
})
}
return songs, nil
}
// Helper function to convert ExternalImage objects from the API to the agents package
func convertExternalImages(images []*api.ExternalImage) []agents.ExternalImage {
result := make([]agents.ExternalImage, 0, len(images))
for _, img := range images {
result = append(result, agents.ExternalImage{
URL: img.GetUrl(),
Size: int(img.GetSize()),
})
}
return result
}
-229
View File
@@ -1,229 +0,0 @@
package plugins
import (
"context"
"errors"
"time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/metrics"
"github.com/navidrome/navidrome/plugins/api"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Adapter Media Agent", func() {
var ctx context.Context
var mgr *managerImpl
BeforeEach(func() {
ctx = GinkgoT().Context()
// Ensure plugins folder is set to testdata
DeferCleanup(configtest.SetupConfig())
conf.Server.Plugins.Folder = testDataDir
conf.Server.DevPluginCompilationTimeout = 2 * time.Minute
mgr = createManager(nil, metrics.NewNoopInstance())
mgr.ScanPlugins()
// Wait for all plugins to compile to avoid race conditions
err := mgr.EnsureCompiled("multi_plugin")
Expect(err).NotTo(HaveOccurred(), "multi_plugin should compile successfully")
err = mgr.EnsureCompiled("fake_album_agent")
Expect(err).NotTo(HaveOccurred(), "fake_album_agent should compile successfully")
})
Describe("AgentName and PluginName", func() {
It("should return the plugin name", func() {
agent := mgr.LoadPlugin("multi_plugin", "MetadataAgent")
Expect(agent).NotTo(BeNil(), "multi_plugin should be loaded")
Expect(agent.PluginID()).To(Equal("multi_plugin"))
})
It("should return the agent name", func() {
agent, ok := mgr.LoadMediaAgent("multi_plugin")
Expect(ok).To(BeTrue(), "multi_plugin should be loaded as media agent")
Expect(agent.AgentName()).To(Equal("multi_plugin"))
})
})
Describe("Album methods", func() {
var agent *wasmMediaAgent
BeforeEach(func() {
a, ok := mgr.LoadMediaAgent("fake_album_agent")
Expect(ok).To(BeTrue(), "fake_album_agent should be loaded")
agent = a.(*wasmMediaAgent)
})
Context("GetAlbumInfo", func() {
It("should return album information", func() {
info, err := agent.GetAlbumInfo(ctx, "Test Album", "Test Artist", "mbid")
Expect(err).NotTo(HaveOccurred())
Expect(info).NotTo(BeNil())
Expect(info.Name).To(Equal("Test Album"))
Expect(info.MBID).To(Equal("album-mbid-123"))
Expect(info.Description).To(Equal("This is a test album description"))
Expect(info.URL).To(Equal("https://example.com/album"))
})
It("should return ErrNotFound when plugin returns not found", func() {
_, err := agent.GetAlbumInfo(ctx, "Test Album", "", "mbid")
Expect(err).To(Equal(agents.ErrNotFound))
})
It("should return ErrNotFound when plugin returns nil response", func() {
_, err := agent.GetAlbumInfo(ctx, "", "", "")
Expect(err).To(Equal(agents.ErrNotFound))
})
})
Context("GetAlbumImages", func() {
It("should return album images", func() {
images, err := agent.GetAlbumImages(ctx, "Test Album", "Test Artist", "mbid")
Expect(err).NotTo(HaveOccurred())
Expect(images).To(Equal([]agents.ExternalImage{
{URL: "https://example.com/album1.jpg", Size: 300},
{URL: "https://example.com/album2.jpg", Size: 400},
}))
})
})
})
Describe("Artist methods", func() {
var agent *wasmMediaAgent
BeforeEach(func() {
a, ok := mgr.LoadMediaAgent("fake_artist_agent")
Expect(ok).To(BeTrue(), "fake_artist_agent should be loaded")
agent = a.(*wasmMediaAgent)
})
Context("GetArtistMBID", func() {
It("should return artist MBID", func() {
mbid, err := agent.GetArtistMBID(ctx, "artist-id", "Test Artist")
Expect(err).NotTo(HaveOccurred())
Expect(mbid).To(Equal("1234567890"))
})
It("should return ErrNotFound when plugin returns not found", func() {
_, err := agent.GetArtistMBID(ctx, "artist-id", "")
Expect(err).To(Equal(agents.ErrNotFound))
})
})
Context("GetArtistURL", func() {
It("should return artist URL", func() {
url, err := agent.GetArtistURL(ctx, "artist-id", "Test Artist", "mbid")
Expect(err).NotTo(HaveOccurred())
Expect(url).To(Equal("https://example.com"))
})
})
Context("GetArtistBiography", func() {
It("should return artist biography", func() {
bio, err := agent.GetArtistBiography(ctx, "artist-id", "Test Artist", "mbid")
Expect(err).NotTo(HaveOccurred())
Expect(bio).To(Equal("This is a test biography"))
})
})
Context("GetSimilarArtists", func() {
It("should return similar artists", func() {
artists, err := agent.GetSimilarArtists(ctx, "artist-id", "Test Artist", "mbid", 10)
Expect(err).NotTo(HaveOccurred())
Expect(artists).To(Equal([]agents.Artist{
{Name: "Similar Artist 1", MBID: "mbid1"},
{Name: "Similar Artist 2", MBID: "mbid2"},
}))
})
})
Context("GetArtistImages", func() {
It("should return artist images", func() {
images, err := agent.GetArtistImages(ctx, "artist-id", "Test Artist", "mbid")
Expect(err).NotTo(HaveOccurred())
Expect(images).To(Equal([]agents.ExternalImage{
{URL: "https://example.com/image1.jpg", Size: 100},
{URL: "https://example.com/image2.jpg", Size: 200},
}))
})
})
Context("GetArtistTopSongs", func() {
It("should return artist top songs", func() {
songs, err := agent.GetArtistTopSongs(ctx, "artist-id", "Test Artist", "mbid", 10)
Expect(err).NotTo(HaveOccurred())
Expect(songs).To(Equal([]agents.Song{
{Name: "Song 1", MBID: "mbid1"},
{Name: "Song 2", MBID: "mbid2"},
}))
})
})
})
Describe("Helper functions", func() {
It("convertExternalImages should convert API image objects to agent image objects", func() {
apiImages := []*api.ExternalImage{
{Url: "https://example.com/image1.jpg", Size: 100},
{Url: "https://example.com/image2.jpg", Size: 200},
}
agentImages := convertExternalImages(apiImages)
Expect(agentImages).To(HaveLen(2))
for i, img := range agentImages {
Expect(img.URL).To(Equal(apiImages[i].Url))
Expect(img.Size).To(Equal(int(apiImages[i].Size)))
}
})
It("convertExternalImages should handle empty slice", func() {
agentImages := convertExternalImages([]*api.ExternalImage{})
Expect(agentImages).To(BeEmpty())
})
It("convertExternalImages should handle nil", func() {
agentImages := convertExternalImages(nil)
Expect(agentImages).To(BeEmpty())
})
})
Describe("Error mapping", func() {
var agent wasmMediaAgent
It("should map API ErrNotFound to agents.ErrNotFound", func() {
err := agent.mapError(api.ErrNotFound)
Expect(err).To(Equal(agents.ErrNotFound))
})
It("should map API ErrNotImplemented to agents.ErrNotFound", func() {
err := agent.mapError(api.ErrNotImplemented)
Expect(err).To(Equal(agents.ErrNotFound))
})
It("should pass through other errors", func() {
testErr := errors.New("test error")
err := agent.mapError(testErr)
Expect(err).To(Equal(testErr))
})
It("should handle nil error", func() {
err := agent.mapError(nil)
Expect(err).To(BeNil())
})
})
})
-46
View File
@@ -1,46 +0,0 @@
package plugins
import (
"context"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/plugins/api"
"github.com/tetratelabs/wazero"
)
// newWasmSchedulerCallback creates a new adapter for a SchedulerCallback plugin
func newWasmSchedulerCallback(wasmPath, pluginID string, m *managerImpl, runtime api.WazeroNewRuntime, mc wazero.ModuleConfig) WasmPlugin {
loader, err := api.NewSchedulerCallbackPlugin(context.Background(), api.WazeroRuntime(runtime), api.WazeroModuleConfig(mc))
if err != nil {
log.Error("Error creating scheduler callback plugin", "plugin", pluginID, "path", wasmPath, err)
return nil
}
return &wasmSchedulerCallback{
baseCapability: newBaseCapability[api.SchedulerCallback, *api.SchedulerCallbackPlugin](
wasmPath,
pluginID,
CapabilitySchedulerCallback,
m.metrics,
loader,
func(ctx context.Context, l *api.SchedulerCallbackPlugin, path string) (api.SchedulerCallback, error) {
return l.Load(ctx, path)
},
),
}
}
// wasmSchedulerCallback adapts a SchedulerCallback plugin
type wasmSchedulerCallback struct {
*baseCapability[api.SchedulerCallback, *api.SchedulerCallbackPlugin]
}
func (w *wasmSchedulerCallback) OnSchedulerCallback(ctx context.Context, scheduleID string, payload []byte, isRecurring bool) error {
_, err := callMethod(ctx, w, "OnSchedulerCallback", func(inst api.SchedulerCallback) (*api.SchedulerCallbackResponse, error) {
return inst.OnSchedulerCallback(ctx, &api.SchedulerCallbackRequest{
ScheduleId: scheduleID,
Payload: payload,
IsRecurring: isRecurring,
})
})
return err
}
-136
View File
@@ -1,136 +0,0 @@
package plugins
import (
"context"
"time"
"github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/plugins/api"
"github.com/tetratelabs/wazero"
)
func newWasmScrobblerPlugin(wasmPath, pluginID string, m *managerImpl, runtime api.WazeroNewRuntime, mc wazero.ModuleConfig) WasmPlugin {
loader, err := api.NewScrobblerPlugin(context.Background(), api.WazeroRuntime(runtime), api.WazeroModuleConfig(mc))
if err != nil {
log.Error("Error creating scrobbler service plugin", "plugin", pluginID, "path", wasmPath, err)
return nil
}
return &wasmScrobblerPlugin{
baseCapability: newBaseCapability[api.Scrobbler, *api.ScrobblerPlugin](
wasmPath,
pluginID,
CapabilityScrobbler,
m.metrics,
loader,
func(ctx context.Context, l *api.ScrobblerPlugin, path string) (api.Scrobbler, error) {
return l.Load(ctx, path)
},
),
}
}
type wasmScrobblerPlugin struct {
*baseCapability[api.Scrobbler, *api.ScrobblerPlugin]
}
func (w *wasmScrobblerPlugin) IsAuthorized(ctx context.Context, userId string) bool {
username, _ := request.UsernameFrom(ctx)
if username == "" {
u, ok := request.UserFrom(ctx)
if ok {
username = u.UserName
}
}
resp, err := callMethod(ctx, w, "IsAuthorized", func(inst api.Scrobbler) (*api.ScrobblerIsAuthorizedResponse, error) {
return inst.IsAuthorized(ctx, &api.ScrobblerIsAuthorizedRequest{
UserId: userId,
Username: username,
})
})
if err != nil {
log.Warn("Error calling IsAuthorized", "userId", userId, "pluginID", w.id, err)
}
return err == nil && resp.Authorized
}
func (w *wasmScrobblerPlugin) NowPlaying(ctx context.Context, userId string, track *model.MediaFile, position int) error {
username, _ := request.UsernameFrom(ctx)
if username == "" {
u, ok := request.UserFrom(ctx)
if ok {
username = u.UserName
}
}
trackInfo := w.toTrackInfo(track, position)
_, err := callMethod(ctx, w, "NowPlaying", func(inst api.Scrobbler) (struct{}, error) {
resp, err := inst.NowPlaying(ctx, &api.ScrobblerNowPlayingRequest{
UserId: userId,
Username: username,
Track: trackInfo,
Timestamp: time.Now().Unix(),
})
if err != nil {
return struct{}{}, err
}
if resp.Error != "" {
return struct{}{}, nil
}
return struct{}{}, nil
})
return err
}
func (w *wasmScrobblerPlugin) Scrobble(ctx context.Context, userId string, s scrobbler.Scrobble) error {
username, _ := request.UsernameFrom(ctx)
if username == "" {
u, ok := request.UserFrom(ctx)
if ok {
username = u.UserName
}
}
trackInfo := w.toTrackInfo(&s.MediaFile, 0)
_, err := callMethod(ctx, w, "Scrobble", func(inst api.Scrobbler) (struct{}, error) {
resp, err := inst.Scrobble(ctx, &api.ScrobblerScrobbleRequest{
UserId: userId,
Username: username,
Track: trackInfo,
Timestamp: s.TimeStamp.Unix(),
})
if err != nil {
return struct{}{}, err
}
if resp.Error != "" {
return struct{}{}, nil
}
return struct{}{}, nil
})
return err
}
func (w *wasmScrobblerPlugin) toTrackInfo(track *model.MediaFile, position int) *api.TrackInfo {
artists := make([]*api.Artist, 0, len(track.Participants[model.RoleArtist]))
for _, a := range track.Participants[model.RoleArtist] {
artists = append(artists, &api.Artist{Name: a.Name, Mbid: a.MbzArtistID})
}
albumArtists := make([]*api.Artist, 0, len(track.Participants[model.RoleAlbumArtist]))
for _, a := range track.Participants[model.RoleAlbumArtist] {
albumArtists = append(albumArtists, &api.Artist{Name: a.Name, Mbid: a.MbzArtistID})
}
trackInfo := &api.TrackInfo{
Id: track.ID,
Mbid: track.MbzRecordingID,
Name: track.Title,
Album: track.Album,
AlbumMbid: track.MbzAlbumID,
Artists: artists,
AlbumArtists: albumArtists,
Length: int32(track.Duration),
Position: int32(position),
}
return trackInfo
}
-35
View File
@@ -1,35 +0,0 @@
package plugins
import (
"context"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/plugins/api"
"github.com/tetratelabs/wazero"
)
// newWasmWebSocketCallback creates a new adapter for a WebSocketCallback plugin
func newWasmWebSocketCallback(wasmPath, pluginID string, m *managerImpl, runtime api.WazeroNewRuntime, mc wazero.ModuleConfig) WasmPlugin {
loader, err := api.NewWebSocketCallbackPlugin(context.Background(), api.WazeroRuntime(runtime), api.WazeroModuleConfig(mc))
if err != nil {
log.Error("Error creating WebSocket callback plugin", "plugin", pluginID, "path", wasmPath, err)
return nil
}
return &wasmWebSocketCallback{
baseCapability: newBaseCapability[api.WebSocketCallback, *api.WebSocketCallbackPlugin](
wasmPath,
pluginID,
CapabilityWebSocketCallback,
m.metrics,
loader,
func(ctx context.Context, l *api.WebSocketCallbackPlugin, path string) (api.WebSocketCallback, error) {
return l.Load(ctx, path)
},
),
}
}
// wasmWebSocketCallback adapts a WebSocketCallback plugin
type wasmWebSocketCallback struct {
*baseCapability[api.WebSocketCallback, *api.WebSocketCallbackPlugin]
}
File diff suppressed because it is too large Load Diff
-246
View File
@@ -1,246 +0,0 @@
syntax = "proto3";
package api;
option go_package = "github.com/navidrome/navidrome/plugins/api;api";
// go:plugin type=plugin version=1
service MetadataAgent {
// Artist metadata methods
rpc GetArtistMBID(ArtistMBIDRequest) returns (ArtistMBIDResponse);
rpc GetArtistURL(ArtistURLRequest) returns (ArtistURLResponse);
rpc GetArtistBiography(ArtistBiographyRequest) returns (ArtistBiographyResponse);
rpc GetSimilarArtists(ArtistSimilarRequest) returns (ArtistSimilarResponse);
rpc GetArtistImages(ArtistImageRequest) returns (ArtistImageResponse);
rpc GetArtistTopSongs(ArtistTopSongsRequest) returns (ArtistTopSongsResponse);
// Album metadata methods
rpc GetAlbumInfo(AlbumInfoRequest) returns (AlbumInfoResponse);
rpc GetAlbumImages(AlbumImagesRequest) returns (AlbumImagesResponse);
}
message ArtistMBIDRequest {
string id = 1;
string name = 2;
}
message ArtistMBIDResponse {
string mbid = 1;
}
message ArtistURLRequest {
string id = 1;
string name = 2;
string mbid = 3;
}
message ArtistURLResponse {
string url = 1;
}
message ArtistBiographyRequest {
string id = 1;
string name = 2;
string mbid = 3;
}
message ArtistBiographyResponse {
string biography = 1;
}
message ArtistSimilarRequest {
string id = 1;
string name = 2;
string mbid = 3;
int32 limit = 4;
}
message Artist {
string name = 1;
string mbid = 2;
}
message ArtistSimilarResponse {
repeated Artist artists = 1;
}
message ArtistImageRequest {
string id = 1;
string name = 2;
string mbid = 3;
}
message ExternalImage {
string url = 1;
int32 size = 2;
}
message ArtistImageResponse {
repeated ExternalImage images = 1;
}
message ArtistTopSongsRequest {
string id = 1;
string artistName = 2;
string mbid = 3;
int32 count = 4;
}
message Song {
string name = 1;
string mbid = 2;
}
message ArtistTopSongsResponse {
repeated Song songs = 1;
}
message AlbumInfoRequest {
string name = 1;
string artist = 2;
string mbid = 3;
}
message AlbumInfo {
string name = 1;
string mbid = 2;
string description = 3;
string url = 4;
}
message AlbumInfoResponse {
AlbumInfo info = 1;
}
message AlbumImagesRequest {
string name = 1;
string artist = 2;
string mbid = 3;
}
message AlbumImagesResponse {
repeated ExternalImage images = 1;
}
// go:plugin type=plugin version=1
service Scrobbler {
rpc IsAuthorized(ScrobblerIsAuthorizedRequest) returns (ScrobblerIsAuthorizedResponse);
rpc NowPlaying(ScrobblerNowPlayingRequest) returns (ScrobblerNowPlayingResponse);
rpc Scrobble(ScrobblerScrobbleRequest) returns (ScrobblerScrobbleResponse);
}
message ScrobblerIsAuthorizedRequest {
string user_id = 1;
string username = 2;
}
message ScrobblerIsAuthorizedResponse {
bool authorized = 1;
string error = 2;
}
message TrackInfo {
string id = 1;
string mbid = 2;
string name = 3;
string album = 4;
string album_mbid = 5;
repeated Artist artists = 6;
repeated Artist album_artists = 7;
int32 length = 8; // seconds
int32 position = 9; // seconds
}
message ScrobblerNowPlayingRequest {
string user_id = 1;
string username = 2;
TrackInfo track = 3;
int64 timestamp = 4;
}
message ScrobblerNowPlayingResponse {
string error = 1;
}
message ScrobblerScrobbleRequest {
string user_id = 1;
string username = 2;
TrackInfo track = 3;
int64 timestamp = 4;
}
message ScrobblerScrobbleResponse {
string error = 1;
}
// go:plugin type=plugin version=1
service SchedulerCallback {
rpc OnSchedulerCallback(SchedulerCallbackRequest) returns (SchedulerCallbackResponse);
}
message SchedulerCallbackRequest {
string schedule_id = 1; // ID of the scheduled job that triggered this callback
bytes payload = 2; // The data passed when the job was scheduled
bool is_recurring = 3; // Whether this is from a recurring schedule (cron job)
}
message SchedulerCallbackResponse {
string error = 1; // Error message if the callback failed
}
// go:plugin type=plugin version=1
service LifecycleManagement {
rpc OnInit(InitRequest) returns (InitResponse);
}
message InitRequest {
map<string, string> config = 1; // Configuration specific to this plugin
}
message InitResponse {
string error = 1; // Error message if initialization failed
}
// go:plugin type=plugin version=1
service WebSocketCallback {
// Called when a text message is received
rpc OnTextMessage(OnTextMessageRequest) returns (OnTextMessageResponse);
// Called when a binary message is received
rpc OnBinaryMessage(OnBinaryMessageRequest) returns (OnBinaryMessageResponse);
// Called when an error occurs
rpc OnError(OnErrorRequest) returns (OnErrorResponse);
// Called when the connection is closed
rpc OnClose(OnCloseRequest) returns (OnCloseResponse);
}
message OnTextMessageRequest {
string connection_id = 1;
string message = 2;
}
message OnTextMessageResponse {}
message OnBinaryMessageRequest {
string connection_id = 1;
bytes data = 2;
}
message OnBinaryMessageResponse {}
message OnErrorRequest {
string connection_id = 1;
string error = 2;
}
message OnErrorResponse {}
message OnCloseRequest {
string connection_id = 1;
int32 code = 2;
string reason = 3;
}
message OnCloseResponse {}
File diff suppressed because it is too large Load Diff
-47
View File
@@ -1,47 +0,0 @@
//go:build !wasip1
// Code generated by protoc-gen-go-plugin. DO NOT EDIT.
// versions:
// protoc-gen-go-plugin v0.1.0
// protoc v5.29.3
// source: api/api.proto
package api
import (
context "context"
wazero "github.com/tetratelabs/wazero"
wasi_snapshot_preview1 "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
)
type wazeroConfigOption func(plugin *WazeroConfig)
type WazeroNewRuntime func(context.Context) (wazero.Runtime, error)
type WazeroConfig struct {
newRuntime func(context.Context) (wazero.Runtime, error)
moduleConfig wazero.ModuleConfig
}
func WazeroRuntime(newRuntime WazeroNewRuntime) wazeroConfigOption {
return func(h *WazeroConfig) {
h.newRuntime = newRuntime
}
}
func DefaultWazeroRuntime() WazeroNewRuntime {
return func(ctx context.Context) (wazero.Runtime, error) {
r := wazero.NewRuntime(ctx)
if _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil {
return nil, err
}
return r, nil
}
}
func WazeroModuleConfig(moduleConfig wazero.ModuleConfig) wazeroConfigOption {
return func(h *WazeroConfig) {
h.moduleConfig = moduleConfig
}
}
-487
View File
@@ -1,487 +0,0 @@
//go:build wasip1
// Code generated by protoc-gen-go-plugin. DO NOT EDIT.
// versions:
// protoc-gen-go-plugin v0.1.0
// protoc v5.29.3
// source: api/api.proto
package api
import (
context "context"
wasm "github.com/knqyf263/go-plugin/wasm"
)
const MetadataAgentPluginAPIVersion = 1
//go:wasmexport metadata_agent_api_version
func _metadata_agent_api_version() uint64 {
return MetadataAgentPluginAPIVersion
}
var metadataAgent MetadataAgent
func RegisterMetadataAgent(p MetadataAgent) {
metadataAgent = p
}
//go:wasmexport metadata_agent_get_artist_mbid
func _metadata_agent_get_artist_mbid(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ArtistMBIDRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := metadataAgent.GetArtistMBID(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport metadata_agent_get_artist_url
func _metadata_agent_get_artist_url(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ArtistURLRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := metadataAgent.GetArtistURL(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport metadata_agent_get_artist_biography
func _metadata_agent_get_artist_biography(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ArtistBiographyRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := metadataAgent.GetArtistBiography(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport metadata_agent_get_similar_artists
func _metadata_agent_get_similar_artists(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ArtistSimilarRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := metadataAgent.GetSimilarArtists(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport metadata_agent_get_artist_images
func _metadata_agent_get_artist_images(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ArtistImageRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := metadataAgent.GetArtistImages(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport metadata_agent_get_artist_top_songs
func _metadata_agent_get_artist_top_songs(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ArtistTopSongsRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := metadataAgent.GetArtistTopSongs(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport metadata_agent_get_album_info
func _metadata_agent_get_album_info(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(AlbumInfoRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := metadataAgent.GetAlbumInfo(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport metadata_agent_get_album_images
func _metadata_agent_get_album_images(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(AlbumImagesRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := metadataAgent.GetAlbumImages(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
const ScrobblerPluginAPIVersion = 1
//go:wasmexport scrobbler_api_version
func _scrobbler_api_version() uint64 {
return ScrobblerPluginAPIVersion
}
var scrobbler Scrobbler
func RegisterScrobbler(p Scrobbler) {
scrobbler = p
}
//go:wasmexport scrobbler_is_authorized
func _scrobbler_is_authorized(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ScrobblerIsAuthorizedRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := scrobbler.IsAuthorized(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport scrobbler_now_playing
func _scrobbler_now_playing(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ScrobblerNowPlayingRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := scrobbler.NowPlaying(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport scrobbler_scrobble
func _scrobbler_scrobble(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(ScrobblerScrobbleRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := scrobbler.Scrobble(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
const SchedulerCallbackPluginAPIVersion = 1
//go:wasmexport scheduler_callback_api_version
func _scheduler_callback_api_version() uint64 {
return SchedulerCallbackPluginAPIVersion
}
var schedulerCallback SchedulerCallback
func RegisterSchedulerCallback(p SchedulerCallback) {
schedulerCallback = p
}
//go:wasmexport scheduler_callback_on_scheduler_callback
func _scheduler_callback_on_scheduler_callback(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(SchedulerCallbackRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := schedulerCallback.OnSchedulerCallback(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
const LifecycleManagementPluginAPIVersion = 1
//go:wasmexport lifecycle_management_api_version
func _lifecycle_management_api_version() uint64 {
return LifecycleManagementPluginAPIVersion
}
var lifecycleManagement LifecycleManagement
func RegisterLifecycleManagement(p LifecycleManagement) {
lifecycleManagement = p
}
//go:wasmexport lifecycle_management_on_init
func _lifecycle_management_on_init(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(InitRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := lifecycleManagement.OnInit(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
const WebSocketCallbackPluginAPIVersion = 1
//go:wasmexport web_socket_callback_api_version
func _web_socket_callback_api_version() uint64 {
return WebSocketCallbackPluginAPIVersion
}
var webSocketCallback WebSocketCallback
func RegisterWebSocketCallback(p WebSocketCallback) {
webSocketCallback = p
}
//go:wasmexport web_socket_callback_on_text_message
func _web_socket_callback_on_text_message(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(OnTextMessageRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := webSocketCallback.OnTextMessage(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport web_socket_callback_on_binary_message
func _web_socket_callback_on_binary_message(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(OnBinaryMessageRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := webSocketCallback.OnBinaryMessage(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport web_socket_callback_on_error
func _web_socket_callback_on_error(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(OnErrorRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := webSocketCallback.OnError(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
//go:wasmexport web_socket_callback_on_close
func _web_socket_callback_on_close(ptr, size uint32) uint64 {
b := wasm.PtrToByte(ptr, size)
req := new(OnCloseRequest)
if err := req.UnmarshalVT(b); err != nil {
return 0
}
response, err := webSocketCallback.OnClose(context.Background(), req)
if err != nil {
ptr, size = wasm.ByteToPtr([]byte(err.Error()))
return (uint64(ptr) << uint64(32)) | uint64(size) |
// Indicate that this is the error string by setting the 32-th bit, assuming that
// no data exceeds 31-bit size (2 GiB).
(1 << 31)
}
b, err = response.MarshalVT()
if err != nil {
return 0
}
ptr, size = wasm.ByteToPtr(b)
return (uint64(ptr) << uint64(32)) | uint64(size)
}
-34
View File
@@ -1,34 +0,0 @@
//go:build !wasip1
package api
import "github.com/navidrome/navidrome/plugins/host/scheduler"
// This file exists to provide stubs for the plugin registration functions when building for non-WASM targets.
// This is useful for testing and development purposes, as it allows you to build and run your plugin code
// without having to compile it to WASM.
// In a real-world scenario, you would compile your plugin to WASM and use the generated registration functions.
func RegisterMetadataAgent(MetadataAgent) {
panic("not implemented")
}
func RegisterScrobbler(Scrobbler) {
panic("not implemented")
}
func RegisterSchedulerCallback(SchedulerCallback) {
panic("not implemented")
}
func RegisterLifecycleManagement(LifecycleManagement) {
panic("not implemented")
}
func RegisterWebSocketCallback(WebSocketCallback) {
panic("not implemented")
}
func RegisterNamedSchedulerCallback(name string, cb SchedulerCallback) scheduler.SchedulerService {
panic("not implemented")
}
@@ -1,94 +0,0 @@
//go:build wasip1
package api
import (
"context"
"strings"
"github.com/navidrome/navidrome/plugins/host/scheduler"
)
var callbacks = make(namedCallbacks)
// RegisterNamedSchedulerCallback registers a named scheduler callback. Named callbacks allow multiple callbacks to be registered
// within the same plugin, and for the schedules to be scoped to the named callback. If you only need a single callback, you can use
// the default (unnamed) callback registration function, RegisterSchedulerCallback.
// It returns a scheduler.SchedulerService that can be used to schedule jobs for the named callback.
//
// Notes:
//
// - You can't mix named and unnamed callbacks within the same plugin.
// - The name should be unique within the plugin, and it's recommended to use a short, descriptive name.
// - The name is case-sensitive.
func RegisterNamedSchedulerCallback(name string, cb SchedulerCallback) scheduler.SchedulerService {
callbacks[name] = cb
RegisterSchedulerCallback(&callbacks)
return &namedSchedulerService{name: name, svc: scheduler.NewSchedulerService()}
}
const zwsp = string('\u200b')
// namedCallbacks is a map of named scheduler callbacks. The key is the name of the callback, and the value is the callback itself.
type namedCallbacks map[string]SchedulerCallback
func parseKey(key string) (string, string) {
parts := strings.SplitN(key, zwsp, 2)
if len(parts) != 2 {
return "", ""
}
return parts[0], parts[1]
}
func (n *namedCallbacks) OnSchedulerCallback(ctx context.Context, req *SchedulerCallbackRequest) (*SchedulerCallbackResponse, error) {
name, scheduleId := parseKey(req.ScheduleId)
cb, exists := callbacks[name]
if !exists {
return nil, nil
}
req.ScheduleId = scheduleId
return cb.OnSchedulerCallback(ctx, req)
}
// namedSchedulerService is a wrapper around the host scheduler service that prefixes the schedule IDs with the
// callback name. It is returned by RegisterNamedSchedulerCallback, and should be used by the plugin to schedule
// jobs for the named callback.
type namedSchedulerService struct {
name string
cb SchedulerCallback
svc scheduler.SchedulerService
}
func (n *namedSchedulerService) makeKey(id string) string {
return n.name + zwsp + id
}
func (n *namedSchedulerService) mapResponse(resp *scheduler.ScheduleResponse, err error) (*scheduler.ScheduleResponse, error) {
if err != nil {
return nil, err
}
_, resp.ScheduleId = parseKey(resp.ScheduleId)
return resp, nil
}
func (n *namedSchedulerService) ScheduleOneTime(ctx context.Context, request *scheduler.ScheduleOneTimeRequest) (*scheduler.ScheduleResponse, error) {
key := n.makeKey(request.ScheduleId)
request.ScheduleId = key
return n.mapResponse(n.svc.ScheduleOneTime(ctx, request))
}
func (n *namedSchedulerService) ScheduleRecurring(ctx context.Context, request *scheduler.ScheduleRecurringRequest) (*scheduler.ScheduleResponse, error) {
key := n.makeKey(request.ScheduleId)
request.ScheduleId = key
return n.mapResponse(n.svc.ScheduleRecurring(ctx, request))
}
func (n *namedSchedulerService) CancelSchedule(ctx context.Context, request *scheduler.CancelRequest) (*scheduler.CancelResponse, error) {
key := n.makeKey(request.ScheduleId)
request.ScheduleId = key
return n.svc.CancelSchedule(ctx, request)
}
func (n *namedSchedulerService) TimeNow(ctx context.Context, request *scheduler.TimeNowRequest) (*scheduler.TimeNowResponse, error) {
return n.svc.TimeNow(ctx, request)
}
File diff suppressed because it is too large Load Diff
-12
View File
@@ -1,12 +0,0 @@
package api
import "errors"
var (
// ErrNotImplemented indicates that the plugin does not implement the requested method.
// No logic should be executed by the plugin.
ErrNotImplemented = errors.New("plugin:not_implemented")
// ErrNotFound indicates that the requested resource was not found by the plugin.
ErrNotFound = errors.New("plugin:not_found")
)
-159
View File
@@ -1,159 +0,0 @@
package plugins
import (
"context"
"errors"
"fmt"
"time"
"github.com/navidrome/navidrome/core/metrics"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model/id"
"github.com/navidrome/navidrome/plugins/api"
)
// newBaseCapability creates a new instance of baseCapability with the required parameters.
func newBaseCapability[S any, P any](wasmPath, id, capability string, m metrics.Metrics, loader P, loadFunc loaderFunc[S, P]) *baseCapability[S, P] {
return &baseCapability[S, P]{
wasmPath: wasmPath,
id: id,
capability: capability,
loader: loader,
loadFunc: loadFunc,
metrics: m,
}
}
// LoaderFunc is a generic function type that loads a plugin instance.
type loaderFunc[S any, P any] func(ctx context.Context, loader P, path string) (S, error)
// baseCapability is a generic base implementation for WASM plugins.
// S is the capability interface type and P is the plugin loader type.
type baseCapability[S any, P any] struct {
wasmPath string
id string
capability string
loader P
loadFunc loaderFunc[S, P]
metrics metrics.Metrics
}
func (w *baseCapability[S, P]) PluginID() string {
return w.id
}
func (w *baseCapability[S, P]) serviceName() string {
return w.id + "_" + w.capability
}
func (w *baseCapability[S, P]) getMetrics() metrics.Metrics {
return w.metrics
}
// getInstance loads a new plugin instance and returns a cleanup function.
func (w *baseCapability[S, P]) getInstance(ctx context.Context, methodName string) (S, func(), error) {
start := time.Now()
// Add context metadata for tracing
ctx = log.NewContext(ctx, "capability", w.serviceName(), "method", methodName)
inst, err := w.loadFunc(ctx, w.loader, w.wasmPath)
if err != nil {
var zero S
return zero, func() {}, fmt.Errorf("baseCapability: failed to load instance for %s: %w", w.serviceName(), err)
}
// Add context metadata for tracing
ctx = log.NewContext(ctx, "instanceID", getInstanceID(inst))
log.Trace(ctx, "baseCapability: loaded instance", "elapsed", time.Since(start))
return inst, func() {
log.Trace(ctx, "baseCapability: finished using instance", "elapsed", time.Since(start))
if closer, ok := any(inst).(interface{ Close(context.Context) error }); ok {
_ = closer.Close(ctx)
}
}, nil
}
type wasmPlugin[S any] interface {
PluginID() string
getInstance(ctx context.Context, methodName string) (S, func(), error)
getMetrics() metrics.Metrics
}
func callMethod[S any, R any](ctx context.Context, wp WasmPlugin, methodName string, fn func(inst S) (R, error)) (R, error) {
// Add a unique call ID to the context for tracing
ctx = log.NewContext(ctx, "callID", id.NewRandom())
var r R
p, ok := wp.(wasmPlugin[S])
if !ok {
log.Error(ctx, "callMethod: not a wasm plugin", "method", methodName, "pluginID", wp.PluginID())
return r, fmt.Errorf("wasm plugin: not a wasm plugin: %s", wp.PluginID())
}
inst, done, err := p.getInstance(ctx, methodName)
if err != nil {
return r, err
}
start := time.Now()
defer done()
r, err = checkErr(fn(inst))
elapsed := time.Since(start)
if !errors.Is(err, api.ErrNotImplemented) {
id := p.PluginID()
isOk := err == nil
metrics := p.getMetrics()
if metrics != nil {
metrics.RecordPluginRequest(ctx, id, methodName, isOk, elapsed.Milliseconds())
log.Trace(ctx, "callMethod: sending metrics", "plugin", id, "method", methodName, "ok", isOk, "elapsed", elapsed)
}
}
return r, err
}
// errorResponse is an interface that defines a method to retrieve an error message.
// It is automatically implemented (generated) by all plugin responses that have an Error field
type errorResponse interface {
GetError() string
}
// checkErr returns an updated error if the response implements errorResponse and contains an error message.
// If the response is nil, it returns the original error. Otherwise, it wraps or creates an error as needed.
// It also maps error strings to their corresponding api.Err* constants.
func checkErr[T any](resp T, err error) (T, error) {
if any(resp) == nil {
return resp, mapAPIError(err)
}
respErr, ok := any(resp).(errorResponse)
if ok && respErr.GetError() != "" {
respErrMsg := respErr.GetError()
respErrErr := errors.New(respErrMsg)
mappedErr := mapAPIError(respErrErr)
// Check if the error was mapped to an API error (different from the temp error)
if errors.Is(mappedErr, api.ErrNotImplemented) || errors.Is(mappedErr, api.ErrNotFound) {
// Return the mapped API error instead of wrapping
return resp, mappedErr
}
// For non-API errors, use wrap the original error if it is not nil
return resp, errors.Join(respErrErr, err)
}
return resp, mapAPIError(err)
}
// mapAPIError maps error strings to their corresponding api.Err* constants.
// This is needed as errors from plugins may not be of type api.Error, due to serialization/deserialization.
func mapAPIError(err error) error {
if err == nil {
return nil
}
errStr := err.Error()
switch errStr {
case api.ErrNotImplemented.Error():
return api.ErrNotImplemented
case api.ErrNotFound.Error():
return api.ErrNotFound
default:
return err
}
}
-285
View File
@@ -1,285 +0,0 @@
package plugins
import (
"context"
"errors"
"github.com/navidrome/navidrome/plugins/api"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type nilInstance struct{}
var _ = Describe("baseCapability", func() {
var ctx = context.Background()
It("should load instance using loadFunc", func() {
called := false
plugin := &baseCapability[*nilInstance, any]{
wasmPath: "",
id: "test",
capability: "test",
loadFunc: func(ctx context.Context, _ any, path string) (*nilInstance, error) {
called = true
return &nilInstance{}, nil
},
}
inst, done, err := plugin.getInstance(ctx, "test")
defer done()
Expect(err).To(BeNil())
Expect(inst).ToNot(BeNil())
Expect(called).To(BeTrue())
})
})
var _ = Describe("checkErr", func() {
Context("when resp is nil", func() {
It("should return nil error when both resp and err are nil", func() {
var resp *testErrorResponse
result, err := checkErr(resp, nil)
Expect(result).To(BeNil())
Expect(err).To(BeNil())
})
It("should return original error unchanged for non-API errors", func() {
var resp *testErrorResponse
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(BeNil())
Expect(err).To(Equal(originalErr))
})
It("should return mapped API error for ErrNotImplemented", func() {
var resp *testErrorResponse
err := errors.New("plugin:not_implemented")
result, mappedErr := checkErr(resp, err)
Expect(result).To(BeNil())
Expect(mappedErr).To(Equal(api.ErrNotImplemented))
})
It("should return mapped API error for ErrNotFound", func() {
var resp *testErrorResponse
err := errors.New("plugin:not_found")
result, mappedErr := checkErr(resp, err)
Expect(result).To(BeNil())
Expect(mappedErr).To(Equal(api.ErrNotFound))
})
})
Context("when resp is a typed nil that implements errorResponse", func() {
It("should not panic and return original error", func() {
var resp *testErrorResponse // typed nil
originalErr := errors.New("original error")
// This should not panic
result, err := checkErr(resp, originalErr)
Expect(result).To(BeNil())
Expect(err).To(Equal(originalErr))
})
It("should handle typed nil with nil error gracefully", func() {
var resp *testErrorResponse // typed nil
// This should not panic
result, err := checkErr(resp, nil)
Expect(result).To(BeNil())
Expect(err).To(BeNil())
})
})
Context("when resp implements errorResponse with non-empty error", func() {
It("should create new error when original error is nil", func() {
resp := &testErrorResponse{errorMsg: "plugin error"}
result, err := checkErr(resp, nil)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError("plugin error"))
})
It("should wrap original error when both exist", func() {
resp := &testErrorResponse{errorMsg: "plugin error"}
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(HaveOccurred())
// Check that both error messages are present in the joined error
errStr := err.Error()
Expect(errStr).To(ContainSubstring("plugin error"))
Expect(errStr).To(ContainSubstring("original error"))
})
It("should return mapped API error for ErrNotImplemented when no original error", func() {
resp := &testErrorResponse{errorMsg: "plugin:not_implemented"}
result, err := checkErr(resp, nil)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(api.ErrNotImplemented))
})
It("should return mapped API error for ErrNotFound when no original error", func() {
resp := &testErrorResponse{errorMsg: "plugin:not_found"}
result, err := checkErr(resp, nil)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(api.ErrNotFound))
})
It("should return mapped API error for ErrNotImplemented even with original error", func() {
resp := &testErrorResponse{errorMsg: "plugin:not_implemented"}
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(api.ErrNotImplemented))
})
It("should return mapped API error for ErrNotFound even with original error", func() {
resp := &testErrorResponse{errorMsg: "plugin:not_found"}
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(api.ErrNotFound))
})
})
Context("when resp implements errorResponse with empty error", func() {
It("should return original error unchanged", func() {
resp := &testErrorResponse{errorMsg: ""}
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(originalErr))
})
It("should return nil error when both are empty/nil", func() {
resp := &testErrorResponse{errorMsg: ""}
result, err := checkErr(resp, nil)
Expect(result).To(Equal(resp))
Expect(err).To(BeNil())
})
It("should map original API error when response error is empty", func() {
resp := &testErrorResponse{errorMsg: ""}
originalErr := errors.New("plugin:not_implemented")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(api.ErrNotImplemented))
})
})
Context("when resp does not implement errorResponse", func() {
It("should return original error unchanged", func() {
resp := &testNonErrorResponse{data: "some data"}
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(Equal(originalErr))
})
It("should return nil error when original error is nil", func() {
resp := &testNonErrorResponse{data: "some data"}
result, err := checkErr(resp, nil)
Expect(result).To(Equal(resp))
Expect(err).To(BeNil())
})
It("should map original API error when response doesn't implement errorResponse", func() {
resp := &testNonErrorResponse{data: "some data"}
originalErr := errors.New("plugin:not_found")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(api.ErrNotFound))
})
})
Context("when resp is a value type (not pointer)", func() {
It("should handle value types that implement errorResponse", func() {
resp := testValueErrorResponse{errorMsg: "value error"}
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(HaveOccurred())
// Check that both error messages are present in the joined error
errStr := err.Error()
Expect(errStr).To(ContainSubstring("value error"))
Expect(errStr).To(ContainSubstring("original error"))
})
It("should handle value types with empty error", func() {
resp := testValueErrorResponse{errorMsg: ""}
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(originalErr))
})
It("should handle value types with API error", func() {
resp := testValueErrorResponse{errorMsg: "plugin:not_implemented"}
originalErr := errors.New("original error")
result, err := checkErr(resp, originalErr)
Expect(result).To(Equal(resp))
Expect(err).To(MatchError(api.ErrNotImplemented))
})
})
})
// Test helper types
type testErrorResponse struct {
errorMsg string
}
func (t *testErrorResponse) GetError() string {
if t == nil {
return "" // This is what would typically happen with a typed nil
}
return t.errorMsg
}
type testNonErrorResponse struct {
data string
}
type testValueErrorResponse struct {
errorMsg string
}
func (t testValueErrorResponse) GetError() string {
return t.errorMsg
}
+47
View File
@@ -0,0 +1,47 @@
package plugins
// Capability represents a plugin capability type.
// Capabilities are detected by checking which functions a plugin exports.
type Capability string
// capabilityFunctions maps each capability to its required/optional functions.
// A plugin has a capability if it exports at least one of these functions.
var capabilityFunctions = map[Capability][]string{}
// registerCapability registers a capability with its associated functions.
func registerCapability(cap Capability, functions ...string) {
capabilityFunctions[cap] = functions
}
// functionExistsChecker is an interface for checking if a function exists in a plugin.
// This allows for testing without a real plugin instance.
type functionExistsChecker interface {
FunctionExists(name string) bool
}
// detectCapabilities detects which capabilities a plugin has by checking
// which functions it exports.
func detectCapabilities(plugin functionExistsChecker) []Capability {
var capabilities []Capability
for cap, functions := range capabilityFunctions {
for _, fn := range functions {
if plugin.FunctionExists(fn) {
capabilities = append(capabilities, cap)
break // Found at least one function, plugin has this capability
}
}
}
return capabilities
}
// hasCapability checks if the given capabilities slice contains a specific capability.
func hasCapability(capabilities []Capability, cap Capability) bool {
for _, c := range capabilities {
if c == cap {
return true
}
}
return false
}
+87
View File
@@ -0,0 +1,87 @@
# Navidrome Plugin Capabilities
This directory contains the Go interface definitions for Navidrome plugin capabilities. These interfaces are the **source of truth** for plugin development and are used to generate:
1. **Go PDK packages** (`pdk/go/*/`) - Type-safe wrappers for Go plugin developers
2. **Rust PDK crates** (`pdk/rust/*/`) - Type-safe wrappers for Rust plugin developers
3. **XTP YAML schemas** (`*.yaml`) - Schema files for other [Extism plugin languages](https://extism.org/docs/concepts/pdk/) (TypeScript, Python, C#, Zig, C++, ...)
## For Go Plugin Developers
Go developers should use the generated PDK packages in `plugins/pdk/go/`. See the example Go plugins in `plugins/examples/` for usage patterns.
## For Rust Plugin Developers
Rust developers should use the generated PDK crate in `plugins/pdk/rust/nd-pdk`. See the example Rust plugins in `plugins/examples` for usage patterns.
## For Non-Go Plugin Developers
If you're developing plugins in other languages (TypeScript, Rust, Python, C#, Zig, C++), you can use the XTP CLI to generate type-safe bindings from the YAML schema files in this directory.
### Prerequisites
Install the XTP CLI:
```bash
# macOS
brew install dylibso/tap/xtp
# Other platforms - see https://docs.xtp.dylibso.com/docs/cli
curl https://static.dylibso.com/cli/install.sh | bash
```
### Generating Plugin Scaffolding
Use the XTP CLI to generate plugin boilerplate from any capability schema:
```bash
# TypeScript
xtp plugin init --schema-file plugins/capabilities/metadata_agent.yaml \
--template typescript --path my-plugin
# Rust
xtp plugin init --schema-file plugins/capabilities/scrobbler.yaml \
--template rust --path my-plugin
# Python
xtp plugin init --schema-file plugins/capabilities/lifecycle.yaml \
--template python --path my-plugin
# C#
xtp plugin init --schema-file plugins/capabilities/scheduler_callback.yaml \
--template csharp --path my-plugin
# Go (alternative to using the PDK packages)
xtp plugin init --schema-file plugins/capabilities/websocket_callback.yaml \
--template go --path my-plugin
```
### Available Capabilities
| Capability | Schema File | Description |
|--------------------|---------------------------|-------------------------------------------------------------|
| Metadata Agent | `metadata_agent.yaml` | Fetch artist biographies, album images, and similar artists |
| Scrobbler | `scrobbler.yaml` | Report listening activity to external services |
| Lifecycle | `lifecycle.yaml` | Plugin initialization callbacks |
| Scheduler Callback | `scheduler_callback.yaml` | Scheduled task execution |
| WebSocket Callback | `websocket_callback.yaml` | Real-time WebSocket message handling |
### Building Your Plugin
After generating the scaffolding, implement the required functions and build your plugin as a WebAssembly module. The exact build process depends on your chosen language - see the [Extism PDK documentation](https://extism.org/docs/concepts/pdk) for language-specific guides.
## XTP Schema Generation
The YAML schemas in this package are automatically generated from the capability Go interfaces using `ndpgen`.
To regenerate the schemas after modifying the interfaces, run:
```bash
cd plugins/cmd/ndpgen && go run . -schemas -input=./plugins/capabilities
```
## Resources
- [XTP Documentation](https://docs.xtp.dylibso.com/)
- [XTP Bindgen Repository](https://github.com/dylibso/xtp-bindgen)
- [Extism Plugin Development Kit](https://extism.org/docs/concepts/pdk)
- [XTP Schema Definition](https://raw.githubusercontent.com/dylibso/xtp-bindgen/5090518dd86ba5e734dc225a33066ecc0ed2e12d/plugin/schema.json)
+56
View File
@@ -0,0 +1,56 @@
// Package capabilities defines Go interfaces for Navidrome plugin capabilities.
//
// These interfaces serve as the source of truth for capability definitions.
// The ndpgen tool generates:
// - Go export wrappers in plugins/pdk/go/<capability>/ for Go plugins
// - XTP YAML schemas for non-Go plugins (Rust, TypeScript, etc.)
//
// Each capability is defined as an annotated interface:
//
// //nd:capability name=metadata
// type MetadataAgent interface {
// //nd:export name=nd_get_artist_biography
// GetArtistBiography(ArtistRequest) (*ArtistBiographyResponse, error)
// }
//
// Annotation Reference:
//
// //nd:capability name=<pkg> [required=true]
// - Marks an interface as a capability
// - name: Generated package name (e.g., name=metadata → pdk/go/metadata/)
// - required: If true, all methods must be implemented (default: false)
//
// //nd:export name=<func>
// - Marks a method as an exported WASM function
// - name: The export name (e.g., nd_get_artist_biography)
//
// Generated Code Structure:
//
// For a capability like MetadataAgent with required=false:
//
// package metadata
//
// // Agent is the marker interface
// type Agent interface{}
//
// // Optional provider interfaces
// type ArtistBiographyProvider interface {
// GetArtistBiography(ArtistRequest) (*ArtistBiographyResponse, error)
// }
//
// // Registration function
// func Register(impl Agent) { ... }
//
// For a capability with required=true:
//
// package scrobbler
//
// // Scrobbler requires all methods
// type Scrobbler interface {
// IsAuthorized(IsAuthorizedRequest) (bool, error)
// NowPlaying(NowPlayingRequest) error
// Scrobble(ScrobbleRequest) error
// }
//
// func Register(impl Scrobbler) { ... }
package capabilities
+19
View File
@@ -0,0 +1,19 @@
package capabilities
// Lifecycle provides plugin lifecycle hooks.
// This capability allows plugins to perform initialization when loaded,
// such as establishing connections, starting background processes, or
// validating configuration.
//
// The OnInit function is called once when the plugin is loaded, and is NOT
// called when the plugin is hot-reloaded. Plugins should not assume this
// function will be called on every startup.
//
//nd:capability name=lifecycle
type Lifecycle interface {
// OnInit is called after a plugin is fully loaded with all services registered.
// Plugins can use this function to perform one-time initialization tasks.
// Errors are logged but will not prevent the plugin from being loaded.
//nd:export name=nd_on_init
OnInit() error
}
+7
View File
@@ -0,0 +1,7 @@
version: v1-draft
exports:
nd_on_init:
description: |-
OnInit is called after a plugin is fully loaded with all services registered.
Plugins can use this function to perform one-time initialization tasks.
Errors are logged but will not prevent the plugin from being loaded.
+167
View File
@@ -0,0 +1,167 @@
package capabilities
// MetadataAgent provides artist and album metadata retrieval.
// This capability allows plugins to provide external metadata for artists and albums,
// such as biographies, images, similar artists, and top songs.
//
// Plugins implementing this capability can choose which methods to implement.
// Each method is optional - plugins only need to provide the functionality they support.
//
//nd:capability name=metadata
type MetadataAgent interface {
// GetArtistMBID retrieves the MusicBrainz ID for an artist.
//nd:export name=nd_get_artist_mbid
GetArtistMBID(ArtistMBIDRequest) (*ArtistMBIDResponse, error)
// GetArtistURL retrieves the external URL for an artist.
//nd:export name=nd_get_artist_url
GetArtistURL(ArtistRequest) (*ArtistURLResponse, error)
// GetArtistBiography retrieves the biography for an artist.
//nd:export name=nd_get_artist_biography
GetArtistBiography(ArtistRequest) (*ArtistBiographyResponse, error)
// GetSimilarArtists retrieves similar artists for a given artist.
//nd:export name=nd_get_similar_artists
GetSimilarArtists(SimilarArtistsRequest) (*SimilarArtistsResponse, error)
// GetArtistImages retrieves images for an artist.
//nd:export name=nd_get_artist_images
GetArtistImages(ArtistRequest) (*ArtistImagesResponse, error)
// GetArtistTopSongs retrieves top songs for an artist.
//nd:export name=nd_get_artist_top_songs
GetArtistTopSongs(TopSongsRequest) (*TopSongsResponse, error)
// GetAlbumInfo retrieves album information.
//nd:export name=nd_get_album_info
GetAlbumInfo(AlbumRequest) (*AlbumInfoResponse, error)
// GetAlbumImages retrieves images for an album.
//nd:export name=nd_get_album_images
GetAlbumImages(AlbumRequest) (*AlbumImagesResponse, error)
}
// ArtistMBIDRequest is the request for GetArtistMBID.
type ArtistMBIDRequest struct {
// ID is the internal Navidrome artist ID.
ID string `json:"id"`
// Name is the artist name.
Name string `json:"name"`
}
// ArtistMBIDResponse is the response for GetArtistMBID.
type ArtistMBIDResponse struct {
// MBID is the MusicBrainz ID for the artist.
MBID string `json:"mbid"`
}
// ArtistRequest is the common request for artist-related functions.
type ArtistRequest struct {
// ID is the internal Navidrome artist ID.
ID string `json:"id"`
// Name is the artist name.
Name string `json:"name"`
// MBID is the MusicBrainz ID for the artist (if known).
MBID string `json:"mbid,omitempty"`
}
// ArtistURLResponse is the response for GetArtistURL.
type ArtistURLResponse struct {
// URL is the external URL for the artist.
URL string `json:"url"`
}
// ArtistBiographyResponse is the response for GetArtistBiography.
type ArtistBiographyResponse struct {
// Biography is the artist biography text.
Biography string `json:"biography"`
}
// SimilarArtistsRequest is the request for GetSimilarArtists.
type SimilarArtistsRequest struct {
// ID is the internal Navidrome artist ID.
ID string `json:"id"`
// Name is the artist name.
Name string `json:"name"`
// MBID is the MusicBrainz ID for the artist (if known).
MBID string `json:"mbid,omitempty"`
// Limit is the maximum number of similar artists to return.
Limit int32 `json:"limit"`
}
// SimilarArtistsResponse is the response for GetSimilarArtists.
type SimilarArtistsResponse struct {
// Artists is the list of similar artists.
Artists []ArtistRef `json:"artists"`
}
// ImageInfo represents an image with URL and size.
type ImageInfo struct {
// URL is the URL of the image.
URL string `json:"url"`
// Size is the size of the image in pixels (width or height).
Size int32 `json:"size"`
}
// ArtistImagesResponse is the response for GetArtistImages.
type ArtistImagesResponse struct {
// Images is the list of artist images.
Images []ImageInfo `json:"images"`
}
// TopSongsRequest is the request for GetArtistTopSongs.
type TopSongsRequest struct {
// ID is the internal Navidrome artist ID.
ID string `json:"id"`
// Name is the artist name.
Name string `json:"name"`
// MBID is the MusicBrainz ID for the artist (if known).
MBID string `json:"mbid,omitempty"`
// Count is the maximum number of top songs to return.
Count int32 `json:"count"`
}
// SongRef is a reference to a song with name and optional MBID.
type SongRef struct {
// ID is the internal Navidrome mediafile ID (if known).
ID string `json:"id,omitempty"`
// Name is the song name.
Name string `json:"name"`
// MBID is the MusicBrainz ID for the song.
MBID string `json:"mbid,omitempty"`
}
// TopSongsResponse is the response for GetArtistTopSongs.
type TopSongsResponse struct {
// Songs is the list of top songs.
Songs []SongRef `json:"songs"`
}
// AlbumRequest is the common request for album-related functions.
type AlbumRequest struct {
// Name is the album name.
Name string `json:"name"`
// Artist is the album artist name.
Artist string `json:"artist"`
// MBID is the MusicBrainz ID for the album (if known).
MBID string `json:"mbid,omitempty"`
}
// AlbumInfoResponse is the response for GetAlbumInfo.
type AlbumInfoResponse struct {
// Name is the album name.
Name string `json:"name"`
// MBID is the MusicBrainz ID for the album.
MBID string `json:"mbid"`
// Description is the album description/notes.
Description string `json:"description"`
// URL is the external URL for the album.
URL string `json:"url"`
}
// AlbumImagesResponse is the response for GetAlbumImages.
type AlbumImagesResponse struct {
// Images is the list of album images.
Images []ImageInfo `json:"images"`
}
+275
View File
@@ -0,0 +1,275 @@
version: v1-draft
exports:
nd_get_artist_mbid:
description: GetArtistMBID retrieves the MusicBrainz ID for an artist.
input:
$ref: '#/components/schemas/ArtistMBIDRequest'
contentType: application/json
output:
$ref: '#/components/schemas/ArtistMBIDResponse'
contentType: application/json
nd_get_artist_url:
description: GetArtistURL retrieves the external URL for an artist.
input:
$ref: '#/components/schemas/ArtistRequest'
contentType: application/json
output:
$ref: '#/components/schemas/ArtistURLResponse'
contentType: application/json
nd_get_artist_biography:
description: GetArtistBiography retrieves the biography for an artist.
input:
$ref: '#/components/schemas/ArtistRequest'
contentType: application/json
output:
$ref: '#/components/schemas/ArtistBiographyResponse'
contentType: application/json
nd_get_similar_artists:
description: GetSimilarArtists retrieves similar artists for a given artist.
input:
$ref: '#/components/schemas/SimilarArtistsRequest'
contentType: application/json
output:
$ref: '#/components/schemas/SimilarArtistsResponse'
contentType: application/json
nd_get_artist_images:
description: GetArtistImages retrieves images for an artist.
input:
$ref: '#/components/schemas/ArtistRequest'
contentType: application/json
output:
$ref: '#/components/schemas/ArtistImagesResponse'
contentType: application/json
nd_get_artist_top_songs:
description: GetArtistTopSongs retrieves top songs for an artist.
input:
$ref: '#/components/schemas/TopSongsRequest'
contentType: application/json
output:
$ref: '#/components/schemas/TopSongsResponse'
contentType: application/json
nd_get_album_info:
description: GetAlbumInfo retrieves album information.
input:
$ref: '#/components/schemas/AlbumRequest'
contentType: application/json
output:
$ref: '#/components/schemas/AlbumInfoResponse'
contentType: application/json
nd_get_album_images:
description: GetAlbumImages retrieves images for an album.
input:
$ref: '#/components/schemas/AlbumRequest'
contentType: application/json
output:
$ref: '#/components/schemas/AlbumImagesResponse'
contentType: application/json
components:
schemas:
AlbumImagesResponse:
description: AlbumImagesResponse is the response for GetAlbumImages.
properties:
images:
type: array
description: Images is the list of album images.
items:
$ref: '#/components/schemas/ImageInfo'
required:
- images
AlbumInfoResponse:
description: AlbumInfoResponse is the response for GetAlbumInfo.
properties:
name:
type: string
description: Name is the album name.
mbid:
type: string
description: MBID is the MusicBrainz ID for the album.
description:
type: string
description: Description is the album description/notes.
url:
type: string
description: URL is the external URL for the album.
required:
- name
- mbid
- description
- url
AlbumRequest:
description: AlbumRequest is the common request for album-related functions.
properties:
name:
type: string
description: Name is the album name.
artist:
type: string
description: Artist is the album artist name.
mbid:
type: string
description: MBID is the MusicBrainz ID for the album (if known).
required:
- name
- artist
ArtistBiographyResponse:
description: ArtistBiographyResponse is the response for GetArtistBiography.
properties:
biography:
type: string
description: Biography is the artist biography text.
required:
- biography
ArtistImagesResponse:
description: ArtistImagesResponse is the response for GetArtistImages.
properties:
images:
type: array
description: Images is the list of artist images.
items:
$ref: '#/components/schemas/ImageInfo'
required:
- images
ArtistMBIDRequest:
description: ArtistMBIDRequest is the request for GetArtistMBID.
properties:
id:
type: string
description: ID is the internal Navidrome artist ID.
name:
type: string
description: Name is the artist name.
required:
- id
- name
ArtistMBIDResponse:
description: ArtistMBIDResponse is the response for GetArtistMBID.
properties:
mbid:
type: string
description: MBID is the MusicBrainz ID for the artist.
required:
- mbid
ArtistRef:
description: ArtistRef is a reference to an artist with name and optional MBID.
properties:
id:
type: string
description: ID is the internal Navidrome artist ID (if known).
name:
type: string
description: Name is the artist name.
mbid:
type: string
description: MBID is the MusicBrainz ID for the artist.
required:
- name
ArtistRequest:
description: ArtistRequest is the common request for artist-related functions.
properties:
id:
type: string
description: ID is the internal Navidrome artist ID.
name:
type: string
description: Name is the artist name.
mbid:
type: string
description: MBID is the MusicBrainz ID for the artist (if known).
required:
- id
- name
ArtistURLResponse:
description: ArtistURLResponse is the response for GetArtistURL.
properties:
url:
type: string
description: URL is the external URL for the artist.
required:
- url
ImageInfo:
description: ImageInfo represents an image with URL and size.
properties:
url:
type: string
description: URL is the URL of the image.
size:
type: integer
format: int32
description: Size is the size of the image in pixels (width or height).
required:
- url
- size
SimilarArtistsRequest:
description: SimilarArtistsRequest is the request for GetSimilarArtists.
properties:
id:
type: string
description: ID is the internal Navidrome artist ID.
name:
type: string
description: Name is the artist name.
mbid:
type: string
description: MBID is the MusicBrainz ID for the artist (if known).
limit:
type: integer
format: int32
description: Limit is the maximum number of similar artists to return.
required:
- id
- name
- limit
SimilarArtistsResponse:
description: SimilarArtistsResponse is the response for GetSimilarArtists.
properties:
artists:
type: array
description: Artists is the list of similar artists.
items:
$ref: '#/components/schemas/ArtistRef'
required:
- artists
SongRef:
description: SongRef is a reference to a song with name and optional MBID.
properties:
id:
type: string
description: ID is the internal Navidrome mediafile ID (if known).
name:
type: string
description: Name is the song name.
mbid:
type: string
description: MBID is the MusicBrainz ID for the song.
required:
- name
TopSongsRequest:
description: TopSongsRequest is the request for GetArtistTopSongs.
properties:
id:
type: string
description: ID is the internal Navidrome artist ID.
name:
type: string
description: Name is the artist name.
mbid:
type: string
description: MBID is the MusicBrainz ID for the artist (if known).
count:
type: integer
format: int32
description: Count is the maximum number of top songs to return.
required:
- id
- name
- count
TopSongsResponse:
description: TopSongsResponse is the response for GetArtistTopSongs.
properties:
songs:
type: array
description: Songs is the list of top songs.
items:
$ref: '#/components/schemas/SongRef'
required:
- songs
@@ -0,0 +1,27 @@
package capabilities
// SchedulerCallback provides scheduled task handling.
// This capability allows plugins to receive callbacks when their scheduled tasks execute.
// Plugins that use the scheduler host service must implement this capability
// to handle task execution.
//
//nd:capability name=scheduler
type SchedulerCallback interface {
// OnCallback is called when a scheduled task fires.
// Errors are logged but do not affect the scheduling system.
//nd:export name=nd_scheduler_callback
OnCallback(SchedulerCallbackRequest) error
}
// SchedulerCallbackRequest is the request provided when a scheduled task fires.
type SchedulerCallbackRequest struct {
// ScheduleID is the unique identifier for this scheduled task.
// This is either the ID provided when scheduling, or an auto-generated UUID if none was specified.
ScheduleID string `json:"scheduleId"`
// Payload is the payload data that was provided when the task was scheduled.
// Can be used to pass context or parameters to the callback handler.
Payload string `json:"payload"`
// IsRecurring is true if this is a recurring schedule (created via ScheduleRecurring),
// false if it's a one-time schedule (created via ScheduleOneTime).
IsRecurring bool `json:"isRecurring"`
}
@@ -0,0 +1,33 @@
version: v1-draft
exports:
nd_scheduler_callback:
description: |-
OnCallback is called when a scheduled task fires.
Errors are logged but do not affect the scheduling system.
input:
$ref: '#/components/schemas/SchedulerCallbackRequest'
contentType: application/json
components:
schemas:
SchedulerCallbackRequest:
description: SchedulerCallbackRequest is the request provided when a scheduled task fires.
properties:
scheduleId:
type: string
description: |-
ScheduleID is the unique identifier for this scheduled task.
This is either the ID provided when scheduling, or an auto-generated UUID if none was specified.
payload:
type: string
description: |-
Payload is the payload data that was provided when the task was scheduled.
Can be used to pass context or parameters to the callback handler.
isRecurring:
type: boolean
description: |-
IsRecurring is true if this is a recurring schedule (created via ScheduleRecurring),
false if it's a one-time schedule (created via ScheduleOneTime).
required:
- scheduleId
- payload
- isRecurring
+106
View File
@@ -0,0 +1,106 @@
package capabilities
// Scrobbler provides scrobbling functionality to external services.
// This capability allows plugins to submit listening history to services like Last.fm,
// ListenBrainz, or custom scrobbling backends.
//
// All methods are required - plugins implementing this capability must provide
// all three functions: IsAuthorized, NowPlaying, and Scrobble.
//
//nd:capability name=scrobbler required=true
type Scrobbler interface {
// IsAuthorized checks if a user is authorized to scrobble to this service.
//nd:export name=nd_scrobbler_is_authorized
IsAuthorized(IsAuthorizedRequest) (bool, error)
// NowPlaying sends a now playing notification to the scrobbling service.
//nd:export name=nd_scrobbler_now_playing
NowPlaying(NowPlayingRequest) error
// Scrobble submits a completed scrobble to the scrobbling service.
//nd:export name=nd_scrobbler_scrobble
Scrobble(ScrobbleRequest) error
}
// IsAuthorizedRequest is the request for authorization check.
type IsAuthorizedRequest struct {
// Username is the username of the user.
Username string `json:"username"`
}
// ArtistRef is a reference to an artist with name and optional MBID.
type ArtistRef struct {
// ID is the internal Navidrome artist ID (if known).
ID string `json:"id,omitempty"`
// Name is the artist name.
Name string `json:"name"`
// MBID is the MusicBrainz ID for the artist.
MBID string `json:"mbid,omitempty"`
}
// TrackInfo contains track metadata for scrobbling.
type TrackInfo struct {
// ID is the internal Navidrome track ID.
ID string `json:"id"`
// Title is the track title.
Title string `json:"title"`
// Album is the album name.
Album string `json:"album"`
// Artist is the formatted artist name for display (e.g., "Artist1 • Artist2").
Artist string `json:"artist"`
// AlbumArtist is the formatted album artist name for display.
AlbumArtist string `json:"albumArtist"`
// Artists is the list of track artists.
Artists []ArtistRef `json:"artists"`
// AlbumArtists is the list of album artists.
AlbumArtists []ArtistRef `json:"albumArtists"`
// Duration is the track duration in seconds.
Duration float32 `json:"duration"`
// TrackNumber is the track number on the album.
TrackNumber int32 `json:"trackNumber"`
// DiscNumber is the disc number.
DiscNumber int32 `json:"discNumber"`
// MBZRecordingID is the MusicBrainz recording ID.
MBZRecordingID string `json:"mbzRecordingId,omitempty"`
// MBZAlbumID is the MusicBrainz album/release ID.
MBZAlbumID string `json:"mbzAlbumId,omitempty"`
// MBZReleaseGroupID is the MusicBrainz release group ID.
MBZReleaseGroupID string `json:"mbzReleaseGroupId,omitempty"`
// MBZReleaseTrackID is the MusicBrainz release track ID.
MBZReleaseTrackID string `json:"mbzReleaseTrackId,omitempty"`
}
// NowPlayingRequest is the request for now playing notification.
type NowPlayingRequest struct {
// Username is the username of the user.
Username string `json:"username"`
// Track is the track currently playing.
Track TrackInfo `json:"track"`
// Position is the current playback position in seconds.
Position int32 `json:"position"`
}
// ScrobbleRequest is the request for submitting a scrobble.
type ScrobbleRequest struct {
// Username is the username of the user.
Username string `json:"username"`
// Track is the track that was played.
Track TrackInfo `json:"track"`
// Timestamp is the Unix timestamp when the track started playing.
Timestamp int64 `json:"timestamp"`
}
// ScrobblerError represents an error type for scrobbling operations.
type ScrobblerError string
const (
// ScrobblerErrorNotAuthorized indicates the user is not authorized.
ScrobblerErrorNotAuthorized ScrobblerError = "scrobbler(not_authorized)"
// ScrobblerErrorRetryLater indicates the operation should be retried later.
ScrobblerErrorRetryLater ScrobblerError = "scrobbler(retry_later)"
// ScrobblerErrorUnrecoverable indicates an unrecoverable error.
ScrobblerErrorUnrecoverable ScrobblerError = "scrobbler(unrecoverable)"
)
// Error implements the error interface for ScrobblerError.
func (e ScrobblerError) Error() string { return string(e) }
+141
View File
@@ -0,0 +1,141 @@
version: v1-draft
exports:
nd_scrobbler_is_authorized:
description: IsAuthorized checks if a user is authorized to scrobble to this service.
input:
$ref: '#/components/schemas/IsAuthorizedRequest'
contentType: application/json
output:
type: boolean
contentType: application/json
nd_scrobbler_now_playing:
description: NowPlaying sends a now playing notification to the scrobbling service.
input:
$ref: '#/components/schemas/NowPlayingRequest'
contentType: application/json
nd_scrobbler_scrobble:
description: Scrobble submits a completed scrobble to the scrobbling service.
input:
$ref: '#/components/schemas/ScrobbleRequest'
contentType: application/json
components:
schemas:
ArtistRef:
description: ArtistRef is a reference to an artist with name and optional MBID.
properties:
id:
type: string
description: ID is the internal Navidrome artist ID (if known).
name:
type: string
description: Name is the artist name.
mbid:
type: string
description: MBID is the MusicBrainz ID for the artist.
required:
- name
IsAuthorizedRequest:
description: IsAuthorizedRequest is the request for authorization check.
properties:
username:
type: string
description: Username is the username of the user.
required:
- username
NowPlayingRequest:
description: NowPlayingRequest is the request for now playing notification.
properties:
username:
type: string
description: Username is the username of the user.
track:
$ref: '#/components/schemas/TrackInfo'
description: Track is the track currently playing.
position:
type: integer
format: int32
description: Position is the current playback position in seconds.
required:
- username
- track
- position
ScrobbleRequest:
description: ScrobbleRequest is the request for submitting a scrobble.
properties:
username:
type: string
description: Username is the username of the user.
track:
$ref: '#/components/schemas/TrackInfo'
description: Track is the track that was played.
timestamp:
type: integer
format: int64
description: Timestamp is the Unix timestamp when the track started playing.
required:
- username
- track
- timestamp
TrackInfo:
description: TrackInfo contains track metadata for scrobbling.
properties:
id:
type: string
description: ID is the internal Navidrome track ID.
title:
type: string
description: Title is the track title.
album:
type: string
description: Album is the album name.
artist:
type: string
description: Artist is the formatted artist name for display (e.g., "Artist1 • Artist2").
albumArtist:
type: string
description: AlbumArtist is the formatted album artist name for display.
artists:
type: array
description: Artists is the list of track artists.
items:
$ref: '#/components/schemas/ArtistRef'
albumArtists:
type: array
description: AlbumArtists is the list of album artists.
items:
$ref: '#/components/schemas/ArtistRef'
duration:
type: number
format: float
description: Duration is the track duration in seconds.
trackNumber:
type: integer
format: int32
description: TrackNumber is the track number on the album.
discNumber:
type: integer
format: int32
description: DiscNumber is the disc number.
mbzRecordingId:
type: string
description: MBZRecordingID is the MusicBrainz recording ID.
mbzAlbumId:
type: string
description: MBZAlbumID is the MusicBrainz album/release ID.
mbzReleaseGroupId:
type: string
description: MBZReleaseGroupID is the MusicBrainz release group ID.
mbzReleaseTrackId:
type: string
description: MBZReleaseTrackID is the MusicBrainz release track ID.
required:
- id
- title
- album
- artist
- albumArtist
- artists
- albumArtists
- duration
- trackNumber
- discNumber
@@ -0,0 +1,61 @@
package capabilities
// WebSocketCallback provides WebSocket message handling.
// This capability allows plugins to receive callbacks for WebSocket events
// such as text messages, binary messages, errors, and connection closures.
// Plugins that use the WebSocket host service must implement this capability
// to handle incoming events.
//
//nd:capability name=websocket
type WebSocketCallback interface {
// OnTextMessage is called when a text message is received on a WebSocket connection.
//nd:export name=nd_websocket_on_text_message
OnTextMessage(OnTextMessageRequest) error
// OnBinaryMessage is called when a binary message is received on a WebSocket connection.
//nd:export name=nd_websocket_on_binary_message
OnBinaryMessage(OnBinaryMessageRequest) error
// OnError is called when an error occurs on a WebSocket connection.
//nd:export name=nd_websocket_on_error
OnError(OnErrorRequest) error
// OnClose is called when a WebSocket connection is closed.
//nd:export name=nd_websocket_on_close
OnClose(OnCloseRequest) error
}
// OnTextMessageRequest is the request provided when a text message is received.
type OnTextMessageRequest struct {
// ConnectionID is the unique identifier for the WebSocket connection that received the message.
ConnectionID string `json:"connectionId"`
// Message is the text message content received from the WebSocket.
Message string `json:"message"`
}
// OnBinaryMessageRequest is the request provided when a binary message is received.
type OnBinaryMessageRequest struct {
// ConnectionID is the unique identifier for the WebSocket connection that received the message.
ConnectionID string `json:"connectionId"`
// Data is the binary data received from the WebSocket, encoded as base64.
Data string `json:"data"`
}
// OnErrorRequest is the request provided when an error occurs on a WebSocket connection.
type OnErrorRequest struct {
// ConnectionID is the unique identifier for the WebSocket connection where the error occurred.
ConnectionID string `json:"connectionId"`
// Error is the error message describing what went wrong.
Error string `json:"error"`
}
// OnCloseRequest is the request provided when a WebSocket connection is closed.
type OnCloseRequest struct {
// ConnectionID is the unique identifier for the WebSocket connection that was closed.
ConnectionID string `json:"connectionId"`
// Code is the WebSocket close status code (e.g., 1000 for normal closure,
// 1001 for going away, 1006 for abnormal closure).
Code int32 `json:"code"`
// Reason is the human-readable reason for the connection closure, if provided.
Reason string `json:"reason"`
}
@@ -0,0 +1,79 @@
version: v1-draft
exports:
nd_websocket_on_text_message:
description: OnTextMessage is called when a text message is received on a WebSocket connection.
input:
$ref: '#/components/schemas/OnTextMessageRequest'
contentType: application/json
nd_websocket_on_binary_message:
description: OnBinaryMessage is called when a binary message is received on a WebSocket connection.
input:
$ref: '#/components/schemas/OnBinaryMessageRequest'
contentType: application/json
nd_websocket_on_error:
description: OnError is called when an error occurs on a WebSocket connection.
input:
$ref: '#/components/schemas/OnErrorRequest'
contentType: application/json
nd_websocket_on_close:
description: OnClose is called when a WebSocket connection is closed.
input:
$ref: '#/components/schemas/OnCloseRequest'
contentType: application/json
components:
schemas:
OnBinaryMessageRequest:
description: OnBinaryMessageRequest is the request provided when a binary message is received.
properties:
connectionId:
type: string
description: ConnectionID is the unique identifier for the WebSocket connection that received the message.
data:
type: string
description: Data is the binary data received from the WebSocket, encoded as base64.
required:
- connectionId
- data
OnCloseRequest:
description: OnCloseRequest is the request provided when a WebSocket connection is closed.
properties:
connectionId:
type: string
description: ConnectionID is the unique identifier for the WebSocket connection that was closed.
code:
type: integer
format: int32
description: |-
Code is the WebSocket close status code (e.g., 1000 for normal closure,
1001 for going away, 1006 for abnormal closure).
reason:
type: string
description: Reason is the human-readable reason for the connection closure, if provided.
required:
- connectionId
- code
- reason
OnErrorRequest:
description: OnErrorRequest is the request provided when an error occurs on a WebSocket connection.
properties:
connectionId:
type: string
description: ConnectionID is the unique identifier for the WebSocket connection where the error occurred.
error:
type: string
description: Error is the error message describing what went wrong.
required:
- connectionId
- error
OnTextMessageRequest:
description: OnTextMessageRequest is the request provided when a text message is received.
properties:
connectionId:
type: string
description: ConnectionID is the unique identifier for the WebSocket connection that received the message.
message:
type: string
description: Message is the text message content received from the WebSocket.
required:
- connectionId
- message
+81
View File
@@ -0,0 +1,81 @@
package plugins
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
// mockFunctionChecker implements functionExistsChecker for testing
type mockFunctionChecker struct {
functions map[string]bool
}
func (m *mockFunctionChecker) FunctionExists(name string) bool {
return m.functions[name]
}
var _ = Describe("Capabilities", func() {
Describe("detectCapabilities", func() {
It("detects MetadataAgent capability when plugin exports artist biography function", func() {
checker := &mockFunctionChecker{
functions: map[string]bool{
FuncGetArtistBiography: true,
},
}
caps := detectCapabilities(checker)
Expect(caps).To(ContainElement(CapabilityMetadataAgent))
})
It("detects MetadataAgent capability when plugin exports multiple functions", func() {
checker := &mockFunctionChecker{
functions: map[string]bool{
FuncGetArtistMBID: true,
FuncGetArtistURL: true,
FuncGetAlbumInfo: true,
FuncGetAlbumImages: true,
},
}
caps := detectCapabilities(checker)
Expect(caps).To(ContainElement(CapabilityMetadataAgent))
Expect(caps).To(HaveLen(1)) // Should only have one MetadataAgent capability
})
It("returns empty slice when no capability functions are exported", func() {
checker := &mockFunctionChecker{
functions: map[string]bool{
"some_other_function": true,
},
}
caps := detectCapabilities(checker)
Expect(caps).To(BeEmpty())
})
It("returns empty slice when plugin exports no functions", func() {
checker := &mockFunctionChecker{
functions: map[string]bool{},
}
caps := detectCapabilities(checker)
Expect(caps).To(BeEmpty())
})
})
Describe("hasCapability", func() {
It("returns true when capability exists", func() {
caps := []Capability{CapabilityMetadataAgent}
Expect(hasCapability(caps, CapabilityMetadataAgent)).To(BeTrue())
})
It("returns false when capability does not exist", func() {
var caps []Capability
Expect(hasCapability(caps, CapabilityMetadataAgent)).To(BeFalse())
})
It("returns false when capabilities slice is nil", func() {
Expect(hasCapability(nil, CapabilityMetadataAgent)).To(BeFalse())
})
})
})
+38
View File
@@ -0,0 +1,38 @@
package plugins
import (
"context"
"github.com/navidrome/navidrome/log"
)
// CapabilityLifecycle indicates the plugin has lifecycle callback functions.
// Detected when the plugin exports the nd_on_init function.
const CapabilityLifecycle Capability = "Lifecycle"
const FuncOnInit = "nd_on_init"
func init() {
registerCapability(
CapabilityLifecycle,
FuncOnInit,
)
}
// callPluginInit calls the plugin's nd_on_init function if it has the Lifecycle capability.
// This is called after the plugin is fully loaded with all services registered.
func callPluginInit(ctx context.Context, instance *plugin) {
if !hasCapability(instance.capabilities, CapabilityLifecycle) {
return
}
log.Debug(ctx, "Calling plugin init function", "plugin", instance.name)
err := callPluginFunctionNoInput(ctx, instance, FuncOnInit)
if err != nil {
log.Error(ctx, "Plugin init function failed", "plugin", instance.name, err)
return
}
log.Debug(ctx, "Plugin init function completed", "plugin", instance.name)
}
+1
View File
@@ -0,0 +1 @@
ndpgen
+198
View File
@@ -0,0 +1,198 @@
# ndpgen
Navidrome Plugin Development Kit (PDK) code generator. It reads Go interface definitions with special annotations and generates client wrappers for WASM plugins.
This tool is the unified code generator that handle both host function wrappers and capability wrappers.
## Usage
```bash
ndpgen -input <dir> -output <dir> [-package <name>] [-v] [-dry-run] [-host-only] [-go] [-python] [-rust]
```
### Flags
| Flag | Description | Default |
|--------------|----------------------------------------------------------------|----------------------|
| `-input` | Directory containing Go source files with annotated interfaces | Required |
| `-output` | Directory where generated files will be written | Same as input |
| `-package` | Package name for generated files | Inferred from output |
| `-v` | Verbose output | `false` |
| `-dry-run` | Parse and validate without writing files | `false` |
| `-host-only` | Generate only host function wrappers (capability support TBD) | `true` |
| `-go` | Generate Go client wrappers | `true`* |
| `-python` | Generate Python client wrappers | `false` |
| `-rust` | Generate Rust client wrappers | `false` |
\* `-go` is enabled by default when neither `-python` nor `-rust` is specified. Use combinations like `-go -python -rust` to generate multiple languages.
### Example
```bash
go run ./plugins/cmd/ndpgen \
-input ./plugins/host \
-output ./plugins/pdk
```
## Annotations
### `//nd:hostservice`
Marks an interface as a host service that will have wrappers generated.
```go
//nd:hostservice name=<ServiceName> permission=<permission>
type MyService interface { ... }
```
| Parameter | Description | Required |
|--------------|-----------------------------------------------------------------|----------|
| `name` | Service name used in generated type names and function prefixes | Yes |
| `permission` | Permission required by plugins to use this service | Yes |
### `//nd:hostfunc`
Marks a method within a host service interface for export to plugins.
```go
//nd:hostfunc [name=<export_name>]
MethodName(ctx context.Context, ...) (result Type, err error)
```
| Parameter | Description | Required |
|-----------|-------------------------------------------------------------------------|----------|
| `name` | Custom export name (default: `<servicename>_<methodname>` in lowercase) | No |
## Input Format
Host service interfaces must follow these conventions:
1. **First parameter must be `context.Context`** - Required for all methods
2. **Last return value should be `error`** - For proper error handling
3. **Annotations must be on consecutive lines** - No blank comment lines between doc and annotation
### Example Interface
```go
package host
import "context"
// SubsonicAPIService provides access to Navidrome's Subsonic API.
// This documentation becomes part of the generated code.
//nd:hostservice name=SubsonicAPI permission=subsonicapi
type SubsonicAPIService interface {
// Call executes a Subsonic API request and returns the response.
//nd:hostfunc
Call(ctx context.Context, uri string) (response string, err error)
}
```
## Generated Output
### Go Client Library (Go/TinyGo WASM)
Generated files are named `nd_host_<servicename>.go` (lowercase) and placed in `$output/go/host/`. The `$output/go/` directory becomes a complete Go module (`github.com/navidrome/navidrome/plugins/pdk/go`) with package name `host`, intended for import by Navidrome plugins built with TinyGo.
The generator creates:
- `nd_host_<servicename>.go` - Client wrapper code (WASM build)
- `nd_host_<servicename>_stub.go` - Mock implementations for non-WASM platforms (testing)
- `doc.go` - Package documentation listing all available services
- `go.mod` - Go module file with required dependencies
Each service file includes:
- `// Code generated by ndpgen. DO NOT EDIT.` header
- Required imports (`encoding/json`, `errors`, `github.com/extism/go-pdk`)
- `//go:wasmimport` declarations for each host function
- Response struct types and any struct definitions from the service
- Wrapper functions that handle memory allocation and JSON parsing
### Testing Plugins with Mocks
The stub files (`*_stub.go`) contain [testify/mock](https://github.com/stretchr/testify) implementations that allow plugin authors to unit test their code on non-WASM platforms.
Each host service has:
- A private mock struct embedding `mock.Mock`
- An exported auto-instantiated mock instance (e.g., `host.CacheMock`, `host.ArtworkMock`)
- Wrapper functions that delegate to the mock
**Example: Testing a plugin that uses the Cache service**
```go
package myplugin
import (
"testing"
"github.com/navidrome/navidrome/plugins/pdk/go/host"
)
func TestMyPluginFunction(t *testing.T) {
// Set expectations on the mock
host.CacheMock.On("GetString", "my-key").Return("cached-value", true, nil)
host.CacheMock.On("SetString", "new-key", "new-value", int64(3600)).Return(nil)
// Call your plugin code that uses host.CacheGetString and host.CacheSetString
result := myPluginFunction()
// Assert the result
if result != "expected" {
t.Errorf("unexpected result: %s", result)
}
// Verify all expected calls were made
host.CacheMock.AssertExpectations(t)
}
```
**Resetting mocks between tests:**
If you need to reset mock state between tests, testify's mock doesn't have a built-in reset. Either use separate test functions (testify automatically resets between test runs), or create a helper to set up fresh expectations.
### Python Client Library
When using `-python`, Python client files are generated in a `python/` subdirectory.
### Rust Client Library
When using `-rust`, Rust client files are generated in a `rust/` subdirectory.
## Supported Types
ndpgen supports these Go types in method signatures:
| Type | JSON Representation |
|-------------------------------|------------------------------------------|
| `string`, `int`, `bool`, etc. | Native JSON types |
| `[]T` (slices) | JSON arrays |
| `map[K]V` (maps) | JSON objects |
| `*T` (pointers) | Nullable fields |
| `interface{}` / `any` | Converts to `any` |
| Custom structs | JSON objects (must be JSON-serializable) |
### Multiple Return Values
Methods can return multiple values (plus error):
```go
//nd:hostfunc
Search(ctx context.Context, query string) (results []string, total int, hasMore bool, err error)
```
Generates:
```go
type ServiceSearchResponse struct {
Results []string `json:"results,omitempty"`
Total int `json:"total,omitempty"`
HasMore bool `json:"hasMore,omitempty"`
Error string `json:"error,omitempty"`
}
```
## Running Tests
```bash
go test ./plugins/cmd/ndpgen/...
```
+28
View File
@@ -0,0 +1,28 @@
module github.com/navidrome/navidrome/plugins/cmd/ndpgen
go 1.25
require (
github.com/extism/go-pdk v1.1.3
github.com/onsi/ginkgo/v2 v2.27.3
github.com/onsi/gomega v1.38.3
github.com/xeipuuv/gojsonschema v1.2.0
golang.org/x/tools v0.40.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/Masterminds/semver/v3 v3.4.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.31.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
)
+80
View File
@@ -0,0 +1,80 @@
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/extism/go-pdk v1.1.3 h1:hfViMPWrqjN6u67cIYRALZTZLk/enSPpNKa+rZ9X2SQ=
github.com/extism/go-pdk v1.1.3/go.mod h1:Gz+LIU/YCKnKXhgge8yo5Yu1F/lbv7KtKFkiCSzW/P4=
github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs=
github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo=
github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M=
github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk=
github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE=
github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J0b1vyeLSOYI8bm5wbJM/8yDe8=
github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE=
github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/maruel/natural v1.1.1 h1:Hja7XhhmvEFhcByqDoHz9QZbkWey+COd9xWfCfn1ioo=
github.com/maruel/natural v1.1.1/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg=
github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE=
github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A=
github.com/onsi/ginkgo/v2 v2.27.3 h1:ICsZJ8JoYafeXFFlFAG75a7CxMsJHwgKwtO+82SE9L8=
github.com/onsi/ginkgo/v2 v2.27.3/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo=
github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM=
github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A=
google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+534
View File
@@ -0,0 +1,534 @@
package main
import (
"fmt"
"go/format"
"os"
"os/exec"
"path/filepath"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
// normalizeGeneratedCode normalizes generated code for comparison with expected output.
func normalizeGeneratedCode(code string) string {
// Replace package names (generated uses ndpdk, testdata may use ndhost)
code = strings.ReplaceAll(code, "package ndhost", "package ndpdk")
return code
}
var _ = Describe("ndpgen CLI", Ordered, func() {
var (
testDir string
outputDir string
ndpgenBin string
)
BeforeAll(func() {
// Set testdata directory (relative to ndpgen root)
testdataDir = filepath.Join(mustGetWd(GinkgoT()), "testdata")
// Build the ndpgen binary
ndpgenBin = filepath.Join(os.TempDir(), "ndpgen-test")
cmd := exec.Command("go", "build", "-o", ndpgenBin, ".")
cmd.Dir = mustGetWd(GinkgoT())
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Failed to build ndpgen: %s", output)
DeferCleanup(func() {
os.Remove(ndpgenBin)
})
})
BeforeEach(func() {
var err error
testDir, err = os.MkdirTemp("", "ndpgen-test-input-*")
Expect(err).ToNot(HaveOccurred())
outputDir, err = os.MkdirTemp("", "ndpgen-test-output-*")
Expect(err).ToNot(HaveOccurred())
})
AfterEach(func() {
os.RemoveAll(testDir)
os.RemoveAll(outputDir)
})
Describe("CLI flags and behavior", func() {
BeforeEach(func() {
serviceCode := `package testpkg
import "context"
//nd:hostservice name=Test permission=test
type TestService interface {
//nd:hostfunc
DoAction(ctx context.Context, input string) (output string, err error)
}
`
Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
})
It("supports verbose mode", func() {
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-v")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
outputStr := string(output)
Expect(outputStr).To(ContainSubstring("Input directory:"))
Expect(outputStr).To(ContainSubstring("Base output directory:"))
Expect(outputStr).To(ContainSubstring("Go output directory:"))
Expect(outputStr).To(ContainSubstring("Found 1 host service(s)"))
Expect(outputStr).To(ContainSubstring("Generated"))
})
It("supports dry-run mode", func() {
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-dry-run")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
Expect(string(output)).To(ContainSubstring("func TestDoAction("))
Expect(filepath.Join(outputDir, "nd_host_test.go")).ToNot(BeAnExistingFile())
})
It("uses default package name 'host'", func() {
customOutput, err := os.MkdirTemp("", "mypkg")
Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(customOutput)
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", customOutput)
_, err = cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred())
// Go code goes to $output/go/host/
content, err := os.ReadFile(filepath.Join(customOutput, "go", "host", "nd_host_test.go"))
Expect(err).ToNot(HaveOccurred())
Expect(string(content)).To(ContainSubstring("package host"))
})
It("returns error for invalid input directory", func() {
cmd := exec.Command(ndpgenBin, "-input", "/nonexistent/path")
output, err := cmd.CombinedOutput()
Expect(err).To(HaveOccurred())
Expect(string(output)).To(ContainSubstring("parsing source files"))
})
It("handles no annotated services gracefully", func() {
Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte("package testpkg\n"), 0600)).To(Succeed())
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-v")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
Expect(string(output)).To(ContainSubstring("No host services found"))
})
It("generates separate files for multiple services", func() {
// Remove service.go created by BeforeEach
Expect(os.Remove(filepath.Join(testDir, "service.go"))).To(Succeed())
service1 := `package testpkg
import "context"
//nd:hostservice name=ServiceA permission=a
type ServiceA interface {
//nd:hostfunc
MethodA(ctx context.Context) error
}
`
service2 := `package testpkg
import "context"
//nd:hostservice name=ServiceB permission=b
type ServiceB interface {
//nd:hostfunc
MethodB(ctx context.Context) error
}
`
Expect(os.WriteFile(filepath.Join(testDir, "a.go"), []byte(service1), 0600)).To(Succeed())
Expect(os.WriteFile(filepath.Join(testDir, "b.go"), []byte(service2), 0600)).To(Succeed())
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-v")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
Expect(string(output)).To(ContainSubstring("Found 2 host service(s)"))
// Go code goes to $output/go/host/
goHostDir := filepath.Join(outputDir, "go", "host")
Expect(filepath.Join(goHostDir, "nd_host_servicea.go")).To(BeAnExistingFile())
Expect(filepath.Join(goHostDir, "nd_host_serviceb.go")).To(BeAnExistingFile())
})
It("generates Go client code by default", func() {
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
// Go client code goes to $output/go/host/
goHostDir := filepath.Join(outputDir, "go", "host")
Expect(filepath.Join(goHostDir, "nd_host_test.go")).To(BeAnExistingFile())
// Stub file also generated
Expect(filepath.Join(goHostDir, "nd_host_test_stub.go")).To(BeAnExistingFile())
// doc.go in host dir
Expect(filepath.Join(goHostDir, "doc.go")).To(BeAnExistingFile())
// go.mod at parent $output/go/ for consolidated module
goDir := filepath.Join(outputDir, "go")
Expect(filepath.Join(goDir, "go.mod")).To(BeAnExistingFile())
})
})
Describe("code generation", func() {
DescribeTable("generates correct client output",
func(serviceFile, goClientExpectedFile, pyClientExpectedFile, rsClientExpectedFile string) {
serviceCode := readTestdata(serviceFile)
goClientExpected := readTestdata(goClientExpectedFile)
pyClientExpected := readTestdata(pyClientExpectedFile)
rsClientExpected := readTestdata(rsClientExpectedFile)
Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
// Generate all client code (Go, Python, Rust)
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-go", "-python", "-rust")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
// Verify Go client code (now in $output/go/host/)
goHostDir := filepath.Join(outputDir, "go", "host")
entries, err := os.ReadDir(goHostDir)
Expect(err).ToNot(HaveOccurred())
var goClientFiles []string
for _, e := range entries {
if !e.IsDir() &&
!strings.HasSuffix(e.Name(), "_stub.go") &&
e.Name() != "doc.go" && e.Name() != "go.mod" {
goClientFiles = append(goClientFiles, e.Name())
}
}
Expect(goClientFiles).To(HaveLen(1), "Expected exactly one Go client file, got: %v", goClientFiles)
goClientActual, err := os.ReadFile(filepath.Join(goHostDir, goClientFiles[0]))
Expect(err).ToNot(HaveOccurred())
formattedGoClientActual, err := format.Source(goClientActual)
Expect(err).ToNot(HaveOccurred(), "Generated Go client code is not valid Go:\n%s", goClientActual)
// Normalize expected code to match ndpgen output format
normalizedExpected := normalizeGeneratedCode(goClientExpected)
formattedGoClientExpected, err := format.Source([]byte(normalizedExpected))
Expect(err).ToNot(HaveOccurred(), "Expected Go client code is not valid Go")
Expect(string(formattedGoClientActual)).To(Equal(string(formattedGoClientExpected)), "Go client code mismatch")
// Verify Python client code (now in $output/python/host/)
pythonHostDir := filepath.Join(outputDir, "python", "host")
pyClientEntries, err := os.ReadDir(pythonHostDir)
Expect(err).ToNot(HaveOccurred())
Expect(pyClientEntries).To(HaveLen(1), "Expected exactly one Python client file")
pyClientActual, err := os.ReadFile(filepath.Join(pythonHostDir, pyClientEntries[0].Name()))
Expect(err).ToNot(HaveOccurred())
Expect(string(pyClientActual)).To(Equal(pyClientExpected), "Python client code mismatch")
// Verify Rust client code (now in $output/rust/nd-pdk-host/src/)
rustSrcDir := filepath.Join(outputDir, "rust", "nd-pdk-host", "src")
rsClientEntries, err := os.ReadDir(rustSrcDir)
Expect(err).ToNot(HaveOccurred())
Expect(rsClientEntries).To(HaveLen(2), "Expected Rust client file and lib.rs in src/")
// Find the client file (not lib.rs)
var rsClientName string
for _, entry := range rsClientEntries {
if entry.Name() != "lib.rs" {
rsClientName = entry.Name()
break
}
}
Expect(rsClientName).ToNot(BeEmpty(), "Expected to find Rust client file")
rsClientActual, err := os.ReadFile(filepath.Join(rustSrcDir, rsClientName))
Expect(err).ToNot(HaveOccurred())
Expect(string(rsClientActual)).To(Equal(rsClientExpected), "Rust client code mismatch")
},
Entry("simple string params",
"echo_service.go.txt", "echo_client_expected.go.txt", "echo_client_expected.py", "echo_client_expected.rs"),
Entry("multiple simple params (int32)",
"math_service.go.txt", "math_client_expected.go.txt", "math_client_expected.py", "math_client_expected.rs"),
Entry("struct param with request type",
"store_service.go.txt", "store_client_expected.go.txt", "store_client_expected.py", "store_client_expected.rs"),
Entry("mixed simple and complex params",
"list_service.go.txt", "list_client_expected.go.txt", "list_client_expected.py", "list_client_expected.rs"),
Entry("method without error",
"counter_service.go.txt", "counter_client_expected.go.txt", "counter_client_expected.py", "counter_client_expected.rs"),
Entry("no params, error only",
"ping_service.go.txt", "ping_client_expected.go.txt", "ping_client_expected.py", "ping_client_expected.rs"),
Entry("map and interface types",
"meta_service.go.txt", "meta_client_expected.go.txt", "meta_client_expected.py", "meta_client_expected.rs"),
Entry("pointer types",
"users_service.go.txt", "users_client_expected.go.txt", "users_client_expected.py", "users_client_expected.rs"),
Entry("multiple returns",
"search_service.go.txt", "search_client_expected.go.txt", "search_client_expected.py", "search_client_expected.rs"),
Entry("bytes",
"codec_service.go.txt", "codec_client_expected.go.txt", "codec_client_expected.py", "codec_client_expected.rs"),
Entry("option pattern (value, exists bool)",
"config_service.go.txt", "config_client_expected.go.txt", "config_client_expected.py", "config_client_expected.rs"),
)
It("generates compilable client code for comprehensive service", func() {
serviceCode := readTestdata("comprehensive_service.go.txt")
Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
// Generate client code
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Generation failed: %s", output)
// Go code goes to $output/go/host/
goHostDir := filepath.Join(outputDir, "go", "host")
// Read generated client code
entries, err := os.ReadDir(goHostDir)
Expect(err).ToNot(HaveOccurred())
// Find the client file
var clientFileName string
for _, entry := range entries {
name := entry.Name()
if name != "doc.go" && name != "go.mod" && !strings.HasSuffix(name, "_stub.go") && strings.HasSuffix(name, ".go") {
clientFileName = name
break
}
}
Expect(clientFileName).ToNot(BeEmpty(), "Expected to find Go client file")
content, err := os.ReadFile(filepath.Join(goHostDir, clientFileName))
Expect(err).ToNot(HaveOccurred())
// Verify key expected content
contentStr := string(content)
// Should have wasmimport declarations for all methods
Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_simpleparams"))
Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_structparam"))
Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_noerror"))
Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_noparams"))
Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_noparamsnoreturns"))
// Should have response types for methods with complex returns (private types in client code)
Expect(contentStr).To(ContainSubstring("type comprehensiveSimpleParamsResponse struct"))
Expect(contentStr).To(ContainSubstring("type comprehensiveMultipleReturnsResponse struct"))
// Should have wrapper functions
Expect(contentStr).To(ContainSubstring("func ComprehensiveSimpleParams("))
Expect(contentStr).To(ContainSubstring("func ComprehensiveNoParams()"))
Expect(contentStr).To(ContainSubstring("func ComprehensiveNoParamsNoReturns()"))
// Create a plugin directory with proper import structure
pluginDir := filepath.Join(outputDir, "plugin")
Expect(os.MkdirAll(pluginDir, 0750)).To(Succeed())
// go.mod is at parent $output/go/ for consolidated module
goDir := filepath.Join(outputDir, "go")
// Create go.mod for the plugin that imports the generated library
goMod := fmt.Sprintf(`module testplugin
go 1.25
require github.com/navidrome/navidrome/plugins/pdk/go v0.0.0
replace github.com/navidrome/navidrome/plugins/pdk/go => %s
`, goDir)
Expect(os.WriteFile(filepath.Join(pluginDir, "go.mod"), []byte(goMod), 0600)).To(Succeed())
// Add a simple main function that imports and uses the ndpdk package
mainGo := `package main
import ndpdk "github.com/navidrome/navidrome/plugins/pdk/go/host"
func main() {}
// Use some functions to ensure import is not unused
var _ = ndpdk.ComprehensiveNoParams
`
Expect(os.WriteFile(filepath.Join(pluginDir, "main.go"), []byte(mainGo), 0600)).To(Succeed())
// Tidy dependencies for the generated go library
goTidyLibCmd := exec.Command("go", "mod", "tidy")
goTidyLibCmd.Dir = goDir
goTidyLibOutput, err := goTidyLibCmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "go mod tidy (library) failed: %s", goTidyLibOutput)
// Tidy dependencies for the plugin
goTidyCmd := exec.Command("go", "mod", "tidy")
goTidyCmd.Dir = pluginDir
goTidyOutput, err := goTidyCmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "go mod tidy (plugin) failed: %s", goTidyOutput)
// Build as WASM plugin - this validates the client code compiles correctly
buildCmd := exec.Command("go", "build", "-buildmode=c-shared", "-o", "plugin.wasm", ".")
buildCmd.Dir = pluginDir
buildCmd.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm")
buildOutput, err := buildCmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "WASM build failed: %s", buildOutput)
// Verify .wasm file was created
Expect(filepath.Join(pluginDir, "plugin.wasm")).To(BeAnExistingFile())
})
It("generates Python client code with -python flag", func() {
serviceCode := `package testpkg
import "context"
//nd:hostservice name=Test permission=test
type TestService interface {
//nd:hostfunc
DoAction(ctx context.Context, input string) (output string, err error)
}
`
Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-python")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
// Verify Python client code exists in $output/python/host/
pythonHostDir := filepath.Join(outputDir, "python", "host")
Expect(pythonHostDir).To(BeADirectory())
pythonFile := filepath.Join(pythonHostDir, "nd_host_test.py")
Expect(pythonFile).To(BeAnExistingFile())
content, err := os.ReadFile(pythonFile)
Expect(err).ToNot(HaveOccurred())
contentStr := string(content)
Expect(contentStr).To(ContainSubstring("Code generated by ndpgen. DO NOT EDIT."))
Expect(contentStr).To(ContainSubstring("class HostFunctionError(Exception):"))
Expect(contentStr).To(ContainSubstring(`@extism.import_fn("extism:host/user", "test_doaction")`))
Expect(contentStr).To(ContainSubstring("def test_do_action(input: str) -> str:"))
})
It("generates both Go and Python client code with -go -python flags", func() {
serviceCode := `package testpkg
import "context"
//nd:hostservice name=Test permission=test
type TestService interface {
//nd:hostfunc
DoAction(ctx context.Context, input string) (output string, err error)
}
`
Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-go", "-python")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
// Verify Go client code exists in $output/go/host/
goHostDir := filepath.Join(outputDir, "go", "host")
Expect(filepath.Join(goHostDir, "nd_host_test.go")).To(BeAnExistingFile())
// Verify Python client code exists in $output/python/host/
pythonHostDir := filepath.Join(outputDir, "python", "host")
Expect(pythonHostDir).To(BeADirectory())
Expect(filepath.Join(pythonHostDir, "nd_host_test.py")).To(BeAnExistingFile())
})
It("generates Python code with dataclass for multi-value returns", func() {
serviceCode := `package testpkg
import "context"
//nd:hostservice name=Cache permission=cache
type CacheService interface {
//nd:hostfunc
GetString(ctx context.Context, key string) (value string, exists bool, err error)
}
`
Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-python")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
content, err := os.ReadFile(filepath.Join(outputDir, "python", "host", "nd_host_cache.py"))
Expect(err).ToNot(HaveOccurred())
contentStr := string(content)
Expect(contentStr).To(ContainSubstring("@dataclass"))
Expect(contentStr).To(ContainSubstring("class CacheGetStringResult:"))
Expect(contentStr).To(ContainSubstring("value: str"))
Expect(contentStr).To(ContainSubstring("exists: bool"))
Expect(contentStr).To(ContainSubstring("def cache_get_string(key: str) -> CacheGetStringResult:"))
})
It("generates Python code for methods with no parameters", func() {
serviceCode := `package testpkg
import "context"
//nd:hostservice name=Test permission=test
type TestService interface {
//nd:hostfunc
Ping(ctx context.Context) (status string, err error)
}
`
Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-python")
output, err := cmd.CombinedOutput()
Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
content, err := os.ReadFile(filepath.Join(outputDir, "python", "host", "nd_host_test.py"))
Expect(err).ToNot(HaveOccurred())
contentStr := string(content)
Expect(contentStr).To(ContainSubstring("def test_ping() -> str:"))
Expect(contentStr).To(ContainSubstring(`request_bytes = b"{}"`))
})
})
})
var testdataDir string
func readTestdata(filename string) string {
content, err := os.ReadFile(filepath.Join(testdataDir, filename))
Expect(err).ToNot(HaveOccurred(), "Failed to read testdata file: %s", filename)
return string(content)
}
func mustGetWd(t FullGinkgoTInterface) string {
dir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
// Look for ndpgen's own go.mod (the subproject root)
for {
goModPath := filepath.Join(dir, "go.mod")
if _, err := os.Stat(goModPath); err == nil {
// Check if this is the ndpgen go.mod by reading it
content, err := os.ReadFile(goModPath)
if err == nil && strings.Contains(string(content), "plugins/cmd/ndpgen") {
return dir
}
}
parent := filepath.Dir(dir)
if parent == dir {
t.Fatal("could not find ndpgen project root")
}
dir = parent
}
}
+859
View File
@@ -0,0 +1,859 @@
package internal
import (
"bytes"
"embed"
"fmt"
"strings"
"text/template"
)
//go:embed templates/*.tmpl
var templatesFS embed.FS
// hostFuncMap returns the template functions for host code generation.
func hostFuncMap(svc Service) template.FuncMap {
return template.FuncMap{
"lower": strings.ToLower,
"title": strings.Title,
"exportName": func(m Method) string { return m.FunctionName(svc.ExportPrefix()) },
"requestType": func(m Method) string { return m.RequestTypeName(svc.Name) },
"responseType": func(m Method) string { return m.ResponseTypeName(svc.Name) },
}
}
// clientFuncMap returns the template functions for client code generation.
// Uses private (lowercase) type names for request/response structs.
func clientFuncMap(svc Service) template.FuncMap {
return template.FuncMap{
"lower": strings.ToLower,
"title": strings.Title,
"exportName": func(m Method) string { return m.FunctionName(svc.ExportPrefix()) },
"requestType": func(m Method) string { return m.ClientRequestTypeName(svc.Name) },
"responseType": func(m Method) string { return m.ClientResponseTypeName(svc.Name) },
"formatDoc": formatDoc,
"mockReturnValues": mockReturnValues,
}
}
// mockReturnValues generates the testify mock return value accessors for a method.
// For example: args.String(0), args.Bool(1), args.Error(2)
func mockReturnValues(m Method) string {
var parts []string
idx := 0
for _, r := range m.Returns {
parts = append(parts, mockAccessor(r.Type, idx))
idx++
}
if m.HasError {
parts = append(parts, fmt.Sprintf("args.Error(%d)", idx))
}
return strings.Join(parts, ", ")
}
// mockAccessor returns the testify mock accessor call for a given type and index.
func mockAccessor(typ string, idx int) string {
switch {
case typ == "string":
return fmt.Sprintf("args.String(%d)", idx)
case typ == "bool":
return fmt.Sprintf("args.Bool(%d)", idx)
case typ == "int":
return fmt.Sprintf("args.Int(%d)", idx)
case typ == "int64":
return fmt.Sprintf("args.Get(%d).(int64)", idx)
case typ == "int32":
return fmt.Sprintf("args.Get(%d).(int32)", idx)
case typ == "float64":
return fmt.Sprintf("args.Get(%d).(float64)", idx)
case typ == "float32":
return fmt.Sprintf("args.Get(%d).(float32)", idx)
case typ == "[]byte":
return fmt.Sprintf("args.Get(%d).([]byte)", idx)
default:
// For slices, maps, pointers, and custom types, use Get with type assertion
return fmt.Sprintf("args.Get(%d).(%s)", idx, typ)
}
}
// pythonFuncMap returns the template functions for Python client code generation.
func pythonFuncMap(svc Service) template.FuncMap {
return template.FuncMap{
"lower": strings.ToLower,
"exportName": func(m Method) string { return m.FunctionName(svc.ExportPrefix()) },
"pythonFunc": func(m Method) string { return m.PythonFunctionName(svc.ExportPrefix()) },
"pythonResultType": func(m Method) string { return m.PythonResultTypeName(svc.Name) },
"pythonDefault": pythonDefaultValue,
}
}
// GenerateHost generates the host function wrapper code for a service.
func GenerateHost(svc Service, pkgName string) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/host.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading host template: %w", err)
}
tmpl, err := template.New("host").Funcs(hostFuncMap(svc)).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := templateData{
Package: pkgName,
Service: svc,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// GenerateClientGo generates client wrapper code for plugins to call host functions.
func GenerateClientGo(svc Service, pkgName string) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/client.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading client template: %w", err)
}
tmpl, err := template.New("client").Funcs(clientFuncMap(svc)).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := templateData{
Package: pkgName,
Service: svc,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// GenerateClientGoStub generates stub code for non-WASM platforms.
// These stubs provide type definitions and function signatures for IDE support,
// but panic at runtime since host functions are only available in WASM plugins.
func GenerateClientGoStub(svc Service, pkgName string) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/client_stub.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading client stub template: %w", err)
}
tmpl, err := template.New("client_stub").Funcs(clientFuncMap(svc)).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := templateData{
Package: pkgName,
Service: svc,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
type templateData struct {
Package string
Service Service
}
// formatDoc formats a documentation string for Go comments.
// It prefixes each line with "// " and trims trailing whitespace.
func formatDoc(doc string) string {
if doc == "" {
return ""
}
lines := strings.Split(strings.TrimSpace(doc), "\n")
var result []string
for _, line := range lines {
result = append(result, "// "+strings.TrimRight(line, " \t"))
}
return strings.Join(result, "\n")
}
// GenerateClientPython generates Python client wrapper code for plugins.
func GenerateClientPython(svc Service) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/client.py.tmpl")
if err != nil {
return nil, fmt.Errorf("reading Python client template: %w", err)
}
tmpl, err := template.New("client_py").Funcs(pythonFuncMap(svc)).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := templateData{
Service: svc,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// pythonDefaultValue returns a Python default value for response.get() calls.
func pythonDefaultValue(p Param) string {
switch p.Type {
case "string":
return `, ""`
case "int", "int32", "int64":
return ", 0"
case "float32", "float64":
return ", 0.0"
case "bool":
return ", False"
case "[]byte":
return ", b\"\""
default:
return ", None"
}
}
// rustFuncMap returns the template functions for Rust client code generation.
func rustFuncMap(svc Service) template.FuncMap {
knownStructs := svc.KnownStructs()
return template.FuncMap{
"lower": strings.ToLower,
"exportName": func(m Method) string { return m.FunctionName(svc.ExportPrefix()) },
"requestType": func(m Method) string { return m.RequestTypeName(svc.Name) },
"responseType": func(m Method) string { return m.ResponseTypeName(svc.Name) },
"rustFunc": func(m Method) string { return m.RustFunctionName(svc.ExportPrefix()) },
"rustDocComment": RustDocComment,
"rustType": func(p Param) string { return p.RustTypeWithStructs(knownStructs) },
"rustParamType": func(p Param) string { return p.RustParamTypeWithStructs(knownStructs) },
"fieldRustType": func(f FieldDef) string { return f.RustType(knownStructs) },
}
}
// GenerateClientRust generates Rust client wrapper code for plugins.
func GenerateClientRust(svc Service) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/client.rs.tmpl")
if err != nil {
return nil, fmt.Errorf("reading Rust client template: %w", err)
}
tmpl, err := template.New("client_rs").Funcs(rustFuncMap(svc)).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := templateData{
Service: svc,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// firstLine returns the first line of a multi-line string, with the first word removed.
func firstLine(s string) string {
line := s
if idx := strings.Index(s, "\n"); idx >= 0 {
line = s[:idx]
}
// Remove the first word (service name like "ArtworkService")
if idx := strings.Index(line, " "); idx >= 0 {
line = line[idx+1:]
}
return line
}
// GenerateRustLib generates the lib.rs file that exposes all service modules.
func GenerateRustLib(services []Service) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/lib.rs.tmpl")
if err != nil {
return nil, fmt.Errorf("reading Rust lib template: %w", err)
}
tmpl, err := template.New("lib_rs").Funcs(template.FuncMap{
"lower": strings.ToLower,
"firstLine": firstLine,
}).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := struct {
Services []Service
}{
Services: services,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// GenerateGoDoc generates the doc.go file that provides package documentation.
func GenerateGoDoc(services []Service, pkgName string) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/doc.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading Go doc template: %w", err)
}
tmpl, err := template.New("doc_go").Funcs(template.FuncMap{
"firstLine": firstLine,
}).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := struct {
Package string
Services []Service
}{
Package: pkgName,
Services: services,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// GenerateGoMod generates the go.mod file for the Go client library.
func GenerateGoMod() ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/go.mod.tmpl")
if err != nil {
return nil, fmt.Errorf("reading go.mod template: %w", err)
}
return tmplContent, nil
}
// capabilityTemplateData holds data for capability template execution.
type capabilityTemplateData struct {
Package string
Capability Capability
}
// capabilityFuncMap returns template functions for capability code generation.
func capabilityFuncMap(cap Capability) template.FuncMap {
return template.FuncMap{
"formatDoc": formatDoc,
"indent": indentText,
"agentName": capabilityAgentName,
"providerInterface": func(e Export) string { return e.ProviderInterfaceName() },
"implVar": func(e Export) string { return e.ImplVarName() },
"exportFunc": func(e Export) string { return e.ExportFuncName() },
}
}
// indentText adds n tabs to each line of text.
func indentText(n int, s string) string {
indent := strings.Repeat("\t", n)
lines := strings.Split(s, "\n")
for i, line := range lines {
if line != "" {
lines[i] = indent + line
}
}
return strings.Join(lines, "\n")
}
// capabilityAgentName returns the interface name for a capability.
// Uses the Go interface name stripped of common suffixes.
func capabilityAgentName(cap Capability) string {
name := cap.Interface
// Remove common suffixes to get a clean name
for _, suffix := range []string{"Agent", "Callback", "Service"} {
if strings.HasSuffix(name, suffix) {
name = name[:len(name)-len(suffix)]
break
}
}
// Use the shortened name or the original if no suffix found
if name == "" {
name = cap.Interface
}
return name
}
// GenerateCapabilityGo generates Go export wrapper code for a capability.
func GenerateCapabilityGo(cap Capability, pkgName string) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/capability.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading capability template: %w", err)
}
tmpl, err := template.New("capability").Funcs(capabilityFuncMap(cap)).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := capabilityTemplateData{
Package: pkgName,
Capability: cap,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// GenerateCapabilityGoStub generates stub code for non-WASM platforms.
func GenerateCapabilityGoStub(cap Capability, pkgName string) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/capability_stub.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading capability stub template: %w", err)
}
tmpl, err := template.New("capability_stub").Funcs(capabilityFuncMap(cap)).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := capabilityTemplateData{
Package: pkgName,
Capability: cap,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// rustCapabilityFuncMap returns template functions for Rust capability code generation.
func rustCapabilityFuncMap(cap Capability) template.FuncMap {
knownStructs := cap.KnownStructs()
return template.FuncMap{
"rustDocComment": RustDocComment,
"rustTypeAlias": rustTypeAlias,
"rustConstType": rustConstType,
"rustConstName": rustConstName,
"rustFieldName": func(name string) string { return ToSnakeCase(name) },
"rustMethodName": func(name string) string { return ToSnakeCase(name) },
"fieldRustType": func(f FieldDef) string { return f.RustType(knownStructs) },
"rustOutputType": rustOutputType,
"isPrimitiveRust": isPrimitiveRustType,
"skipSerializingFunc": skipSerializingFunc,
"hasHashMap": hasHashMap,
"agentName": capabilityAgentName,
"providerInterface": func(e Export) string { return e.ProviderInterfaceName() },
"registerMacroName": func(name string) string { return registerMacroName(cap.Name, name) },
"snakeCase": ToSnakeCase,
"indent": func(spaces int, s string) string {
indent := strings.Repeat(" ", spaces)
lines := strings.Split(s, "\n")
for i, line := range lines {
if line != "" {
lines[i] = indent + line
}
}
return strings.Join(lines, "\n")
},
}
}
// rustTypeAlias converts a Go type to its Rust equivalent for type aliases.
// For string types used as error sentinels/constants, we use &'static str
// since Rust consts can't be heap-allocated String values.
func rustTypeAlias(goType string) string {
switch goType {
case "string":
return "&'static str"
case "int", "int32":
return "i32"
case "int64":
return "i64"
default:
return goType
}
}
// rustConstType converts a Go type to its Rust equivalent for const declarations.
// For String types, it returns &'static str since Rust consts can't be heap-allocated.
func rustConstType(goType string) string {
switch goType {
case "string", "String":
return "&'static str"
case "int", "int32":
return "i32"
case "int64":
return "i64"
default:
return goType
}
}
// rustOutputType converts a Go type to Rust for capability method signatures.
// It handles pointer types specially - for capability outputs, pointers become the base type
// (not Option<T>) because Rust's Result<T, Error> already provides optional semantics.
//
// TODO: Pointer to primitive types (e.g., *string, *int32) are not handled correctly.
// Currently "*string" returns "string" instead of "String". This would generate invalid
// Rust code. No current capability uses this pattern, but it should be fixed if needed.
func rustOutputType(goType string) string {
// Strip pointer prefix - capability outputs use Result<T, Error> for optionality
if strings.HasPrefix(goType, "*") {
return goType[1:]
}
// Convert Go primitives to Rust primitives
switch goType {
case "bool":
return "bool"
case "string":
return "String"
case "int", "int32":
return "i32"
case "int64":
return "i64"
case "float32":
return "f32"
case "float64":
return "f64"
}
return goType
}
// isPrimitiveRustType returns true if the Go type maps to a Rust primitive type.
func isPrimitiveRustType(goType string) bool {
// Strip pointer prefix first
if strings.HasPrefix(goType, "*") {
goType = goType[1:]
}
switch goType {
case "bool", "string", "int", "int32", "int64", "float32", "float64":
return true
}
return false
}
// rustConstName converts a Go const name to Rust convention (SCREAMING_SNAKE_CASE).
func rustConstName(name string) string {
return strings.ToUpper(ToSnakeCase(name))
}
// skipSerializingFunc returns the appropriate skip_serializing_if function name.
func skipSerializingFunc(goType string) string {
if strings.HasPrefix(goType, "*") || strings.HasPrefix(goType, "[]") || strings.HasPrefix(goType, "map[") {
return "Option::is_none"
}
switch goType {
case "string":
return "String::is_empty"
case "bool":
return "std::ops::Not::not"
default:
return "Option::is_none"
}
}
// hasHashMap returns true if any struct in the capability uses HashMap.
func hasHashMap(cap Capability) bool {
for _, st := range cap.Structs {
for _, f := range st.Fields {
if strings.HasPrefix(f.Type, "map[") {
return true
}
}
}
return false
}
// registerMacroName returns the macro name for registering an optional method.
// For package "websocket" and method "OnClose", returns "register_websocket_close".
func registerMacroName(pkg, name string) string {
// Remove common prefixes from method name
for _, prefix := range []string{"Get", "On"} {
if strings.HasPrefix(name, prefix) {
name = name[len(prefix):]
break
}
}
return "register_" + ToSnakeCase(pkg) + "_" + ToSnakeCase(name)
}
// GenerateCapabilityRust generates Rust export wrapper code for a capability.
func GenerateCapabilityRust(cap Capability) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/capability.rs.tmpl")
if err != nil {
return nil, fmt.Errorf("reading Rust capability template: %w", err)
}
tmpl, err := template.New("capability_rust").Funcs(rustCapabilityFuncMap(cap)).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
data := capabilityTemplateData{
Package: cap.Name,
Capability: cap,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// GenerateCapabilityRustLib generates the lib.rs file for the Rust capabilities crate.
func GenerateCapabilityRustLib(capabilities []Capability) ([]byte, error) {
var buf bytes.Buffer
buf.WriteString("// Code generated by ndpgen. DO NOT EDIT.\n\n")
buf.WriteString("//! Navidrome Plugin Development Kit - Capability Wrappers\n")
buf.WriteString("//!\n")
buf.WriteString("//! This crate provides type definitions, traits, and registration macros\n")
buf.WriteString("//! for implementing Navidrome plugin capabilities in Rust.\n\n")
// Module declarations
for _, cap := range capabilities {
moduleName := ToSnakeCase(cap.Name)
buf.WriteString(fmt.Sprintf("pub mod %s;\n", moduleName))
}
return buf.Bytes(), nil
}
// pdkFuncMap returns the template functions for PDK code generation.
func pdkFuncMap() template.FuncMap {
return template.FuncMap{
"firstSentence": firstSentence,
"paramList": pdkParamList,
"returnList": pdkReturnList,
"argList": pdkArgList,
"argListWithReceiver": pdkArgListWithReceiver,
"mockReturns": pdkMockReturns,
"constValue": pdkConstValue,
"stubTypeUnderlying": stubTypeUnderlying,
"methodReceiver": pdkMethodReceiver,
}
}
// stubTypeUnderlying returns the appropriate stub type for non-WASM builds.
// For types that reference internal packages (like memory.Memory), returns "struct{}".
func stubTypeUnderlying(t PDKType) string {
underlying := t.Underlying
// If the underlying type references a package (contains a dot), use a stub struct
if strings.Contains(underlying, ".") {
return "struct{}"
}
// For simple types like int, int32, return as-is
return underlying
}
// firstSentence returns the first sentence of a doc string, normalized to a single line.
func firstSentence(doc string) string {
if doc == "" {
return ""
}
// Normalize whitespace (replace newlines with spaces, collapse multiple spaces)
doc = strings.Join(strings.Fields(doc), " ")
// Find first period followed by space or end
for i, r := range doc {
if r == '.' && (i+1 >= len(doc) || doc[i+1] == ' ') {
return doc[:i+1]
}
}
return doc
}
// pdkParamList generates a parameter list string for function signature.
func pdkParamList(params []PDKParam) string {
var parts []string
for _, p := range params {
if p.Name != "" {
parts = append(parts, p.Name+" "+p.Type)
} else {
parts = append(parts, p.Type)
}
}
return strings.Join(parts, ", ")
}
// pdkReturnList generates a return list string for function signature.
func pdkReturnList(returns []PDKReturn) string {
if len(returns) == 0 {
return ""
}
if len(returns) == 1 && returns[0].Name == "" {
return " " + returns[0].Type
}
var parts []string
for _, r := range returns {
if r.Name != "" {
parts = append(parts, r.Name+" "+r.Type)
} else {
parts = append(parts, r.Type)
}
}
return " (" + strings.Join(parts, ", ") + ")"
}
// pdkArgList generates an argument list string for function call.
func pdkArgList(params []PDKParam) string {
var parts []string
for _, p := range params {
if p.Name != "" {
parts = append(parts, p.Name)
} else {
parts = append(parts, "_")
}
}
return strings.Join(parts, ", ")
}
// pdkArgListWithReceiver generates an argument list that includes the receiver variable
// as the first argument to PDKMock.Called(). This allows tests to verify which instance
// a method was called on.
func pdkArgListWithReceiver(params []PDKParam, typeName string) string {
// Use lowercase first letter of type name as receiver variable
receiverVar := strings.ToLower(typeName[:1])
parts := []string{receiverVar}
for _, p := range params {
if p.Name != "" {
parts = append(parts, p.Name)
} else {
parts = append(parts, "_")
}
}
return strings.Join(parts, ", ")
}
// pdkMethodReceiver generates the receiver declaration for a method.
// Example: "r *HTTPRequest" or "m Memory"
func pdkMethodReceiver(receiver, typeName string) string {
receiverVar := strings.ToLower(typeName[:1])
if strings.HasPrefix(receiver, "*") {
return receiverVar + " *" + typeName
}
return receiverVar + " " + typeName
}
// pdkMockReturns generates the mock return accessors for a function.
func pdkMockReturns(returns []PDKReturn) string {
var parts []string
for i, r := range returns {
parts = append(parts, mockAccessorForType(r.Type, i))
}
return strings.Join(parts, ", ")
}
// mockAccessorForType returns the testify mock accessor for a type.
func mockAccessorForType(typ string, idx int) string {
switch typ {
case "string":
return fmt.Sprintf("args.String(%d)", idx)
case "bool":
return fmt.Sprintf("args.Bool(%d)", idx)
case "int":
return fmt.Sprintf("args.Int(%d)", idx)
case "error":
return fmt.Sprintf("args.Error(%d)", idx)
case "[]byte":
return fmt.Sprintf("args.Get(%d).([]byte)", idx)
case "uint64":
return fmt.Sprintf("args.Get(%d).(uint64)", idx)
case "uint32":
return fmt.Sprintf("args.Get(%d).(uint32)", idx)
case "uint16":
return fmt.Sprintf("args.Get(%d).(uint16)", idx)
default:
return fmt.Sprintf("args.Get(%d).(%s)", idx, typ)
}
}
// pdkConstValue returns the value expression for a constant.
func pdkConstValue(c PDKConst) string {
if c.Value == "" || c.Value == "iota" {
return "iota"
}
return c.Value
}
// GeneratePDKGo generates the WASM implementation of the PDK wrapper package.
func GeneratePDKGo(symbols *PDKSymbols) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/pdk.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading pdk template: %w", err)
}
tmpl, err := template.New("pdk").Funcs(pdkFuncMap()).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, symbols); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// GeneratePDKGoStub generates the native stub implementation of the PDK wrapper package.
func GeneratePDKGoStub(symbols *PDKSymbols) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/pdk_stub.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading pdk stub template: %w", err)
}
tmpl, err := template.New("pdk_stub").Funcs(pdkFuncMap()).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, symbols); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
// GeneratePDKTypesStub generates the native type definitions for the PDK wrapper package.
func GeneratePDKTypesStub(symbols *PDKSymbols) ([]byte, error) {
tmplContent, err := templatesFS.ReadFile("templates/types_stub.go.tmpl")
if err != nil {
return nil, fmt.Errorf("reading types stub template: %w", err)
}
tmpl, err := template.New("types_stub").Funcs(pdkFuncMap()).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, symbols); err != nil {
return nil, fmt.Errorf("executing template: %w", err)
}
return buf.Bytes(), nil
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,13 @@
package internal
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestInternal(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "NDPGen Internal Suite")
}
+846
View File
@@ -0,0 +1,846 @@
package internal
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"maps"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
)
// Annotation patterns
var (
// //nd:hostservice name=ServiceName permission=key
hostServicePattern = regexp.MustCompile(`//nd:hostservice\s+(.*)`)
// //nd:hostfunc [name=CustomName]
hostFuncPattern = regexp.MustCompile(`//nd:hostfunc(?:\s+(.*))?`)
// //nd:capability name=PackageName [required=true]
capabilityPattern = regexp.MustCompile(`//nd:capability\s+(.*)`)
// //nd:export name=ExportName
exportPattern = regexp.MustCompile(`//nd:export\s+(.*)`)
// key=value pairs
keyValuePattern = regexp.MustCompile(`(\w+)=(\S+)`)
)
// ParseDirectory parses all Go source files in a directory and extracts host services.
func ParseDirectory(dir string) ([]Service, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("reading directory: %w", err)
}
var services []Service
fset := token.NewFileSet()
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") {
continue
}
// Skip generated files and test files
if strings.HasSuffix(entry.Name(), "_gen.go") || strings.HasSuffix(entry.Name(), "_test.go") {
continue
}
path := filepath.Join(dir, entry.Name())
parsed, err := parseFile(fset, path)
if err != nil {
return nil, fmt.Errorf("parsing %s: %w", entry.Name(), err)
}
services = append(services, parsed...)
}
return services, nil
}
// ParseCapabilities parses all Go source files in a directory and extracts capabilities.
func ParseCapabilities(dir string) ([]Capability, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("reading directory: %w", err)
}
fset := token.NewFileSet()
// First pass: collect all structs and type aliases from all files in the package
sharedStructMap := make(map[string]StructDef)
sharedAliasMap := make(map[string]TypeAlias)
var allConstGroups []ConstGroup
var goFiles []string
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") {
continue
}
// Skip generated files, test files, and doc.go
if strings.HasSuffix(entry.Name(), "_gen.go") ||
strings.HasSuffix(entry.Name(), "_test.go") ||
entry.Name() == "doc.go" {
continue
}
goFiles = append(goFiles, filepath.Join(dir, entry.Name()))
}
for _, path := range goFiles {
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("parsing %s for types: %w", filepath.Base(path), err)
}
for _, s := range parseStructs(f) {
sharedStructMap[s.Name] = s
}
for _, a := range parseTypeAliases(f) {
sharedAliasMap[a.Name] = a
}
allConstGroups = append(allConstGroups, parseConstGroups(f)...)
}
// Second pass: parse capabilities using the shared type maps
var capabilities []Capability
for _, path := range goFiles {
parsed, err := parseCapabilityFile(fset, path, sharedStructMap, sharedAliasMap, allConstGroups)
if err != nil {
return nil, fmt.Errorf("parsing %s: %w", filepath.Base(path), err)
}
capabilities = append(capabilities, parsed...)
}
return capabilities, nil
}
// parseCapabilityFile parses a single Go source file and extracts capabilities.
func parseCapabilityFile(fset *token.FileSet, path string, structMap map[string]StructDef, aliasMap map[string]TypeAlias, allConstGroups []ConstGroup) ([]Capability, error) {
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return nil, err
}
var capabilities []Capability
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.TYPE {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
interfaceType, ok := typeSpec.Type.(*ast.InterfaceType)
if !ok {
continue
}
// Check for //nd:capability annotation in doc comment
docText, rawDoc := getDocComment(genDecl, typeSpec)
capAnnotation := parseCapabilityAnnotation(rawDoc)
if capAnnotation == nil {
continue
}
// Extract source file base name (e.g., "websocket_callback" from "websocket_callback.go")
baseName := filepath.Base(path)
sourceFile := strings.TrimSuffix(baseName, ".go")
capability := Capability{
Name: capAnnotation["name"],
Interface: typeSpec.Name.Name,
Required: capAnnotation["required"] == "true",
Doc: cleanDoc(docText),
SourceFile: sourceFile,
}
// Parse methods and collect referenced types
referencedTypes := make(map[string]bool)
for _, method := range interfaceType.Methods.List {
if len(method.Names) == 0 {
continue // Embedded interface
}
funcType, ok := method.Type.(*ast.FuncType)
if !ok {
continue
}
// Check for //nd:export annotation
methodDocText, methodRawDoc := getMethodDocComment(method)
exportAnnotation := parseExportAnnotation(methodRawDoc)
if exportAnnotation == nil {
continue
}
export, err := parseExport(method.Names[0].Name, funcType, exportAnnotation, cleanDoc(methodDocText))
if err != nil {
return nil, fmt.Errorf("parsing export %s.%s: %w", typeSpec.Name.Name, method.Names[0].Name, err)
}
capability.Methods = append(capability.Methods, export)
// Collect referenced types from input and output
collectReferencedTypes(export.Input.Type, referencedTypes)
collectReferencedTypes(export.Output.Type, referencedTypes)
}
// Recursively collect all struct dependencies
collectAllStructDependencies(referencedTypes, structMap)
// Sort type names for stable output order
sortedTypeNames := slices.Sorted(maps.Keys(referencedTypes))
// Attach referenced structs to the capability
for _, typeName := range sortedTypeNames {
if s, exists := structMap[typeName]; exists {
capability.Structs = append(capability.Structs, s)
}
}
// Attach referenced type aliases
for _, typeName := range sortedTypeNames {
if a, exists := aliasMap[typeName]; exists {
capability.TypeAliases = append(capability.TypeAliases, a)
}
}
// Also attach type aliases prefixed with interface name (e.g., ScrobblerError for Scrobbler interface)
// This supports error types that are not directly referenced in method signatures
interfaceName := typeSpec.Name.Name
for _, typeName := range slices.Sorted(maps.Keys(aliasMap)) {
a := aliasMap[typeName]
if strings.HasPrefix(typeName, interfaceName) && !referencedTypes[typeName] {
capability.TypeAliases = append(capability.TypeAliases, a)
referencedTypes[typeName] = true // Mark as referenced for const lookup
}
}
// Attach const groups that match referenced type aliases
for _, group := range allConstGroups {
if group.Type == "" {
continue
}
if referencedTypes[group.Type] {
capability.Consts = append(capability.Consts, group)
}
}
if len(capability.Methods) > 0 {
capabilities = append(capabilities, capability)
}
}
}
return capabilities, nil
}
// collectAllStructDependencies recursively collects all struct types referenced by other structs.
func collectAllStructDependencies(referencedTypes map[string]bool, structMap map[string]StructDef) {
// Keep iterating until no new types are added
for {
newTypes := make(map[string]bool)
for typeName := range referencedTypes {
if s, exists := structMap[typeName]; exists {
for _, field := range s.Fields {
collectReferencedTypes(field.Type, newTypes)
}
}
}
// Check if any new types were found
foundNew := false
for t := range newTypes {
if !referencedTypes[t] {
referencedTypes[t] = true
foundNew = true
}
}
if !foundNew {
break
}
}
}
// parseExport parses an export method signature into an Export struct.
func parseExport(name string, funcType *ast.FuncType, annotation map[string]string, doc string) (Export, error) {
export := Export{
Name: name,
ExportName: annotation["name"],
Doc: doc,
}
// Capability exports have exactly one input parameter (the struct type)
if funcType.Params != nil && len(funcType.Params.List) == 1 {
field := funcType.Params.List[0]
typeName := typeToString(field.Type)
paramName := "input"
if len(field.Names) > 0 {
paramName = field.Names[0].Name
}
export.Input = NewParam(paramName, typeName)
}
// Capability exports return (OutputType, error)
if funcType.Results != nil {
for _, field := range funcType.Results.List {
typeName := typeToString(field.Type)
if typeName == "error" {
continue // Skip error return
}
paramName := "output"
if len(field.Names) > 0 {
paramName = field.Names[0].Name
}
export.Output = NewParam(paramName, typeName)
break // Only take the first non-error return
}
}
return export, nil
}
// parseFile parses a single Go source file and extracts host services.
func parseFile(fset *token.FileSet, path string) ([]Service, error) {
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return nil, err
}
// First pass: collect all struct definitions in the file
allStructs := parseStructs(f)
structMap := make(map[string]StructDef)
for _, s := range allStructs {
structMap[s.Name] = s
}
var services []Service
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.TYPE {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
interfaceType, ok := typeSpec.Type.(*ast.InterfaceType)
if !ok {
continue
}
// Check for //nd:hostservice annotation in doc comment
docText, rawDoc := getDocComment(genDecl, typeSpec)
svcAnnotation := parseHostServiceAnnotation(rawDoc)
if svcAnnotation == nil {
continue
}
service := Service{
Name: svcAnnotation["name"],
Permission: svcAnnotation["permission"],
Interface: typeSpec.Name.Name,
Doc: cleanDoc(docText),
}
// Parse methods and collect referenced types
referencedTypes := make(map[string]bool)
for _, method := range interfaceType.Methods.List {
if len(method.Names) == 0 {
continue // Embedded interface
}
funcType, ok := method.Type.(*ast.FuncType)
if !ok {
continue
}
// Check for //nd:hostfunc annotation
methodDocText, methodRawDoc := getMethodDocComment(method)
methodAnnotation := parseHostFuncAnnotation(methodRawDoc)
if methodAnnotation == nil {
continue
}
m, err := parseMethod(method.Names[0].Name, funcType, methodAnnotation, cleanDoc(methodDocText))
if err != nil {
return nil, fmt.Errorf("parsing method %s.%s: %w", typeSpec.Name.Name, method.Names[0].Name, err)
}
service.Methods = append(service.Methods, m)
// Collect referenced types from params and returns
for _, p := range m.Params {
collectReferencedTypes(p.Type, referencedTypes)
}
for _, r := range m.Returns {
collectReferencedTypes(r.Type, referencedTypes)
}
}
// Attach referenced structs to the service (sorted for stable output)
for _, typeName := range slices.Sorted(maps.Keys(referencedTypes)) {
if s, exists := structMap[typeName]; exists {
service.Structs = append(service.Structs, s)
}
}
if len(service.Methods) > 0 {
services = append(services, service)
}
}
}
return services, nil
}
// parseStructs extracts all struct type definitions from a parsed Go file.
func parseStructs(f *ast.File) []StructDef {
var structs []StructDef
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.TYPE {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
structType, ok := typeSpec.Type.(*ast.StructType)
if !ok {
continue
}
docText, _ := getDocComment(genDecl, typeSpec)
s := StructDef{
Name: typeSpec.Name.Name,
Doc: cleanDoc(docText),
}
// Parse struct fields
for _, field := range structType.Fields.List {
if len(field.Names) == 0 {
continue // Embedded field
}
fieldDef := parseStructField(field)
s.Fields = append(s.Fields, fieldDef...)
}
structs = append(structs, s)
}
}
return structs
}
// parseTypeAliases extracts all type alias definitions from a parsed Go file.
// Type aliases are non-struct type declarations like: type MyType string
func parseTypeAliases(f *ast.File) []TypeAlias {
var aliases []TypeAlias
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.TYPE {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
// Skip struct and interface types
if _, isStruct := typeSpec.Type.(*ast.StructType); isStruct {
continue
}
if _, isInterface := typeSpec.Type.(*ast.InterfaceType); isInterface {
continue
}
docText, _ := getDocComment(genDecl, typeSpec)
aliases = append(aliases, TypeAlias{
Name: typeSpec.Name.Name,
Type: typeToString(typeSpec.Type),
Doc: cleanDoc(docText),
})
}
}
return aliases
}
// parseConstGroups extracts const groups from a parsed Go file.
func parseConstGroups(f *ast.File) []ConstGroup {
var groups []ConstGroup
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.CONST {
continue
}
group := ConstGroup{}
for _, spec := range genDecl.Specs {
valueSpec, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
// Get type if specified
if valueSpec.Type != nil && group.Type == "" {
group.Type = typeToString(valueSpec.Type)
}
// Extract values
for i, name := range valueSpec.Names {
def := ConstDef{
Name: name.Name,
}
// Get value if present
if i < len(valueSpec.Values) {
def.Value = exprToString(valueSpec.Values[i])
}
// Get doc comment
if valueSpec.Doc != nil {
def.Doc = cleanDoc(valueSpec.Doc.Text())
} else if valueSpec.Comment != nil {
def.Doc = cleanDoc(valueSpec.Comment.Text())
}
group.Values = append(group.Values, def)
}
}
if len(group.Values) > 0 {
groups = append(groups, group)
}
}
return groups
}
// exprToString converts an AST expression to a Go source string.
func exprToString(expr ast.Expr) string {
switch e := expr.(type) {
case *ast.BasicLit:
return e.Value
case *ast.Ident:
return e.Name
default:
return ""
}
}
// parseStructField parses a struct field and returns FieldDef for each name.
func parseStructField(field *ast.Field) []FieldDef {
var fields []FieldDef
typeName := typeToString(field.Type)
// Parse struct tag for JSON field name and omitempty
jsonTag := ""
omitEmpty := false
if field.Tag != nil {
tag := field.Tag.Value
// Remove backticks
tag = strings.Trim(tag, "`")
// Parse json tag
jsonTag, omitEmpty = parseJSONTag(tag)
}
// Get doc comment
var doc string
if field.Doc != nil {
doc = cleanDoc(field.Doc.Text())
}
for _, name := range field.Names {
fieldJSONTag := jsonTag
if fieldJSONTag == "" {
// Default to field name with camelCase
fieldJSONTag = toJSONName(name.Name)
}
fields = append(fields, FieldDef{
Name: name.Name,
Type: typeName,
JSONTag: fieldJSONTag,
OmitEmpty: omitEmpty,
Doc: doc,
})
}
return fields
}
// parseJSONTag extracts the json field name and omitempty flag from a struct tag.
func parseJSONTag(tag string) (name string, omitEmpty bool) {
// Find json:"..." in the tag
for _, part := range strings.Split(tag, " ") {
if strings.HasPrefix(part, `json:"`) {
value := strings.TrimPrefix(part, `json:"`)
value = strings.TrimSuffix(value, `"`)
parts := strings.Split(value, ",")
if len(parts) > 0 && parts[0] != "-" {
name = parts[0]
}
for _, opt := range parts[1:] {
if opt == "omitempty" {
omitEmpty = true
}
}
return
}
}
return "", false
}
// collectReferencedTypes extracts custom type names from a Go type string.
// It handles pointers, slices, and maps, collecting base type names.
func collectReferencedTypes(goType string, refs map[string]bool) {
// Strip pointer
if strings.HasPrefix(goType, "*") {
collectReferencedTypes(goType[1:], refs)
return
}
// Strip slice
if strings.HasPrefix(goType, "[]") {
if goType != "[]byte" {
collectReferencedTypes(goType[2:], refs)
}
return
}
// Handle map
if strings.HasPrefix(goType, "map[") {
rest := goType[4:] // Remove "map["
depth := 1
keyEnd := 0
for i, r := range rest {
if r == '[' {
depth++
} else if r == ']' {
depth--
if depth == 0 {
keyEnd = i
break
}
}
}
keyType := rest[:keyEnd]
valueType := rest[keyEnd+1:]
collectReferencedTypes(keyType, refs)
collectReferencedTypes(valueType, refs)
return
}
// Check if it's a custom type (starts with uppercase, not a builtin)
if len(goType) > 0 && goType[0] >= 'A' && goType[0] <= 'Z' {
switch goType {
case "String", "Bool", "Int", "Int32", "Int64", "Float32", "Float64":
// Not custom types (just capitalized for some reason)
default:
refs[goType] = true
}
}
}
// toJSONName is imported from types.go via the same package
// getDocComment extracts the doc comment for a type spec.
// Returns both the readable doc text and the raw comment text (which includes pragma-style comments).
func getDocComment(genDecl *ast.GenDecl, typeSpec *ast.TypeSpec) (docText, rawText string) {
var docGroup *ast.CommentGroup
// First check the TypeSpec's own doc (when multiple types in one block)
if typeSpec.Doc != nil {
docGroup = typeSpec.Doc
} else if genDecl.Doc != nil {
// Fall back to GenDecl doc (single type declaration)
docGroup = genDecl.Doc
}
if docGroup == nil {
return "", ""
}
return docGroup.Text(), commentGroupRaw(docGroup)
}
// commentGroupRaw returns all comment text including pragma-style comments (//nd:...).
// Go's ast.CommentGroup.Text() strips comments without a space after //, so we need this.
func commentGroupRaw(cg *ast.CommentGroup) string {
if cg == nil {
return ""
}
var lines []string
for _, c := range cg.List {
lines = append(lines, c.Text)
}
return strings.Join(lines, "\n")
}
// getMethodDocComment extracts the doc comment for a method.
func getMethodDocComment(field *ast.Field) (docText, rawText string) {
if field.Doc == nil {
return "", ""
}
return field.Doc.Text(), commentGroupRaw(field.Doc)
}
// parseHostServiceAnnotation extracts //nd:hostservice annotation parameters.
func parseHostServiceAnnotation(doc string) map[string]string {
for _, line := range strings.Split(doc, "\n") {
line = strings.TrimSpace(line)
match := hostServicePattern.FindStringSubmatch(line)
if match != nil {
return parseKeyValuePairs(match[1])
}
}
return nil
}
// parseHostFuncAnnotation extracts //nd:hostfunc annotation parameters.
func parseHostFuncAnnotation(doc string) map[string]string {
for _, line := range strings.Split(doc, "\n") {
line = strings.TrimSpace(line)
match := hostFuncPattern.FindStringSubmatch(line)
if match != nil {
params := parseKeyValuePairs(match[1])
if params == nil {
params = make(map[string]string)
}
return params
}
}
return nil
}
// parseCapabilityAnnotation extracts //nd:capability annotation parameters.
func parseCapabilityAnnotation(doc string) map[string]string {
for _, line := range strings.Split(doc, "\n") {
line = strings.TrimSpace(line)
match := capabilityPattern.FindStringSubmatch(line)
if match != nil {
return parseKeyValuePairs(match[1])
}
}
return nil
}
// parseExportAnnotation extracts //nd:export annotation parameters.
func parseExportAnnotation(doc string) map[string]string {
for _, line := range strings.Split(doc, "\n") {
line = strings.TrimSpace(line)
match := exportPattern.FindStringSubmatch(line)
if match != nil {
return parseKeyValuePairs(match[1])
}
}
return nil
}
// parseKeyValuePairs extracts key=value pairs from annotation text.
func parseKeyValuePairs(text string) map[string]string {
matches := keyValuePattern.FindAllStringSubmatch(text, -1)
if len(matches) == 0 {
return nil
}
result := make(map[string]string)
for _, m := range matches {
result[m[1]] = m[2]
}
return result
}
// parseMethod parses a method signature into a Method struct.
func parseMethod(name string, funcType *ast.FuncType, annotation map[string]string, doc string) (Method, error) {
m := Method{
Name: name,
ExportName: annotation["name"],
Doc: doc,
}
// Parse parameters (skip context.Context)
if funcType.Params != nil {
for _, field := range funcType.Params.List {
typeName := typeToString(field.Type)
if typeName == "context.Context" {
continue // Skip context parameter
}
for _, name := range field.Names {
m.Params = append(m.Params, NewParam(name.Name, typeName))
}
}
}
// Parse return values
if funcType.Results != nil {
for _, field := range funcType.Results.List {
typeName := typeToString(field.Type)
if typeName == "error" {
m.HasError = true
continue // Track error but don't include in Returns
}
// Handle anonymous returns
if len(field.Names) == 0 {
// Generate a name based on position
m.Returns = append(m.Returns, NewParam("result", typeName))
} else {
for _, name := range field.Names {
m.Returns = append(m.Returns, NewParam(name.Name, typeName))
}
}
}
}
return m, nil
}
// typeToString converts an AST type expression to a string.
func typeToString(expr ast.Expr) string {
switch t := expr.(type) {
case *ast.Ident:
return t.Name
case *ast.SelectorExpr:
return typeToString(t.X) + "." + t.Sel.Name
case *ast.StarExpr:
return "*" + typeToString(t.X)
case *ast.ArrayType:
if t.Len == nil {
return "[]" + typeToString(t.Elt)
}
return fmt.Sprintf("[%s]%s", typeToString(t.Len), typeToString(t.Elt))
case *ast.MapType:
return fmt.Sprintf("map[%s]%s", typeToString(t.Key), typeToString(t.Value))
case *ast.BasicLit:
return t.Value
case *ast.InterfaceType:
// Empty interface (interface{} or any)
if t.Methods == nil || len(t.Methods.List) == 0 {
return "any"
}
// Non-empty interfaces can't be easily represented
return "any"
default:
return fmt.Sprintf("%T", expr)
}
}
// cleanDoc removes annotation lines from documentation.
func cleanDoc(doc string) string {
var lines []string
for _, line := range strings.Split(doc, "\n") {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "//nd:") {
continue
}
lines = append(lines, line)
}
return strings.TrimSpace(strings.Join(lines, "\n"))
}
+547
View File
@@ -0,0 +1,547 @@
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())
})
})
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"))
})
})
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"))
})
})
})
+441
View File
@@ -0,0 +1,441 @@
package internal
import (
"fmt"
"go/ast"
"go/token"
"sort"
"strings"
"golang.org/x/tools/go/packages"
)
// PDKSymbols contains all exported symbols parsed from extism/go-pdk.
type PDKSymbols struct {
Types []PDKType
Consts []PDKConst
Functions []PDKFunc
}
// PDKType represents an exported type from extism/go-pdk.
type PDKType struct {
Name string
Underlying string // The underlying type (e.g., "int" for LogLevel)
IsAlias bool // True if it's a type alias (type X = Y)
Doc string // Documentation comment
Methods []PDKFunc // Methods on this type
Fields []PDKField // Struct fields (if it's a struct type)
}
// PDKField represents a struct field.
type PDKField struct {
Name string
Type string
Tag string // Struct tag (e.g., `json:"name"`)
}
// PDKConst represents an exported constant from extism/go-pdk.
type PDKConst struct {
Name string
Type string // The type name (may be empty for untyped consts)
Value string // The value expression
Doc string
}
// PDKFunc represents an exported function from extism/go-pdk.
type PDKFunc struct {
Name string
Doc string
Receiver string // Empty for package-level functions
Params []PDKParam
Returns []PDKReturn
IsVariadic bool
}
// PDKParam represents a function parameter.
type PDKParam struct {
Name string
Type string
}
// PDKReturn represents a function return value.
type PDKReturn struct {
Name string // May be empty for unnamed returns
Type string
}
// ParseExtismPDK parses the extism/go-pdk package and extracts all exported symbols.
func ParseExtismPDK() (*PDKSymbols, error) {
// Load both packages with syntax trees in one call
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedSyntax | packages.NeedFiles,
}
pkgs, err := packages.Load(cfg,
"github.com/extism/go-pdk",
"github.com/extism/go-pdk/internal/memory",
)
if err != nil {
return nil, fmt.Errorf("loading extism/go-pdk: %w", err)
}
// Find both packages
var pdkPkg, memoryPkg *packages.Package
for _, pkg := range pkgs {
if len(pkg.Errors) > 0 {
return nil, fmt.Errorf("loading %s: %v", pkg.PkgPath, pkg.Errors[0])
}
switch pkg.Name {
case "pdk":
pdkPkg = pkg
case "memory":
memoryPkg = pkg
}
}
if pdkPkg == nil {
return nil, fmt.Errorf("package github.com/extism/go-pdk not found")
}
if memoryPkg == nil {
return nil, fmt.Errorf("package github.com/extism/go-pdk/internal/memory not found")
}
symbols := &PDKSymbols{}
seenTypes := make(map[string]bool)
// Extract Memory type from internal/memory package first
extractMemorySymbols(memoryPkg.Syntax, symbols, seenTypes)
// First pass: collect types from pdk package (skip if already found in internal packages)
for _, file := range pdkPkg.Syntax {
for _, decl := range file.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok {
for _, spec := range genDecl.Specs {
if typeSpec, ok := spec.(*ast.TypeSpec); ok {
if !typeSpec.Name.IsExported() {
continue
}
// Skip if we already have this type (from internal packages)
if seenTypes[typeSpec.Name.Name] {
continue
}
seenTypes[typeSpec.Name.Name] = true
pdkType := extractType(typeSpec, genDecl.Doc)
symbols.Types = append(symbols.Types, pdkType)
}
}
}
}
}
// Build typeMap from the final slice (after all types are added)
typeMap := make(map[string]*PDKType)
for i := range symbols.Types {
typeMap[symbols.Types[i].Name] = &symbols.Types[i]
}
// Second pass: collect functions and methods from pdk package
for _, file := range pdkPkg.Syntax {
for _, decl := range file.Decls {
switch d := decl.(type) {
case *ast.GenDecl:
if d.Tok == token.CONST {
consts := extractConsts(d)
symbols.Consts = append(symbols.Consts, consts...)
}
case *ast.FuncDecl:
if !d.Name.IsExported() {
continue
}
fn := extractFunc(d)
if fn.Receiver != "" {
// It's a method, associate with type
typeName := fn.Receiver
if strings.HasPrefix(typeName, "*") {
typeName = typeName[1:]
}
if t, ok := typeMap[typeName]; ok {
t.Methods = append(t.Methods, fn)
}
} else {
symbols.Functions = append(symbols.Functions, fn)
}
}
}
}
// Sort for consistent output
sort.Slice(symbols.Types, func(i, j int) bool {
return symbols.Types[i].Name < symbols.Types[j].Name
})
sort.Slice(symbols.Consts, func(i, j int) bool {
return symbols.Consts[i].Name < symbols.Consts[j].Name
})
sort.Slice(symbols.Functions, func(i, j int) bool {
return symbols.Functions[i].Name < symbols.Functions[j].Name
})
return symbols, nil
}
func extractType(spec *ast.TypeSpec, doc *ast.CommentGroup) PDKType {
t := PDKType{
Name: spec.Name.Name,
Doc: extractDoc(doc),
}
// Check if it's an alias (type X = Y)
t.IsAlias = spec.Assign.IsValid()
// Extract underlying type
t.Underlying = typeString(spec.Type)
// Extract struct fields if it's a struct type
if structType, ok := spec.Type.(*ast.StructType); ok {
t.Fields = extractStructFields(structType)
}
return t
}
func extractStructFields(st *ast.StructType) []PDKField {
var fields []PDKField
if st.Fields == nil {
return fields
}
for _, field := range st.Fields.List {
fieldType := typeString(field.Type)
tag := ""
if field.Tag != nil {
tag = field.Tag.Value
}
if len(field.Names) == 0 {
// Embedded field
fields = append(fields, PDKField{
Name: fieldType, // Use type name as field name for embedded
Type: fieldType,
Tag: tag,
})
} else {
for _, name := range field.Names {
// Skip unexported fields
if !name.IsExported() {
continue
}
fields = append(fields, PDKField{
Name: name.Name,
Type: fieldType,
Tag: tag,
})
}
}
}
return fields
}
func extractConsts(decl *ast.GenDecl) []PDKConst {
var consts []PDKConst
var currentType string // For iota-style const blocks
for i, spec := range decl.Specs {
valSpec, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
// Update type if specified
if valSpec.Type != nil {
currentType = typeString(valSpec.Type)
}
for j, name := range valSpec.Names {
if !name.IsExported() {
continue
}
c := PDKConst{
Name: name.Name,
Type: currentType,
}
// Extract value
if j < len(valSpec.Values) {
c.Value = exprString(valSpec.Values[j])
} else if i == 0 && j == 0 {
// First const with no value - likely iota
c.Value = "iota"
}
// Extract doc
if valSpec.Doc != nil {
c.Doc = extractDoc(valSpec.Doc)
} else if i == 0 && decl.Doc != nil {
c.Doc = extractDoc(decl.Doc)
}
consts = append(consts, c)
}
}
return consts
}
func extractFunc(decl *ast.FuncDecl) PDKFunc {
fn := PDKFunc{
Name: decl.Name.Name,
Doc: extractDoc(decl.Doc),
}
// Extract receiver
if decl.Recv != nil && len(decl.Recv.List) > 0 {
fn.Receiver = typeString(decl.Recv.List[0].Type)
}
// Extract parameters
if decl.Type.Params != nil {
for _, field := range decl.Type.Params.List {
paramType := typeString(field.Type)
// Check for variadic
if _, ok := field.Type.(*ast.Ellipsis); ok {
fn.IsVariadic = true
}
if len(field.Names) == 0 {
// Unnamed parameter
fn.Params = append(fn.Params, PDKParam{Type: paramType})
} else {
for _, name := range field.Names {
fn.Params = append(fn.Params, PDKParam{
Name: name.Name,
Type: paramType,
})
}
}
}
}
// Extract returns
if decl.Type.Results != nil {
for _, field := range decl.Type.Results.List {
retType := typeString(field.Type)
if len(field.Names) == 0 {
// Unnamed return
fn.Returns = append(fn.Returns, PDKReturn{Type: retType})
} else {
for _, name := range field.Names {
fn.Returns = append(fn.Returns, PDKReturn{
Name: name.Name,
Type: retType,
})
}
}
}
}
return fn
}
func extractDoc(doc *ast.CommentGroup) string {
if doc == nil {
return ""
}
return strings.TrimSpace(doc.Text())
}
func typeString(expr ast.Expr) string {
switch t := expr.(type) {
case *ast.Ident:
return t.Name
case *ast.StarExpr:
return "*" + typeString(t.X)
case *ast.SelectorExpr:
return typeString(t.X) + "." + t.Sel.Name
case *ast.ArrayType:
if t.Len == nil {
return "[]" + typeString(t.Elt)
}
return fmt.Sprintf("[%s]%s", exprString(t.Len), typeString(t.Elt))
case *ast.MapType:
return fmt.Sprintf("map[%s]%s", typeString(t.Key), typeString(t.Value))
case *ast.InterfaceType:
return "any" // Simplified
case *ast.Ellipsis:
return "..." + typeString(t.Elt)
case *ast.StructType:
return "struct{}" // Simplified for anonymous structs
case *ast.FuncType:
return "func()" // Simplified
default:
return fmt.Sprintf("%T", expr)
}
}
func exprString(expr ast.Expr) string {
switch e := expr.(type) {
case *ast.Ident:
return e.Name
case *ast.BasicLit:
return e.Value
case *ast.BinaryExpr:
return exprString(e.X) + " " + e.Op.String() + " " + exprString(e.Y)
case *ast.UnaryExpr:
return e.Op.String() + exprString(e.X)
case *ast.CallExpr:
return typeString(e.Fun) + "(...)"
default:
return fmt.Sprintf("%T", expr)
}
}
// extractMemorySymbols extracts the Memory type and its methods from already-parsed syntax trees.
// This is needed because Memory is defined in internal/memory but re-exported by the pdk package.
func extractMemorySymbols(files []*ast.File, symbols *PDKSymbols, seenTypes map[string]bool) {
// Collect the Memory type
for _, file := range files {
for _, decl := range file.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok {
for _, spec := range genDecl.Specs {
if typeSpec, ok := spec.(*ast.TypeSpec); ok {
// Only interested in Memory type
if typeSpec.Name.Name == "Memory" {
pdkType := extractType(typeSpec, genDecl.Doc)
symbols.Types = append(symbols.Types, pdkType)
seenTypes["Memory"] = true
}
}
}
}
}
}
// Build local type map for method association
localTypeMap := make(map[string]*PDKType)
for i := range symbols.Types {
localTypeMap[symbols.Types[i].Name] = &symbols.Types[i]
}
// Collect methods for Memory
for _, file := range files {
for _, decl := range file.Decls {
if funcDecl, ok := decl.(*ast.FuncDecl); ok {
if !funcDecl.Name.IsExported() {
continue
}
fn := extractFunc(funcDecl)
if fn.Receiver != "" {
typeName := fn.Receiver
if strings.HasPrefix(typeName, "*") {
typeName = typeName[1:]
}
if typeName == "Memory" {
if t, ok := localTypeMap["Memory"]; ok {
t.Methods = append(t.Methods, fn)
}
}
}
}
}
}
}
@@ -0,0 +1,223 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains export wrappers for the {{.Capability.Interface}} capability.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package {{.Package}}
import (
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
{{- /* Generate type alias definitions */ -}}
{{- range .Capability.TypeAliases}}
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
type {{.Name}} {{.Type}}
{{- end}}
{{- /* Generate const definitions */ -}}
{{- range .Capability.Consts}}
{{- if .Values}}
const (
{{- $type := .Type}}
{{- range $i, $v := .Values}}
{{- if $v.Doc}}
{{formatDoc $v.Doc | indent 1}}
{{- end}}
{{- if $type}}
{{$v.Name}} {{$type}} = {{$v.Value}}
{{- else}}
{{$v.Name}} = {{$v.Value}}
{{- end}}
{{- end}}
)
{{- end}}
{{- end}}
{{- /* Generate Error() methods for string type aliases with const values (implements error interface) */ -}}
{{- $consts := .Capability.Consts}}
{{- range .Capability.TypeAliases}}
{{- if eq .Type "string"}}
{{- $typeName := .Name}}
{{- range $consts}}
{{- if eq .Type $typeName}}
// Error implements the error interface for {{$typeName}}.
func (e {{$typeName}}) Error() string { return string(e) }
{{- end}}
{{- end}}
{{- end}}
{{- end}}
{{- /* Generate struct definitions */ -}}
{{- range .Capability.Structs}}
{{- if .Doc}}
{{formatDoc .Doc}}
{{- else}}
// {{.Name}} represents the {{.Name}} data structure.
{{- end}}
type {{.Name}} struct {
{{- range .Fields}}
{{- if .Doc}}
{{formatDoc .Doc | indent 1}}
{{- end}}
{{.Name}} {{.Type}} `json:"{{.JSONTag}}{{if .OmitEmpty}},omitempty{{end}}"`
{{- end}}
}
{{- end}}
{{- /* Generate main interface based on required flag */ -}}
{{if .Capability.Required}}
// {{agentName .Capability}} requires all methods to be implemented.
{{- if .Capability.Doc}}
{{formatDoc .Capability.Doc}}
{{- end}}
type {{agentName .Capability}} interface {
{{- range .Capability.Methods}}
// {{.Name}}{{if .Doc}} - {{.Doc}}{{end}}
{{- if and .HasInput .HasOutput}}
{{.Name}}({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{.Name}}({{.Input.Type}}) error
{{- else if .HasOutput}}
{{.Name}}() ({{.Output.Type}}, error)
{{- else}}
{{.Name}}() error
{{- end}}
{{- end}}
}
{{- else}}
// {{agentName .Capability}} is the marker interface for {{.Package}} plugins.
// Implement one or more of the provider interfaces below.
{{- if .Capability.Doc}}
{{formatDoc .Capability.Doc}}
{{- end}}
type {{agentName .Capability}} interface{}
{{- end}}
{{- /* Generate optional provider interfaces for non-required capabilities */ -}}
{{- if not .Capability.Required}}
{{- range .Capability.Methods}}
// {{providerInterface .}} provides the {{.Name}} function.
type {{providerInterface .}} interface {
{{- if and .HasInput .HasOutput}}
{{.Name}}({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{.Name}}({{.Input.Type}}) error
{{- else if .HasOutput}}
{{.Name}}() ({{.Output.Type}}, error)
{{- else}}
{{.Name}}() error
{{- end}}
}
{{- end}}
{{- end}}
{{- /* Generate implementation function holders */ -}}
// Internal implementation holders
var (
{{- range .Capability.Methods}}
{{- if and .HasInput .HasOutput}}
{{implVar .}} func({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{implVar .}} func({{.Input.Type}}) error
{{- else if .HasOutput}}
{{implVar .}} func() ({{.Output.Type}}, error)
{{- else}}
{{implVar .}} func() error
{{- end}}
{{- end}}
)
// Register registers a {{.Package}} implementation.
{{- if .Capability.Required}}
// All methods are required.
func Register(impl {{agentName .Capability}}) {
{{- range .Capability.Methods}}
{{implVar .}} = impl.{{.Name}}
{{- end}}
}
{{- else}}
// The implementation is checked for optional provider interfaces.
func Register(impl {{agentName .Capability}}) {
{{- range .Capability.Methods}}
if p, ok := impl.({{providerInterface .}}); ok {
{{implVar .}} = p.{{.Name}}
}
{{- end}}
}
{{- end}}
// NotImplementedCode is the standard return code for unimplemented functions.
// The host recognizes this and skips the plugin gracefully.
const NotImplementedCode int32 = -2
{{- /* Generate export wrappers */ -}}
{{range .Capability.Methods}}
//go:wasmexport {{.ExportName}}
func {{exportFunc .}}() int32 {
if {{implVar .}} == nil {
// Return standard code - host will skip this plugin gracefully
return NotImplementedCode
}
{{- if .HasInput}}
var input {{.Input.Type}}
if err := pdk.InputJSON(&input); err != nil {
pdk.SetError(err)
return -1
}
{{- end}}
{{- if and .HasInput .HasOutput}}
output, err := {{implVar .}}(input)
if err != nil {
pdk.SetError(err)
return -1
}
if err := pdk.OutputJSON(output); err != nil {
pdk.SetError(err)
return -1
}
{{- else if .HasInput}}
if err := {{implVar .}}(input); err != nil {
pdk.SetError(err)
return -1
}
{{- else if .HasOutput}}
output, err := {{implVar .}}()
if err != nil {
pdk.SetError(err)
return -1
}
if err := pdk.OutputJSON(output); err != nil {
pdk.SetError(err)
return -1
}
{{- else}}
if err := {{implVar .}}(); err != nil {
pdk.SetError(err)
return -1
}
{{- end}}
return 0
}
{{- end}}
@@ -0,0 +1,184 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains export wrappers for the {{.Capability.Interface}} capability.
// It is intended for use in Navidrome plugins built with extism-pdk.
{{if .Capability.Structs}}
use serde::{Deserialize, Serialize};
{{- if hasHashMap .Capability}}
use std::collections::HashMap;
{{- end}}
{{- end}}
{{- /* Generate type alias definitions */ -}}
{{- range .Capability.TypeAliases}}
{{- if .Doc}}
{{rustDocComment .Doc}}
{{- end}}
pub type {{.Name}} = {{rustTypeAlias .Type}};
{{- end}}
{{- /* Generate const definitions */ -}}
{{- range .Capability.Consts}}
{{- if .Values}}
{{- $type := .Type}}
{{- range $i, $v := .Values}}
{{- if $v.Doc}}
{{rustDocComment $v.Doc}}
{{- end}}
{{- /* Use the type alias name if a named type is provided, otherwise use &'static str */ -}}
{{- if $type}}
pub const {{rustConstName $v.Name}}: {{$type}} = {{$v.Value}};
{{- else}}
pub const {{rustConstName $v.Name}}: &'static str = {{$v.Value}};
{{- end}}
{{- end}}
{{- end}}
{{- end}}
{{- /* Generate struct definitions */ -}}
{{- range .Capability.Structs}}
{{- if .Doc}}
{{rustDocComment .Doc}}
{{- else}}
/// {{.Name}} represents the {{.Name}} data structure.
{{- end}}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct {{.Name}} {
{{- range .Fields}}
{{- if .Doc}}
{{rustDocComment .Doc | indent 4}}
{{- end}}
{{- if .OmitEmpty}}
#[serde(default, skip_serializing_if = "{{skipSerializingFunc .Type}}")]
{{- else}}
#[serde(default)]
{{- end}}
pub {{rustFieldName .Name}}: {{fieldRustType .}},
{{- end}}
}
{{- end}}
/// Error represents an error from a capability method.
#[derive(Debug)]
pub struct Error {
pub message: String,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for Error {}
impl Error {
pub fn new(message: impl Into<String>) -> Self {
Self { message: message.into() }
}
}
{{- /* Generate main interface based on required flag */ -}}
{{if .Capability.Required}}
/// {{agentName .Capability}} requires all methods to be implemented.
{{- if .Capability.Doc}}
{{rustDocComment .Capability.Doc}}
{{- end}}
pub trait {{agentName .Capability}} {
{{- range .Capability.Methods}}
/// {{.Name}}{{if .Doc}} - {{.Doc}}{{end}}
{{- if and .HasInput .HasOutput}}
fn {{rustMethodName .Name}}(&self, req: {{rustOutputType .Input.Type}}) -> Result<{{rustOutputType .Output.Type}}, Error>;
{{- else if .HasInput}}
fn {{rustMethodName .Name}}(&self, req: {{rustOutputType .Input.Type}}) -> Result<(), Error>;
{{- else if .HasOutput}}
fn {{rustMethodName .Name}}(&self) -> Result<{{rustOutputType .Output.Type}}, Error>;
{{- else}}
fn {{rustMethodName .Name}}(&self) -> Result<(), Error>;
{{- end}}
{{- end}}
}
/// Register all exports for the {{agentName .Capability}} capability.
/// This macro generates the WASM export functions for all trait methods.
#[macro_export]
macro_rules! register_{{snakeCase .Package}} {
($plugin_type:ty) => {
{{- range .Capability.Methods}}
#[extism_pdk::plugin_fn]
pub fn {{.ExportName}}(
{{- if .HasInput}}
req: extism_pdk::Json<$crate::{{snakeCase $.Package}}::{{rustOutputType .Input.Type}}>
{{- end}}
) -> extism_pdk::FnResult<{{if .HasOutput}}extism_pdk::Json<{{if isPrimitiveRust .Output.Type}}{{rustOutputType .Output.Type}}{{else}}$crate::{{snakeCase $.Package}}::{{rustOutputType .Output.Type}}{{end}}>{{else}}(){{end}}> {
let plugin = <$plugin_type>::default();
{{- if and .HasInput .HasOutput}}
let result = $crate::{{snakeCase $.Package}}::{{agentName $.Capability}}::{{rustMethodName .Name}}(&plugin, req.into_inner())?;
Ok(extism_pdk::Json(result))
{{- else if .HasInput}}
$crate::{{snakeCase $.Package}}::{{agentName $.Capability}}::{{rustMethodName .Name}}(&plugin, req.into_inner())?;
Ok(())
{{- else if .HasOutput}}
let result = $crate::{{snakeCase $.Package}}::{{agentName $.Capability}}::{{rustMethodName .Name}}(&plugin)?;
Ok(extism_pdk::Json(result))
{{- else}}
$crate::{{snakeCase $.Package}}::{{agentName $.Capability}}::{{rustMethodName .Name}}(&plugin)?;
Ok(())
{{- end}}
}
{{- end}}
};
}
{{- else}}
{{- /* Generate optional provider interfaces for non-required capabilities */ -}}
{{- range .Capability.Methods}}
/// {{providerInterface .}} provides the {{.Name}} function.
pub trait {{providerInterface .}} {
{{- if and .HasInput .HasOutput}}
fn {{rustMethodName .Name}}(&self, req: {{rustOutputType .Input.Type}}) -> Result<{{rustOutputType .Output.Type}}, Error>;
{{- else if .HasInput}}
fn {{rustMethodName .Name}}(&self, req: {{rustOutputType .Input.Type}}) -> Result<(), Error>;
{{- else if .HasOutput}}
fn {{rustMethodName .Name}}(&self) -> Result<{{rustOutputType .Output.Type}}, Error>;
{{- else}}
fn {{rustMethodName .Name}}(&self) -> Result<(), Error>;
{{- end}}
}
/// Register the {{rustMethodName .Name}} export.
/// This macro generates the WASM export function for this method.
#[macro_export]
macro_rules! {{registerMacroName .Name}} {
($plugin_type:ty) => {
#[extism_pdk::plugin_fn]
pub fn {{.ExportName}}(
{{- if .HasInput}}
req: extism_pdk::Json<$crate::{{snakeCase $.Package}}::{{rustOutputType .Input.Type}}>
{{- end}}
) -> extism_pdk::FnResult<{{if .HasOutput}}extism_pdk::Json<{{if isPrimitiveRust .Output.Type}}{{rustOutputType .Output.Type}}{{else}}$crate::{{snakeCase $.Package}}::{{rustOutputType .Output.Type}}{{end}}>{{else}}(){{end}}> {
let plugin = <$plugin_type>::default();
{{- if and .HasInput .HasOutput}}
let result = $crate::{{snakeCase $.Package}}::{{providerInterface .}}::{{rustMethodName .Name}}(&plugin, req.into_inner())?;
Ok(extism_pdk::Json(result))
{{- else if .HasInput}}
$crate::{{snakeCase $.Package}}::{{providerInterface .}}::{{rustMethodName .Name}}(&plugin, req.into_inner())?;
Ok(())
{{- else if .HasOutput}}
let result = $crate::{{snakeCase $.Package}}::{{providerInterface .}}::{{rustMethodName .Name}}(&plugin)?;
Ok(extism_pdk::Json(result))
{{- else}}
$crate::{{snakeCase $.Package}}::{{providerInterface .}}::{{rustMethodName .Name}}(&plugin)?;
Ok(())
{{- end}}
}
};
}
{{- end}}
{{- end}}
@@ -0,0 +1,132 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file provides stub implementations for non-WASM platforms.
// It allows Go plugins to compile and run tests outside of WASM,
// but the actual functionality is only available in WASM builds.
//
//go:build !wasip1
package {{.Package}}
{{- /* Generate type alias definitions */ -}}
{{- range .Capability.TypeAliases}}
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
type {{.Name}} {{.Type}}
{{- end}}
{{- /* Generate const definitions */ -}}
{{- range .Capability.Consts}}
{{- if .Values}}
const (
{{- $type := .Type}}
{{- range $i, $v := .Values}}
{{- if $v.Doc}}
{{formatDoc $v.Doc | indent 1}}
{{- end}}
{{- if $type}}
{{$v.Name}} {{$type}} = {{$v.Value}}
{{- else}}
{{$v.Name}} = {{$v.Value}}
{{- end}}
{{- end}}
)
{{- end}}
{{- end}}
{{- /* Generate Error() methods for string type aliases with const values (implements error interface) */ -}}
{{- $consts := .Capability.Consts}}
{{- range .Capability.TypeAliases}}
{{- if eq .Type "string"}}
{{- $typeName := .Name}}
{{- range $consts}}
{{- if eq .Type $typeName}}
// Error implements the error interface for {{$typeName}}.
func (e {{$typeName}}) Error() string { return string(e) }
{{- end}}
{{- end}}
{{- end}}
{{- end}}
{{- /* Generate struct definitions */ -}}
{{- range .Capability.Structs}}
{{- if .Doc}}
{{formatDoc .Doc}}
{{- else}}
// {{.Name}} represents the {{.Name}} data structure.
{{- end}}
type {{.Name}} struct {
{{- range .Fields}}
{{- if .Doc}}
{{formatDoc .Doc | indent 1}}
{{- end}}
{{.Name}} {{.Type}} `json:"{{.JSONTag}}{{if .OmitEmpty}},omitempty{{end}}"`
{{- end}}
}
{{- end}}
{{- /* Generate main interface based on required flag */ -}}
{{if .Capability.Required}}
// {{agentName .Capability}} requires all methods to be implemented.
{{- if .Capability.Doc}}
{{formatDoc .Capability.Doc}}
{{- end}}
type {{agentName .Capability}} interface {
{{- range .Capability.Methods}}
// {{.Name}}{{if .Doc}} - {{.Doc}}{{end}}
{{- if and .HasInput .HasOutput}}
{{.Name}}({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{.Name}}({{.Input.Type}}) error
{{- else if .HasOutput}}
{{.Name}}() ({{.Output.Type}}, error)
{{- else}}
{{.Name}}() error
{{- end}}
{{- end}}
}
{{- else}}
// {{agentName .Capability}} is the marker interface for {{.Package}} plugins.
// Implement one or more of the provider interfaces below.
{{- if .Capability.Doc}}
{{formatDoc .Capability.Doc}}
{{- end}}
type {{agentName .Capability}} interface{}
{{- end}}
{{- /* Generate optional provider interfaces for non-required capabilities */ -}}
{{- if not .Capability.Required}}
{{- range .Capability.Methods}}
// {{providerInterface .}} provides the {{.Name}} function.
type {{providerInterface .}} interface {
{{- if and .HasInput .HasOutput}}
{{.Name}}({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{.Name}}({{.Input.Type}}) error
{{- else if .HasOutput}}
{{.Name}}() ({{.Output.Type}}, error)
{{- else}}
{{.Name}}() error
{{- end}}
}
{{- end}}
{{- end}}
// NotImplementedCode is the standard return code for unimplemented functions.
const NotImplementedCode int32 = -2
// Register is a no-op on non-WASM platforms.
// This stub allows code to compile outside of WASM.
{{- if .Capability.Required}}
func Register(_ {{agentName .Capability}}) {}
{{- else}}
func Register(_ {{agentName .Capability}}) {}
{{- end}}
@@ -0,0 +1,129 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the {{.Service.Name}} host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package {{.Package}}
import (
"encoding/json"
{{- if .Service.HasErrors}}
"errors"
{{- end}}
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
{{- /* Generate struct definitions */ -}}
{{- range .Service.Structs}}
// {{.Name}} represents the {{.Name}} data structure.
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
type {{.Name}} struct {
{{- range .Fields}}
{{.Name}} {{.Type}} `json:"{{.JSONTag}}"`
{{- end}}
}
{{- end}}
{{- /* Generate wasmimport declarations for each method */ -}}
{{range .Service.Methods}}
// {{exportName .}} is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user {{exportName .}}
func {{exportName .}}(uint64) uint64
{{- end}}
{{- /* Generate request/response types for all methods (private) */ -}}
{{range .Service.Methods}}
{{- if .HasParams}}
type {{requestType .}} struct {
{{- range .Params}}
{{title .Name}} {{.Type}} `json:"{{.JSONName}}"`
{{- end}}
}
{{- end}}
{{- if not .IsErrorOnly}}
type {{responseType .}} struct {
{{- range .Returns}}
{{title .Name}} {{.Type}} `json:"{{.JSONName}},omitempty"`
{{- end}}
{{- if .HasError}}
Error string `json:"error,omitempty"`
{{- end}}
}
{{- end}}
{{- end}}
{{- /* Generate wrapper functions */ -}}
{{range .Service.Methods}}
// {{$.Service.Name}}{{.Name}} calls the {{exportName .}} host function.
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
func {{$.Service.Name}}{{.Name}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}} {{$p.Type}}{{end}}) {{.ReturnSignature}} {
{{- if .HasParams}}
// Marshal request to JSON
req := {{requestType .}}{
{{- range .Params}}
{{title .Name}}: {{.Name}},
{{- end}}
}
reqBytes, err := json.Marshal(req)
if err != nil {
return {{if .HasReturns}}{{.ZeroValues}}{{end}}{{if and .HasReturns .HasError}}, {{end}}{{if .HasError}}err{{end}}
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
{{- else}}
// No parameters - allocate empty JSON object
reqMem := pdk.AllocateBytes([]byte("{}"))
defer reqMem.Free()
{{- end}}
// Call the host function
responsePtr := {{exportName .}}(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
{{- if .IsErrorOnly}}
// Parse error-only response
var response struct {
Error string `json:"error,omitempty"`
}
if err := json.Unmarshal(responseBytes, &response); err != nil {
return err
}
if response.Error != "" {
return errors.New(response.Error)
}
return nil
{{- else}}
// Parse the response
var response {{responseType .}}
if err := json.Unmarshal(responseBytes, &response); err != nil {
return {{if .HasReturns}}{{.ZeroValues}}{{end}}{{if and .HasReturns .HasError}}, {{end}}{{if .HasError}}err{{end}}
}
{{- if .HasError}}
// Convert Error field to Go error
if response.Error != "" {
return {{if .HasReturns}}{{.ZeroValues}}, {{end}}errors.New(response.Error)
}
{{- end}}
return {{range $i, $r := .Returns}}{{if $i}}, {{end}}response.{{title $r.Name}}{{end}}{{if and .HasReturns .HasError}}, {{end}}{{if .HasError}}nil{{end}}
{{- end}}
}
{{- end}}
@@ -0,0 +1,96 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the {{.Service.Name}} host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
{{- /* Generate raw host function imports */ -}}
{{range .Service.Methods}}
@extism.import_fn("extism:host/user", "{{exportName .}}")
def _{{exportName .}}(offset: int) -> int:
"""Raw host function - do not call directly."""
...
{{- end}}
{{- /* Generate dataclasses for multi-value returns */ -}}
{{range .Service.Methods}}
{{- if .NeedsResultClass}}
@dataclass
class {{pythonResultType .}}:
"""Result type for {{pythonFunc .}}."""
{{- range .Returns}}
{{.PythonName}}: {{.PythonType}}
{{- end}}
{{- end}}
{{- end}}
{{- /* Generate wrapper functions */ -}}
{{range .Service.Methods}}
def {{pythonFunc .}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.PythonName}}: {{$p.PythonType}}{{end}}){{if .NeedsResultClass}} -> {{pythonResultType .}}{{else if .HasReturns}} -> {{(index .Returns 0).PythonType}}{{else}} -> None{{end}}:
"""{{if .Doc}}{{.Doc}}{{else}}Call the {{exportName .}} host function.{{end}}
{{- if .HasParams}}
Args:
{{- range .Params}}
{{.PythonName}}: {{.PythonType}} parameter.
{{- end}}
{{- end}}
{{- if .HasReturns}}
Returns:
{{- if .NeedsResultClass}}
{{pythonResultType .}} containing{{range .Returns}} {{.PythonName}},{{end}}.
{{- else}}
{{(index .Returns 0).PythonType}}: The result value.
{{- end}}
{{- end}}
Raises:
HostFunctionError: If the host function returns an error.
"""
{{- if .HasParams}}
request = {
{{- range .Params}}
"{{.JSONName}}": {{.PythonName}},
{{- end}}
}
request_bytes = json.dumps(request).encode("utf-8")
{{- else}}
request_bytes = b"{}"
{{- end}}
request_mem = extism.memory.alloc(request_bytes)
response_offset = _{{exportName .}}(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
{{if .HasError}}
if response.get("error"):
raise HostFunctionError(response["error"])
{{end}}
{{- if .NeedsResultClass}}
return {{pythonResultType .}}(
{{- range .Returns}}
{{.PythonName}}=response.get("{{.JSONName}}"{{pythonDefault .}}),
{{- end}}
)
{{- else if .HasReturns}}
return response.get("{{(index .Returns 0).JSONName}}"{{pythonDefault (index .Returns 0)}})
{{- end}}
{{- end}}
@@ -0,0 +1,134 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the {{.Service.Name}} host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
{{- /* Generate struct definitions */ -}}
{{- range .Service.Structs}}
{{if .Doc}}
{{rustDocComment .Doc}}
{{else}}
{{end}}#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct {{.Name}} {
{{- range .Fields}}
{{- if .NeedsDefault}}
#[serde(default)]
{{- end}}
pub {{.RustName}}: {{fieldRustType .}},
{{- end}}
}
{{- end}}
{{- /* Generate request/response types */ -}}
{{- range .Service.Methods}}
{{- if .HasParams}}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct {{requestType .}} {
{{- range .Params}}
{{.RustName}}: {{rustType .}},
{{- end}}
}
{{- end}}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct {{responseType .}} {
{{- range .Returns}}
#[serde(default)]
{{.RustName}}: {{rustType .}},
{{- end}}
{{- if .HasError}}
#[serde(default)]
error: Option<String>,
{{- end}}
}
{{- end}}
#[host_fn]
extern "ExtismHost" {
{{- range .Service.Methods}}
fn {{exportName .}}(input: Json<{{if .HasParams}}{{requestType .}}{{else}}serde_json::Value{{end}}>) -> Json<{{responseType .}}>;
{{- end}}
}
{{- /* Generate wrapper functions */ -}}
{{range .Service.Methods}}
{{if .Doc}}{{rustDocComment .Doc}}{{else}}/// Calls the {{exportName .}} host function.{{end}}
{{- if .HasParams}}
///
/// # Arguments
{{- range .Params}}
/// * `{{.RustName}}` - {{rustType .}} parameter.
{{- end}}
{{- end}}
{{- if .HasReturns}}
///
/// # Returns
{{- if .IsOptionPattern}}
/// `Some({{(index .Returns 0).RustName}})` if found, `None` otherwise.
{{- else if eq (len .Returns) 1}}
/// The {{(index .Returns 0).RustName}} value.
{{- else}}
/// A tuple of ({{range $i, $r := .Returns}}{{if $i}}, {{end}}{{$r.RustName}}{{end}}).
{{- end}}
{{- end}}
///
/// # Errors
/// Returns an error if the host function call fails.
{{- if .IsOptionPattern}}
pub fn {{rustFunc .}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.RustName}}: {{rustParamType $p}}{{end}}) -> Result<Option<{{rustType (index .Returns 0)}}>, Error> {
let response = unsafe {
{{- if .HasParams}}
{{exportName .}}(Json({{requestType .}} {
{{- range .Params}}
{{.RustName}}: {{.RustName}}{{if .NeedsToOwned}}.to_owned(){{end}},
{{- end}}
}))?
{{- else}}
{{exportName .}}(Json(serde_json::json!({})))?
{{- end}}
};
{{if .HasError}}
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
{{end}}
if response.0.{{(index .Returns 1).RustName}} {
Ok(Some(response.0.{{(index .Returns 0).RustName}}))
} else {
Ok(None)
}
}
{{- else}}
pub fn {{rustFunc .}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.RustName}}: {{rustParamType $p}}{{end}}) -> Result<{{if eq (len .Returns) 0}}(){{else if eq (len .Returns) 1}}{{rustType (index .Returns 0)}}{{else}}({{range $i, $r := .Returns}}{{if $i}}, {{end}}{{rustType $r}}{{end}}){{end}}, Error> {
let response = unsafe {
{{- if .HasParams}}
{{exportName .}}(Json({{requestType .}} {
{{- range .Params}}
{{.RustName}}: {{.RustName}}{{if .NeedsToOwned}}.to_owned(){{end}},
{{- end}}
}))?
{{- else}}
{{exportName .}}(Json(serde_json::json!({})))?
{{- end}}
};
{{if .HasError}}
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
{{end}}
{{- if eq (len .Returns) 0}}
Ok(())
{{- else if eq (len .Returns) 1}}
Ok(response.0.{{(index .Returns 0).RustName}})
{{- else}}
Ok(({{range $i, $r := .Returns}}{{if $i}}, {{end}}response.0.{{$r.RustName}}{{end}}))
{{- end}}
}
{{- end}}
{{- end}}
@@ -0,0 +1,50 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains mock implementations for non-WASM builds.
// These mocks allow IDE support, compilation, and unit testing on non-WASM platforms.
// Plugin authors can use the exported mock instances to set expectations in tests.
//
//go:build !wasip1
package {{.Package}}
import "github.com/stretchr/testify/mock"
{{- /* Generate struct definitions (same as main file, needed for type references in function signatures) */ -}}
{{- range .Service.Structs}}
// {{.Name}} represents the {{.Name}} data structure.
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
type {{.Name}} struct {
{{- range .Fields}}
{{.Name}} {{.Type}} `json:"{{.JSONTag}}"`
{{- end}}
}
{{- end}}
// mock{{.Service.Name}}Service is the mock implementation for testing.
type mock{{.Service.Name}}Service struct {
mock.Mock
}
// {{.Service.Name}}Mock is the auto-instantiated mock instance for testing.
// Use this to set expectations: host.{{.Service.Name}}Mock.On("MethodName", args...).Return(values...)
var {{.Service.Name}}Mock = &mock{{.Service.Name}}Service{}
{{range .Service.Methods}}
// {{.Name}} is the mock method for {{$.Service.Name}}{{.Name}}.
func (m *mock{{$.Service.Name}}Service) {{.Name}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}} {{$p.Type}}{{end}}) {{.ReturnSignature}} {
args := m.Called({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}}{{end}})
return {{mockReturnValues .}}
}
// {{$.Service.Name}}{{.Name}} delegates to the mock instance.
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
func {{$.Service.Name}}{{.Name}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}} {{$p.Type}}{{end}}) {{.ReturnSignature}} {
return {{$.Service.Name}}Mock.{{.Name}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}}{{end}})
}
{{- end}}
@@ -0,0 +1,49 @@
// Code generated by ndpgen. DO NOT EDIT.
/*
Package {{.Package}} provides Navidrome Plugin Development Kit wrappers for Go/TinyGo plugins.
This package is auto-generated by the ndpgen tool and should not be edited manually.
# Usage
Add this module as a dependency in your plugin's go.mod:
require github.com/navidrome/navidrome/plugins/pdk/go/host v0.0.0
Then import the package in your plugin code:
import {{.Package}} "github.com/navidrome/navidrome/plugins/pdk/go/host"
func myPluginFunction() error {
// Use the cache service
_, err := {{.Package}}.CacheSetString("my_key", "my_value", 3600)
if err != nil {
return err
}
// Schedule a recurring task
_, err = {{.Package}}.SchedulerScheduleRecurring("@every 5m", "payload", "task_id")
if err != nil {
return err
}
return nil
}
# Available Services
The following host services are available:
{{range .Services}}
- {{.Name}}: {{if .Doc}}{{.Doc | firstLine}}{{else}}{{.Name}} service{{end}}
{{- end}}
# Building Plugins
Go plugins must be compiled to WebAssembly using TinyGo:
tinygo build -o plugin.wasm -target=wasip1 -buildmode=c-shared .
See the examples directory for complete plugin implementations.
*/
package {{.Package}}
@@ -0,0 +1,8 @@
module github.com/navidrome/navidrome/plugins/pdk/go
go 1.25
require (
github.com/extism/go-pdk v1.1.3
github.com/stretchr/testify v1.11.1
)
@@ -0,0 +1,121 @@
// Code generated by ndpgen. DO NOT EDIT.
package {{.Package}}
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
)
{{- /* Generate request/response types for all methods */ -}}
{{range .Service.Methods}}
{{- if .HasParams}}
// {{requestType .}} is the request type for {{$.Service.Name}}.{{.Name}}.
type {{requestType .}} struct {
{{- range .Params}}
{{title .Name}} {{.Type}} `json:"{{.JSONName}}"`
{{- end}}
}
{{- end}}
// {{responseType .}} is the response type for {{$.Service.Name}}.{{.Name}}.
type {{responseType .}} struct {
{{- range .Returns}}
{{title .Name}} {{.Type}} `json:"{{.JSONName}},omitempty"`
{{- end}}
{{- if .HasError}}
Error string `json:"error,omitempty"`
{{- end}}
}
{{end}}
// Register{{.Service.Name}}HostFunctions registers {{.Service.Name}} service host functions.
// The returned host functions should be added to the plugin's configuration.
func Register{{.Service.Name}}HostFunctions(service {{.Service.Interface}}) []extism.HostFunction {
return []extism.HostFunction{
{{- range .Service.Methods}}
new{{$.Service.Name}}{{.Name}}HostFunction(service),
{{- end}}
}
}
{{range .Service.Methods}}
func new{{$.Service.Name}}{{.Name}}HostFunction(service {{$.Service.Interface}}) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"{{exportName .}}",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
{{- if .HasParams}}
// Read JSON request from plugin memory
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
{{$.Service.Name | lower}}WriteError(p, stack, err)
return
}
var req {{requestType .}}
if err := json.Unmarshal(reqBytes, &req); err != nil {
{{$.Service.Name | lower}}WriteError(p, stack, err)
return
}
{{- end}}
// Call the service method
{{- if .HasReturns}}
{{- if .HasError}}
{{range $i, $r := .Returns}}{{if $i}}, {{end}}{{lower $r.Name}}{{end}}, svcErr := service.{{.Name}}(ctx{{range .Params}}, req.{{title .Name}}{{end}})
if svcErr != nil {
{{$.Service.Name | lower}}WriteError(p, stack, svcErr)
return
}
{{- else}}
{{range $i, $r := .Returns}}{{if $i}}, {{end}}{{lower $r.Name}}{{end}} := service.{{.Name}}(ctx{{range .Params}}, req.{{title .Name}}{{end}})
{{- end}}
{{- else if .HasError}}
if svcErr := service.{{.Name}}(ctx{{range .Params}}, req.{{title .Name}}{{end}}); svcErr != nil {
{{$.Service.Name | lower}}WriteError(p, stack, svcErr)
return
}
{{- else}}
service.{{.Name}}(ctx{{range .Params}}, req.{{title .Name}}{{end}})
{{- end}}
// Write JSON response to plugin memory
resp := {{responseType .}}{
{{- range .Returns}}
{{title .Name}}: {{lower .Name}},
{{- end}}
}
{{$.Service.Name | lower}}WriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
{{end}}
// {{.Service.Name | lower}}WriteResponse writes a JSON response to plugin memory.
func {{.Service.Name | lower}}WriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
{{.Service.Name | lower}}WriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
// {{.Service.Name | lower}}WriteError writes an error response to plugin memory.
func {{.Service.Name | lower}}WriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}
@@ -0,0 +1,47 @@
// Code generated by ndpgen. DO NOT EDIT.
//
//! Navidrome Host Function Wrappers for Rust Plugins
//!
//! This crate provides idiomatic Rust wrappers for all Navidrome host services.
//! It is auto-generated by the ndpgen tool and should not be edited manually.
//!
//! # Usage
//!
//! Add this crate as a dependency in your plugin's Cargo.toml:
//!
//! ```toml
//! [dependencies]
//! nd-host = { path = "../../host/rust" }
//! ```
//!
//! Then import the services you need:
//!
//! ```ignore
//! use nd_host::{cache, scheduler};
//!
//! fn my_plugin_function() -> Result<(), extism_pdk::Error> {
//! // Use the cache service
//! cache::set_string("my_key", "my_value", 3600)?;
//!
//! // Schedule a recurring task
//! scheduler::schedule_recurring("@every 5m", "payload", "task_id")?;
//!
//! Ok(())
//! }
//! ```
//!
//! # Available Services
//!
{{- range .Services}}
//! - [`{{.Name | lower}}`] - {{if .Doc}}{{.Doc | firstLine}}{{else}}{{.Name}} service{{end}}
{{- end}}
{{range .Services}}
#[doc(hidden)]
mod nd_host_{{.Name | lower}};
/// {{if .Doc}}{{.Doc | firstLine}}{{else}}{{.Name}} host service wrappers.{{end}}
pub mod {{.Name | lower}} {
pub use super::nd_host_{{.Name | lower}}::*;
}
{{end}}
// Re-export commonly used types from extism-pdk for convenience
pub use extism_pdk::Error;
@@ -0,0 +1,50 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains wrapper functions for the extism/go-pdk package.
// For WASM builds, it provides type aliases and function wrappers that delegate
// to the real extism/go-pdk package with zero overhead.
//
//go:build wasip1
package pdk
import (
extism "github.com/extism/go-pdk"
)
// Type aliases - zero overhead, full compatibility
{{- range .Types}}
type {{.Name}} = extism.{{.Name}}
{{- end}}
// Constants
{{- $prevType := ""}}
{{- range .Consts}}
{{- if ne .Type $prevType}}
{{- if ne $prevType ""}}
)
{{- end}}
const (
{{- end}}
{{.Name}} = extism.{{.Name}}
{{- $prevType = .Type}}
{{- end}}
{{- if ne $prevType ""}}
)
{{- end}}
// Functions
{{- range .Functions}}
{{- if .Doc}}
// {{.Name}} {{firstSentence .Doc}}
{{- end}}
func {{.Name}}({{paramList .Params}}){{returnList .Returns}} {
{{- if .Returns}}
return extism.{{.Name}}({{argList .Params}})
{{- else}}
extism.{{.Name}}({{argList .Params}})
{{- end}}
}
{{- end}}
@@ -0,0 +1,42 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains mock implementations for non-WASM builds.
// These mocks allow IDE support, compilation, and unit testing on non-WASM platforms.
// Plugin authors can use the exported PDKMock instance to set expectations in tests.
//
//go:build !wasip1
package pdk
import "github.com/stretchr/testify/mock"
// mockPDK is the mock implementation for testing PDK functions.
type mockPDK struct {
mock.Mock
}
// PDKMock is the auto-instantiated mock instance for testing.
// Use this to set expectations: pdk.PDKMock.On("GetConfig", "key").Return("value", true)
var PDKMock = &mockPDK{}
// ResetMock resets the mock to its initial state.
// Call this in test setup/teardown to ensure clean state between tests.
func ResetMock() {
PDKMock = &mockPDK{}
}
// Functions
{{- range .Functions}}
{{- if .Doc}}
// {{.Name}} {{firstSentence .Doc}}
{{- end}}
func {{.Name}}({{paramList .Params}}){{returnList .Returns}} {
{{- if .Returns}}
args := PDKMock.Called({{argList .Params}})
return {{mockReturns .Returns}}
{{- else}}
PDKMock.Called({{argList .Params}})
{{- end}}
}
{{- end}}
@@ -0,0 +1,192 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains type definitions for non-WASM builds.
// These types match the extism/go-pdk signatures to allow compilation and testing
// on native platforms without importing the WASM-only extism package.
//
//go:build !wasip1
package pdk
// LogLevel represents a logging level.
type LogLevel int
// Log level constants
const (
LogTrace LogLevel = iota
LogDebug
LogInfo
LogWarn
LogError
)
// HTTPMethod represents an HTTP method.
type HTTPMethod int32
// HTTP method constants
const (
MethodGet HTTPMethod = iota
MethodHead
MethodPost
MethodPut
MethodPatch
MethodDelete
MethodConnect
MethodOptions
MethodTrace
)
// String returns the string representation of the HTTP method.
func (m HTTPMethod) String() string {
switch m {
case MethodGet:
return "GET"
case MethodHead:
return "HEAD"
case MethodPost:
return "POST"
case MethodPut:
return "PUT"
case MethodPatch:
return "PATCH"
case MethodDelete:
return "DELETE"
case MethodConnect:
return "CONNECT"
case MethodOptions:
return "OPTIONS"
case MethodTrace:
return "TRACE"
default:
return "UNKNOWN"
}
}
// Memory represents memory allocated by (and shared with) the host.
// This is a stub implementation for non-WASM platforms.
type Memory struct {
offset uint64
length uint64
data []byte
}
// Offset returns the offset of the memory block.
func (m Memory) Offset() uint64 {
return m.offset
}
// Length returns the length of the memory block.
func (m Memory) Length() uint64 {
return m.length
}
// ReadBytes reads all bytes from the memory block.
func (m Memory) ReadBytes() []byte {
return m.data
}
// Load reads the memory block into the provided buffer.
func (m *Memory) Load(buffer []byte) {
copy(buffer, m.data)
}
// Store writes data to the memory block.
func (m *Memory) Store(data []byte) {
m.data = make([]byte, len(data))
copy(m.data, data)
m.length = uint64(len(data))
}
// Free frees the memory block.
func (m *Memory) Free() {
m.data = nil
m.length = 0
}
// NewStubMemory creates a new stub Memory for testing.
// This is a helper function not present in the real PDK.
func NewStubMemory(offset, length uint64, data []byte) Memory {
return Memory{
offset: offset,
length: length,
data: data,
}
}
// HTTPRequest represents an HTTP request sent by the host.
// This is a stub implementation for non-WASM platforms.
type HTTPRequest struct {
method HTTPMethod
url string
headers map[string]string
body []byte
}
// SetHeader sets an HTTP header key to value.
func (r *HTTPRequest) SetHeader(key string, value string) *HTTPRequest {
if r.headers == nil {
r.headers = make(map[string]string)
}
r.headers[key] = value
return r
}
// SetBody sets the HTTP request body.
func (r *HTTPRequest) SetBody(body []byte) *HTTPRequest {
r.body = body
return r
}
// Send sends the HTTP request and returns the response.
// In the stub implementation, this delegates to the mock.
func (r *HTTPRequest) Send() HTTPResponse {
args := PDKMock.Called(r)
return args.Get(0).(HTTPResponse)
}
// HTTPRequestMeta represents the metadata associated with an HTTP request.
type HTTPRequestMeta struct {
URL string `json:"url"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
}
// HTTPResponse represents an HTTP response returned from the host.
// This is a stub implementation for non-WASM platforms.
type HTTPResponse struct {
status uint16
headers map[string]string
body []byte
memory Memory
}
// Status returns the status code from the response.
func (r HTTPResponse) Status() uint16 {
return r.status
}
// Headers returns the HTTP response headers.
func (r *HTTPResponse) Headers() map[string]string {
return r.headers
}
// Body returns the body byte slice from the response.
func (r HTTPResponse) Body() []byte {
return r.body
}
// Memory returns the memory associated with the response.
func (r HTTPResponse) Memory() Memory {
return r.memory
}
// NewStubHTTPResponse creates a new stub HTTPResponse for testing.
// This is a helper function not present in the real PDK.
func NewStubHTTPResponse(status uint16, headers map[string]string, body []byte) HTTPResponse {
return HTTPResponse{
status: status,
headers: headers,
body: body,
memory: NewStubMemory(0, uint64(len(body)), body),
}
}
+621
View File
@@ -0,0 +1,621 @@
package internal
import (
"strings"
"unicode"
)
// Service represents a parsed host service interface.
type Service struct {
Name string // Service name from annotation (e.g., "SubsonicAPI")
Permission string // Manifest permission key (e.g., "subsonicapi")
Interface string // Go interface name (e.g., "SubsonicAPIService")
Methods []Method // Methods marked with //nd:hostfunc
Doc string // Documentation comment for the service
Structs []StructDef // Structs used by this service
}
// Capability represents a parsed capability interface for plugin exports.
type Capability struct {
Name string // Package name from annotation (e.g., "metadata")
Interface string // Go interface name (e.g., "MetadataAgent")
Required bool // If true, all methods must be implemented
Methods []Export // Methods marked with //nd:export
Doc string // Documentation comment for the capability
Structs []StructDef // Structs used by this capability
TypeAliases []TypeAlias // Type aliases used by this capability
Consts []ConstGroup // Const groups used by this capability
SourceFile string // Base name of source file without extension (e.g., "websocket_callback")
}
// TypeAlias represents a type alias definition (e.g., type ScrobblerErrorType string).
type TypeAlias struct {
Name string // Type name
Type string // Underlying type
Doc string // Documentation comment
}
// ConstGroup represents a group of const definitions.
type ConstGroup struct {
Type string // Type name for typed consts (empty for untyped)
Values []ConstDef // Const definitions
}
// ConstDef represents a single const definition.
type ConstDef struct {
Name string // Const name
Value string // Const value
Doc string // Documentation comment
}
// KnownStructs returns a map of struct names defined in this capability.
func (c Capability) KnownStructs() map[string]bool {
result := make(map[string]bool)
for _, st := range c.Structs {
result[st.Name] = true
}
return result
}
// Export represents an exported WASM function within a capability.
type Export struct {
Name string // Go method name (e.g., "GetArtistBiography")
ExportName string // WASM export name (e.g., "nd_get_artist_biography")
Input Param // Single input parameter (the struct type)
Output Param // Single output return value (the struct type)
Doc string // Documentation comment for the method
}
// ProviderInterfaceName returns the optional provider interface name.
// For a method "GetArtistBiography", returns "ArtistBiographyProvider".
func (e Export) ProviderInterfaceName() string {
// Remove "Get", "On", etc. prefixes and add "Provider" suffix
name := e.Name
for _, prefix := range []string{"Get", "On"} {
if strings.HasPrefix(name, prefix) {
name = name[len(prefix):]
break
}
}
return name + "Provider"
}
// ImplVarName returns the internal implementation variable name.
// For "GetArtistBiography", returns "artistBiographyImpl".
func (e Export) ImplVarName() string {
name := e.Name
for _, prefix := range []string{"Get", "On"} {
if strings.HasPrefix(name, prefix) {
name = name[len(prefix):]
break
}
}
// Convert to camelCase
if len(name) > 0 {
name = strings.ToLower(string(name[0])) + name[1:]
}
return name + "Impl"
}
// ExportFuncName returns the unexported WASM export function name.
// For "nd_get_artist_biography", returns "_ndGetArtistBiography".
func (e Export) ExportFuncName() string {
// Convert snake_case to PascalCase
parts := strings.Split(e.ExportName, "_")
var result strings.Builder
result.WriteString("_")
for _, part := range parts {
if len(part) > 0 {
result.WriteString(strings.ToUpper(string(part[0])))
result.WriteString(part[1:])
}
}
return result.String()
}
// HasInput returns true if the method has an input parameter.
func (e Export) HasInput() bool {
return e.Input.Type != ""
}
// HasOutput returns true if the method has a non-error return value.
func (e Export) HasOutput() bool {
return e.Output.Type != ""
}
// IsPointerOutput returns true if the output type is a pointer.
func (e Export) IsPointerOutput() bool {
return strings.HasPrefix(e.Output.Type, "*")
}
// StructDef represents a Go struct type definition.
type StructDef struct {
Name string // Go struct name (e.g., "Library")
Fields []FieldDef // Struct fields
Doc string // Documentation comment
}
// FieldDef represents a field within a struct.
type FieldDef struct {
Name string // Go field name (e.g., "TotalSongs")
Type string // Go type (e.g., "int32", "*string", "[]User")
JSONTag string // JSON tag value (e.g., "totalSongs,omitempty")
OmitEmpty bool // Whether the field has omitempty tag
Doc string // Field documentation
}
// OutputFileName returns the generated file name for this service.
func (s Service) OutputFileName() string {
return strings.ToLower(s.Name) + "_gen.go"
}
// ExportPrefix returns the prefix for exported host function names.
func (s Service) ExportPrefix() string {
return strings.ToLower(s.Name)
}
// KnownStructs returns a map of struct names defined in this service.
func (s Service) KnownStructs() map[string]bool {
result := make(map[string]bool)
for _, st := range s.Structs {
result[st.Name] = true
}
return result
}
// HasErrors returns true if any method in the service returns an error.
func (s Service) HasErrors() bool {
for _, m := range s.Methods {
if m.HasError {
return true
}
}
return false
}
// Method represents a host function method within a service.
type Method struct {
Name string // Go method name (e.g., "Call")
ExportName string // Optional override for export name
Params []Param // Method parameters (excluding context.Context)
Returns []Param // Return values (excluding error)
HasError bool // Whether the method returns an error
Doc string // Documentation comment for the method
}
// FunctionName returns the Extism host function export name.
func (m Method) FunctionName(servicePrefix string) string {
if m.ExportName != "" {
return m.ExportName
}
return servicePrefix + "_" + strings.ToLower(m.Name)
}
// RequestTypeName returns the generated request type name (public, for host-side code).
func (m Method) RequestTypeName(serviceName string) string {
return serviceName + m.Name + "Request"
}
// ResponseTypeName returns the generated response type name (public, for host-side code).
func (m Method) ResponseTypeName(serviceName string) string {
return serviceName + m.Name + "Response"
}
// ClientRequestTypeName returns the generated request type name (private, for client/PDK code).
func (m Method) ClientRequestTypeName(serviceName string) string {
return lowerFirst(serviceName) + m.Name + "Request"
}
// ClientResponseTypeName returns the generated response type name (private, for client/PDK code).
func (m Method) ClientResponseTypeName(serviceName string) string {
return lowerFirst(serviceName) + m.Name + "Response"
}
// lowerFirst returns the string with the first letter lowercased.
func lowerFirst(s string) string {
if s == "" {
return s
}
r := []rune(s)
r[0] = unicode.ToLower(r[0])
return string(r)
}
// HasParams returns true if the method has input parameters.
func (m Method) HasParams() bool {
return len(m.Params) > 0
}
// HasReturns returns true if the method has return values (excluding error).
func (m Method) HasReturns() bool {
return len(m.Returns) > 0
}
// IsErrorOnly returns true if the method only returns an error (no data fields).
func (m Method) IsErrorOnly() bool {
return m.HasError && !m.HasReturns()
}
// IsSingleReturn returns true if the method has exactly one return value (excluding error).
func (m Method) IsSingleReturn() bool {
return len(m.Returns) == 1
}
// IsMultiReturn returns true if the method has multiple return values (excluding error).
func (m Method) IsMultiReturn() bool {
return len(m.Returns) > 1
}
// IsOptionPattern returns true if the method returns (value, bool) where the bool
// indicates existence (named "exists", "ok", or "found"). This pattern is used to
// generate Option<T> in Rust instead of a tuple.
func (m Method) IsOptionPattern() bool {
if len(m.Returns) != 2 {
return false
}
if m.Returns[1].Type != "bool" {
return false
}
// Only treat as option pattern if the first return has a meaningful value type
// (not just a bool check like Has())
if m.Returns[0].Type == "bool" {
return false
}
name := strings.ToLower(m.Returns[1].Name)
return name == "exists" || name == "ok" || name == "found"
}
// ReturnSignature returns the Go return type signature for the wrapper function.
// For error-only: "error"
// For single return with error: "(Type, error)"
// For single return no error: "Type"
// For multi return: "(Type1, Type2, ..., error)"
func (m Method) ReturnSignature() string {
if m.IsErrorOnly() {
return "error"
}
var parts []string
for _, r := range m.Returns {
parts = append(parts, r.Type)
}
if m.HasError {
parts = append(parts, "error")
}
// Single return without error doesn't need parentheses
if len(parts) == 1 {
return parts[0]
}
return "(" + strings.Join(parts, ", ") + ")"
}
// ZeroValues returns the zero value expressions for all return types (excluding error).
// Used for error return statements like "return "", false, err".
func (m Method) ZeroValues() string {
var zeros []string
for _, r := range m.Returns {
zeros = append(zeros, zeroValue(r.Type))
}
return strings.Join(zeros, ", ")
}
// zeroValue returns the zero value for a Go type.
func zeroValue(typ string) string {
switch {
case typ == "string":
return `""`
case typ == "bool":
return "false"
case typ == "int", typ == "int8", typ == "int16", typ == "int32", typ == "int64",
typ == "uint", typ == "uint8", typ == "uint16", typ == "uint32", typ == "uint64",
typ == "float32", typ == "float64":
return "0"
case typ == "[]byte":
return "nil"
case strings.HasPrefix(typ, "[]"):
return "nil"
case strings.HasPrefix(typ, "map["):
return "nil"
case strings.HasPrefix(typ, "*"):
return "nil"
case typ == "any", typ == "interface{}":
return "nil"
default:
// For custom struct types, return empty struct
return typ + "{}"
}
}
// Param represents a method parameter or return value.
type Param struct {
Name string // Parameter name
Type string // Go type (e.g., "string", "int32", "[]byte")
JSONName string // JSON field name (camelCase)
}
// NewParam creates a Param with auto-generated JSON name.
func NewParam(name, typ string) Param {
return Param{
Name: name,
Type: typ,
JSONName: toJSONName(name),
}
}
// toJSONName converts a Go identifier to camelCase JSON field name.
// This matches Rust serde's rename_all = "camelCase" behavior.
// Examples: "ConnectionID" -> "connectionId", "NewConnectionID" -> "newConnectionId"
func toJSONName(name string) string {
if name == "" {
return ""
}
runes := []rune(name)
result := make([]rune, 0, len(runes))
for i, r := range runes {
if i == 0 {
// First character is always lowercase
result = append(result, unicode.ToLower(r))
} else if unicode.IsUpper(r) {
// Check if this is part of an acronym (consecutive uppercase)
// or a word boundary
prevIsUpper := unicode.IsUpper(runes[i-1])
nextIsLower := i+1 < len(runes) && unicode.IsLower(runes[i+1])
if prevIsUpper && !nextIsLower {
// Middle of an acronym - lowercase it
result = append(result, unicode.ToLower(r))
} else if prevIsUpper && nextIsLower {
// End of acronym followed by lowercase - this starts a new word
// Keep uppercase
result = append(result, r)
} else {
// Regular word boundary - keep uppercase
result = append(result, r)
}
} else {
result = append(result, r)
}
}
return string(result)
}
// ToPythonType converts a Go type to its Python equivalent.
func ToPythonType(goType string) string {
switch goType {
case "string":
return "str"
case "int", "int32", "int64":
return "int"
case "float32", "float64":
return "float"
case "bool":
return "bool"
case "[]byte":
return "bytes"
default:
return "Any"
}
}
// ToSnakeCase converts a PascalCase or camelCase string to snake_case.
// It handles consecutive uppercase letters correctly (e.g., "ScheduleID" -> "schedule_id").
func ToSnakeCase(s string) string {
var result strings.Builder
runes := []rune(s)
for i, r := range runes {
if i > 0 && r >= 'A' && r <= 'Z' {
// Add underscore before uppercase, but not if:
// - Previous char was uppercase AND next char is uppercase or end of string
// (this handles acronyms like "ID" in "NewScheduleID")
prevUpper := runes[i-1] >= 'A' && runes[i-1] <= 'Z'
nextUpper := i+1 < len(runes) && runes[i+1] >= 'A' && runes[i+1] <= 'Z'
atEnd := i+1 == len(runes)
// Only skip underscore if we're in the middle of an acronym
if !prevUpper || (!nextUpper && !atEnd) {
result.WriteByte('_')
}
}
result.WriteRune(r)
}
return strings.ToLower(result.String())
}
// PythonFunctionName returns the Python function name for a method.
func (m Method) PythonFunctionName(servicePrefix string) string {
return ToSnakeCase(servicePrefix + m.Name)
}
// PythonResultTypeName returns the Python dataclass name for multi-value returns.
func (m Method) PythonResultTypeName(serviceName string) string {
return serviceName + m.Name + "Result"
}
// NeedsResultClass returns true if the method needs a dataclass for returns.
func (m Method) NeedsResultClass() bool {
return len(m.Returns) > 1
}
// PythonType returns the Python type for this parameter.
func (p Param) PythonType() string {
return ToPythonType(p.Type)
}
// PythonName returns the snake_case Python name for this parameter.
func (p Param) PythonName() string {
return ToSnakeCase(p.Name)
}
// ToRustType converts a Go type to its Rust equivalent.
func ToRustType(goType string) string {
return ToRustTypeWithStructs(goType, nil)
}
// RustParamType returns the Rust type for a function parameter (uses &str for strings).
func RustParamType(goType string) string {
if goType == "string" {
return "&str"
}
return ToRustType(goType)
}
// RustDefaultValue returns the default value for a Rust type.
func RustDefaultValue(goType string) string {
switch goType {
case "string":
return `String::new()`
case "int", "int32":
return "0"
case "int64":
return "0"
case "float32", "float64":
return "0.0"
case "bool":
return "false"
default:
if strings.HasPrefix(goType, "[]") {
return "Vec::new()"
}
if strings.HasPrefix(goType, "map[") {
return "std::collections::HashMap::new()"
}
if strings.HasPrefix(goType, "*") {
return "None"
}
return "serde_json::Value::Null"
}
}
// RustFunctionName returns the Rust function name for a method (snake_case).
// Uses just the method name without service prefix since the module provides namespacing.
func (m Method) RustFunctionName(_ string) string {
return ToSnakeCase(m.Name)
}
// RustDocComment returns a properly formatted Rust doc comment.
// Each line of the input doc string is prefixed with "/// ".
func RustDocComment(doc string) string {
if doc == "" {
return ""
}
lines := strings.Split(doc, "\n")
var result []string
for _, line := range lines {
result = append(result, "/// "+line)
}
return strings.Join(result, "\n")
}
// RustType returns the Rust type for this parameter.
func (p Param) RustType() string {
return ToRustType(p.Type)
}
// RustTypeWithStructs returns the Rust type using known struct names.
func (p Param) RustTypeWithStructs(knownStructs map[string]bool) string {
return ToRustTypeWithStructs(p.Type, knownStructs)
}
// RustParamType returns the Rust type for this parameter when used as a function argument.
func (p Param) RustParamType() string {
return RustParamType(p.Type)
}
// RustParamTypeWithStructs returns the Rust param type using known struct names.
func (p Param) RustParamTypeWithStructs(knownStructs map[string]bool) string {
if p.Type == "string" {
return "&str"
}
return ToRustTypeWithStructs(p.Type, knownStructs)
}
// RustName returns the snake_case Rust name for this parameter.
func (p Param) RustName() string {
return ToSnakeCase(p.Name)
}
// NeedsToOwned returns true if the parameter needs .to_owned() when used.
func (p Param) NeedsToOwned() bool {
return p.Type == "string"
}
// RustType returns the Rust type for this field, using known struct names.
func (f FieldDef) RustType(knownStructs map[string]bool) string {
return ToRustTypeWithStructs(f.Type, knownStructs)
}
// RustName returns the snake_case Rust name for this field.
func (f FieldDef) RustName() string {
return ToSnakeCase(f.Name)
}
// NeedsDefault returns true if the field needs #[serde(default)] attribute.
// This is true for fields with omitempty tag.
func (f FieldDef) NeedsDefault() bool {
return f.OmitEmpty
}
// ToRustTypeWithStructs converts a Go type to its Rust equivalent,
// using known struct names instead of serde_json::Value.
func ToRustTypeWithStructs(goType string, knownStructs map[string]bool) string {
// Handle pointer types
if strings.HasPrefix(goType, "*") {
inner := ToRustTypeWithStructs(goType[1:], knownStructs)
return "Option<" + inner + ">"
}
// Handle slice types
if strings.HasPrefix(goType, "[]") {
if goType == "[]byte" {
return "Vec<u8>"
}
inner := ToRustTypeWithStructs(goType[2:], knownStructs)
return "Vec<" + inner + ">"
}
// Handle map types
if strings.HasPrefix(goType, "map[") {
// Extract key and value types from map[K]V
rest := goType[4:] // Remove "map["
depth := 1
keyEnd := 0
for i, r := range rest {
if r == '[' {
depth++
} else if r == ']' {
depth--
if depth == 0 {
keyEnd = i
break
}
}
}
keyType := rest[:keyEnd]
valueType := rest[keyEnd+1:]
return "std::collections::HashMap<" + ToRustTypeWithStructs(keyType, knownStructs) + ", " + ToRustTypeWithStructs(valueType, knownStructs) + ">"
}
switch goType {
case "string":
return "String"
case "int", "int32":
return "i32"
case "int64":
return "i64"
case "float32":
return "f32"
case "float64":
return "f64"
case "bool":
return "bool"
case "interface{}", "any":
return "serde_json::Value"
default:
// Check if this is a known struct type
if knownStructs != nil && knownStructs[goType] {
return goType
}
// For unknown custom types, fall back to Value
return "serde_json::Value"
}
}
+327
View File
@@ -0,0 +1,327 @@
package internal
import (
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// XTP Schema types for YAML marshalling
type (
xtpSchema struct {
Version string `yaml:"version"`
Exports yaml.Node `yaml:"exports,omitempty"`
Components *xtpComponents `yaml:"components,omitempty"`
}
xtpComponents struct {
Schemas yaml.Node `yaml:"schemas"`
}
xtpExport struct {
Description string `yaml:"description,omitempty"`
Input *xtpIOParam `yaml:"input,omitempty"`
Output *xtpIOParam `yaml:"output,omitempty"`
}
xtpIOParam struct {
Ref string `yaml:"$ref,omitempty"`
Type string `yaml:"type,omitempty"`
ContentType string `yaml:"contentType"`
}
// xtpObjectSchema represents an object schema in XTP.
// Per the XTP JSON Schema, ObjectSchema has properties, required, and description
// but NOT a type field.
xtpObjectSchema struct {
Description string `yaml:"description,omitempty"`
Properties yaml.Node `yaml:"properties"`
Required []string `yaml:"required,omitempty"`
}
xtpEnumSchema struct {
Description string `yaml:"description,omitempty"`
Type string `yaml:"type"`
Enum []string `yaml:"enum"`
}
xtpProperty struct {
Ref string `yaml:"$ref,omitempty"`
Type string `yaml:"type,omitempty"`
Format string `yaml:"format,omitempty"`
Description string `yaml:"description,omitempty"`
Nullable bool `yaml:"nullable,omitempty"`
Items *xtpProperty `yaml:"items,omitempty"`
}
)
// GenerateSchema generates an XTP YAML schema from a capability.
func GenerateSchema(cap Capability) ([]byte, error) {
schema := xtpSchema{Version: "v1-draft"}
// Build exports as ordered map
if len(cap.Methods) > 0 {
schema.Exports = yaml.Node{Kind: yaml.MappingNode}
for _, export := range cap.Methods {
addToMap(&schema.Exports, export.ExportName, buildExport(export))
}
}
// Build components/schemas
schemas := buildSchemas(cap)
if len(schemas.Content) > 0 {
schema.Components = &xtpComponents{Schemas: schemas}
}
return yaml.Marshal(schema)
}
func buildExport(export Export) xtpExport {
e := xtpExport{Description: cleanDocForYAML(export.Doc)}
if export.Input.Type != "" {
e.Input = &xtpIOParam{
Ref: "#/components/schemas/" + strings.TrimPrefix(export.Input.Type, "*"),
ContentType: "application/json",
}
}
if export.Output.Type != "" {
outputType := strings.TrimPrefix(export.Output.Type, "*")
// Check if output is a primitive type
if isPrimitiveGoType(outputType) {
e.Output = &xtpIOParam{
Type: goTypeToXTPType(outputType),
ContentType: "application/json",
}
} else {
e.Output = &xtpIOParam{
Ref: "#/components/schemas/" + outputType,
ContentType: "application/json",
}
}
}
return e
}
// isPrimitiveGoType returns true if the Go type is a primitive type.
func isPrimitiveGoType(goType string) bool {
switch goType {
case "bool", "string", "int", "int32", "int64", "float32", "float64", "[]byte":
return true
}
return false
}
func buildSchemas(cap Capability) yaml.Node {
schemas := yaml.Node{Kind: yaml.MappingNode}
knownTypes := cap.KnownStructs()
for _, alias := range cap.TypeAliases {
knownTypes[alias.Name] = true
}
// Collect types that are actually used by exports
usedTypes := collectUsedTypes(cap, knownTypes)
// Sort structs by name for consistent output
structNames := make([]string, 0, len(cap.Structs))
structMap := make(map[string]StructDef)
for _, st := range cap.Structs {
if usedTypes[st.Name] {
structNames = append(structNames, st.Name)
structMap[st.Name] = st
}
}
sort.Strings(structNames)
for _, name := range structNames {
st := structMap[name]
addToMap(&schemas, name, buildObjectSchema(st, knownTypes))
}
// Build enum types from type aliases (only if used by exports)
for _, alias := range cap.TypeAliases {
if !usedTypes[alias.Name] {
continue
}
if alias.Type == "string" {
for _, cg := range cap.Consts {
if cg.Type == alias.Name {
addToMap(&schemas, alias.Name, buildEnumSchema(alias, cg))
break
}
}
}
}
return schemas
}
// collectUsedTypes returns a set of type names that are reachable from exports.
func collectUsedTypes(cap Capability, knownTypes map[string]bool) map[string]bool {
used := make(map[string]bool)
// Start with types directly referenced by exports
for _, export := range cap.Methods {
if export.Input.Type != "" {
addTypeAndDeps(strings.TrimPrefix(export.Input.Type, "*"), cap, knownTypes, used)
}
if export.Output.Type != "" {
outputType := strings.TrimPrefix(export.Output.Type, "*")
if !isPrimitiveGoType(outputType) {
addTypeAndDeps(outputType, cap, knownTypes, used)
}
}
}
return used
}
// addTypeAndDeps adds a type and all its dependencies to the used set.
func addTypeAndDeps(typeName string, cap Capability, knownTypes map[string]bool, used map[string]bool) {
if used[typeName] || !knownTypes[typeName] {
return
}
used[typeName] = true
// Find the struct and add its field types
for _, st := range cap.Structs {
if st.Name == typeName {
for _, field := range st.Fields {
fieldType := strings.TrimPrefix(field.Type, "*")
fieldType = strings.TrimPrefix(fieldType, "[]")
if knownTypes[fieldType] {
addTypeAndDeps(fieldType, cap, knownTypes, used)
}
}
return
}
}
}
func buildObjectSchema(st StructDef, knownTypes map[string]bool) xtpObjectSchema {
schema := xtpObjectSchema{
Description: cleanDocForYAML(st.Doc),
Properties: yaml.Node{Kind: yaml.MappingNode},
}
for _, field := range st.Fields {
propName := getJSONFieldName(field)
addToMap(&schema.Properties, propName, buildProperty(field, knownTypes))
if !strings.HasPrefix(field.Type, "*") && !field.OmitEmpty {
schema.Required = append(schema.Required, propName)
}
}
return schema
}
func buildEnumSchema(alias TypeAlias, cg ConstGroup) xtpEnumSchema {
values := make([]string, 0, len(cg.Values))
for _, cv := range cg.Values {
values = append(values, strings.Trim(cv.Value, `"`))
}
return xtpEnumSchema{
Description: cleanDocForYAML(alias.Doc),
Type: "string",
Enum: values,
}
}
func buildProperty(field FieldDef, knownTypes map[string]bool) xtpProperty {
goType := field.Type
isPointer := strings.HasPrefix(goType, "*")
if isPointer {
goType = goType[1:]
}
prop := xtpProperty{
Description: cleanDocForYAML(field.Doc),
Nullable: isPointer,
}
// Handle reference types (use $ref instead of type)
if isKnownType(goType, knownTypes) && !strings.HasPrefix(goType, "[]") {
prop.Ref = "#/components/schemas/" + goType
return prop
}
// Handle slice types
if strings.HasPrefix(goType, "[]") {
elemType := goType[2:]
prop.Type = "array"
prop.Items = &xtpProperty{}
if isKnownType(elemType, knownTypes) {
prop.Items.Ref = "#/components/schemas/" + elemType
} else {
prop.Items.Type = goTypeToXTPType(elemType)
}
return prop
}
// Handle primitive types
prop.Type, prop.Format = goTypeToXTPTypeAndFormat(goType)
return prop
}
// addToMap adds a key-value pair to a yaml.Node map, preserving insertion order.
func addToMap[T any](node *yaml.Node, key string, value T) {
var valNode yaml.Node
_ = valNode.Encode(value)
node.Content = append(node.Content, &yaml.Node{Kind: yaml.ScalarNode, Value: key}, &valNode)
}
func getJSONFieldName(field FieldDef) string {
propName := field.JSONTag
if idx := strings.Index(propName, ","); idx >= 0 {
propName = propName[:idx]
}
if propName == "" {
propName = field.Name
}
return propName
}
// isKnownType checks if a type is a known struct or type alias.
func isKnownType(typeName string, knownTypes map[string]bool) bool {
return knownTypes[typeName]
}
// goTypeToXTPType converts a Go type to an XTP schema type.
func goTypeToXTPType(goType string) string {
typ, _ := goTypeToXTPTypeAndFormat(goType)
return typ
}
// goTypeToXTPTypeAndFormat converts a Go type to XTP type and format.
func goTypeToXTPTypeAndFormat(goType string) (typ, format string) {
switch goType {
case "string":
return "string", ""
case "int", "int32":
return "integer", "int32"
case "int64":
return "integer", "int64"
case "float32":
return "number", "float"
case "float64":
return "number", "float"
case "bool":
return "boolean", ""
case "[]byte":
return "string", "byte"
default:
return "object", ""
}
}
// cleanDocForYAML cleans documentation for YAML output.
func cleanDocForYAML(doc string) string {
doc = strings.TrimSpace(doc)
// Remove leading "// " from each line if present
lines := strings.Split(doc, "\n")
for i, line := range lines {
lines[i] = strings.TrimPrefix(strings.TrimSpace(line), "// ")
}
return strings.TrimSpace(strings.Join(lines, "\n"))
}
+549
View File
@@ -0,0 +1,549 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"version": {
"$ref": "#/$defs/XtpVersion"
}
},
"required": [
"version"
],
"allOf": [
{
"if": {
"properties": {
"version": {
"const": "v0"
}
}
},
"then": {
"properties": {
"exports": {
"type": "array",
"items": {
"type": "string",
"pattern": "^[a-zA-Z_$][a-zA-Z0-9_$]*$"
}
},
"version": {
"const": "v0"
}
},
"required": [
"exports"
],
"additionalProperties": false
}
},
{
"if": {
"properties": {
"version": {
"const": "v1-draft"
}
}
},
"then": {
"properties": {
"version": {
"$ref": "#/$defs/XtpVersion"
},
"exports": {
"type": "object",
"patternProperties": {
"^[a-zA-Z_$][a-zA-Z0-9_$]*$": {
"$ref": "#/$defs/Export"
}
},
"additionalProperties": false
},
"imports": {
"type": "object",
"patternProperties": {
"^[a-zA-Z_$][a-zA-Z0-9_$]*$": {
"$ref": "#/$defs/Import"
}
},
"additionalProperties": false
},
"components": {
"type": "object",
"properties": {
"schemas": {
"type": "object",
"patternProperties": {
"^[a-zA-Z_$][a-zA-Z0-9_$]*$": {
"$ref": "#/$defs/Schema"
}
},
"additionalProperties": false
}
},
"required": [
"schemas"
],
"additionalProperties": false
}
},
"required": [
"exports"
],
"additionalProperties": false
}
}
],
"$defs": {
"XtpVersion": {
"type": "string",
"enum": [
"v0",
"v1-draft"
]
},
"Export": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"codeSamples": {
"type": "array",
"items": {
"$ref": "#/$defs/CodeSample"
}
},
"input": {
"$ref": "#/$defs/Parameter"
},
"output": {
"$ref": "#/$defs/Parameter"
}
},
"additionalProperties": false
},
"CodeSample": {
"type": "object",
"properties": {
"lang": {
"anyOf": [
{
"type": "string",
"enum": [
"typescript",
"csharp",
"zig",
"rust",
"go",
"python",
"c++"
]
},
{
"type": "string"
}
]
},
"source": {
"type": "string"
},
"label": {
"type": "string"
}
},
"required": [
"lang",
"source"
],
"additionalProperties": false
},
"Import": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"input": {
"$ref": "#/$defs/Parameter"
},
"output": {
"$ref": "#/$defs/Parameter"
}
},
"additionalProperties": false
},
"Schema": {
"oneOf": [
{
"$ref": "#/$defs/ObjectSchema"
},
{
"$ref": "#/$defs/EnumSchema"
}
]
},
"ObjectSchema": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"properties": {
"type": "object",
"patternProperties": {
"^[a-zA-Z_$][a-zA-Z0-9_$]*$": {
"$ref": "#/$defs/Property"
}
},
"additionalProperties": false
},
"required": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"properties"
],
"additionalProperties": false
},
"EnumSchema": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"string"
]
},
"description": {
"type": "string"
},
"enum": {
"type": "array",
"items": {
"type": "string",
"pattern": "^[a-zA-Z_$][a-zA-Z0-9_$]*$"
}
}
},
"required": [
"enum"
],
"additionalProperties": false
},
"Parameter": {
"oneOf": [
{
"$ref": "#/$defs/ValueParameter"
},
{
"$ref": "#/$defs/RefParameter"
},
{
"$ref": "#/$defs/MapParameter"
}
]
},
"RefParameter": {
"type": "object",
"properties": {
"$ref": {
"$ref": "#/$defs/SchemaReference"
},
"description": {
"type": "string"
},
"nullable": {
"type": "boolean",
"default": false
},
"contentType": {
"$ref": "#/$defs/ContentType"
}
},
"required": [
"$ref",
"contentType"
],
"additionalProperties": false
},
"ValueParameter": {
"type": "object",
"properties": {
"contentType": {
"$ref": "#/$defs/ContentType"
},
"type": {
"$ref": "#/$defs/XtpType"
},
"format": {
"$ref": "#/$defs/XtpFormat"
},
"nullable": {
"type": "boolean",
"default": false
},
"description": {
"type": "string"
},
"items": {
"type": "object",
"$ref": "#/$defs/ArrayItem"
}
},
"required": [
"type",
"contentType"
],
"additionalProperties": false
},
"MapParameter": {
"type": "object",
"properties": {
"type": {
"const": "object"
},
"description": {
"type": "string"
},
"additionalProperties": {
"allOf": [
{
"$ref": "#/$defs/NonMapProperty"
},
{
"type": "object",
"properties": {
"description": false
},
"additionalProperties": false
}
]
},
"nullable": {
"type": "boolean",
"default": false
},
"contentType": {
"$ref": "#/$defs/ContentType"
}
},
"required": [
"additionalProperties",
"contentType"
]
},
"NonMapProperty": {
"oneOf": [
{
"$ref": "#/$defs/ValueProperty"
},
{
"$ref": "#/$defs/RefProperty"
}
]
},
"Property": {
"oneOf": [
{
"$ref": "#/$defs/ValueProperty"
},
{
"$ref": "#/$defs/RefProperty"
},
{
"$ref": "#/$defs/MapProperty"
}
]
},
"ValueProperty": {
"type": "object",
"properties": {
"type": {
"$ref": "#/$defs/XtpType"
},
"format": {
"$ref": "#/$defs/XtpFormat"
},
"nullable": {
"type": "boolean",
"default": false
},
"description": {
"type": "string"
},
"items": {
"type": "object",
"$ref": "#/$defs/ArrayItem"
}
},
"required": [
"type"
],
"additionalProperties": false
},
"MapProperty": {
"type": "object",
"properties": {
"type": {
"const": "object"
},
"description": {
"type": "string"
},
"additionalProperties": {
"allOf": [
{
"$ref": "#/$defs/NonMapProperty"
},
{
"not": {
"type": "object",
"required": ["description"]
}
}
]
},
"nullable": {
"type": "boolean",
"default": false
}
},
"required": [
"additionalProperties"
],
"additionalProperties": false
},
"RefProperty": {
"type": "object",
"properties": {
"$ref": {
"$ref": "#/$defs/SchemaReference"
},
"description": {
"type": "string"
},
"nullable": {
"type": "boolean",
"default": false
}
},
"required": [
"$ref"
],
"additionalProperties": false
},
"ContentType": {
"type": "string",
"enum": [
"application/json",
"application/x-binary",
"text/plain; charset=utf-8"
]
},
"SchemaReference": {
"type": "string",
"pattern": "^#/components/schemas/[^/]+$"
},
"XtpType": {
"type": "string",
"enum": [
"integer",
"string",
"number",
"boolean",
"object",
"array",
"buffer"
]
},
"XtpFormat": {
"type": "string",
"enum": [
"int32",
"int64",
"float",
"double",
"date-time",
"byte"
]
},
"ArrayItem": {
"type": "object",
"oneOf": [
{
"$ref": "#/$defs/ValueArrayItem"
},
{
"$ref": "#/$defs/RefArrayItem"
},
{
"$ref": "#/$defs/MapArrayItem"
}
]
},
"ValueArrayItem": {
"type": "object",
"properties": {
"type": {
"$ref": "#/$defs/XtpType"
},
"format": {
"$ref": "#/$defs/XtpFormat"
},
"nullable": {
"type": "boolean"
}
},
"required": [
"type"
],
"additionalProperties": false
},
"RefArrayItem": {
"type": "object",
"properties": {
"$ref": {
"$ref": "#/$defs/SchemaReference"
},
"nullable": {
"type": "boolean",
"default": false
}
},
"required": [
"$ref"
],
"additionalProperties": false
},
"MapArrayItem": {
"type": "object",
"properties": {
"type": {
"const": "object"
},
"additionalProperties": {
"allOf": [
{
"$ref": "#/$defs/NonMapProperty"
},
{
"not": {
"type": "object",
"required": ["description"]
}
}
]
}
},
"required": [
"additionalProperties"
],
"additionalProperties": false
}
}
}
@@ -0,0 +1,722 @@
package internal
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"gopkg.in/yaml.v3"
)
var _ = Describe("XTP Schema Generation", func() {
parseSchema := func(schema []byte) map[string]any {
var doc map[string]any
Expect(yaml.Unmarshal(schema, &doc)).To(Succeed())
return doc
}
Describe("GenerateSchema", func() {
Context("basic capability with one export", func() {
var schema []byte
BeforeEach(func() {
capability := Capability{
Name: "test",
Doc: "Test capability",
SourceFile: "test",
Methods: []Export{
{
ExportName: "test_method",
Doc: "Test method does something",
Input: NewParam("input", "TestInput"),
Output: NewParam("output", "TestOutput"),
},
},
Structs: []StructDef{
{
Name: "TestInput",
Doc: "Input for test",
Fields: []FieldDef{
{Name: "Name", Type: "string", JSONTag: "name", Doc: "The name"},
{Name: "Count", Type: "int", JSONTag: "count", Doc: "The count"},
},
},
{
Name: "TestOutput",
Doc: "Output for test",
Fields: []FieldDef{
{Name: "Result", Type: "string", JSONTag: "result", Doc: "The result"},
},
},
},
}
var err error
schema, err = GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(schema).NotTo(BeEmpty())
})
It("should validate against XTP JSONSchema", func() {
Expect(ValidateXTPSchema(schema)).To(Succeed())
})
It("should have correct version", func() {
doc := parseSchema(schema)
Expect(doc["version"]).To(Equal("v1-draft"))
})
It("should include exports with description", func() {
doc := parseSchema(schema)
exports := doc["exports"].(map[string]any)
Expect(exports).To(HaveKey("test_method"))
method := exports["test_method"].(map[string]any)
Expect(method["description"]).To(Equal("Test method does something"))
})
It("should include schemas for input and output types", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
Expect(schemas).To(HaveKey("TestInput"))
Expect(schemas).To(HaveKey("TestOutput"))
})
It("should define input schema with correct properties", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
input := schemas["TestInput"].(map[string]any)
// Per XTP spec, ObjectSchema does NOT have a type field - only properties, required, description
Expect(input).NotTo(HaveKey("type"))
props := input["properties"].(map[string]any)
Expect(props).To(HaveKey("name"))
Expect(props).To(HaveKey("count"))
})
It("should mark non-pointer, non-omitempty fields as required", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
input := schemas["TestInput"].(map[string]any)
required := input["required"].([]any)
Expect(required).To(ContainElement("name"))
Expect(required).To(ContainElement("count"))
})
})
Context("capability with pointer fields (nullable)", func() {
var schema []byte
BeforeEach(func() {
capability := Capability{
Name: "nullable_test",
SourceFile: "nullable_test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
{
Name: "Input",
Fields: []FieldDef{
{Name: "Required", Type: "string", JSONTag: "required"},
{Name: "Optional", Type: "*string", JSONTag: "optional,omitempty", OmitEmpty: true},
},
},
{
Name: "Output",
Fields: []FieldDef{
{Name: "Value", Type: "string", JSONTag: "value"},
},
},
},
}
var err error
schema, err = GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
})
It("should validate against XTP JSONSchema", func() {
Expect(ValidateXTPSchema(schema)).To(Succeed())
})
It("should not mark required field as nullable", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
input := schemas["Input"].(map[string]any)
props := input["properties"].(map[string]any)
requiredField := props["required"].(map[string]any)
Expect(requiredField).NotTo(HaveKey("nullable"))
})
It("should mark optional pointer field as nullable", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
input := schemas["Input"].(map[string]any)
props := input["properties"].(map[string]any)
optionalField := props["optional"].(map[string]any)
Expect(optionalField["nullable"]).To(BeTrue())
})
It("should only include non-pointer fields in required array", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
input := schemas["Input"].(map[string]any)
required := input["required"].([]any)
Expect(required).To(ContainElement("required"))
Expect(required).NotTo(ContainElement("optional"))
})
})
Context("capability with enum", func() {
var schema []byte
BeforeEach(func() {
capability := Capability{
Name: "enum_test",
SourceFile: "enum_test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
{
Name: "Input",
Fields: []FieldDef{
{Name: "Status", Type: "Status", JSONTag: "status"},
},
},
{
Name: "Output",
Fields: []FieldDef{
{Name: "Value", Type: "string", JSONTag: "value"},
},
},
},
TypeAliases: []TypeAlias{
{Name: "Status", Type: "string", Doc: "Status type"},
},
Consts: []ConstGroup{
{
Type: "Status",
Values: []ConstDef{
{Name: "StatusPending", Value: `"pending"`},
{Name: "StatusActive", Value: `"active"`},
{Name: "StatusDone", Value: `"done"`},
},
},
},
}
var err error
schema, err = GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
})
It("should validate against XTP JSONSchema", func() {
Expect(ValidateXTPSchema(schema)).To(Succeed())
})
It("should define enum type with correct values", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
Expect(schemas).To(HaveKey("Status"))
status := schemas["Status"].(map[string]any)
Expect(status["type"]).To(Equal("string"))
enum := status["enum"].([]any)
Expect(enum).To(ConsistOf("pending", "active", "done"))
})
It("should use $ref for enum field in struct", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
input := schemas["Input"].(map[string]any)
props := input["properties"].(map[string]any)
statusRef := props["status"].(map[string]any)
Expect(statusRef["$ref"]).To(Equal("#/components/schemas/Status"))
})
})
Context("capability with array types", func() {
var schema []byte
BeforeEach(func() {
capability := Capability{
Name: "array_test",
SourceFile: "array_test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
{
Name: "Input",
Fields: []FieldDef{
{Name: "Tags", Type: "[]string", JSONTag: "tags"},
{Name: "Items", Type: "[]Item", JSONTag: "items"},
},
},
{
Name: "Output",
Fields: []FieldDef{
{Name: "Value", Type: "string", JSONTag: "value"},
},
},
{
Name: "Item",
Fields: []FieldDef{
{Name: "ID", Type: "string", JSONTag: "id"},
},
},
},
}
var err error
schema, err = GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
})
It("should validate against XTP JSONSchema", func() {
Expect(ValidateXTPSchema(schema)).To(Succeed())
})
It("should define string array with primitive type", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
input := schemas["Input"].(map[string]any)
props := input["properties"].(map[string]any)
tags := props["tags"].(map[string]any)
Expect(tags["type"]).To(Equal("array"))
tagItems := tags["items"].(map[string]any)
Expect(tagItems["type"]).To(Equal("string"))
})
It("should define struct array with $ref", func() {
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
input := schemas["Input"].(map[string]any)
props := input["properties"].(map[string]any)
items := props["items"].(map[string]any)
Expect(items["type"]).To(Equal("array"))
itemItems := items["items"].(map[string]any)
Expect(itemItems["$ref"]).To(Equal("#/components/schemas/Item"))
})
})
Context("capability with nullable ref", func() {
It("should mark pointer to enum as nullable with $ref", func() {
capability := Capability{
Name: "nullable_ref_test",
SourceFile: "nullable_ref_test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
{
Name: "Input",
Fields: []FieldDef{
{Name: "Value", Type: "string", JSONTag: "value"},
},
},
{
Name: "Output",
Fields: []FieldDef{
{Name: "Status", Type: "*ErrorType", JSONTag: "status,omitempty", OmitEmpty: true},
},
},
},
TypeAliases: []TypeAlias{
{Name: "ErrorType", Type: "string"},
},
Consts: []ConstGroup{
{
Type: "ErrorType",
Values: []ConstDef{
{Name: "ErrorNone", Value: `"none"`},
{Name: "ErrorFatal", Value: `"fatal"`},
},
},
},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
// Validate against XTP JSONSchema
Expect(ValidateXTPSchema(schema)).To(Succeed())
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
output := schemas["Output"].(map[string]any)
props := output["properties"].(map[string]any)
status := props["status"].(map[string]any)
Expect(status["$ref"]).To(Equal("#/components/schemas/ErrorType"))
Expect(status["nullable"]).To(BeTrue())
})
})
})
Describe("goTypeToXTPTypeAndFormat", func() {
DescribeTable("should convert Go types to XTP types",
func(goType, wantType, wantFormat string) {
gotType, gotFormat := goTypeToXTPTypeAndFormat(goType)
Expect(gotType).To(Equal(wantType))
Expect(gotFormat).To(Equal(wantFormat))
},
Entry("string", "string", "string", ""),
Entry("int", "int", "integer", "int32"),
Entry("int32", "int32", "integer", "int32"),
Entry("int64", "int64", "integer", "int64"),
Entry("float32", "float32", "number", "float"),
Entry("float64", "float64", "number", "float"),
Entry("bool", "bool", "boolean", ""),
Entry("[]byte", "[]byte", "string", "byte"),
Entry("unknown types default to object", "CustomType", "object", ""),
)
})
Describe("cleanDocForYAML", func() {
DescribeTable("should clean documentation strings",
func(doc, want string) {
Expect(cleanDocForYAML(doc)).To(Equal(want))
},
Entry("empty", "", ""),
Entry("single line", "Simple description", "Simple description"),
Entry("multiline", "First line\nSecond line", "First line\nSecond line"),
Entry("trailing newline", "Description\n", "Description"),
Entry("whitespace", " Description ", "Description"),
)
})
Describe("isPrimitiveGoType", func() {
DescribeTable("should identify primitive Go types",
func(goType string, want bool) {
Expect(isPrimitiveGoType(goType)).To(Equal(want))
},
Entry("bool", "bool", true),
Entry("string", "string", true),
Entry("int", "int", true),
Entry("int32", "int32", true),
Entry("int64", "int64", true),
Entry("float32", "float32", true),
Entry("float64", "float64", true),
Entry("[]byte", "[]byte", true),
Entry("custom type", "CustomType", false),
Entry("struct type", "MyStruct", false),
Entry("slice of string", "[]string", false),
Entry("map type", "map[string]int", false),
)
})
Describe("GenerateSchema with primitive output types", func() {
inputStruct := StructDef{
Name: "Input",
Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}},
}
Context("export with primitive string output", func() {
It("should use type instead of $ref and validate against XTP JSONSchema", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "get_name", Input: NewParam("input", "Input"), Output: NewParam("output", "string")},
},
Structs: []StructDef{inputStruct},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(schema).NotTo(BeEmpty())
Expect(ValidateXTPSchema(schema)).To(Succeed())
doc := parseSchema(schema)
exports := doc["exports"].(map[string]any)
method := exports["get_name"].(map[string]any)
output := method["output"].(map[string]any)
Expect(output["type"]).To(Equal("string"))
Expect(output).NotTo(HaveKey("$ref"))
Expect(output["contentType"]).To(Equal("application/json"))
})
})
Context("export with primitive bool output", func() {
It("should use boolean type and validate against XTP JSONSchema", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "is_valid", Input: NewParam("input", "Input"), Output: NewParam("output", "bool")},
},
Structs: []StructDef{inputStruct},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
doc := parseSchema(schema)
exports := doc["exports"].(map[string]any)
method := exports["is_valid"].(map[string]any)
output := method["output"].(map[string]any)
Expect(output["type"]).To(Equal("boolean"))
Expect(output).NotTo(HaveKey("$ref"))
})
})
Context("export with primitive int output", func() {
It("should use integer type and validate against XTP JSONSchema", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "get_count", Input: NewParam("input", "Input"), Output: NewParam("output", "int32")},
},
Structs: []StructDef{inputStruct},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
doc := parseSchema(schema)
exports := doc["exports"].(map[string]any)
method := exports["get_count"].(map[string]any)
output := method["output"].(map[string]any)
Expect(output["type"]).To(Equal("integer"))
Expect(output).NotTo(HaveKey("$ref"))
})
})
Context("export with pointer to primitive output", func() {
It("should strip pointer and use primitive type and validate against XTP JSONSchema", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "get_optional_string", Input: NewParam("input", "Input"), Output: NewParam("output", "*string")},
},
Structs: []StructDef{inputStruct},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
doc := parseSchema(schema)
exports := doc["exports"].(map[string]any)
method := exports["get_optional_string"].(map[string]any)
output := method["output"].(map[string]any)
Expect(output["type"]).To(Equal("string"))
Expect(output).NotTo(HaveKey("$ref"))
})
})
Context("export with struct output", func() {
It("should still use $ref and validate against XTP JSONSchema", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "get_result", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
inputStruct,
{Name: "Output", Fields: []FieldDef{{Name: "Value", Type: "string", JSONTag: "value"}}},
},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
doc := parseSchema(schema)
exports := doc["exports"].(map[string]any)
method := exports["get_result"].(map[string]any)
output := method["output"].(map[string]any)
Expect(output["$ref"]).To(Equal("#/components/schemas/Output"))
Expect(output).NotTo(HaveKey("type"))
})
})
})
Describe("collectUsedTypes", func() {
getSchemas := func(schema []byte) map[string]any {
doc := parseSchema(schema)
components, hasComponents := doc["components"].(map[string]any)
if !hasComponents {
return make(map[string]any)
}
schemas, ok := components["schemas"].(map[string]any)
if !ok {
return make(map[string]any)
}
return schemas
}
It("should only include types referenced by exports", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "UsedInput"), Output: NewParam("output", "UsedOutput")},
},
Structs: []StructDef{
{Name: "UsedInput", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
{Name: "UsedOutput", Fields: []FieldDef{{Name: "Value", Type: "string", JSONTag: "value"}}},
{Name: "UnusedStruct", Fields: []FieldDef{{Name: "Foo", Type: "string", JSONTag: "foo"}}},
},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
schemas := getSchemas(schema)
Expect(schemas).To(HaveKey("UsedInput"))
Expect(schemas).To(HaveKey("UsedOutput"))
Expect(schemas).NotTo(HaveKey("UnusedStruct"))
})
It("should include transitively referenced types", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
{Name: "Input", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
{Name: "Output", Fields: []FieldDef{{Name: "Nested", Type: "NestedType", JSONTag: "nested"}}},
{Name: "NestedType", Fields: []FieldDef{{Name: "Value", Type: "string", JSONTag: "value"}}},
},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
schemas := getSchemas(schema)
Expect(schemas).To(HaveKey("Input"))
Expect(schemas).To(HaveKey("Output"))
Expect(schemas).To(HaveKey("NestedType"))
})
It("should include array element types", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
{Name: "Input", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
{Name: "Output", Fields: []FieldDef{{Name: "Items", Type: "[]Item", JSONTag: "items"}}},
{Name: "Item", Fields: []FieldDef{{Name: "Name", Type: "string", JSONTag: "name"}}},
},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
schemas := getSchemas(schema)
Expect(schemas).To(HaveKey("Input"))
Expect(schemas).To(HaveKey("Output"))
Expect(schemas).To(HaveKey("Item"))
})
It("should include pointer types", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
{Name: "Input", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
{Name: "Output", Fields: []FieldDef{{Name: "Optional", Type: "*OptionalType", JSONTag: "optional"}}},
{Name: "OptionalType", Fields: []FieldDef{{Name: "Value", Type: "string", JSONTag: "value"}}},
},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
schemas := getSchemas(schema)
Expect(schemas).To(HaveKey("Input"))
Expect(schemas).To(HaveKey("Output"))
Expect(schemas).To(HaveKey("OptionalType"))
})
It("should exclude primitive output types from schema", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "string")},
},
Structs: []StructDef{
{Name: "Input", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
schemas := getSchemas(schema)
Expect(schemas).To(HaveKey("Input"))
})
})
Describe("GenerateSchema enum filtering", func() {
It("should only include enums that are actually used by exports", func() {
capability := Capability{
Name: "test",
SourceFile: "test",
Methods: []Export{
{ExportName: "test", Input: NewParam("input", "Input"), Output: NewParam("output", "Output")},
},
Structs: []StructDef{
{
Name: "Input",
Fields: []FieldDef{{Name: "Status", Type: "UsedStatus", JSONTag: "status"}},
},
{
Name: "Output",
Fields: []FieldDef{{Name: "Value", Type: "string", JSONTag: "value"}},
},
},
TypeAliases: []TypeAlias{
{Name: "UsedStatus", Type: "string"},
{Name: "UnusedStatus", Type: "string"},
},
Consts: []ConstGroup{
{
Type: "UsedStatus",
Values: []ConstDef{
{Name: "StatusActive", Value: `"active"`},
{Name: "StatusInactive", Value: `"inactive"`},
},
},
{
Type: "UnusedStatus",
Values: []ConstDef{
{Name: "UnusedPending", Value: `"pending"`},
},
},
},
}
schema, err := GenerateSchema(capability)
Expect(err).NotTo(HaveOccurred())
Expect(ValidateXTPSchema(schema)).To(Succeed())
doc := parseSchema(schema)
components := doc["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
// UsedStatus should be included because it's referenced by Input
Expect(schemas).To(HaveKey("UsedStatus"))
usedStatus := schemas["UsedStatus"].(map[string]any)
Expect(usedStatus["type"]).To(Equal("string"))
enum := usedStatus["enum"].([]any)
Expect(enum).To(ConsistOf("active", "inactive"))
// UnusedStatus should NOT be included
Expect(schemas).NotTo(HaveKey("UnusedStatus"))
})
})
})
@@ -0,0 +1,51 @@
package internal
import (
_ "embed"
"encoding/json"
"fmt"
"strings"
"github.com/xeipuuv/gojsonschema"
"gopkg.in/yaml.v3"
)
// XTP JSONSchema specification, from
// https://raw.githubusercontent.com/dylibso/xtp-bindgen/5090518dd86ba5e734dc225a33066ecc0ed2e12d/plugin/schema.json
//
//go:embed xtp_schema.json
var xtpSchemaJSON string
// ValidateXTPSchema validates that the generated schema conforms to the XTP JSONSchema specification.
// Returns nil if valid, or an error with validation details if invalid.
func ValidateXTPSchema(generatedSchema []byte) error {
// Parse the YAML schema to JSON for validation
var schemaDoc map[string]any
if err := yaml.Unmarshal(generatedSchema, &schemaDoc); err != nil {
return fmt.Errorf("failed to parse generated schema as YAML: %w", err)
}
// Convert to JSON for the validator
jsonBytes, err := json.Marshal(schemaDoc)
if err != nil {
return fmt.Errorf("failed to convert schema to JSON: %w", err)
}
schemaLoader := gojsonschema.NewStringLoader(xtpSchemaJSON)
documentLoader := gojsonschema.NewBytesLoader(jsonBytes)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return fmt.Errorf("schema validation failed: %w", err)
}
if !result.Valid() {
var errs []string
for _, desc := range result.Errors() {
errs = append(errs, fmt.Sprintf("- %s", desc))
}
return fmt.Errorf("schema validation errors:\n%s", strings.Join(errs, "\n"))
}
return nil
}
+957
View File
@@ -0,0 +1,957 @@
// ndpgen generates Navidrome Plugin Development Kit (PDK) code from annotated Go interfaces.
//
// This is the unified code generator that handles both host function wrappers
// and capability export wrappers.
//
// Usage:
//
// # Generate host wrappers for Navidrome server (output to input directory)
// ndpgen -host-wrappers -input=./plugins/host -package=host
//
// # Generate PDK client wrappers (from plugins/host to plugins/pdk)
// ndpgen -host-only -input=./plugins/host -output=./plugins/pdk
//
// # Generate capability wrappers (from plugins/capabilities to plugins/pdk)
// ndpgen -capability-only -input=./plugins/capabilities -output=./plugins/pdk
//
// # Generate XTP schemas from capabilities (output to input directory)
// ndpgen -schemas -input=./plugins/capabilities
//
// Output directories:
// - Host wrappers: $input/<servicename>_gen.go (server-side, used by Navidrome)
// - Host functions: $output/go/host/, $output/python/host/, $output/rust/host/
// - Capabilities: $output/go/<capability>/ (e.g., $output/go/metadata/)
// - Schemas: $input/<capability>.yaml (co-located with Go sources)
//
// Flags:
//
// -input Input directory containing Go source files with annotated interfaces
// -output Output directory base for generated files (default: same as input)
// -package Output package name for Go (default: host for host-only, auto for capabilities)
// -host-wrappers Generate server-side host wrappers (used by Navidrome, output to input directory)
// -host-only Generate PDK client wrappers for calling host functions
// -capability-only Generate only capability export wrappers
// -schemas Generate XTP YAML schemas from capabilities
// -go Generate Go client wrappers (default: true when not using -python/-rust)
// -python Generate Python client wrappers (default: false)
// -rust Generate Rust client wrappers (default: false)
// -v Verbose output
// -dry-run Preview generated code without writing files
package main
import (
"flag"
"fmt"
"go/format"
"os"
"path/filepath"
"strings"
"github.com/navidrome/navidrome/plugins/cmd/ndpgen/internal"
)
// config holds the parsed command-line configuration.
type config struct {
inputDir string
outputDir string // Base output directory (e.g., plugins/pdk)
goOutputDir string // Go output: $outputDir/go/host (for host-only)
pythonOutputDir string // Python output: $outputDir/python/host
rustOutputDir string // Rust output: $outputDir/rust/host
pkgName string
hostOnly bool
hostWrappers bool // Generate host wrappers (used by Navidrome server)
capabilityOnly bool
schemasOnly bool // Generate XTP schemas from capabilities (output goes to inputDir)
pdkOnly bool // Generate PDK abstraction layer wrapper
generateGoClient bool
generatePyClient bool
generateRsClient bool
verbose bool
dryRun bool
}
func main() {
cfg, err := parseConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if cfg.schemasOnly {
if err := runSchemaGeneration(cfg); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
return
}
if cfg.pdkOnly {
if err := runPDKGeneration(cfg); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
return
}
if cfg.capabilityOnly {
if err := runCapabilityGeneration(cfg); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
return
}
if cfg.hostWrappers {
if err := runHostWrapperGeneration(cfg); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
return
}
// Default: host-only mode
services, err := parseServices(cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if len(services) == 0 {
return
}
if err := generateAllCode(cfg, services); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// runCapabilityGeneration handles capability-only code generation.
func runCapabilityGeneration(cfg *config) error {
capabilities, err := parseCapabilities(cfg)
if err != nil {
return err
}
if len(capabilities) == 0 {
if cfg.verbose {
fmt.Println("No capabilities found")
}
return nil
}
return generateCapabilityCode(cfg, capabilities)
}
// runSchemaGeneration handles XTP schema generation from capabilities.
func runSchemaGeneration(cfg *config) error {
capabilities, err := parseCapabilities(cfg)
if err != nil {
return err
}
if len(capabilities) == 0 {
if cfg.verbose {
fmt.Println("No capabilities found")
}
return nil
}
return generateSchemas(cfg, capabilities)
}
// runPDKGeneration handles PDK abstraction layer code generation.
// This generates the pdk wrapper package that wraps extism/go-pdk
// with mockable implementations for unit testing on native platforms.
func runPDKGeneration(cfg *config) error {
// Output directory is $output/go/pdk/
outputDir := filepath.Join(cfg.outputDir, "go", "pdk")
return generatePDKPackageWithParsing(outputDir, cfg.dryRun, cfg.verbose)
}
// generatePDKPackageWithParsing generates the PDK abstraction layer using AST parsing.
// It extracts all exported symbols from extism/go-pdk and generates wrappers for them.
func generatePDKPackageWithParsing(outputDir string, dryRun, verbose bool) error {
if verbose {
fmt.Println("Parsing extism/go-pdk to extract exported symbols...")
}
// Parse extism/go-pdk to get all exported symbols
symbols, err := internal.ParseExtismPDK()
if err != nil {
return fmt.Errorf("parsing extism/go-pdk: %w", err)
}
if verbose {
fmt.Printf("Found %d types, %d constants, %d functions\n",
len(symbols.Types), len(symbols.Consts), len(symbols.Functions))
for _, t := range symbols.Types {
fmt.Printf(" Type %s: %d methods, %d fields\n", t.Name, len(t.Methods), len(t.Fields))
for _, m := range t.Methods {
fmt.Printf(" Method: %s (receiver: %s)\n", m.Name, m.Receiver)
}
}
fmt.Printf("Generating PDK abstraction layer to: %s\n", outputDir)
}
// Generate the WASM implementation (pdk.go)
pdkCode, err := internal.GeneratePDKGo(symbols)
if err != nil {
return fmt.Errorf("generating pdk.go: %w", err)
}
formatted, err := format.Source(pdkCode)
if err != nil {
return fmt.Errorf("formatting pdk.go: %w\nRaw code:\n%s", err, pdkCode)
}
pdkFile := filepath.Join(outputDir, "pdk.go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", pdkFile, formatted)
} else {
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("creating output directory: %w", err)
}
if err := os.WriteFile(pdkFile, formatted, 0600); err != nil {
return fmt.Errorf("writing pdk.go: %w", err)
}
if verbose {
fmt.Printf("Generated: %s\n", pdkFile)
}
}
// Generate the types stub (types_stub.go)
typesStubCode, err := internal.GeneratePDKTypesStub(symbols)
if err != nil {
return fmt.Errorf("generating types_stub.go: %w", err)
}
formattedTypesStub, err := format.Source(typesStubCode)
if err != nil {
return fmt.Errorf("formatting types_stub.go: %w\nRaw code:\n%s", err, typesStubCode)
}
typesStubFile := filepath.Join(outputDir, "types_stub.go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", typesStubFile, formattedTypesStub)
} else {
if err := os.WriteFile(typesStubFile, formattedTypesStub, 0600); err != nil {
return fmt.Errorf("writing types_stub.go: %w", err)
}
if verbose {
fmt.Printf("Generated: %s\n", typesStubFile)
}
}
// Generate the stub implementation (pdk_stub.go)
stubCode, err := internal.GeneratePDKGoStub(symbols)
if err != nil {
return fmt.Errorf("generating pdk_stub.go: %w", err)
}
formattedStub, err := format.Source(stubCode)
if err != nil {
return fmt.Errorf("formatting pdk_stub.go: %w\nRaw code:\n%s", err, stubCode)
}
stubFile := filepath.Join(outputDir, "pdk_stub.go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", stubFile, formattedStub)
} else {
if err := os.WriteFile(stubFile, formattedStub, 0600); err != nil {
return fmt.Errorf("writing pdk_stub.go: %w", err)
}
if verbose {
fmt.Printf("Generated: %s\n", stubFile)
}
}
return nil
}
// generatePDKPackage generates the PDK abstraction layer to a specific directory.
// This is called by generateAllCode to include the PDK package alongside host client code.
func generatePDKPackage(outputDir string, dryRun, verbose bool) error {
return generatePDKPackageWithParsing(outputDir, dryRun, verbose)
}
// runHostWrapperGeneration handles host wrapper code generation.
// This generates the *_gen.go files in the input directory that are used
// by Navidrome server to expose host functions to plugins.
func runHostWrapperGeneration(cfg *config) error {
services, err := parseServices(cfg)
if err != nil {
return err
}
if len(services) == 0 {
if cfg.verbose {
fmt.Println("No host services found")
}
return nil
}
// Generate host wrappers for each service
for _, svc := range services {
if err := generateHostWrapperCode(svc, cfg.inputDir, cfg.pkgName, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating host wrapper for %s: %w", svc.Name, err)
}
}
return nil
}
// parseConfig parses command-line flags and returns the configuration.
func parseConfig() (*config, error) {
var (
inputDir = flag.String("input", ".", "Input directory containing Go source files")
outputDir = flag.String("output", "", "Base output directory for generated files (default: same as input)")
pkgName = flag.String("package", "", "Output package name for Go (default: host for host-only, auto for capabilities)")
hostOnly = flag.Bool("host-only", false, "Generate only host function wrappers")
hostWrappers = flag.Bool("host-wrappers", false, "Generate host wrappers (used by Navidrome server, output to input directory)")
capabilityOnly = flag.Bool("capability-only", false, "Generate only capability export wrappers")
schemasOnly = flag.Bool("schemas", false, "Generate XTP YAML schemas from capabilities (output to input directory)")
pdkOnly = flag.Bool("extism-pdk", false, "Generate PDK abstraction layer by parsing extism/go-pdk")
goClient = flag.Bool("go", false, "Generate Go client wrappers")
pyClient = flag.Bool("python", false, "Generate Python client wrappers")
rsClient = flag.Bool("rust", false, "Generate Rust client wrappers")
verbose = flag.Bool("v", false, "Verbose output")
dryRun = flag.Bool("dry-run", false, "Preview generated code without writing files")
)
flag.Parse()
// Count how many mode flags are specified
modeCount := 0
if *hostOnly {
modeCount++
}
if *hostWrappers {
modeCount++
}
if *capabilityOnly {
modeCount++
}
if *schemasOnly {
modeCount++
}
if *pdkOnly {
modeCount++
}
// Default to host-only if no mode is specified
if modeCount == 0 {
*hostOnly = true
}
// Cannot specify multiple modes
if modeCount > 1 {
return nil, fmt.Errorf("cannot specify multiple modes (-host-only, -host-wrappers, -capability-only, -schemas, -pdk)")
}
if *outputDir == "" {
*outputDir = *inputDir
}
// Default package name based on mode
if *pkgName == "" {
if *hostOnly {
*pkgName = "host"
}
// For capability-only, package name is derived from capability annotation
}
absInput, err := filepath.Abs(*inputDir)
if err != nil {
return nil, fmt.Errorf("resolving input path: %w", err)
}
absOutput, err := filepath.Abs(*outputDir)
if err != nil {
return nil, fmt.Errorf("resolving output path: %w", err)
}
// Set output directories for each language
// Go host wrappers: $output/go/host/
// Python host wrappers: $output/python/host/
// Rust host wrappers: $output/rust/nd-pdk-host/ (renamed crate)
absGoOutput := filepath.Join(absOutput, "go", "host")
absPythonOutput := filepath.Join(absOutput, "python", "host")
absRustOutput := filepath.Join(absOutput, "rust", "nd-pdk-host")
// Determine what to generate
// Default: generate Go clients if no language flag is specified
anyLangFlag := *goClient || *pyClient || *rsClient
return &config{
inputDir: absInput,
outputDir: absOutput,
goOutputDir: absGoOutput,
pythonOutputDir: absPythonOutput,
rustOutputDir: absRustOutput,
pkgName: *pkgName,
hostOnly: *hostOnly,
hostWrappers: *hostWrappers,
capabilityOnly: *capabilityOnly,
schemasOnly: *schemasOnly,
pdkOnly: *pdkOnly,
generateGoClient: *goClient || !anyLangFlag,
generatePyClient: *pyClient,
generateRsClient: *rsClient,
verbose: *verbose,
dryRun: *dryRun,
}, nil
}
// parseServices parses source files and returns discovered services.
func parseServices(cfg *config) ([]internal.Service, error) {
if cfg.verbose {
fmt.Printf("Input directory: %s\n", cfg.inputDir)
fmt.Printf("Base output directory: %s\n", cfg.outputDir)
if cfg.generateGoClient {
fmt.Printf("Go output directory: %s\n", cfg.goOutputDir)
}
if cfg.generatePyClient {
fmt.Printf("Python output directory: %s\n", cfg.pythonOutputDir)
}
if cfg.generateRsClient {
fmt.Printf("Rust output directory: %s\n", cfg.rustOutputDir)
}
fmt.Printf("Package name: %s\n", cfg.pkgName)
fmt.Printf("Host-only mode: %v\n", cfg.hostOnly)
fmt.Printf("Generate Go client code: %v\n", cfg.generateGoClient)
fmt.Printf("Generate Python client code: %v\n", cfg.generatePyClient)
fmt.Printf("Generate Rust client code: %v\n", cfg.generateRsClient)
}
services, err := internal.ParseDirectory(cfg.inputDir)
if err != nil {
return nil, fmt.Errorf("parsing source files: %w", err)
}
if len(services) == 0 {
if cfg.verbose {
fmt.Println("No host services found")
}
return nil, nil
}
if cfg.verbose {
fmt.Printf("Found %d host service(s)\n", len(services))
for _, svc := range services {
fmt.Printf(" - %s (%d methods)\n", svc.Name, len(svc.Methods))
}
}
return services, nil
}
// parseCapabilities parses source files and returns discovered capabilities.
func parseCapabilities(cfg *config) ([]internal.Capability, error) {
if cfg.verbose {
fmt.Printf("Input directory: %s\n", cfg.inputDir)
fmt.Printf("Base output directory: %s\n", cfg.outputDir)
fmt.Printf("Capability-only mode: %v\n", cfg.capabilityOnly)
}
capabilities, err := internal.ParseCapabilities(cfg.inputDir)
if err != nil {
return nil, fmt.Errorf("parsing capability files: %w", err)
}
if len(capabilities) == 0 {
return nil, nil
}
if cfg.verbose {
fmt.Printf("Found %d capability(ies)\n", len(capabilities))
for _, cap := range capabilities {
fmt.Printf(" - %s (%d exports, required=%v)\n", cap.Name, len(cap.Methods), cap.Required)
}
}
return capabilities, nil
}
// generateCapabilityCode generates export wrappers for all capabilities.
func generateCapabilityCode(cfg *config, capabilities []internal.Capability) error {
// Generate Go capability wrappers (always, for now)
for _, cap := range capabilities {
// Output directory is $output/go/<capability_name>/
outputDir := filepath.Join(cfg.outputDir, "go", cap.Name)
if err := generateCapabilityGoCode(cap, outputDir, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating Go capability code for %s: %w", cap.Name, err)
}
}
// Generate Rust capability wrappers if -rust flag is set
if cfg.generateRsClient {
rustOutputDir := filepath.Join(cfg.outputDir, "rust", "nd-pdk-capabilities", "src")
if err := generateCapabilityRustCode(capabilities, rustOutputDir, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating Rust capability code: %w", err)
}
}
return nil
}
// generateCapabilityGoCode generates Go export wrapper code for a capability.
func generateCapabilityGoCode(cap internal.Capability, outputDir string, dryRun, verbose bool) error {
// Use the capability name as the package name
pkgName := cap.Name
// Generate the main WASM code
code, err := internal.GenerateCapabilityGo(cap, pkgName)
if err != nil {
return fmt.Errorf("generating code: %w", err)
}
formatted, err := format.Source(code)
if err != nil {
return fmt.Errorf("formatting code: %w\nRaw code:\n%s", err, code)
}
mainFile := filepath.Join(outputDir, cap.Name+".go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", mainFile, formatted)
} else {
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("creating output directory: %w", err)
}
if err := os.WriteFile(mainFile, formatted, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated capability code: %s\n", mainFile)
}
}
// Generate the stub code for non-WASM platforms
stubCode, err := internal.GenerateCapabilityGoStub(cap, pkgName)
if err != nil {
return fmt.Errorf("generating stub code: %w", err)
}
formattedStub, err := format.Source(stubCode)
if err != nil {
return fmt.Errorf("formatting stub code: %w\nRaw code:\n%s", err, stubCode)
}
stubFile := filepath.Join(outputDir, cap.Name+"_stub.go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", stubFile, formattedStub)
} else {
if err := os.WriteFile(stubFile, formattedStub, 0600); err != nil {
return fmt.Errorf("writing stub file: %w", err)
}
if verbose {
fmt.Printf("Generated capability stub: %s\n", stubFile)
}
}
return nil
}
// generateCapabilityRustCode generates Rust export wrapper code for all capabilities.
func generateCapabilityRustCode(capabilities []internal.Capability, outputDir string, dryRun, verbose bool) error {
// Generate individual capability modules
for _, cap := range capabilities {
code, err := internal.GenerateCapabilityRust(cap)
if err != nil {
return fmt.Errorf("generating Rust code for %s: %w", cap.Name, err)
}
fileName := internal.ToSnakeCase(cap.Name) + ".rs"
filePath := filepath.Join(outputDir, fileName)
if dryRun {
fmt.Printf("=== %s ===\n%s\n", filePath, code)
} else {
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("creating output directory: %w", err)
}
if err := os.WriteFile(filePath, code, 0600); err != nil {
return fmt.Errorf("writing file %s: %w", filePath, err)
}
if verbose {
fmt.Printf("Generated Rust capability code: %s\n", filePath)
}
}
}
// Generate lib.rs
libCode, err := internal.GenerateCapabilityRustLib(capabilities)
if err != nil {
return fmt.Errorf("generating lib.rs: %w", err)
}
libPath := filepath.Join(outputDir, "lib.rs")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", libPath, libCode)
} else {
if err := os.WriteFile(libPath, libCode, 0600); err != nil {
return fmt.Errorf("writing lib.rs: %w", err)
}
if verbose {
fmt.Printf("Generated Rust lib.rs: %s\n", libPath)
}
}
return nil
}
// generateAllCode generates all requested code for the services.
func generateAllCode(cfg *config, services []internal.Service) error {
for _, svc := range services {
if cfg.generateGoClient {
if err := generateGoClientCode(svc, cfg.goOutputDir, cfg.pkgName, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating Go client code for %s: %w", svc.Name, err)
}
}
if cfg.generatePyClient {
if err := generatePythonClientCode(svc, cfg.pythonOutputDir, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating Python client code for %s: %w", svc.Name, err)
}
}
if cfg.generateRsClient {
if err := generateRustClientCode(svc, cfg.rustOutputDir, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating Rust client code for %s: %w", svc.Name, err)
}
}
}
if cfg.generateRsClient && len(services) > 0 {
if err := generateRustLibFile(services, cfg.rustOutputDir, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating Rust lib.rs: %w", err)
}
}
if cfg.generateGoClient && len(services) > 0 {
if err := generateGoDocFile(services, cfg.goOutputDir, cfg.pkgName, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating Go doc.go: %w", err)
}
if err := generateGoModFile(cfg.goOutputDir, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating Go go.mod: %w", err)
}
// Generate PDK abstraction layer alongside host client code
pdkDir := filepath.Join(filepath.Dir(cfg.goOutputDir), "pdk")
if err := generatePDKPackage(pdkDir, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating PDK package: %w", err)
}
}
return nil
}
// generateHostWrapperCode generates host wrapper code for a service.
// This generates the *_gen.go files that are used by Navidrome server
// to expose host functions to plugins via Extism.
func generateHostWrapperCode(svc internal.Service, outputDir, pkgName string, dryRun, verbose bool) error {
code, err := internal.GenerateHost(svc, pkgName)
if err != nil {
return fmt.Errorf("generating code: %w", err)
}
formatted, err := format.Source(code)
if err != nil {
return fmt.Errorf("formatting code: %w\nRaw code:\n%s", err, code)
}
// Host wrapper file follows the pattern <servicename>_gen.go
hostFile := filepath.Join(outputDir, strings.ToLower(svc.Name)+"_gen.go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", hostFile, formatted)
} else {
if err := os.WriteFile(hostFile, formatted, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated host wrapper: %s\n", hostFile)
}
}
return nil
}
// generateGoClientCode generates Go client-side code for a service.
func generateGoClientCode(svc internal.Service, outputDir, pkgName string, dryRun, verbose bool) error {
code, err := internal.GenerateClientGo(svc, pkgName)
if err != nil {
return fmt.Errorf("generating code: %w", err)
}
formatted, err := format.Source(code)
if err != nil {
return fmt.Errorf("formatting code: %w\nRaw code:\n%s", err, code)
}
// Client code goes directly in the output directory
clientFile := filepath.Join(outputDir, "nd_host_"+strings.ToLower(svc.Name)+".go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", clientFile, formatted)
} else {
// Create output directory if needed
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("creating output directory: %w", err)
}
if err := os.WriteFile(clientFile, formatted, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated Go client code: %s\n", clientFile)
}
}
// Also generate stub file for non-WASM platforms
return generateGoClientStubCode(svc, outputDir, pkgName, dryRun, verbose)
}
// generateGoClientStubCode generates stub code for non-WASM platforms.
func generateGoClientStubCode(svc internal.Service, outputDir, pkgName string, dryRun, verbose bool) error {
code, err := internal.GenerateClientGoStub(svc, pkgName)
if err != nil {
return fmt.Errorf("generating stub code: %w", err)
}
formatted, err := format.Source(code)
if err != nil {
return fmt.Errorf("formatting stub code: %w\nRaw code:\n%s", err, code)
}
// Stub code goes directly in output directory with _stub suffix
stubFile := filepath.Join(outputDir, "nd_host_"+strings.ToLower(svc.Name)+"_stub.go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", stubFile, formatted)
return nil
}
// Create output directory if needed
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("creating output directory: %w", err)
}
if err := os.WriteFile(stubFile, formatted, 0600); err != nil {
return fmt.Errorf("writing stub file: %w", err)
}
if verbose {
fmt.Printf("Generated Go client stub: %s\n", stubFile)
}
return nil
}
// generatePythonClientCode generates Python client-side code for a service.
func generatePythonClientCode(svc internal.Service, outputDir string, dryRun, verbose bool) error {
code, err := internal.GenerateClientPython(svc)
if err != nil {
return fmt.Errorf("generating code: %w", err)
}
// Python code goes directly in the output directory
clientFile := filepath.Join(outputDir, "nd_host_"+strings.ToLower(svc.Name)+".py")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", clientFile, code)
return nil
}
// Create output directory if needed
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("creating python client directory: %w", err)
}
if err := os.WriteFile(clientFile, code, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated Python client code: %s\n", clientFile)
}
return nil
}
// generateRustClientCode generates Rust client-side code for a service.
func generateRustClientCode(svc internal.Service, outputDir string, dryRun, verbose bool) error {
code, err := internal.GenerateClientRust(svc)
if err != nil {
return fmt.Errorf("generating code: %w", err)
}
// Rust code goes in src/ subdirectory (standard Rust convention)
srcDir := filepath.Join(outputDir, "src")
clientFile := filepath.Join(srcDir, "nd_host_"+strings.ToLower(svc.Name)+".rs")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", clientFile, code)
return nil
}
// Create src directory if needed
if err := os.MkdirAll(srcDir, 0755); err != nil {
return fmt.Errorf("creating rust src directory: %w", err)
}
if err := os.WriteFile(clientFile, code, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated Rust client code: %s\n", clientFile)
}
return nil
}
// generateRustLibFile generates the lib.rs file that exposes all Rust modules.
func generateRustLibFile(services []internal.Service, outputDir string, dryRun, verbose bool) error {
code, err := internal.GenerateRustLib(services)
if err != nil {
return fmt.Errorf("generating lib.rs: %w", err)
}
// lib.rs goes in src/ subdirectory (standard Rust convention)
srcDir := filepath.Join(outputDir, "src")
libFile := filepath.Join(srcDir, "lib.rs")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", libFile, code)
return nil
}
// Create src directory if needed
if err := os.MkdirAll(srcDir, 0755); err != nil {
return fmt.Errorf("creating rust src directory: %w", err)
}
if err := os.WriteFile(libFile, code, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated Rust lib.rs: %s\n", libFile)
}
return nil
}
// generateGoDocFile generates the doc.go file for the Go library.
func generateGoDocFile(services []internal.Service, outputDir, pkgName string, dryRun, verbose bool) error {
code, err := internal.GenerateGoDoc(services, pkgName)
if err != nil {
return fmt.Errorf("generating doc.go: %w", err)
}
formatted, err := format.Source(code)
if err != nil {
return fmt.Errorf("formatting doc.go: %w\nRaw code:\n%s", err, code)
}
docFile := filepath.Join(outputDir, "doc.go")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", docFile, formatted)
return nil
}
// Create output directory if needed
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("creating output directory: %w", err)
}
if err := os.WriteFile(docFile, formatted, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated Go doc.go: %s\n", docFile)
}
return nil
}
// generateGoModFile generates the go.mod file for the Go library.
// The go.mod is placed at the parent directory ($output/go/) to create a unified
// module that includes both host wrappers and capabilities.
func generateGoModFile(outputDir string, dryRun, verbose bool) error {
code, err := internal.GenerateGoMod()
if err != nil {
return fmt.Errorf("generating go.mod: %w", err)
}
// Output to parent directory ($output/go/) instead of host directory
parentDir := filepath.Dir(outputDir)
modFile := filepath.Join(parentDir, "go.mod")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", modFile, code)
return nil
}
// Create parent directory if needed
if err := os.MkdirAll(parentDir, 0755); err != nil {
return fmt.Errorf("creating output directory: %w", err)
}
if err := os.WriteFile(modFile, code, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated Go go.mod: %s\n", modFile)
}
return nil
}
// generateSchemas generates XTP YAML schemas from capabilities.
func generateSchemas(cfg *config, capabilities []internal.Capability) error {
for _, cap := range capabilities {
if err := generateSchemaFile(cap, cfg.inputDir, cfg.dryRun, cfg.verbose); err != nil {
return fmt.Errorf("generating schema for %s: %w", cap.Name, err)
}
}
return nil
}
// generateSchemaFile generates an XTP YAML schema file for a capability.
func generateSchemaFile(cap internal.Capability, outputDir string, dryRun, verbose bool) error {
schema, err := internal.GenerateSchema(cap)
if err != nil {
return fmt.Errorf("generating schema: %w", err)
}
// Validate the generated schema against XTP JSONSchema spec
if err := internal.ValidateXTPSchema(schema); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Schema validation for %s:\n%s\n", cap.Name, err)
}
// Use the source file name: websocket_callback.go -> websocket_callback.yaml
schemaFile := filepath.Join(outputDir, cap.SourceFile+".yaml")
if dryRun {
fmt.Printf("=== %s ===\n%s\n", schemaFile, schema)
return nil
}
if err := os.WriteFile(schemaFile, schema, 0600); err != nil {
return fmt.Errorf("writing file: %w", err)
}
if verbose {
fmt.Printf("Generated XTP schema: %s\n", schemaFile)
}
return nil
}
+13
View File
@@ -0,0 +1,13 @@
package main
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestNdpgen(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "NDPGen CLI Suite")
}
@@ -0,0 +1,63 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Codec host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package ndhost
import (
"encoding/json"
"errors"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
// codec_encode is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user codec_encode
func codec_encode(uint64) uint64
type codecEncodeRequest struct {
Data []byte `json:"data"`
}
type codecEncodeResponse struct {
Result []byte `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
// CodecEncode calls the codec_encode host function.
func CodecEncode(data []byte) ([]byte, error) {
// Marshal request to JSON
req := codecEncodeRequest{
Data: data,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := codec_encode(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response codecEncodeResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return nil, err
}
// Convert Error field to Go error
if response.Error != "" {
return nil, errors.New(response.Error)
}
return response.Result, nil
}
+52
View File
@@ -0,0 +1,52 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the Codec host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
@extism.import_fn("extism:host/user", "codec_encode")
def _codec_encode(offset: int) -> int:
"""Raw host function - do not call directly."""
...
def codec_encode(data: bytes) -> bytes:
"""Call the codec_encode host function.
Args:
data: bytes parameter.
Returns:
bytes: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"data": data,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _codec_encode(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("result", b"")
+51
View File
@@ -0,0 +1,51 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Codec host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct CodecEncodeRequest {
data: Vec<u8>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CodecEncodeResponse {
#[serde(default)]
result: Vec<u8>,
#[serde(default)]
error: Option<String>,
}
#[host_fn]
extern "ExtismHost" {
fn codec_encode(input: Json<CodecEncodeRequest>) -> Json<CodecEncodeResponse>;
}
/// Calls the codec_encode host function.
///
/// # Arguments
/// * `data` - Vec<u8> parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn encode(data: Vec<u8>) -> Result<Vec<u8>, Error> {
let response = unsafe {
codec_encode(Json(CodecEncodeRequest {
data: data,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
+88
View File
@@ -0,0 +1,88 @@
// Code generated by ndpgen. DO NOT EDIT.
package testpkg
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
)
// CodecEncodeRequest is the request type for Codec.Encode.
type CodecEncodeRequest struct {
Data []byte `json:"data"`
}
// CodecEncodeResponse is the response type for Codec.Encode.
type CodecEncodeResponse struct {
Result []byte `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
// RegisterCodecHostFunctions registers Codec service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterCodecHostFunctions(service CodecService) []extism.HostFunction {
return []extism.HostFunction{
newCodecEncodeHostFunction(service),
}
}
func newCodecEncodeHostFunction(service CodecService) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"codec_encode",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
// Read JSON request from plugin memory
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
codecWriteError(p, stack, err)
return
}
var req CodecEncodeRequest
if err := json.Unmarshal(reqBytes, &req); err != nil {
codecWriteError(p, stack, err)
return
}
// Call the service method
result, svcErr := service.Encode(ctx, req.Data)
if svcErr != nil {
codecWriteError(p, stack, svcErr)
return
}
// Write JSON response to plugin memory
resp := CodecEncodeResponse{
Result: result,
}
codecWriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
// codecWriteResponse writes a JSON response to plugin memory.
func codecWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
codecWriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
// codecWriteError writes an error response to plugin memory.
func codecWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}
+9
View File
@@ -0,0 +1,9 @@
package testpkg
import "context"
//nd:hostservice name=Codec permission=codec
type CodecService interface {
//nd:hostfunc
Encode(ctx context.Context, data []byte) ([]byte, error)
}
@@ -0,0 +1,341 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the Comprehensive host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
@extism.import_fn("extism:host/user", "comprehensive_simpleparams")
def _comprehensive_simpleparams(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_structparam")
def _comprehensive_structparam(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_mixedparams")
def _comprehensive_mixedparams(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_noerror")
def _comprehensive_noerror(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_noparams")
def _comprehensive_noparams(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_noparamsnoreturns")
def _comprehensive_noparamsnoreturns(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_pointerparams")
def _comprehensive_pointerparams(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_mapparams")
def _comprehensive_mapparams(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_multiplereturns")
def _comprehensive_multiplereturns(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "comprehensive_byteslice")
def _comprehensive_byteslice(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@dataclass
class ComprehensiveMultipleReturnsResult:
"""Result type for comprehensive_multiple_returns."""
results: Any
total: int
def comprehensive_simple_params(name: str, count: int) -> str:
"""Call the comprehensive_simpleparams host function.
Args:
name: str parameter.
count: int parameter.
Returns:
str: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"name": name,
"count": count,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_simpleparams(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("result", "")
def comprehensive_struct_param(user: Any) -> None:
"""Call the comprehensive_structparam host function.
Args:
user: Any parameter.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"user": user,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_structparam(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
def comprehensive_mixed_params(id: str, filter: Any) -> int:
"""Call the comprehensive_mixedparams host function.
Args:
id: str parameter.
filter: Any parameter.
Returns:
int: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"id": id,
"filter": filter,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_mixedparams(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("result", 0)
def comprehensive_no_error(name: str) -> str:
"""Call the comprehensive_noerror host function.
Args:
name: str parameter.
Returns:
str: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"name": name,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_noerror(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("result", "")
def comprehensive_no_params() -> None:
"""Call the comprehensive_noparams host function.
Raises:
HostFunctionError: If the host function returns an error.
"""
request_bytes = b"{}"
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_noparams(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
def comprehensive_no_params_no_returns() -> None:
"""Call the comprehensive_noparamsnoreturns host function.
Raises:
HostFunctionError: If the host function returns an error.
"""
request_bytes = b"{}"
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_noparamsnoreturns(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
def comprehensive_pointer_params(id: Any, user: Any) -> Any:
"""Call the comprehensive_pointerparams host function.
Args:
id: Any parameter.
user: Any parameter.
Returns:
Any: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"id": id,
"user": user,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_pointerparams(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("result", None)
def comprehensive_map_params(data: Any) -> Any:
"""Call the comprehensive_mapparams host function.
Args:
data: Any parameter.
Returns:
Any: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"data": data,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_mapparams(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("result", None)
def comprehensive_multiple_returns(query: str) -> ComprehensiveMultipleReturnsResult:
"""Call the comprehensive_multiplereturns host function.
Args:
query: str parameter.
Returns:
ComprehensiveMultipleReturnsResult containing results, total,.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"query": query,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_multiplereturns(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return ComprehensiveMultipleReturnsResult(
results=response.get("results", None),
total=response.get("total", 0),
)
def comprehensive_byte_slice(data: bytes) -> bytes:
"""Call the comprehensive_byteslice host function.
Args:
data: bytes parameter.
Returns:
bytes: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"data": data,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _comprehensive_byteslice(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("result", b"")
@@ -0,0 +1,398 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Comprehensive host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct User2 {
pub id: String,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Filter2 {
pub active: bool,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveSimpleParamsRequest {
name: String,
count: i32,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveSimpleParamsResponse {
#[serde(default)]
result: String,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveStructParamRequest {
user: User2,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveStructParamResponse {
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveMixedParamsRequest {
id: String,
filter: Filter2,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveMixedParamsResponse {
#[serde(default)]
result: i32,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveNoErrorRequest {
name: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveNoErrorResponse {
#[serde(default)]
result: String,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveNoParamsResponse {
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveNoParamsNoReturnsResponse {
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensivePointerParamsRequest {
id: Option<String>,
user: Option<User2>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensivePointerParamsResponse {
#[serde(default)]
result: Option<User2>,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveMapParamsRequest {
data: std::collections::HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveMapParamsResponse {
#[serde(default)]
result: serde_json::Value,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveMultipleReturnsRequest {
query: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveMultipleReturnsResponse {
#[serde(default)]
results: Vec<User2>,
#[serde(default)]
total: i32,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveByteSliceRequest {
data: Vec<u8>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComprehensiveByteSliceResponse {
#[serde(default)]
result: Vec<u8>,
#[serde(default)]
error: Option<String>,
}
#[host_fn]
extern "ExtismHost" {
fn comprehensive_simpleparams(input: Json<ComprehensiveSimpleParamsRequest>) -> Json<ComprehensiveSimpleParamsResponse>;
fn comprehensive_structparam(input: Json<ComprehensiveStructParamRequest>) -> Json<ComprehensiveStructParamResponse>;
fn comprehensive_mixedparams(input: Json<ComprehensiveMixedParamsRequest>) -> Json<ComprehensiveMixedParamsResponse>;
fn comprehensive_noerror(input: Json<ComprehensiveNoErrorRequest>) -> Json<ComprehensiveNoErrorResponse>;
fn comprehensive_noparams(input: Json<serde_json::Value>) -> Json<ComprehensiveNoParamsResponse>;
fn comprehensive_noparamsnoreturns(input: Json<serde_json::Value>) -> Json<ComprehensiveNoParamsNoReturnsResponse>;
fn comprehensive_pointerparams(input: Json<ComprehensivePointerParamsRequest>) -> Json<ComprehensivePointerParamsResponse>;
fn comprehensive_mapparams(input: Json<ComprehensiveMapParamsRequest>) -> Json<ComprehensiveMapParamsResponse>;
fn comprehensive_multiplereturns(input: Json<ComprehensiveMultipleReturnsRequest>) -> Json<ComprehensiveMultipleReturnsResponse>;
fn comprehensive_byteslice(input: Json<ComprehensiveByteSliceRequest>) -> Json<ComprehensiveByteSliceResponse>;
}
/// Calls the comprehensive_simpleparams host function.
///
/// # Arguments
/// * `name` - String parameter.
/// * `count` - i32 parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn simple_params(name: &str, count: i32) -> Result<String, Error> {
let response = unsafe {
comprehensive_simpleparams(Json(ComprehensiveSimpleParamsRequest {
name: name.to_owned(),
count: count,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
/// Calls the comprehensive_structparam host function.
///
/// # Arguments
/// * `user` - User2 parameter.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn struct_param(user: User2) -> Result<(), Error> {
let response = unsafe {
comprehensive_structparam(Json(ComprehensiveStructParamRequest {
user: user,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(())
}
/// Calls the comprehensive_mixedparams host function.
///
/// # Arguments
/// * `id` - String parameter.
/// * `filter` - Filter2 parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn mixed_params(id: &str, filter: Filter2) -> Result<i32, Error> {
let response = unsafe {
comprehensive_mixedparams(Json(ComprehensiveMixedParamsRequest {
id: id.to_owned(),
filter: filter,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
/// Calls the comprehensive_noerror host function.
///
/// # Arguments
/// * `name` - String parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn no_error(name: &str) -> Result<String, Error> {
let response = unsafe {
comprehensive_noerror(Json(ComprehensiveNoErrorRequest {
name: name.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
/// Calls the comprehensive_noparams host function.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn no_params() -> Result<(), Error> {
let response = unsafe {
comprehensive_noparams(Json(serde_json::json!({})))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(())
}
/// Calls the comprehensive_noparamsnoreturns host function.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn no_params_no_returns() -> Result<(), Error> {
let response = unsafe {
comprehensive_noparamsnoreturns(Json(serde_json::json!({})))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(())
}
/// Calls the comprehensive_pointerparams host function.
///
/// # Arguments
/// * `id` - Option<String> parameter.
/// * `user` - Option<User2> parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn pointer_params(id: Option<String>, user: Option<User2>) -> Result<Option<User2>, Error> {
let response = unsafe {
comprehensive_pointerparams(Json(ComprehensivePointerParamsRequest {
id: id,
user: user,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
/// Calls the comprehensive_mapparams host function.
///
/// # Arguments
/// * `data` - std::collections::HashMap<String, serde_json::Value> parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn map_params(data: std::collections::HashMap<String, serde_json::Value>) -> Result<serde_json::Value, Error> {
let response = unsafe {
comprehensive_mapparams(Json(ComprehensiveMapParamsRequest {
data: data,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
/// Calls the comprehensive_multiplereturns host function.
///
/// # Arguments
/// * `query` - String parameter.
///
/// # Returns
/// A tuple of (results, total).
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn multiple_returns(query: &str) -> Result<(Vec<User2>, i32), Error> {
let response = unsafe {
comprehensive_multiplereturns(Json(ComprehensiveMultipleReturnsRequest {
query: query.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok((response.0.results, response.0.total))
}
/// Calls the comprehensive_byteslice host function.
///
/// # Arguments
/// * `data` - Vec<u8> parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn byte_slice(data: Vec<u8>) -> Result<Vec<u8>, Error> {
let response = unsafe {
comprehensive_byteslice(Json(ComprehensiveByteSliceRequest {
data: data,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
@@ -0,0 +1,36 @@
package testpkg
import "context"
type User2 struct {
ID string
Name string
}
type Filter2 struct {
Active bool
}
//nd:hostservice name=Comprehensive permission=comprehensive
type ComprehensiveService interface {
//nd:hostfunc
SimpleParams(ctx context.Context, name string, count int32) (string, error)
//nd:hostfunc
StructParam(ctx context.Context, user User2) error
//nd:hostfunc
MixedParams(ctx context.Context, id string, filter Filter2) (int32, error)
//nd:hostfunc
NoError(ctx context.Context, name string) string
//nd:hostfunc
NoParams(ctx context.Context) error
//nd:hostfunc
NoParamsNoReturns(ctx context.Context)
//nd:hostfunc
PointerParams(ctx context.Context, id *string, user *User2) (*User2, error)
//nd:hostfunc
MapParams(ctx context.Context, data map[string]any) (interface{}, error)
//nd:hostfunc
MultipleReturns(ctx context.Context, query string) (results []User2, total int32, err error)
//nd:hostfunc
ByteSlice(ctx context.Context, data []byte) ([]byte, error)
}
@@ -0,0 +1,156 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Config host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package ndhost
import (
"encoding/json"
"errors"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
// config_get is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user config_get
func config_get(uint64) uint64
// config_set is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user config_set
func config_set(uint64) uint64
// config_has is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user config_has
func config_has(uint64) uint64
type configGetRequest struct {
Key string `json:"key"`
}
type configGetResponse struct {
Value string `json:"value,omitempty"`
Exists bool `json:"exists,omitempty"`
Error string `json:"error,omitempty"`
}
type configSetRequest struct {
Key string `json:"key"`
Value string `json:"value"`
}
type configHasRequest struct {
Key string `json:"key"`
}
type configHasResponse struct {
Exists bool `json:"exists,omitempty"`
Error string `json:"error,omitempty"`
}
// ConfigGet calls the config_get host function.
func ConfigGet(key string) (string, bool, error) {
// Marshal request to JSON
req := configGetRequest{
Key: key,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return "", false, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := config_get(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response configGetResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return "", false, err
}
// Convert Error field to Go error
if response.Error != "" {
return "", false, errors.New(response.Error)
}
return response.Value, response.Exists, nil
}
// ConfigSet calls the config_set host function.
func ConfigSet(key string, value string) error {
// Marshal request to JSON
req := configSetRequest{
Key: key,
Value: value,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := config_set(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse error-only response
var response struct {
Error string `json:"error,omitempty"`
}
if err := json.Unmarshal(responseBytes, &response); err != nil {
return err
}
if response.Error != "" {
return errors.New(response.Error)
}
return nil
}
// ConfigHas calls the config_has host function.
func ConfigHas(key string) (bool, error) {
// Marshal request to JSON
req := configHasRequest{
Key: key,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return false, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := config_has(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response configHasResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return false, err
}
// Convert Error field to Go error
if response.Error != "" {
return false, errors.New(response.Error)
}
return response.Exists, nil
}
+126
View File
@@ -0,0 +1,126 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the Config host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
@extism.import_fn("extism:host/user", "config_get")
def _config_get(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "config_set")
def _config_set(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "config_has")
def _config_has(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@dataclass
class ConfigGetResult:
"""Result type for config_get."""
value: str
exists: bool
def config_get(key: str) -> ConfigGetResult:
"""Call the config_get host function.
Args:
key: str parameter.
Returns:
ConfigGetResult containing value, exists,.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"key": key,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _config_get(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return ConfigGetResult(
value=response.get("value", ""),
exists=response.get("exists", False),
)
def config_set(key: str, value: str) -> None:
"""Call the config_set host function.
Args:
key: str parameter.
value: str parameter.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"key": key,
"value": value,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _config_set(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
def config_has(key: str) -> bool:
"""Call the config_has host function.
Args:
key: str parameter.
Returns:
bool: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"key": key,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _config_has(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("exists", False)
+135
View File
@@ -0,0 +1,135 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Config host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ConfigGetRequest {
key: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ConfigGetResponse {
#[serde(default)]
value: String,
#[serde(default)]
exists: bool,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ConfigSetRequest {
key: String,
value: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ConfigSetResponse {
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ConfigHasRequest {
key: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ConfigHasResponse {
#[serde(default)]
exists: bool,
#[serde(default)]
error: Option<String>,
}
#[host_fn]
extern "ExtismHost" {
fn config_get(input: Json<ConfigGetRequest>) -> Json<ConfigGetResponse>;
fn config_set(input: Json<ConfigSetRequest>) -> Json<ConfigSetResponse>;
fn config_has(input: Json<ConfigHasRequest>) -> Json<ConfigHasResponse>;
}
/// Calls the config_get host function.
///
/// # Arguments
/// * `key` - String parameter.
///
/// # Returns
/// `Some(value)` if found, `None` otherwise.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn get(key: &str) -> Result<Option<String>, Error> {
let response = unsafe {
config_get(Json(ConfigGetRequest {
key: key.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
if response.0.exists {
Ok(Some(response.0.value))
} else {
Ok(None)
}
}
/// Calls the config_set host function.
///
/// # Arguments
/// * `key` - String parameter.
/// * `value` - String parameter.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn set(key: &str, value: &str) -> Result<(), Error> {
let response = unsafe {
config_set(Json(ConfigSetRequest {
key: key.to_owned(),
value: value.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(())
}
/// Calls the config_has host function.
///
/// # Arguments
/// * `key` - String parameter.
///
/// # Returns
/// The exists value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn has(key: &str) -> Result<bool, Error> {
let response = unsafe {
config_has(Json(ConfigHasRequest {
key: key.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.exists)
}
+15
View File
@@ -0,0 +1,15 @@
package testpkg
import "context"
//nd:hostservice name=Config permission=config
type ConfigService interface {
//nd:hostfunc
Get(ctx context.Context, key string) (value string, exists bool, err error)
//nd:hostfunc
Set(ctx context.Context, key string, value string) error
//nd:hostfunc
Has(ctx context.Context, key string) (exists bool, err error)
}
@@ -0,0 +1,56 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Counter host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package ndhost
import (
"encoding/json"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
// counter_count is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user counter_count
func counter_count(uint64) uint64
type counterCountRequest struct {
Name string `json:"name"`
}
type counterCountResponse struct {
Value int32 `json:"value,omitempty"`
}
// CounterCount calls the counter_count host function.
func CounterCount(name string) int32 {
// Marshal request to JSON
req := counterCountRequest{
Name: name,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return 0
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := counter_count(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response counterCountResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return 0
}
return response.Value
}
+49
View File
@@ -0,0 +1,49 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the Counter host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
@extism.import_fn("extism:host/user", "counter_count")
def _counter_count(offset: int) -> int:
"""Raw host function - do not call directly."""
...
def counter_count(name: str) -> int:
"""Call the counter_count host function.
Args:
name: str parameter.
Returns:
int: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"name": name,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _counter_count(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
return response.get("value", 0)
+45
View File
@@ -0,0 +1,45 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Counter host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct CounterCountRequest {
name: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CounterCountResponse {
#[serde(default)]
value: i32,
}
#[host_fn]
extern "ExtismHost" {
fn counter_count(input: Json<CounterCountRequest>) -> Json<CounterCountResponse>;
}
/// Calls the counter_count host function.
///
/// # Arguments
/// * `name` - String parameter.
///
/// # Returns
/// The value value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn count(name: &str) -> Result<i32, Error> {
let response = unsafe {
counter_count(Json(CounterCountRequest {
name: name.to_owned(),
}))?
};
Ok(response.0.value)
}
+83
View File
@@ -0,0 +1,83 @@
// Code generated by ndpgen. DO NOT EDIT.
package testpkg
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
)
// CounterCountRequest is the request type for Counter.Count.
type CounterCountRequest struct {
Name string `json:"name"`
}
// CounterCountResponse is the response type for Counter.Count.
type CounterCountResponse struct {
Value int32 `json:"value,omitempty"`
}
// RegisterCounterHostFunctions registers Counter service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterCounterHostFunctions(service CounterService) []extism.HostFunction {
return []extism.HostFunction{
newCounterCountHostFunction(service),
}
}
func newCounterCountHostFunction(service CounterService) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"counter_count",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
// Read JSON request from plugin memory
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
counterWriteError(p, stack, err)
return
}
var req CounterCountRequest
if err := json.Unmarshal(reqBytes, &req); err != nil {
counterWriteError(p, stack, err)
return
}
// Call the service method
value := service.Count(ctx, req.Name)
// Write JSON response to plugin memory
resp := CounterCountResponse{
Value: value,
}
counterWriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
// counterWriteResponse writes a JSON response to plugin memory.
func counterWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
counterWriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
// counterWriteError writes an error response to plugin memory.
func counterWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}
+9
View File
@@ -0,0 +1,9 @@
package testpkg
import "context"
//nd:hostservice name=Counter permission=counter
type CounterService interface {
//nd:hostfunc
Count(ctx context.Context, name string) (value int32)
}
+63
View File
@@ -0,0 +1,63 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Echo host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package ndhost
import (
"encoding/json"
"errors"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
// echo_echo is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user echo_echo
func echo_echo(uint64) uint64
type echoEchoRequest struct {
Message string `json:"message"`
}
type echoEchoResponse struct {
Reply string `json:"reply,omitempty"`
Error string `json:"error,omitempty"`
}
// EchoEcho calls the echo_echo host function.
func EchoEcho(message string) (string, error) {
// Marshal request to JSON
req := echoEchoRequest{
Message: message,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return "", err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := echo_echo(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response echoEchoResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return "", err
}
// Convert Error field to Go error
if response.Error != "" {
return "", errors.New(response.Error)
}
return response.Reply, nil
}
+52
View File
@@ -0,0 +1,52 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the Echo host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
@extism.import_fn("extism:host/user", "echo_echo")
def _echo_echo(offset: int) -> int:
"""Raw host function - do not call directly."""
...
def echo_echo(message: str) -> str:
"""Call the echo_echo host function.
Args:
message: str parameter.
Returns:
str: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"message": message,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _echo_echo(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("reply", "")
+51
View File
@@ -0,0 +1,51 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Echo host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct EchoEchoRequest {
message: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct EchoEchoResponse {
#[serde(default)]
reply: String,
#[serde(default)]
error: Option<String>,
}
#[host_fn]
extern "ExtismHost" {
fn echo_echo(input: Json<EchoEchoRequest>) -> Json<EchoEchoResponse>;
}
/// Calls the echo_echo host function.
///
/// # Arguments
/// * `message` - String parameter.
///
/// # Returns
/// The reply value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn echo(message: &str) -> Result<String, Error> {
let response = unsafe {
echo_echo(Json(EchoEchoRequest {
message: message.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.reply)
}
+88
View File
@@ -0,0 +1,88 @@
// Code generated by ndpgen. DO NOT EDIT.
package testpkg
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
)
// EchoEchoRequest is the request type for Echo.Echo.
type EchoEchoRequest struct {
Message string `json:"message"`
}
// EchoEchoResponse is the response type for Echo.Echo.
type EchoEchoResponse struct {
Reply string `json:"reply,omitempty"`
Error string `json:"error,omitempty"`
}
// RegisterEchoHostFunctions registers Echo service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterEchoHostFunctions(service EchoService) []extism.HostFunction {
return []extism.HostFunction{
newEchoEchoHostFunction(service),
}
}
func newEchoEchoHostFunction(service EchoService) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"echo_echo",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
// Read JSON request from plugin memory
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
echoWriteError(p, stack, err)
return
}
var req EchoEchoRequest
if err := json.Unmarshal(reqBytes, &req); err != nil {
echoWriteError(p, stack, err)
return
}
// Call the service method
reply, svcErr := service.Echo(ctx, req.Message)
if svcErr != nil {
echoWriteError(p, stack, svcErr)
return
}
// Write JSON response to plugin memory
resp := EchoEchoResponse{
Reply: reply,
}
echoWriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
// echoWriteResponse writes a JSON response to plugin memory.
func echoWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
echoWriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
// echoWriteError writes an error response to plugin memory.
func echoWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}
+9
View File
@@ -0,0 +1,9 @@
package testpkg
import "context"
//nd:hostservice name=Echo permission=echo
type EchoService interface {
//nd:hostfunc
Echo(ctx context.Context, message string) (reply string, err error)
}
+70
View File
@@ -0,0 +1,70 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the List host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package ndhost
import (
"encoding/json"
"errors"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
// Filter represents the Filter data structure.
type Filter struct {
Active bool `json:"active"`
}
// list_items is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user list_items
func list_items(uint64) uint64
type listItemsRequest struct {
Name string `json:"name"`
Filter Filter `json:"filter"`
}
type listItemsResponse struct {
Count int32 `json:"count,omitempty"`
Error string `json:"error,omitempty"`
}
// ListItems calls the list_items host function.
func ListItems(name string, filter Filter) (int32, error) {
// Marshal request to JSON
req := listItemsRequest{
Name: name,
Filter: filter,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return 0, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := list_items(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response listItemsResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return 0, err
}
// Convert Error field to Go error
if response.Error != "" {
return 0, errors.New(response.Error)
}
return response.Count, nil
}
+54
View File
@@ -0,0 +1,54 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the List host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
@extism.import_fn("extism:host/user", "list_items")
def _list_items(offset: int) -> int:
"""Raw host function - do not call directly."""
...
def list_items(name: str, filter: Any) -> int:
"""Call the list_items host function.
Args:
name: str parameter.
filter: Any parameter.
Returns:
int: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"name": name,
"filter": filter,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _list_items(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("count", 0)
+60
View File
@@ -0,0 +1,60 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the List host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Filter {
pub active: bool,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ListItemsRequest {
name: String,
filter: Filter,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ListItemsResponse {
#[serde(default)]
count: i32,
#[serde(default)]
error: Option<String>,
}
#[host_fn]
extern "ExtismHost" {
fn list_items(input: Json<ListItemsRequest>) -> Json<ListItemsResponse>;
}
/// Calls the list_items host function.
///
/// # Arguments
/// * `name` - String parameter.
/// * `filter` - Filter parameter.
///
/// # Returns
/// The count value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn items(name: &str, filter: Filter) -> Result<i32, Error> {
let response = unsafe {
list_items(Json(ListItemsRequest {
name: name.to_owned(),
filter: filter,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.count)
}
+89
View File
@@ -0,0 +1,89 @@
// Code generated by ndpgen. DO NOT EDIT.
package testpkg
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
)
// ListItemsRequest is the request type for List.Items.
type ListItemsRequest struct {
Name string `json:"name"`
Filter Filter `json:"filter"`
}
// ListItemsResponse is the response type for List.Items.
type ListItemsResponse struct {
Count int32 `json:"count,omitempty"`
Error string `json:"error,omitempty"`
}
// RegisterListHostFunctions registers List service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterListHostFunctions(service ListService) []extism.HostFunction {
return []extism.HostFunction{
newListItemsHostFunction(service),
}
}
func newListItemsHostFunction(service ListService) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"list_items",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
// Read JSON request from plugin memory
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
listWriteError(p, stack, err)
return
}
var req ListItemsRequest
if err := json.Unmarshal(reqBytes, &req); err != nil {
listWriteError(p, stack, err)
return
}
// Call the service method
count, svcErr := service.Items(ctx, req.Name, req.Filter)
if svcErr != nil {
listWriteError(p, stack, svcErr)
return
}
// Write JSON response to plugin memory
resp := ListItemsResponse{
Count: count,
}
listWriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
// listWriteResponse writes a JSON response to plugin memory.
func listWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
listWriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
// listWriteError writes an error response to plugin memory.
func listWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}
+13
View File
@@ -0,0 +1,13 @@
package testpkg
import "context"
type Filter struct {
Active bool
}
//nd:hostservice name=List permission=list
type ListService interface {
//nd:hostfunc
Items(ctx context.Context, name string, filter Filter) (count int32, err error)
}
+65
View File
@@ -0,0 +1,65 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Math host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package ndhost
import (
"encoding/json"
"errors"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
// math_add is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user math_add
func math_add(uint64) uint64
type mathAddRequest struct {
A int32 `json:"a"`
B int32 `json:"b"`
}
type mathAddResponse struct {
Result int32 `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
// MathAdd calls the math_add host function.
func MathAdd(a int32, b int32) (int32, error) {
// Marshal request to JSON
req := mathAddRequest{
A: a,
B: b,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return 0, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := math_add(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response mathAddResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return 0, err
}
// Convert Error field to Go error
if response.Error != "" {
return 0, errors.New(response.Error)
}
return response.Result, nil
}
+54
View File
@@ -0,0 +1,54 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the Math host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
@extism.import_fn("extism:host/user", "math_add")
def _math_add(offset: int) -> int:
"""Raw host function - do not call directly."""
...
def math_add(a: int, b: int) -> int:
"""Call the math_add host function.
Args:
a: int parameter.
b: int parameter.
Returns:
int: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"a": a,
"b": b,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _math_add(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("result", 0)
+54
View File
@@ -0,0 +1,54 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Math host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct MathAddRequest {
a: i32,
b: i32,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct MathAddResponse {
#[serde(default)]
result: i32,
#[serde(default)]
error: Option<String>,
}
#[host_fn]
extern "ExtismHost" {
fn math_add(input: Json<MathAddRequest>) -> Json<MathAddResponse>;
}
/// Calls the math_add host function.
///
/// # Arguments
/// * `a` - i32 parameter.
/// * `b` - i32 parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn add(a: i32, b: i32) -> Result<i32, Error> {
let response = unsafe {
math_add(Json(MathAddRequest {
a: a,
b: b,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
+89
View File
@@ -0,0 +1,89 @@
// Code generated by ndpgen. DO NOT EDIT.
package testpkg
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
)
// MathAddRequest is the request type for Math.Add.
type MathAddRequest struct {
A int32 `json:"a"`
B int32 `json:"b"`
}
// MathAddResponse is the response type for Math.Add.
type MathAddResponse struct {
Result int32 `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
// RegisterMathHostFunctions registers Math service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterMathHostFunctions(service MathService) []extism.HostFunction {
return []extism.HostFunction{
newMathAddHostFunction(service),
}
}
func newMathAddHostFunction(service MathService) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"math_add",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
// Read JSON request from plugin memory
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
mathWriteError(p, stack, err)
return
}
var req MathAddRequest
if err := json.Unmarshal(reqBytes, &req); err != nil {
mathWriteError(p, stack, err)
return
}
// Call the service method
result, svcErr := service.Add(ctx, req.A, req.B)
if svcErr != nil {
mathWriteError(p, stack, svcErr)
return
}
// Write JSON response to plugin memory
resp := MathAddResponse{
Result: result,
}
mathWriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
// mathWriteResponse writes a JSON response to plugin memory.
func mathWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
mathWriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
// mathWriteError writes an error response to plugin memory.
func mathWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}
+9
View File
@@ -0,0 +1,9 @@
package testpkg
import "context"
//nd:hostservice name=Math permission=math
type MathService interface {
//nd:hostfunc
Add(ctx context.Context, a int32, b int32) (result int32, err error)
}
+105
View File
@@ -0,0 +1,105 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Meta host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package ndhost
import (
"encoding/json"
"errors"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
// meta_get is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user meta_get
func meta_get(uint64) uint64
// meta_set is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user meta_set
func meta_set(uint64) uint64
type metaGetRequest struct {
Key string `json:"key"`
}
type metaGetResponse struct {
Value any `json:"value,omitempty"`
Error string `json:"error,omitempty"`
}
type metaSetRequest struct {
Data map[string]any `json:"data"`
}
// MetaGet calls the meta_get host function.
func MetaGet(key string) (any, error) {
// Marshal request to JSON
req := metaGetRequest{
Key: key,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := meta_get(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response metaGetResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return nil, err
}
// Convert Error field to Go error
if response.Error != "" {
return nil, errors.New(response.Error)
}
return response.Value, nil
}
// MetaSet calls the meta_set host function.
func MetaSet(data map[string]any) error {
// Marshal request to JSON
req := metaSetRequest{
Data: data,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := meta_set(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse error-only response
var response struct {
Error string `json:"error,omitempty"`
}
if err := json.Unmarshal(responseBytes, &response); err != nil {
return err
}
if response.Error != "" {
return errors.New(response.Error)
}
return nil
}
+81
View File
@@ -0,0 +1,81 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the Meta host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
@extism.import_fn("extism:host/user", "meta_get")
def _meta_get(offset: int) -> int:
"""Raw host function - do not call directly."""
...
@extism.import_fn("extism:host/user", "meta_set")
def _meta_set(offset: int) -> int:
"""Raw host function - do not call directly."""
...
def meta_get(key: str) -> Any:
"""Call the meta_get host function.
Args:
key: str parameter.
Returns:
Any: The result value.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"key": key,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _meta_get(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
return response.get("value", None)
def meta_set(data: Any) -> None:
"""Call the meta_set host function.
Args:
data: Any parameter.
Raises:
HostFunctionError: If the host function returns an error.
"""
request = {
"data": data,
}
request_bytes = json.dumps(request).encode("utf-8")
request_mem = extism.memory.alloc(request_bytes)
response_offset = _meta_set(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
if response.get("error"):
raise HostFunctionError(response["error"])
+86
View File
@@ -0,0 +1,86 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Meta host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct MetaGetRequest {
key: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct MetaGetResponse {
#[serde(default)]
value: serde_json::Value,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct MetaSetRequest {
data: std::collections::HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct MetaSetResponse {
#[serde(default)]
error: Option<String>,
}
#[host_fn]
extern "ExtismHost" {
fn meta_get(input: Json<MetaGetRequest>) -> Json<MetaGetResponse>;
fn meta_set(input: Json<MetaSetRequest>) -> Json<MetaSetResponse>;
}
/// Calls the meta_get host function.
///
/// # Arguments
/// * `key` - String parameter.
///
/// # Returns
/// The value value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn get(key: &str) -> Result<serde_json::Value, Error> {
let response = unsafe {
meta_get(Json(MetaGetRequest {
key: key.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.value)
}
/// Calls the meta_set host function.
///
/// # Arguments
/// * `data` - std::collections::HashMap<String, serde_json::Value> parameter.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn set(data: std::collections::HashMap<String, serde_json::Value>) -> Result<(), Error> {
let response = unsafe {
meta_set(Json(MetaSetRequest {
data: data,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(())
}

Some files were not shown because too many files have changed in this diff Show More