addons

package
v0.0.0-...-95891f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package addons manages the extension framework — installable addons (plugins, systems, widgets, integrations) with per-campaign enable/disable controls. Admin manages the global addon registry; campaign owners toggle addons per campaign.

Package addons manages the extension framework — installable addons (modules, widgets, integrations) with per-campaign enable/disable controls.

Index

Constants

View Source
const JotNotesAddonSlug = "jot-notes"

JotNotesAddonSlug is the switch for the floating Jot notes tab, separate from the Journal ("notes") so each switch turns on one thing you see.

Variables

This section is empty.

Functions

func IconColumns

func IconColumns() []database.IconColumn

IconColumns lists this plugin's stored icon columns and the default that replaces an unusable value, for the boot-time icon reconciler.

func IsInstalled

func IsInstalled(slug string) bool

IsInstalled reports whether an addon slug has backing code in the codebase.

func RegisterAdminRoutes

func RegisterAdminRoutes(adminGroup *echo.Group, h *Handler, reauth echo.MiddlewareFunc)

RegisterAdminRoutes adds addon management routes to the admin group. These routes require site admin privileges. reauth guards deleting a feature, which removes it from every campaign.

func RegisterCampaignRoutes

func RegisterCampaignRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)

RegisterCampaignRoutes adds per-campaign addon management routes. Campaign owners can toggle addons and view/configure their settings.

func RegisterSystemAddon

func RegisterSystemAddon(slug, name, description, version, icon, author string)

RegisterSystemAddon registers a dynamically discovered game system as a built-in addon. Called from app wiring after the systems registry has been initialized, before SeedInstalledAddons(). Also called at runtime when a system package is installed/updated so the addon metadata stays current without requiring a server restart.

Idempotent: if the slug already exists, its metadata is updated in place rather than creating a duplicate entry.

func RequireAddon

func RequireAddon(svc AddonService, slug string) echo.MiddlewareFunc

RequireAddon returns middleware that checks whether the specified addon is enabled for the current campaign. It queries the AddonService directly (one cheap DB query) because the LayoutInjector only runs at render time.

When the addon is disabled:

  • HTMX requests receive a 404 with a human-readable message
  • fetch()/JSON callers (widgets that parse every response as JSON, e.g. entity_notes.js) receive a 404 JSON body instead of an HTML redirect
  • Other browser requests redirect to the campaign dashboard

Must be applied AFTER RequireCampaignAccess (needs campaign :id param).

Types

type ActivityRecorder

type ActivityRecorder interface {
	RecordAdminChange(c *echo.Context, action, targetType, targetID, label string)
}

ActivityRecorder is the slice of the admin change log this plugin writes to. It is declared here, not imported from the admin plugin, so the plugins stay independent; app wiring supplies an adapter that stamps the signed-in admin. Recording is best-effort: implementations must not fail the request.

type Addon

type Addon struct {
	ID           int            `json:"id"`
	Slug         string         `json:"slug"`
	Name         string         `json:"name"`
	Description  *string        `json:"description,omitempty"`
	Version      string         `json:"version"`
	Category     AddonCategory  `json:"category"`
	Status       AddonStatus    `json:"status"`
	Icon         string         `json:"icon"`
	Author       *string        `json:"author,omitempty"`
	ConfigSchema map[string]any `json:"config_schema,omitempty"` // JSON schema for addon-specific config.
	Installed    bool           `json:"installed"`               // Whether backing code exists (set by service, not persisted).
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
}

Addon represents a registered extension in the global addon registry.

type AddonCategory

type AddonCategory string

AddonCategory classifies what kind of addon this is.

const (
	CategorySystem      AddonCategory = "system"
	CategoryWidget      AddonCategory = "widget"
	CategoryIntegration AddonCategory = "integration"
	CategoryPlugin      AddonCategory = "plugin"
)

type AddonRepository

