Documentation
¶
Overview ¶
Package modding loads and runs sandboxed TSX/JS game mods on top of NSGo's tsx runtime.
A mod lives in a directory containing a mod.yaml manifest (ModManifest, version 1 or 2, read by ParseManifest and written by EncodeManifest) and an entry script (such as mod.tsx or mod.js), or content directories declared under contributes for content-only version 2 mods. Mods import the capability-gated "game" module to subscribe to simulation steps and events, emit events, spawn entities, read and write scoped game state, play audio, persist per-mod storage, write logs, and optionally mount TSX UI panels or HUD widgets. Hosts can also register custom TSX modules (ModModule) gated by host-defined dotted capabilities (HostCapability), look up the calling mod with Caller, enforce per-call permissions with ModAPI.RequireHost, narrow grants with ManagerOptions.GrantHost and Manager.SetHostGrant, and emit TypeScript declarations with WriteModAPIDTS.
Manager discovers mods from the filesystem or any io/fs.FS, isolates discovery failures per mod (StateFailed on ModInfo) so one broken mod never blocks sibling mods, installs or removes individual mods dynamically (Manager.Install, Manager.Uninstall), validates manifests and platform filters, resolves required dependencies, optional dependencies, and conflicts (ErrConflictingMods) in deterministic topological order, overlays loaded mods' contributed content directories through Manager.ContentFS with strict mod-directory path and symlink confinement, isolates runtime faults, persists enabled/disabled state via core.Storage, and drives step hooks from [game.Loop].
Workshop integrates Steam Workshop (Steamworks ISteamUGC) with Manager through a WorkshopBackend: NewSteamWorkshop binds the Steamworks flat C API via purego on macOS, Linux and Windows (returning ErrWorkshopUnavailable when Steam is absent or on web/mobile), while NewMemoryWorkshop simulates multi-user publishing, subscriptions and updates on disk for tests and offline workflows. Published mods store deterministic Workshop metadata in workshop.yaml (WorkshopMetadata).
Index ¶
- Constants
- Variables
- func CheckConstraint(version, constraint string) (bool, error)
- func EncodeManifest(m ModManifest) ([]byte, error)
- func EncodeWorkshopMetadata(m WorkshopMetadata) ([]byte, error)
- func RegisterModule(mod ModModule)
- func SupportedPlatforms() []string
- func ValidHostCapability(name string) bool
- func ValidateConstraint(constraint string) error
- func WriteGameAPIDTS(dst string) error
- func WriteModAPIDTS(dir string, opts ManagerOptions) error
- type Capability
- func (c Capability) Has(req Capability) bool
- func (c Capability) MarshalJSON() ([]byte, error)
- func (c Capability) MarshalYAML() (any, error)
- func (c Capability) Names() []string
- func (c Capability) String() string
- func (c *Capability) UnmarshalJSON(data []byte) error
- func (c *Capability) UnmarshalYAML(value *yaml.Node) error
- type Event
- type GameBridge
- type HostCapability
- type InstallInfo
- type InstalledWorkshopItem
- type LogEntry
- type Manager
- func (m *Manager) API(id string) (*ModAPI, bool)
- func (m *Manager) Call(id, fnName string, args []any, done func(result any, err error))
- func (m *Manager) Close()
- func (m *Manager) ContentFS() fs.FS
- func (m *Manager) Disable(id string) error
- func (m *Manager) Discover(dir string) ([]ModManifest, error)
- func (m *Manager) DiscoverFS(fsys fs.FS) ([]ModManifest, error)
- func (m *Manager) Emit(name string, payload any)
- func (m *Manager) Enable(id string) error
- func (m *Manager) GetState(key string) (any, bool)
- func (m *Manager) HostCapabilities() []HostCapability
- func (m *Manager) Info(id string) (ModInfo, bool)
- func (m *Manager) Install(dir string) (ModManifest, error)
- func (m *Manager) InstallFS(fsys fs.FS, dirName string) (ModManifest, error)
- func (m *Manager) List() []ModInfo
- func (m *Manager) Load(id string) error
- func (m *Manager) LoadAll() error
- func (m *Manager) Logs(id string) []LogEntry
- func (m *Manager) Panels(slot string) []Panel
- func (m *Manager) PanelsView(slot string) core.Node
- func (m *Manager) Reload(id string) error
- func (m *Manager) SetGrant(id string, caps Capability) error
- func (m *Manager) SetHostGrant(id string, caps []string) error
- func (m *Manager) SetState(key string, val any)
- func (m *Manager) Step(dt time.Duration)
- func (m *Manager) Uninstall(id string) error
- func (m *Manager) Unload(id string) error
- type ManagerOptions
- type MemoryWorkshop
- func (m *MemoryWorkshop) AsUser(steamUserID uint64) WorkshopBackend
- func (m *MemoryWorkshop) CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)
- func (m *MemoryWorkshop) DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) error
- func (m *MemoryWorkshop) ItemContentDir(id PublishedFileID) (string, bool)
- func (m *MemoryWorkshop) ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)
- func (m *MemoryWorkshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
- func (m *MemoryWorkshop) SetNeedsLegalAgreement(userID uint64, required bool)
- func (m *MemoryWorkshop) SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)
- func (m *MemoryWorkshop) Subscribe(ctx context.Context, id PublishedFileID) error
- func (m *MemoryWorkshop) SubscribedItems(ctx context.Context) ([]PublishedFileID, error)
- func (m *MemoryWorkshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
- type ModAPI
- func (a *ModAPI) Capabilities() Capability
- func (a *ModAPI) Emit(name string, payload any) error
- func (a *ModAPI) GetState(key string) (any, bool, error)
- func (a *ModAPI) HasHostCapability(capability string) bool
- func (a *ModAPI) HostCapabilities() []string
- func (a *ModAPI) Log(msg string)
- func (a *ModAPI) Logs() []LogEntry
- func (a *ModAPI) Manifest() ModManifest
- func (a *ModAPI) MountPanel(id string, render func() core.Node, slot string) error
- func (a *ModAPI) OnEvent(name string, fn func(payload any)) (func(), error)
- func (a *ModAPI) OnStep(fn func(dt float64)) (func(), error)
- func (a *ModAPI) PlaySound(name string, opts map[string]any) error
- func (a *ModAPI) RegisterHook(event string, fn func(any)) (func(), error)
- func (a *ModAPI) RequireHost(capability, action string) error
- func (a *ModAPI) SetState(key string, val any) error
- func (a *ModAPI) Spawn(prefab string, x, y float64, props map[string]any) (string, error)
- func (a *ModAPI) StorageGet(key string) (string, bool, error)
- func (a *ModAPI) StorageRemove(key string) error
- func (a *ModAPI) StorageSet(key, val string) error
- func (a *ModAPI) UnmountPanel(id string) error
- type ModContributes
- type ModInfo
- type ModManifest
- type ModModule
- type ModState
- type Panel
- type PermissionError
- type PublishOptions
- type PublishRequest
- type PublishResult
- type PublishedFileID
- type SemVer
- type SoundRequest
- type SpawnRequest
- type SteamWorkshop
- func (w *SteamWorkshop) Close() error
- func (w *SteamWorkshop) CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)
- func (w *SteamWorkshop) DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) error
- func (w *SteamWorkshop) ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)
- func (w *SteamWorkshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
- func (w *SteamWorkshop) SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)
- func (w *SteamWorkshop) Subscribe(ctx context.Context, id PublishedFileID) error
- func (w *SteamWorkshop) SubscribedItems(ctx context.Context) ([]PublishedFileID, error)
- func (w *SteamWorkshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
- type SteamWorkshopOptions
- type SyncResult
- type Workshop
- func (w *Workshop) InstallSubscribed(ctx context.Context, id PublishedFileID) (InstalledWorkshopItem, error)
- func (w *Workshop) Installed() []InstalledWorkshopItem
- func (w *Workshop) Publish(ctx context.Context, dir string, opts PublishOptions) (PublishResult, error)
- func (w *Workshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
- func (w *Workshop) Subscribe(ctx context.Context, id PublishedFileID) error
- func (w *Workshop) SyncSubscribed(ctx context.Context) (SyncResult, error)
- func (w *Workshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
- type WorkshopBackend
- type WorkshopItem
- type WorkshopMetadata
- type WorkshopOptions
- type WorkshopQuery
- type WorkshopVisibility
Examples ¶
Constants ¶
const ( // MinManifestVersion is the oldest mod manifest schema version this package reads and writes (1). MinManifestVersion = 1 // ManifestVersion is the newest mod manifest schema version this package reads and writes (2), adding optionalDependencies, conflicts, platforms, and contributes. ManifestVersion = 2 // SchemaURL is where the JSON Schema of version 1 mod.yaml manifests is published. SchemaURL = "https://game.nsgo.dev/schemas/mod.v1.json" // SchemaURLV2 is where the JSON Schema of version 2 mod.yaml manifests is published. SchemaURLV2 = "https://game.nsgo.dev/schemas/mod.v2.json" )
const ( // WorkshopFile is the deterministic YAML metadata file stored beside mod.yaml in a mod // directory published to Steam Workshop. WorkshopFile = "workshop.yaml" // WorkshopMetadataVersion is the workshop.yaml schema version this package reads and writes. WorkshopMetadataVersion = 1 // WorkshopLegalAgreementURL is the Steam Workshop Subscriber Agreement page shown when // Steamworks reports that the publisher must accept the legal agreement before an item // becomes visible to other players. WorkshopLegalAgreementURL = "https://steamcommunity.com/sharedfiles/workshoplegalagreement" )
const GameAPIDTS = `` /* 3427-byte string literal not displayed */
GameAPIDTS is the TypeScript declaration file (game.d.ts) for the sandboxed "game" module. Mod authors can include it in their tsconfig.json to get full TypeScript type checking.
const GameModule = "game"
GameModule is the module specifier mods import to reach the sandboxed game API:
import { onStep, onEvent, emit, spawn, getState, setState, log } from "game";
const ManifestFile = "mod.yaml"
ManifestFile is the name of the manifest file Manager reads from each mod's directory.
Variables ¶
var ( // ErrPermission is returned when a mod calls an API it lacks the capability for. ErrPermission = errors.New("modding: permission denied") // ErrNotFound is returned when a mod ID is not known to the manager. ErrNotFound = errors.New("modding: mod not found") // ErrDuplicateMod is returned when two discovered mods share the same ID. ErrDuplicateMod = errors.New("modding: duplicate mod id") // ErrMissingDependency is returned when a mod declares a dependency that was not discovered. ErrMissingDependency = errors.New("modding: missing dependency") // ErrVersionMismatch is returned when a dependency or game version fails a version constraint. ErrVersionMismatch = errors.New("modding: incompatible version") // ErrCyclicDependency is returned when mod dependencies form a cycle. ErrCyclicDependency = errors.New("modding: cyclic dependency") // ErrConflictingMods is returned when two mods cannot be loaded together because one declares a conflict matching the other. ErrConflictingMods = errors.New("modding: conflicting mods") // ErrUnsupportedPlatform is returned when a mod's platforms list does not include the host platform. ErrUnsupportedPlatform = errors.New("modding: unsupported platform") // ErrUnsafePath is returned when a mod file or symlink escapes its mod directory. ErrUnsafePath = errors.New("modding: unsafe mod path") // ErrInvalidManifest is returned when a mod.yaml manifest fails parsing or validation. ErrInvalidManifest = errors.New("modding: invalid manifest") // ErrModDisabled is returned when attempting to load a disabled mod. ErrModDisabled = errors.New("modding: mod is disabled") // ErrModFailed is returned when interacting with a mod in StateFailed. ErrModFailed = errors.New("modding: mod failed") // ErrWebUnisolated is returned when a mod would load on the web, where its capabilities cannot be enforced, without ManagerOptions.WebUnisolated. ErrWebUnisolated = errors.New("modding: the web cannot isolate mods from the page; set ManagerOptions.WebUnisolated to run them with the page's authority") // ErrUnknownCapability is returned when a mod manifest requests a host capability the manager does not define. ErrUnknownCapability = errors.New("modding: unknown host capability") )
var ( // Steam client not running, or unsupported platform such as web or mobile). ErrWorkshopUnavailable = errors.New("modding: steam workshop unavailable") // ErrWorkshopNotFound is returned when a Workshop PublishedFileID does not exist. ErrWorkshopNotFound = errors.New("modding: workshop item not found") // ErrWorkshopNotInstalled is returned when a Workshop item is not downloaded locally // or needs an update before it can be read from disk. ErrWorkshopNotInstalled = errors.New("modding: workshop item not installed") // ErrWorkshopLegalAgreementRequired is returned when Steamworks requires the author to // accept the Steam Workshop Subscriber Agreement before the item is public. ErrWorkshopLegalAgreementRequired = errors.New("modding: steam workshop legal agreement acceptance required") // ErrInvalidWorkshopMetadata is returned when workshop.yaml fails parsing or validation. ErrInvalidWorkshopMetadata = errors.New("modding: invalid workshop metadata") // ErrWorkshopUnsafePath is returned when a Workshop directory or file escapes its // allowed root or mod directory via path traversal or symlinks. ErrWorkshopUnsafePath = errors.New("modding: unsafe workshop path") )
Functions ¶
func CheckConstraint ¶
CheckConstraint reports whether version satisfies constraint. Supported operators: *, =, >=, >, <=, <, ^, ~, partial versions such as ^1.2, and space/comma-separated conjunctions.
Example ¶
CheckConstraint tests a version against a constraint such as a manifest's gameVersion.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/modding"
)
func main() {
for _, c := range []string{"^1.2.0", ">=2.0.0", "~1.4.0"} {
ok, err := modding.CheckConstraint("1.4.3", c)
fmt.Println(c, ok, err)
}
v, _ := modding.ParseSemVer("2.0.0-beta.1")
stable, _ := modding.ParseSemVer("2.0.0")
fmt.Println(v, v.Compare(stable))
}
Output: ^1.2.0 true <nil> >=2.0.0 false <nil> ~1.4.0 true <nil> 2.0.0-beta.1 -1
func EncodeManifest ¶
func EncodeManifest(m ModManifest) ([]byte, error)
EncodeManifest validates m and writes it as deterministic 2-space YAML: fields in a fixed order, built-in capabilities in canonical order followed by host capabilities sorted in byte order, maps (dependencies, optionalDependencies, conflicts) sorted by ID in byte order, and platforms as a flow sequence sorted in byte order. A ManifestVersion of 0 (a manifest built in code) is written as ManifestVersion; version 1 and version 2 manifests preserve their ManifestVersion so existing v1 files round-trip byte for byte.
func EncodeWorkshopMetadata ¶
func EncodeWorkshopMetadata(m WorkshopMetadata) ([]byte, error)
EncodeWorkshopMetadata validates m and encodes it as deterministic 2-space YAML with fixed key order and tags sorted in byte order. A Version of 0 is written as WorkshopMetadataVersion.
func RegisterModule ¶
func RegisterModule(mod ModModule)
RegisterModule pre-registers a host ModModule's function signatures with tsx.RegisterFunctions before any TSX runtime starts (for example, from a package init function).
Subsequent NewManager calls in the same process—including after TSX runtimes have started or across multiple game sessions—can pass a ModModule with the same Name and matching function signatures to bind per-manager implementations. Panics if mod is invalid or already registered.
func SupportedPlatforms ¶
func SupportedPlatforms() []string
SupportedPlatforms returns a copy of the canonical target platform names accepted in a v2 manifest's platforms field.
func ValidHostCapability ¶
ValidHostCapability reports whether name is a valid host capability name: two or more dot-separated lower camel case ASCII segments (such as "inventory.read" or "editor.contextAction").
func ValidateConstraint ¶
ValidateConstraint checks that constraint is a syntactically valid version constraint.
func WriteGameAPIDTS ¶
WriteGameAPIDTS writes GameAPIDTS to dst (creating parent directories as needed) so mod projects can reference game.d.ts for TypeScript type checking.
func WriteModAPIDTS ¶
func WriteModAPIDTS(dir string, opts ManagerOptions) error
WriteModAPIDTS writes game.d.ts plus one TypeScript declaration file per host module in opts.Modules under dir, using GameAPIDTS for "game" and tsx.Declarations for each host module. Parent directories are created as needed.
Types ¶
type Capability ¶
type Capability uint32
Capability is a bitmask of permissions granted to a mod. A mod may only call game API operations covered by both its manifest and the host's grant.
const ( // CapNone grants no privileged game API capabilities (hooks and logging remain available). CapNone Capability = 0 // CapReadState allows reading scoped game state via getState. CapReadState Capability = 1 << iota // CapWriteState allows writing scoped game state via setState. CapWriteState // CapSpawnEntity allows spawning entities via spawn. CapSpawnEntity // CapEmitEvent allows emitting game events via emit. CapEmitEvent // CapUI allows mounting and unmounting TSX UI panels and HUD widgets. CapUI // CapAudio allows playing sounds through the game bridge and NSGo audio. CapAudio // CapStorage allows reading/writing persistent per-mod storage (and scoped state writes). CapStorage // CapAll includes every defined game modding capability. CapAll = CapReadState | CapWriteState | CapSpawnEntity | CapEmitEvent | CapUI | CapAudio | CapStorage )
func ParseCapability ¶
func ParseCapability(name string) (Capability, error)
ParseCapability parses a capability name (camelCase, snake_case, or kebab-case).
func (Capability) Has ¶
func (c Capability) Has(req Capability) bool
Has reports whether c contains all capabilities in req.
func (Capability) MarshalJSON ¶
func (c Capability) MarshalJSON() ([]byte, error)
MarshalJSON encodes c as a JSON array of canonical capability names.
func (Capability) MarshalYAML ¶
func (c Capability) MarshalYAML() (any, error)
MarshalYAML encodes c as a flow sequence of canonical capability names in table order, so a manifest's capabilities always serialize the same way regardless of how they were listed.
func (Capability) Names ¶
func (c Capability) Names() []string
Names returns the canonical names of the capabilities set in c, in deterministic order.
func (Capability) String ¶
func (c Capability) String() string
String returns a comma-separated list of capability names, or "none" when empty.
func (*Capability) UnmarshalJSON ¶
func (c *Capability) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a JSON array of capability names into c.
func (*Capability) UnmarshalYAML ¶
func (c *Capability) UnmarshalYAML(value *yaml.Node) error
UnmarshalYAML decodes a YAML sequence of canonical capability names (such as readState) into c. Unknown, non-canonical and repeated names are refused.
type Event ¶
type Event struct {
// ModID is the emitting mod's ID, or empty when emitted by the host.
ModID string
Name string
Payload any
}
Event describes an event emitted by a mod or by the host game.
type GameBridge ¶
type GameBridge struct {
// OnSpawn handles entity spawn requests from mods with CapSpawnEntity.
// Returning an entity ID passes it back to the mod; returning an error throws in JS.
OnSpawn func(req SpawnRequest) (string, error)
// OnEmit is notified whenever a mod with CapEmitEvent emits an event.
// Events are also dispatched to subscribed mods in load order.
OnEmit func(ev Event)
// OnGetState reads a scoped state key for mods with CapReadState.
// When nil, reads from the manager's built-in state map.
OnGetState func(modID, key string) (any, bool)
// OnSetState writes a scoped state key for mods with CapWriteState or CapStorage.
// When nil, writes to the manager's built-in state map.
OnSetState func(modID, key string, val any) error
// OnPlaySound handles audio playback requests from mods with CapAudio.
OnPlaySound func(req SoundRequest) error
// OnLog is notified whenever a mod logs a message, in addition to the per-mod log buffer.
OnLog func(entry LogEntry)
// OnPanelsChange is notified whenever a mod mounts or unmounts a UI panel.
OnPanelsChange func()
}
GameBridge connects sandboxed mods to the host game. All callbacks are optional: when nil, Manager supplies safe built-in defaults for scoped state, entity ID generation, event dispatch, and UI panels.
type HostCapability ¶
type HostCapability struct {
// Name is the canonical capability name in "<namespace>.<name>" form,
// using dot-separated lower camel case segments (such as "inventory.read").
Name string
// Doc describes what the capability permits, for display in player permission prompts.
Doc string
}
HostCapability defines a host-owned capability that mods can request in mod.yaml and that gates host-registered TSX modules or individual host module functions.
type InstallInfo ¶
type InstallInfo struct {
ID PublishedFileID
SizeOnDisk uint64
Folder string
Timestamp time.Time
}
InstallInfo describes a locally downloaded Steam Workshop item on disk.
type InstalledWorkshopItem ¶
type InstalledWorkshopItem struct {
ID PublishedFileID
ModID string
Manifest ModManifest
Folder string
Timestamp time.Time
}
InstalledWorkshopItem links a Steam Workshop PublishedFileID to the mod installed in Manager.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager discovers, validates, loads, isolates, and steps TSX/JS game mods under a *core.Scope. All methods should be called on the engine's goroutine, as NSGo scopes and game.Loop are.
Example ¶
A Manager discovers mods in a directory, one per subdirectory with a mod.yaml, checks their manifests, entries and dependencies, and keeps them in load order; Disable keeps a mod from loading and, with a StorageKey, remembers that in the app's storage. Load then runs an enabled mod's entry in its TSX sandbox.
package main
import (
"fmt"
"testing/fstest"
"github.com/nsgo-dev/game/pkg/modding"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
root := core.NewRoot(core.RootOptions{})
defer root.Dispose()
mods := fstest.MapFS{
"hats/mod.yaml": {Data: []byte("manifestVersion: 1\nid: slime-hats\nname: Slime Hats\nversion: 1.0.0\nentry: mod.ts\ndependencies:\n more-slimes: '>=1.1.0'\n")},
"hats/mod.ts": {Data: []byte("export function init() {}\n")},
"slimes/mod.yaml": {Data: []byte("manifestVersion: 1\nid: more-slimes\nname: More Slimes\nversion: 1.2.0\nentry: mod.ts\ngameVersion: ^1.0.0\n")},
"slimes/mod.ts": {Data: []byte("export function init() {}\n")},
}
opts := modding.ManagerOptions{StorageKey: "mods", GameVersion: "1.4.0"}
m := modding.NewManager(root, opts)
if _, err := m.DiscoverFS(mods); err != nil {
fmt.Println(err)
return
}
_ = m.Disable("slime-hats")
m.Close()
// A later session finds the preference in storage.
again := modding.NewManager(root, opts)
defer again.Close()
if _, err := again.DiscoverFS(mods); err != nil {
fmt.Println(err)
return
}
for _, info := range again.List() {
fmt.Println(info.Order, info.Manifest.ID, info.State, info.Enabled)
}
}
Output: 0 more-slimes discovered true 1 slime-hats disabled false
func NewManager ¶
func NewManager(cx *core.Scope, opts ManagerOptions) *Manager
NewManager creates a mod manager scoped to cx. Disposing cx automatically unloads all mods.
Any host modules in opts.Modules are validated against opts.Capabilities and registered with tsx.RegisterFunctions (or attached to a prior RegisterModule registration). NewManager panics if opts.Capabilities or opts.Modules contain invalid names, duplicates, a name colliding with "game" or "nsgo", or a module without a declared capability.
func (*Manager) Close ¶
func (m *Manager) Close()
Close unloads all mods and releases resources held by the manager. Afterwards no mod reports StateLoaded: Manager.Info shows each loaded mod as discovered, or disabled when it is.
func (*Manager) ContentFS ¶
ContentFS returns a read-only io/fs.FS overlaying the contributes directories of every currently loaded mod in load order (later mods win per path).
Files appear under the canonical category directories declared by ModContributes: "assets/...", "scenes/...", "l10n/...", and "datatables/...". A host can pass the returned FS directly to [assets.WithFS] or take a category subtree with io/fs.Sub (for example, fs.Sub(mgr.ContentFS(), "assets") or fs.Sub(mgr.ContentFS(), "l10n")).
The returned FS reflects load, unload, reload, and discovery updates safely across goroutines. Paths are strictly confined to each mod's directory; path traversal and symlinks escaping a mod's directory are refused.
func (*Manager) Disable ¶
Disable marks mod id as disabled, unloads it if currently loaded, and persists the preference when StorageKey is configured.
func (*Manager) Discover ¶
func (m *Manager) Discover(dir string) ([]ModManifest, error)
Discover scans immediate subdirectories of dir for mod.yaml manifests, validates them, resolves dependency order, and registers them with the manager.
func (*Manager) DiscoverFS ¶
func (m *Manager) DiscoverFS(fsys fs.FS) ([]ModManifest, error)
DiscoverFS scans immediate subdirectories of fsys for mod.yaml manifests (ManifestFile), validates them, checks GameVersion, platform compatibility, entry files, and contributes directories, resolves dependency order via topological sort, and registers them with the manager. Subdirectories without a manifest are skipped; one that still has only a mod.json fails with ErrInvalidManifest.
Failures are isolated per mod: a bad manifest, missing entry or contributes directory, unsupported platform, duplicate ID (failing both mods), conflict (failing both mods), unsatisfied or failed dependency, or dependency cycle records that mod as StateFailed with its Error on ModInfo and continues scanning the rest. Healthy mods are registered and returned in deterministic topological order, and any per-mod failures are returned as a joined error.
If the top-level directory itself cannot be read, existing loaded mods are left untouched.
func (*Manager) Emit ¶
Emit dispatches a host event to all loaded mods subscribed via onEvent or registerHook, in deterministic load order, with fault isolation.
func (*Manager) Enable ¶
Enable marks mod id as enabled and persists the preference when StorageKey is configured.
func (*Manager) GetState ¶
GetState reads a value from the manager's built-in scoped game state map.
func (*Manager) HostCapabilities ¶
func (m *Manager) HostCapabilities() []HostCapability
HostCapabilities returns a copy of the host capabilities declared in ManagerOptions.Capabilities.
func (*Manager) Install ¶
func (m *Manager) Install(dir string) (ModManifest, error)
Install validates a single mod directory on disk and installs or updates it in the manager without disturbing unrelated mods. If a mod with the same ID is already registered, its running instance (if any) is unloaded and replaced. Call Manager.Load or Manager.LoadAll to start the installed mod.
func (*Manager) InstallFS ¶
InstallFS validates a single mod rooted at fsys and installs or updates it in the manager without disturbing unrelated mods. dirName labels the mod directory in manifest errors. Dependency order across all registered mods is re-validated; if validation fails, existing mods remain untouched.
func (*Manager) List ¶
List returns snapshots of all discovered mods in deterministic load order, followed by any mods that failed during discovery in deterministic directory order.
func (*Manager) Load ¶
Load compiles and starts mod id in its sandbox (or activates its contributed content for content-only v2 mods without an entry script). Any required dependencies and present enabled optional dependencies not yet loaded are loaded first. Compilation, entry execution, or panic failures are caught cleanly, marking the mod StateFailed without crashing the host or other mods.
func (*Manager) LoadAll ¶
LoadAll loads all enabled discovered mods in deterministic topological order. A failure in one mod is isolated (marking that mod StateFailed) and does not prevent sibling mods from loading. Returns a joined error if any mod failed.
func (*Manager) Panels ¶
Panels returns all currently mounted UI panels across loaded mods in deterministic order. When slot is non-empty, only panels mounted for that slot are returned.
func (*Manager) PanelsView ¶
PanelsView returns a reactive core.Node rendering all TSX UI panels mounted for slot (or all slots when slot is empty). Each panel is wrapped in a core.Catch boundary so a render error in one mod's UI never crashes the host game or other mods.
func (*Manager) Reload ¶
Reload re-reads mod id's manifest if present, validates it, then unloads the mod and loads it fresh from its FS.
A manifest that cannot be read or fails validation (bad syntax, changed ID, incompatible game version, unsupported platform, missing entry/contributes, or unresolvable dependencies/conflicts) is reported without unloading, so the previously loaded version keeps running (#546). A mod whose mod.yaml has been replaced by a mod.json is refused the same way with ErrInvalidManifest, as Manager.DiscoverFS refuses it.
func (*Manager) SetGrant ¶
func (m *Manager) SetGrant(id string, caps Capability) error
SetGrant sets a per-mod capability grant for id, further narrowing its manifest capabilities (and ManagerOptions.Grant if set).
On a loaded mod it takes effect at once (#546): the game module checks the new capabilities from the next call, revoking CapUI removes the panels the mod mounted, and when the change reaches what the sandbox itself enforces (CapAudio, CapStorage), the mod is unloaded and loaded again with a sandbox built for them, running its entry script again. The error is that load's.
func (*Manager) SetHostGrant ¶
SetHostGrant sets a per-mod host capability grant for id, further narrowing its manifest host capabilities (and ManagerOptions.GrantHost if non-nil). Passing nil or an empty slice revokes all host capabilities for id.
On a loaded mod it takes effect at once: host module trampolines and ModAPI.RequireHost enforce the narrowed host capabilities from the next call. On subsequent loads or reloads, the mod's sandbox module import allowlist also reflects the grant.
func (*Manager) Step ¶
Step invokes all loaded mods' onStep (and registerHook("step", ...)) callbacks in deterministic load order. A runtime error or panic inside one mod isolates and marks that mod StateFailed without interrupting other mods.
type ManagerOptions ¶
type ManagerOptions struct {
// Bridge connects mod API calls to the host game.
Bridge GameBridge
// StorageKey, when non-empty, persists mod enabled/disabled state in cx.Storage()
// under "<StorageKey>.enabled.<id>" and isolates per-mod CapStorage keys under
// "<StorageKey>.mod.<id>.<key>".
StorageKey string
// GameVersion, when non-empty, checks each discovered mod's manifest.GameVersion constraint.
GameVersion string
// Platform overrides the host platform checked against a v2 manifest's platforms list
// (such as "windows", "macos", "linux", "ios", "android", or "web"). When empty, it
// defaults to the current runtime platform (mapping "darwin" to "macos" and "js" to "web").
Platform string
// Grant, when non-nil, narrows every mod's manifest capabilities to (manifest.Capabilities & *Grant).
Grant *Capability
// GrantHost, when non-nil, narrows every mod's manifest host capabilities to those listed here.
// A nil slice applies no host-level narrowing; a non-nil empty slice ([]string{}) denies all host capabilities.
GrantHost []string
// Modules registers host TSX modules that mods can import when granted the module's capability.
// Each module's functions are registered with [tsx.RegisterFunctions] (or attached to an earlier [RegisterModule] registration with matching signatures).
Modules []ModModule
// Capabilities declares the host-defined capabilities that mods may request in mod.yaml.
Capabilities []HostCapability
// Limits overrides tsx.DefaultLimits for each mod's sandbox.
Limits *tsx.Limits
// MaxLogs caps the number of retained log entries per mod (256 when <= 0).
MaxLogs int
// WebUnisolated lets mods run on web targets, where the browser cannot isolate a mod from the page: a mod there can use the page's own APIs (XMLHttpRequest, WebSocket, localStorage) whatever its capabilities say. Without it, loading a mod on the web fails with ErrWebUnisolated. Other targets isolate mods and ignore it. It is forwarded as tsx.Sandbox.WebUnisolated.
WebUnisolated bool
}
ManagerOptions configures a Manager.
type MemoryWorkshop ¶
type MemoryWorkshop struct {
// contains filtered or unexported fields
}
MemoryWorkshop is an in-memory and filesystem-backed WorkshopBackend that simulates Steam Workshop publishing, querying, subscribing, downloading, and updates without requiring the Steam client. It supports multiple users via MemoryWorkshop.AsUser so one user can publish a mod and another player can subscribe and install it through Manager.
func NewMemoryWorkshop ¶
func NewMemoryWorkshop(rootDir string) *MemoryWorkshop
NewMemoryWorkshop creates a MemoryWorkshop storing published item snapshots and per-user downloaded copies inside rootDir.
func (*MemoryWorkshop) AsUser ¶
func (m *MemoryWorkshop) AsUser(steamUserID uint64) WorkshopBackend
AsUser returns a WorkshopBackend view scoped to steamUserID sharing this Workshop catalog.
func (*MemoryWorkshop) CreateItem ¶
func (m *MemoryWorkshop) CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)
CreateItem implements WorkshopBackend for the default user (ID 0).
func (*MemoryWorkshop) DownloadItem ¶
func (m *MemoryWorkshop) DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) error
DownloadItem implements WorkshopBackend for the default user (ID 0).
func (*MemoryWorkshop) ItemContentDir ¶
func (m *MemoryWorkshop) ItemContentDir(id PublishedFileID) (string, bool)
ItemContentDir returns the stored Workshop snapshot directory for id, if published.
func (*MemoryWorkshop) ItemInstallInfo ¶
func (m *MemoryWorkshop) ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)
ItemInstallInfo implements WorkshopBackend for the default user (ID 0).
func (*MemoryWorkshop) QueryItems ¶
func (m *MemoryWorkshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
QueryItems implements WorkshopBackend for the default user (ID 0).
func (*MemoryWorkshop) SetNeedsLegalAgreement ¶
func (m *MemoryWorkshop) SetNeedsLegalAgreement(userID uint64, required bool)
SetNeedsLegalAgreement configures whether SubmitUpdate reports NeedsLegalAgreement for userID (use 0 for the default user when calling methods directly on *MemoryWorkshop).
func (*MemoryWorkshop) SubmitUpdate ¶
func (m *MemoryWorkshop) SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)
SubmitUpdate implements WorkshopBackend for the default user (ID 0).
func (*MemoryWorkshop) Subscribe ¶
func (m *MemoryWorkshop) Subscribe(ctx context.Context, id PublishedFileID) error
Subscribe implements WorkshopBackend for the default user (ID 0).
func (*MemoryWorkshop) SubscribedItems ¶
func (m *MemoryWorkshop) SubscribedItems(ctx context.Context) ([]PublishedFileID, error)
SubscribedItems implements WorkshopBackend for the default user (ID 0).
func (*MemoryWorkshop) Unsubscribe ¶
func (m *MemoryWorkshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
Unsubscribe implements WorkshopBackend for the default user (ID 0).
type ModAPI ¶
type ModAPI struct {
// contains filtered or unexported fields
}
ModAPI is the capability-gated game API bound to a single loaded mod instance. TSX/JS mods access it by importing functions from the "game" module; Go code may also inspect or invoke it via Manager.API.
func Caller ¶
Caller returns the *ModAPI of the mod whose code is running in cx, for host module functions.
func (*ModAPI) Capabilities ¶
func (a *ModAPI) Capabilities() Capability
Capabilities returns the effective built-in capabilities granted to this mod.
func (*ModAPI) Emit ¶
Emit emits an event to the host bridge and all loaded mods subscribed to name. Requires CapEmitEvent.
func (*ModAPI) GetState ¶
GetState reads a key from scoped game state. Requires CapReadState.
func (*ModAPI) HasHostCapability ¶
HasHostCapability reports whether this mod is currently granted the named host capability.
func (*ModAPI) HostCapabilities ¶
HostCapabilities returns a copy of the effective host capability names granted to this mod, sorted in byte order.
func (*ModAPI) Log ¶
Log appends a message to the mod's captured log buffer and notifies Bridge.OnLog.
func (*ModAPI) Manifest ¶
func (a *ModAPI) Manifest() ModManifest
Manifest returns the mod's manifest.
func (*ModAPI) MountPanel ¶
MountPanel mounts or replaces a TSX UI panel or HUD widget for this mod. Requires CapUI.
func (*ModAPI) OnEvent ¶
OnEvent registers a callback invoked whenever an event named name is emitted.
func (*ModAPI) OnStep ¶
OnStep registers a callback invoked on each Manager.Step tick with dt in seconds.
func (*ModAPI) PlaySound ¶
PlaySound requests the host game to play a named sound. Requires CapAudio.
func (*ModAPI) RegisterHook ¶
RegisterHook subscribes fn to event. Event "step" subscribes to fixed simulation steps (receiving dt in seconds); any other name subscribes to emitted events of that name.
func (*ModAPI) RequireHost ¶
RequireHost verifies that this mod is active and currently holds the named host capability. When denied, it returns a *PermissionError wrapping ErrPermission and a *core.Error with core.CodeAccessDenied.
func (*ModAPI) SetState ¶
SetState writes a key to scoped game state. Requires CapWriteState or CapStorage.
func (*ModAPI) Spawn ¶
Spawn requests the host game to spawn an entity of prefab at (x, y) with optional props. Requires CapSpawnEntity.
func (*ModAPI) StorageGet ¶
StorageGet reads a string value from this mod's isolated persistent storage. Requires CapStorage.
func (*ModAPI) StorageRemove ¶
StorageRemove removes a key from this mod's isolated persistent storage. Requires CapStorage.
func (*ModAPI) StorageSet ¶
StorageSet writes a string value to this mod's isolated persistent storage. Requires CapStorage.
type ModContributes ¶
type ModContributes struct {
// Assets is the mod-relative directory of asset files (images, audio, fonts, models) overlaid under "assets/" in ContentFS.
Assets string `yaml:"assets,omitempty" json:"assets,omitempty"`
// Scenes is the mod-relative directory of scene files overlaid under "scenes/" in ContentFS.
Scenes string `yaml:"scenes,omitempty" json:"scenes,omitempty"`
// L10n is the mod-relative directory of localization string tables overlaid under "l10n/" in ContentFS.
L10n string `yaml:"l10n,omitempty" json:"l10n,omitempty"`
// DataTables is the mod-relative directory of data tables overlaid under "datatables/" in ContentFS.
DataTables string `yaml:"datatables,omitempty" json:"datatables,omitempty"`
}
ModContributes declares read-only content directories that a manifestVersion 2 mod overlays onto the host game via Manager.ContentFS. Each non-empty field is a slash-separated directory path relative to the mod's directory.
func (ModContributes) IsEmpty ¶
func (c ModContributes) IsEmpty() bool
IsEmpty reports whether c declares no content directories.
type ModInfo ¶
type ModInfo struct {
Manifest ModManifest
State ModState
Enabled bool
Capabilities Capability
HostCapabilities []string
Error error
Logs []LogEntry
Order int
// Dir is the mod's directory name inside the discovered mods file system.
Dir string
}
ModInfo is a snapshot of a managed mod's manifest, state, effective capabilities, error, and logs.
type ModManifest ¶
type ModManifest struct {
// ManifestVersion is the schema version of the manifest file (1 or 2). A mod.yaml must state [MinManifestVersion] or [ManifestVersion]; a manifest built in code may leave it 0, and [EncodeManifest] writes [ManifestVersion].
ManifestVersion int `yaml:"manifestVersion" json:"manifestVersion" schema:"required"`
// ID uniquely identifies the mod, such as com.example.boss-rush.
ID string `yaml:"id" json:"id" schema:"required,minLength=1"`
// Name is the mod's human-readable name.
Name string `yaml:"name" json:"name" schema:"required,minLength=1"`
// Version is the mod's own semantic version, which dependency constraints are checked against.
Version string `yaml:"version" json:"version" schema:"required,minLength=1"`
// Author optionally names the mod's author.
Author string `yaml:"author,omitempty" json:"author,omitempty"`
// Description optionally describes the mod.
Description string `yaml:"description,omitempty" json:"description,omitempty"`
// Entry is the entry script's slash-separated path relative to the mod's directory. Required in manifestVersion 1; optional in manifestVersion 2 when contributes declares at least one content directory.
Entry string `yaml:"entry,omitempty" json:"entry,omitempty"`
// GameVersion optionally constrains the host game versions the mod runs on, such as ">=0.2.0".
GameVersion string `yaml:"gameVersion,omitempty" json:"gameVersion,omitempty"`
// Capabilities lists the built-in game API capabilities the mod requests. In mod.yaml, the capabilities sequence may also contain dotted host capability names (<namespace>.<name>), which [ParseManifest] decodes into [ModManifest.HostCapabilities] and [EncodeManifest] writes after the built-in names in sorted order.
Capabilities Capability `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
// HostCapabilities lists the dotted host capability names (such as "inventory.read") requested in mod.yaml's capabilities sequence, sorted in byte order.
HostCapabilities []string `yaml:"-" json:"hostCapabilities,omitempty"`
// Dependencies maps the IDs of mods this mod requires to version constraints.
Dependencies map[string]string `yaml:"dependencies,omitempty" json:"dependencies,omitempty"`
// OptionalDependencies maps the IDs of optional mods to version constraints (manifestVersion 2). When present, an optional dependency loads before this mod and its version must satisfy the constraint; when absent, it is ignored.
OptionalDependencies map[string]string `yaml:"optionalDependencies,omitempty" json:"optionalDependencies,omitempty"`
// Conflicts maps the IDs of incompatible mods to version constraints (manifestVersion 2). A conflicting pair is refused together in either direction.
Conflicts map[string]string `yaml:"conflicts,omitempty" json:"conflicts,omitempty"`
// Platforms lists the target platforms the mod runs on, such as [windows, macos, linux] (manifestVersion 2). When omitted, the mod runs on all platforms.
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
// Contributes declares mod-relative content directories overlaid into [Manager.ContentFS] (manifestVersion 2).
Contributes ModContributes `yaml:"contributes,omitempty" json:"contributes,omitempty"`
}
ModManifest describes a mod. Mod authors write it as YAML in a ManifestFile (mod.yaml) in the mod's directory; ParseManifest reads it and EncodeManifest writes it.
func ParseManifest ¶
func ParseManifest(data []byte) (ModManifest, error)
ParseManifest parses and validates a mod.yaml manifest (version 1 or 2). Unknown fields, duplicate keys, trailing YAML documents, version 2 fields in a version 1 file, and a missing or unsupported manifestVersion are refused.
Its errors match ErrInvalidManifest (or ErrCyclicDependency) with errors.Is, and are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile, as Manager does.
Example ¶
ParseManifest reads and validates a mod's manifest, including built-in and dotted host capabilities the mod asks for.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/modding"
)
func main() {
m, err := modding.ParseManifest([]byte(`manifestVersion: 1
id: more-slimes
name: More Slimes
version: 1.2.0
entry: mod.ts
capabilities: [spawnEntity, readState, inventory.read]
gameVersion: ^1.0.0
`))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m.ID, m.Version, m.Capabilities.Names(), m.HostCapabilities)
fmt.Println(m.Capabilities.Has(modding.CapSpawnEntity), m.Capabilities.Has(modding.CapStorage))
}
Output: more-slimes 1.2.0 [readState spawnEntity] [inventory.read] true false
func ResolveOrder ¶
func ResolveOrder(manifests []ModManifest) ([]ModManifest, error)
ResolveOrder validates manifests and returns them in deterministic topological load order (every required dependency and every present optional dependency precedes every mod that depends on it, with lexicographical ID tie-breaking). It rejects duplicate IDs, conflicting pairs (ErrConflictingMods), missing required dependencies, version mismatches (on required or present optional dependencies), and cycles.
Example ¶
ResolveOrder sorts mods so each loads after the mods it depends on, and refuses a dependency that is missing or of the wrong version.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/modding"
)
func main() {
mods := []modding.ModManifest{
{ID: "slime-hats", Name: "Slime Hats", Version: "1.0.0", Entry: "mod.ts", Dependencies: map[string]string{"more-slimes": ">=1.1.0"}},
{ID: "more-slimes", Name: "More Slimes", Version: "1.2.0", Entry: "mod.ts"},
}
ordered, err := modding.ResolveOrder(mods)
if err != nil {
fmt.Println(err)
return
}
for _, m := range ordered {
fmt.Println(m.ID)
}
}
Output: more-slimes slime-hats
func (ModManifest) Validate ¶
func (m ModManifest) Validate() error
Validate checks that m has a valid schema version, ID, name, version, entry path (or contributes in v2), capabilities, version constraints, platforms, and content directory paths. ManifestVersion may be 0 for a manifest built in code, or MinManifestVersion..ManifestVersion; ParseManifest additionally requires a file to state MinManifestVersion or ManifestVersion. Its errors are *loaderr.Error values that name the field at fault and how to fix it, and match ErrInvalidManifest or ErrCyclicDependency with errors.Is.
type ModModule ¶
type ModModule struct {
// Name is the JS/TS import specifier, such as "mygame/inventory".
// It must not be "game" or use NSGo's reserved "nsgo" prefix.
Name string
// Funcs maps exported JS function names to Go functions, as [tsx.RegisterFunctions] takes them.
// Functions receive the calling mod's *core.Scope as their first parameter (or after context.Context for async functions) and can look up the calling mod with [Caller].
Funcs map[string]any
// Capability is the declared host capability required to import this module, such as "inventory.read".
// Either Capability or Capabilities must be set.
Capability string
// Capabilities is an optional list of declared host capabilities for modules whose exports span multiple permissions.
// When set (with Capability empty), a mod may import the module when it holds at least one listed capability, and individual functions enforce their specific permission via [ModAPI.RequireHost].
Capabilities []string
// Doc optionally describes this module for generated TypeScript declarations and host UIs.
Doc string
}
ModModule defines a host-registered TSX module importable by mods that hold its capability.
type ModState ¶
type ModState uint8
ModState is the lifecycle state of a managed mod.
const ( // StateDiscovered means the mod manifest was discovered and validated, and is not loaded. StateDiscovered ModState = iota // StateLoaded means the mod is compiled, running in its sandbox, and receiving hooks. StateLoaded // StateDisabled means the mod was explicitly disabled and will not be loaded. StateDisabled // StateFailed means the mod failed to compile, load, or faulted at runtime. StateFailed )
type PermissionError ¶
type PermissionError struct {
ModID string
Capability Capability
HostCapability string
Action string
}
PermissionError reports a blocked capability check. It unwraps to both ErrPermission and a *core.Error with core.CodeAccessDenied, so TSX catches receive error.code, error.permission, and error.resource.
func (*PermissionError) Error ¶
func (e *PermissionError) Error() string
func (*PermissionError) Unwrap ¶
func (e *PermissionError) Unwrap() []error
Unwrap exposes ErrPermission and a structured core.Error with CodeAccessDenied.
type PublishOptions ¶
type PublishOptions struct {
AppID uint32
Title string
Description string
Tags []string
Visibility WorkshopVisibility
Preview string // relative slash-separated path inside the mod directory
ChangeNote string
}
PublishOptions customizes a single Workshop.Publish call. Non-zero fields override values from workshop.yaml and mod.yaml.
type PublishRequest ¶
type PublishRequest struct {
AppID uint32
ID PublishedFileID
Title string
Description string
Tags []string
Visibility WorkshopVisibility
PreviewFile string // absolute path to preview image on disk, or empty
ContentDir string // absolute path to mod content directory on disk
ChangeNote string
}
PublishRequest describes a Steam Workshop item update submitted via WorkshopBackend.SubmitUpdate.
type PublishResult ¶
type PublishResult struct {
ID PublishedFileID
NeedsLegalAgreement bool
LegalAgreementURL string
}
PublishResult reports the outcome of submitting a Steam Workshop item update.
type PublishedFileID ¶
type PublishedFileID uint64
PublishedFileID uniquely identifies an item on Steam Workshop (Steamworks PublishedFileId_t).
func (PublishedFileID) String ¶
func (id PublishedFileID) String() string
String formats id as a decimal Steam Workshop item ID.
type SemVer ¶
SemVer is a parsed semantic version (MAJOR.MINOR.PATCH[-prerelease]).
func ParseSemVer ¶
ParseSemVer parses a semantic version string with an optional leading "v", such as "1.2.3", "v1.2.3", or "0.4.0-beta.1".
type SoundRequest ¶
SoundRequest describes a sound playback requested by a mod.
type SpawnRequest ¶
SpawnRequest describes an entity spawn requested by a mod.
type SteamWorkshop ¶
type SteamWorkshop struct {
// contains filtered or unexported fields
}
SteamWorkshop implements WorkshopBackend against the local Steamworks shared library (libsteam_api.dylib on macOS, libsteam_api.so on Linux, steam_api64.dll on Windows) using purego and the Steamworks flat C API without CGo.
func NewSteamWorkshop ¶
func NewSteamWorkshop(opts SteamWorkshopOptions) (*SteamWorkshop, error)
NewSteamWorkshop loads the Steamworks shared library via purego, initializes Steamworks (unless opts.SkipInit is set), and binds the flat ISteamUGC and ISteamUtils APIs. When the Steamworks library or running Steam client is absent, it returns an error matching ErrWorkshopUnavailable.
func (*SteamWorkshop) Close ¶
func (w *SteamWorkshop) Close() error
Close shuts down Steamworks (if initialized by NewSteamWorkshop) and unloads the library.
func (*SteamWorkshop) CreateItem ¶
func (w *SteamWorkshop) CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)
CreateItem creates a new empty Steam Workshop community item under appID.
func (*SteamWorkshop) DownloadItem ¶
func (w *SteamWorkshop) DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) error
DownloadItem starts downloading or updating Workshop item id and waits until Steam reports it is installed and up to date (or ctx is canceled).
func (*SteamWorkshop) ItemInstallInfo ¶
func (w *SteamWorkshop) ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)
ItemInstallInfo returns the local install folder, size, and update timestamp for id. If the item is not installed or needs an update, it returns ErrWorkshopNotInstalled.
func (*SteamWorkshop) QueryItems ¶
func (w *SteamWorkshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
QueryItems queries Steam Workshop for items matching query.
func (*SteamWorkshop) SubmitUpdate ¶
func (w *SteamWorkshop) SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)
SubmitUpdate uploads updated metadata, preview image, and content directory for req.ID.
func (*SteamWorkshop) Subscribe ¶
func (w *SteamWorkshop) Subscribe(ctx context.Context, id PublishedFileID) error
Subscribe subscribes the local Steam user to Workshop item id.
func (*SteamWorkshop) SubscribedItems ¶
func (w *SteamWorkshop) SubscribedItems(ctx context.Context) ([]PublishedFileID, error)
SubscribedItems returns all Workshop item IDs the local Steam user is subscribed to.
func (*SteamWorkshop) Unsubscribe ¶
func (w *SteamWorkshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
Unsubscribe unsubscribes the local Steam user from Workshop item id.
type SteamWorkshopOptions ¶
type SteamWorkshopOptions struct {
// LibraryPath optionally specifies the exact path to the Steamworks shared library
// (libsteam_api.dylib on macOS, libsteam_api.so on Linux, steam_api64.dll on Windows).
// When empty, standard Steamworks library names are probed.
LibraryPath string
// SkipInit skips calling SteamAPI_Init and SteamAPI_Shutdown when the host game
// already manages Steamworks initialization elsewhere.
SkipInit bool
// PollInterval sets how often async SteamAPICall_t handles pump SteamAPI_RunCallbacks
// while waiting for completion. Defaults to 10ms when <= 0.
PollInterval time.Duration
}
SteamWorkshopOptions configures NewSteamWorkshop.
type SyncResult ¶
type SyncResult struct {
Installed []InstalledWorkshopItem
Updated []InstalledWorkshopItem
Removed []InstalledWorkshopItem
Unchanged []InstalledWorkshopItem
}
SyncResult summarizes the changes Workshop.SyncSubscribed applied to Manager.
type Workshop ¶
type Workshop struct {
// contains filtered or unexported fields
}
Workshop connects a WorkshopBackend to a *Manager so players can publish mods and levels to Steam Workshop and automatically download, validate, install, update, and remove subscribed items through the mod manager.
func NewWorkshop ¶
func NewWorkshop(backend WorkshopBackend, manager *Manager, opts WorkshopOptions) *Workshop
NewWorkshop creates a Workshop client backed by backend and installing into manager. manager may be nil for publish-only workflows (such as a mod uploader CLI).
func (*Workshop) InstallSubscribed ¶
func (w *Workshop) InstallSubscribed(ctx context.Context, id PublishedFileID) (InstalledWorkshopItem, error)
InstallSubscribed ensures subscribed Workshop item id is downloaded, validates its folder and mod.yaml safely, and installs or updates it in the mod Manager.
func (*Workshop) Installed ¶
func (w *Workshop) Installed() []InstalledWorkshopItem
Installed returns a deterministic snapshot of Workshop items currently installed in the manager.
func (*Workshop) Publish ¶
func (w *Workshop) Publish(ctx context.Context, dir string, opts PublishOptions) (PublishResult, error)
Publish validates the mod in dir, creates a Steam Workshop item if workshop.yaml does not yet record a PublishedFileID, submits the update, and writes deterministic workshop.yaml metadata back to dir so subsequent publishes update the same item.
If Steamworks reports that the author must accept the Steam Workshop Subscriber Agreement, Publish still saves the assigned PublishedFileID to workshop.yaml and returns the populated PublishResult alongside an error matching ErrWorkshopLegalAgreementRequired.
func (*Workshop) QueryItems ¶
func (w *Workshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
QueryItems queries Steam Workshop items matching query.
func (*Workshop) Subscribe ¶
func (w *Workshop) Subscribe(ctx context.Context, id PublishedFileID) error
Subscribe subscribes the active player to Workshop item id.
func (*Workshop) SyncSubscribed ¶
func (w *Workshop) SyncSubscribed(ctx context.Context) (SyncResult, error)
SyncSubscribed reconciles the mod Manager with all currently subscribed Steam Workshop items: unsubscribed items are unloaded and removed, missing or outdated items are downloaded, install folders and manifests are validated safely, and valid mods are installed in topological dependency order. Failures in individual items are isolated and returned as a joined error so healthy subscribed mods still sync.
func (*Workshop) Unsubscribe ¶
func (w *Workshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
Unsubscribe unsubscribes the active player from Workshop item id.
type WorkshopBackend ¶
type WorkshopBackend interface {
CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)
SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)
Subscribe(ctx context.Context, id PublishedFileID) error
Unsubscribe(ctx context.Context, id PublishedFileID) error
SubscribedItems(ctx context.Context) ([]PublishedFileID, error)
ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)
DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) error
QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
}
WorkshopBackend abstracts the Steamworks ISteamUGC workflow. Use NewSteamWorkshop to talk to the local Steam client on desktop platforms, or NewMemoryWorkshop for deterministic tests and offline workflows.
type WorkshopItem ¶
type WorkshopItem struct {
ID PublishedFileID
AppID uint32
Title string
Description string
Tags []string
Visibility WorkshopVisibility
OwnerID uint64
UpdatedAt time.Time
VotesUp uint32
VotesDown uint32
}
WorkshopItem describes a Steam Workshop item returned by WorkshopBackend.QueryItems.
type WorkshopMetadata ¶
type WorkshopMetadata struct {
// Version is the schema version of workshop.yaml. Files must state [WorkshopMetadataVersion];
// a value built in code may leave it 0 and [EncodeWorkshopMetadata] writes [WorkshopMetadataVersion].
Version int `yaml:"version" json:"version"`
// AppID is the Steam application ID that owns this Workshop item.
AppID uint32 `yaml:"appId" json:"appId"`
// PublishedFileID is the Steam Workshop item ID assigned on first publish, or 0 before upload.
PublishedFileID PublishedFileID `yaml:"publishedFileId,omitempty" json:"publishedFileId,omitempty"`
// Title is the Steam Workshop item title (defaults to ModManifest.Name when omitted).
Title string `yaml:"title,omitempty" json:"title,omitempty"`
// Description is the Steam Workshop item description (defaults to ModManifest.Description when omitted).
Description string `yaml:"description,omitempty" json:"description,omitempty"`
// Tags lists Steam Workshop discovery tags such as "level", "gameplay", or "ui".
Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"`
// Visibility controls who can see the Workshop item (public, friendsOnly, private, unlisted).
Visibility WorkshopVisibility `yaml:"visibility,omitempty" json:"visibility,omitempty"`
// Preview is a relative slash-separated path inside the mod directory to a preview image.
Preview string `yaml:"preview,omitempty" json:"preview,omitempty"`
}
WorkshopMetadata is the deterministic YAML sidecar (workshop.yaml) stored in a mod or level directory published to Steam Workshop. Storing PublishedFileID lets subsequent publishes update the existing Workshop item instead of creating duplicates.
func ParseWorkshopMetadata ¶
func ParseWorkshopMetadata(data []byte) (WorkshopMetadata, error)
ParseWorkshopMetadata parses and validates a workshop.yaml file. Unknown fields, duplicate keys, trailing YAML documents, invalid visibility/preview/tag values, and a missing or unsupported version are refused as ErrInvalidWorkshopMetadata.
func (WorkshopMetadata) Validate ¶
func (m WorkshopMetadata) Validate() error
Validate checks that m has valid Steam Workshop metadata fields. Version may be 0 for a value constructed in Go, or WorkshopMetadataVersion; ParseWorkshopMetadata requires files to state version: 1.
type WorkshopOptions ¶
type WorkshopOptions struct {
// AppID is the default Steam App ID used when creating or publishing items if
// workshop.yaml and PublishOptions do not specify one.
AppID uint32
// AllowedRoots optionally restricts the filesystem roots from which Workshop
// item install directories may be loaded. When non-empty, ItemInstallInfo.Folder
// must resolve inside at least one of these directories after symlink evaluation.
AllowedRoots []string
// AutoLoad automatically calls [Manager.Load] on newly installed or updated enabled
// Workshop mods during [Workshop.SyncSubscribed] and [Workshop.InstallSubscribed].
AutoLoad bool
}
WorkshopOptions configures a Workshop client.
type WorkshopQuery ¶
type WorkshopQuery struct {
AppID uint32
IDs []PublishedFileID
SearchText string
Tags []string
Page uint32 // 1-based page number (0 is treated as 1)
}
WorkshopQuery filters items returned by WorkshopBackend.QueryItems.
type WorkshopVisibility ¶
type WorkshopVisibility string
WorkshopVisibility controls who can view an item on Steam Workshop.
const ( // VisibilityPublic makes the item visible to everyone on Steam Workshop. VisibilityPublic WorkshopVisibility = "public" // VisibilityFriendsOnly restricts visibility to the author's Steam friends. VisibilityFriendsOnly WorkshopVisibility = "friendsOnly" // VisibilityPrivate restricts visibility to the author and contributors. VisibilityPrivate WorkshopVisibility = "private" // VisibilityUnlisted hides the item from browse/search while allowing direct link access. VisibilityUnlisted WorkshopVisibility = "unlisted" )
func (WorkshopVisibility) Valid ¶
func (v WorkshopVisibility) Valid() bool
Valid reports whether v is one of the defined Workshop visibility values.