type AddonRepository interface {
	// Global addon registry.
	Count(ctx context.Context) (int, error)
	List(ctx context.Context) ([]Addon, error)
	FindByID(ctx context.Context, id int) (*Addon, error)
	FindBySlug(ctx context.Context, slug string) (*Addon, error)
	Create(ctx context.Context, addon *Addon) error
	Update(ctx context.Context, addon *Addon) error
	Delete(ctx context.Context, id int) error
	UpdateStatus(ctx context.Context, id int, status AddonStatus) error

	// Upsert inserts or updates an addon by slug (used for startup registration).
	Upsert(ctx context.Context, addon *Addon) error

	// Per-campaign addon settings.
	ListForCampaign(ctx context.Context, campaignID string) ([]CampaignAddon, error)
	EnableForCampaign(ctx context.Context, campaignID string, addonID int, userID string) error
	DisableForCampaign(ctx context.Context, campaignID string, addonID int) error
	IsEnabledForCampaign(ctx context.Context, campaignID string, addonSlug string) (bool, error)
	// HasCampaignAddonRecord reports whether a campaign_addons row exists for
	// this campaign + addon slug regardless of enabled value. Unlike
	// IsEnabledForCampaign, it distinguishes "never configured" from
	// "explicitly switched off", so a backfill (see ReconcileAddonEnablement
	// in syncapi) does not resurrect a toggle the owner turned off.
	HasCampaignAddonRecord(ctx context.Context, campaignID string, addonSlug string) (bool, error)
	CountCampaignsUsingAddon(ctx context.Context, addonSlug string) (int, error)
	// ListCampaignsUsingAddon returns the IDs of every campaign that has the
	// addon enabled. Backs one-time startup backfills that must replay an
	// addon's enable-effects across already-enabled campaigns.
	ListCampaignsUsingAddon(ctx context.Context, addonSlug string) ([]string, error)
	UpdateCampaignConfig(ctx context.Context, campaignID string, addonID int, config map[string]any) error
}

AddonRepository defines the data access contract for addon operations.

func NewAddonRepository

func NewAddonRepository(db *sql.DB) AddonRepository

NewAddonRepository creates a new addon repository.

type AddonService

type AddonService interface {
	// Global registry (admin only).
	CountAddons(ctx context.Context) (int, error)
	CountFeatures(ctx context.Context) (int, error)
	List(ctx context.Context) ([]Addon, error)
	GetByID(ctx context.Context, id int) (*Addon, error)
	GetBySlug(ctx context.Context, slug string) (*Addon, error)
	Create(ctx context.Context, input CreateAddonInput) (*Addon, error)
	Update(ctx context.Context, id int, input UpdateAddonInput) (*Addon, error)
	Delete(ctx context.Context, id int) error
	UpdateStatus(ctx context.Context, id int, status AddonStatus) error

	// SeedInstalledAddons upserts all built-in addons at startup.
	SeedInstalledAddons(ctx context.Context) error

	// Per-campaign controls (campaign owner).
	ListForCampaign(ctx context.Context, campaignID string) ([]CampaignAddon, error)
	EnableForCampaign(ctx context.Context, campaignID string, addonID int, userID string) error
	DisableForCampaign(ctx context.Context, campaignID string, addonID int) error
	IsEnabledForCampaign(ctx context.Context, campaignID string, addonSlug string) (bool, error)
	// EnableForCampaignBySlug is EnableForCampaign addressed by slug instead
	// of by numeric addon ID. Other plugins know their own addon by slug and
	// have no business looking up an ID in the addons table to call the
	// ID-keyed method — that would be a repo reach-through in disguise.
	EnableForCampaignBySlug(ctx context.Context, campaignID string, addonSlug string, userID string) error
	// HasCampaignAddonRecord reports whether the campaign has a
	// campaign_addons row for this addon at all, enabled or not. See the
	// repository doc comment: it is the only way to distinguish "never
	// configured" from "explicitly disabled".
	HasCampaignAddonRecord(ctx context.Context, campaignID string, addonSlug string) (bool, error)
	CountCampaignsUsingAddon(ctx context.Context, addonSlug string) (int, error)
	// ListCampaignsUsingAddon returns the IDs of every campaign with the addon
	// enabled — used by startup backfills that replay enable-effects.
	ListCampaignsUsingAddon(ctx context.Context, addonSlug string) ([]string, error)
	UpdateCampaignConfig(ctx context.Context, campaignID string, addonID int, config map[string]any) error

	// EnableSystemForCampaign looks up a system addon by slug and enables it
	// for the campaign. Other system addons are auto-disabled (mutual exclusivity).
	EnableSystemForCampaign(ctx context.Context, campaignID, systemSlug, userID string) error

	// DisableAllSystemsForCampaign disables all game system addons for the campaign.
	DisableAllSystemsForCampaign(ctx context.Context, campaignID string) error

	// SetPresetApplier injects the preset applier for auto-creating entity
	// types when a game system addon is enabled. Optional — if nil, no
	// presets are applied.
	SetPresetApplier(applier PresetApplier)

	// SetSystemFinder injects the system manifest finder for self-healing
	// addon registration. Optional — if nil, missing addons return an error.
	SetSystemFinder(finder SystemManifestFinder)

	// Extension settings / onboarding framework (see setup_provider.go).
	// RegisterSetupProvider registers a per-addon SetupProvider at startup.
	RegisterSetupProvider(p SetupProvider)
	// SetupProviderFor returns the provider for an addon slug, if registered.
	SetupProviderFor(slug string) (SetupProvider, bool)
	// NeedsSetup reports whether the owner should be nudged to open this addon's
	// settings page (provider exists, enabled, not done/dismissed, has an
	// actionable check). Used for the Features-card "Setup" badge.
	NeedsSetup(ctx context.Context, campaignID, addonSlug string) (bool, error)
	// GetSetupState / SaveSetupState read and persist per-campaign setup state
	// under campaign_addons.config_json["setup"].
	GetSetupState(ctx context.Context, campaignID, addonSlug string) (SetupState, error)
	SaveSetupState(ctx context.Context, campaignID, addonSlug string, state SetupState) error

	// SetConnectionRevoker injects the hub's revocation surface, used by
	// DisableForCampaign. Late-bound and nil-safe: a nil revoker only
	// skips the live-drop, since AuthenticateKeyForWS still gates reconnect.
	SetConnectionRevoker(cr ConnectionRevoker)
}

AddonService handles business logic for addon operations. Admin-level methods manage the global registry; campaign-scoped methods control which addons are enabled per campaign.

func NewAddonService

func NewAddonService(repo AddonRepository) AddonService

NewAddonService creates a new addon service.

type AddonStatus

type AddonStatus string

AddonStatus tracks the lifecycle state of an addon.

const (
	StatusActive     AddonStatus = "active"
	StatusPlanned    AddonStatus = "planned"
	StatusDeprecated AddonStatus = "deprecated"
)

type CampaignAddon

type CampaignAddon struct {
	ID         int            `json:"id"`
	CampaignID string         `json:"campaign_id"`
	AddonID    int            `json:"addon_id"`
	Enabled    bool           `json:"enabled"`
	ConfigJSON map[string]any `json:"config_json,omitempty"` // Addon-specific campaign config.
	EnabledAt  time.Time      `json:"enabled_at"`
	EnabledBy  *string        `json:"enabled_by,omitempty"`

	// Joined from addons table.
	AddonSlug     string        `json:"addon_slug,omitempty"`
	AddonName     string        `json:"addon_name,omitempty"`
	AddonIcon     string        `json:"addon_icon,omitempty"`
	AddonCategory AddonCategory `json:"addon_category,omitempty"`
	AddonStatus   AddonStatus   `json:"addon_status,omitempty"`
	// AddonDescription is the addon's canonical one-line description, sourced
	// from builtinAddons (ADR-056: the text exists once, there — every
	// consuming surface reads it through here rather than keeping its own
	// copy). ListForCampaign's query already SELECTed this column; before
	// ADR-056 it was scanned into a throwaway local and dropped, which is why
	// 8 of 14 addon cards showed generic filler on the page an owner uses to
	// decide whether to enable them.
	AddonDescription string `json:"addon_description,omitempty"`
	Installed        bool   `json:"installed"` // Whether backing code exists (set by service, not persisted).
}

CampaignAddon represents a per-campaign addon configuration.

type ConnectionRevoker

type ConnectionRevoker interface {
	RevokeAPIKeyClients(campaignID string)
}

ConnectionRevoker is the narrow hub view this plugin needs: force- disconnect a campaign's Foundry sockets when Sync API turns off. Declared locally (not imported) so the plugin states only what it needs.

type CreateAddonInput

type CreateAddonInput struct {
	Slug        string
	Name        string
	Description string
	Version     string
	Category    AddonCategory
	Icon        string
	Author      string
}

CreateAddonInput is the validated input for registering a new addon.

type ExtensionSettingsView

type ExtensionSettingsView struct {
	CampaignID  string
	Slug        string
	AddonName   string
	AddonIcon   string
	HasProvider bool // false → "nothing to set up" panel
	Checks      []SetupCheck
	Questions   []SetupQuestion
	State       SetupState
	CSRFToken   string
	SuccessMsgs []string
	ErrMsg      string
}

ExtensionSettingsView is the view-model the settings templates render. It is provider-agnostic: the handler fills it from whatever SetupProvider (if any) is registered for the addon slug.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler handles addon-related HTTP requests. Admin routes manage the global registry; campaign-scoped routes manage per-campaign toggles.

func NewHandler

func NewHandler(service AddonService) *Handler

NewHandler creates a new addon handler.

func (*Handler) AdminAddonsPage

func (h *Handler) AdminAddonsPage(c *echo.Context) error

AdminAddonsPage renders the admin addon management page (GET /admin/addons). Filters out module-category addons (shown on Content Packs page) and planned addons without backing code (future work, not actionable).

func (*Handler) ApplyExtensionSettings

func (h *Handler) ApplyExtensionSettings(c *echo.Context) error

ApplyExtensionSettings applies the owner's answers (POST /campaigns/:id/extensions/:slug/settings/apply). On success it persists the answers + completion, re-renders the body with the result, and fires the hub-refresh + a toast. Owner-gated by the route.

func (*Handler) CampaignAddonsAPI

func (h *Handler) CampaignAddonsAPI(c *echo.Context) error

CampaignAddonsAPI returns the addon list with per-campaign enabled state (GET /campaigns/:id/addons).

func (*Handler) CampaignAddonsFragment

func (h *Handler) CampaignAddonsFragment(c *echo.Context) error

CampaignAddonsFragment returns the addons list fragment for embedding in the Customization Hub Extensions tab (GET /campaigns/:id/addons/fragment).

func (*Handler) CreateAddon

func (h *Handler) CreateAddon(c *echo.Context) error

CreateAddon handles POST /admin/addons to register a new addon.

func (*Handler) DeleteAddon

func (h *Handler) DeleteAddon(c *echo.Context) error

DeleteAddon handles DELETE /admin/addons/:addonID.

func (*Handler) DismissExtensionSetup

func (h *Handler) DismissExtensionSetup(c *echo.Context) error

DismissExtensionSetup marks setup as dismissed so the Features card stops nudging (POST /campaigns/:id/extensions/:slug/settings/dismiss). The owner can reopen the page any time. Owner-gated by the route.

func (*Handler) ExtensionSettings

func (h *Handler) ExtensionSettings(c *echo.Context) error

ExtensionSettings renders an extension's settings page (GET /campaigns/:id/extensions/:slug/settings). HTMX requests get the modal overlay (so the Extensions hub can inject it); normal requests get the full page (deep-link / no-JS fallback). Owner-gated by the route.

func (*Handler) SetActivityRecorder

func (h *Handler) SetActivityRecorder(r ActivityRecorder)

SetActivityRecorder wires the admin change log. Optional: nil disables it.

func (*Handler) ToggleCampaignAddon

func (h *Handler) ToggleCampaignAddon(c *echo.Context) error

ToggleCampaignAddon handles PUT /campaigns/:id/addons/:addonID/toggle.

func (*Handler) UpdateAddonStatus

func (h *Handler) UpdateAddonStatus(c *echo.Context) error

UpdateAddonStatus handles PUT /admin/addons/:addonID/status.

type PresetApplier

type PresetApplier interface {
	ApplySystemPresets(ctx context.Context, campaignID, systemSlug string) (int, error)
	// ApplyAddonEnableEffects runs entity-type side effects for a NON-system
	// addon when it is enabled (e.g. premaking the "Player Characters" type when
	// the claiming addon is enabled). No-op for addons without effects.
	ApplyAddonEnableEffects(ctx context.Context, campaignID, addonSlug string) error
}

PresetApplier creates entity types from system presets when a game system addon is enabled for a campaign. Implemented outside the addons package to avoid circular imports with entities and systems packages.

type QuestionKind

type QuestionKind string

QuestionKind enumerates the input control the template renders for a question.

const (
	QuestionChoice QuestionKind = "choice" // radio group over Options
	QuestionText   QuestionKind = "text"   // free-text input
	QuestionBool   QuestionKind = "bool"   // checkbox
)

type SetupCheck

type SetupCheck struct {
	ID       string        // stable id, e.g. "pc.duplicate"
	Severity SetupSeverity // drives icon/colour and the needs-setup nudge
	Title    string        // short headline
	Detail   string        // one-sentence explanation
	// ActionLabel optionally names the action the questions below let the owner
	// take to resolve this check (rendered as a hint). May be empty.
	ActionLabel string
}

SetupCheck is one diagnostic line shown on the extension settings page.

type SetupOption

type SetupOption struct {
	Value string
	Label string
	Hint  string // optional helper text shown next to the option
}

SetupOption is one selectable answer for a QuestionChoice.

type SetupProvider

type SetupProvider interface {
	// Slug is the addon slug this provider configures.
	Slug() string
	// RunChecks inspects the campaign and returns health/QOL findings.
	RunChecks(ctx context.Context, campaignID string) ([]SetupCheck, error)
	// Questions returns the onboarding questions to ask the owner.
	Questions(ctx context.Context, campaignID string) ([]SetupQuestion, error)
	// Apply applies the owner's answers. Must be idempotent — the owner may
	// re-open the page and Apply again. answers maps question ID -> value.
	Apply(ctx context.Context, campaignID string, answers map[string]string) (SetupResult, error)
}

SetupProvider supplies the checks, questions, and apply logic for one addon's settings page. Implemented in the app layer (see internal/app/setup_pc.go) so addons never imports entities/systems. One provider per addon slug.

type SetupQuestion

type SetupQuestion struct {
	ID      string        // form field name, e.g. "naming"
	Kind    QuestionKind  // control type
	Title   string        // label
	Help    string        // optional helper text under the control
	Options []SetupOption // for QuestionChoice
	Default string        // default Value (choice/text) or "true"/"false" (bool)
	// ShowIfCheckID, when set, marks this question as only relevant if a check
	// with that ID was emitted. The template still renders it (progressive
	// disclosure is best-effort), but providers use it to keep Questions in sync
	// with RunChecks. May be empty (always relevant).
	ShowIfCheckID string
}

SetupQuestion is one onboarding question rendered as a form control.

type SetupResult

type SetupResult struct {
	Messages  []string // human-readable summary lines ("Merged 3 characters into Heroes")
	Completed bool     // whether setup is now considered complete (clears the nudge)
}

SetupResult is what Apply returns for the success/refresh render.

type SetupSeverity

type SetupSeverity string

SetupSeverity classifies a setup check result for rendering (icon + colour) and for deciding whether the Features card should nudge the owner.

const (
	SeverityInfo       SetupSeverity = "info"       // neutral fact, no action needed
	SeveritySuggestion SetupSeverity = "suggestion" // optional QOL improvement
	SeverityWarning    SetupSeverity = "warning"    // something the owner probably wants to fix
	SeverityError      SetupSeverity = "error"      // a real problem the owner should resolve
)

type SetupState

type SetupState struct {
	Completed bool              `json:"completed"`
	Dismissed bool              `json:"dismissed"`
	Answers   map[string]string `json:"answers,omitempty"`
}

SetupState is the persisted per-campaign setup state for an addon, stored under campaign_addons.config_json["setup"].

type SystemManifestFinder

type SystemManifestFinder interface {
	FindManifest(id string) *SystemManifestInfo
}

SystemManifestFinder looks up a system manifest by ID. Used for self-healing addon registration when a system is in the registry but not in the addons DB.

type SystemManifestInfo

type SystemManifestInfo struct {
	ID          string
	Name        string
	Description string
	Version     string
	Icon        string
	Author      string
}

SystemManifestInfo holds the minimal manifest data needed to auto-register a system addon. Avoids importing the systems package directly.

type UpdateAddonInput

type UpdateAddonInput struct {
	Name        string
	Description string
	Version     string
	Status      AddonStatus
	Icon        string
}

UpdateAddonInput is the validated input for updating an addon's metadata.

Jump to

Keyboard shortcuts

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