schema

package
v0.0.16 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package schema provides a dynamic UI schema system for building settings forms with validation, forgeui component rendering, and plugin extensibility.

Index

Constants

View Source
const (
	SectionIDGeneral        = "general"
	SectionIDSecurity       = "security"
	SectionIDSession        = "session"
	SectionIDNotification   = "notification"
	SectionIDAuthentication = "authentication"
	SectionIDBranding       = "branding"
)

Section IDs.

View Source
const DefaultAppSettingsSchemaID = "app_settings"

DefaultAppSettingsSchemaID is the ID for the default app settings schema.

View Source
const DefaultAppSettingsSchemaName = "Application Settings"

DefaultAppSettingsSchemaName is the name for the default app settings schema.

Variables

View Source
var (
	ErrSectionNotFound    = &SchemaError{Type: "section_not_found", Message: "Section not found"}
	ErrFieldNotFound      = &SchemaError{Type: "field_not_found", Message: "Field not found"}
	ErrInvalidFieldType   = &SchemaError{Type: "invalid_field_type", Message: "Invalid field type"}
	ErrDuplicateSectionID = &SchemaError{Type: "duplicate_section", Message: "Section ID already exists"}
	ErrDuplicateFieldID   = &SchemaError{Type: "duplicate_field", Message: "Field ID already exists in section"}
	ErrSchemaNotFound     = &SchemaError{Type: "schema_not_found", Message: "Schema not found"}
)

Common schema errors.

Functions

func RegisterDefaultSections

func RegisterDefaultSections() error

RegisterDefaultSections registers all default sections in the global registry.

func RegisterProvider

func RegisterProvider(provider SettingsProvider) error

RegisterProvider registers a provider in the global registry.

func RegisterSection

func RegisterSection(section *Section) error

RegisterSection registers a section in the global registry.

Types

type AsyncValidator

type AsyncValidator interface {
	// ValidateAsync validates the value asynchronously
	ValidateAsync(ctx context.Context, fieldID string, value any) error
	// Name returns the validator name for identification
	Name() string
}

AsyncValidator is the interface for asynchronous field validators These are used for validations that require I/O operations like database lookups, API calls, or other async operations.

func CompositeAsyncValidator

func CompositeAsyncValidator(validators ...AsyncValidator) AsyncValidator

CompositeAsyncValidator combines multiple async validators.

func ConditionalAsyncValidator

func ConditionalAsyncValidator(condition func(ctx context.Context, fieldID string, value any) bool, validator AsyncValidator) AsyncValidator

ConditionalAsyncValidator runs an async validator only when a condition is met.

func CustomAsyncValidator

func CustomAsyncValidator(name string, message string, fn func(ctx context.Context, fieldID string, value any) bool) AsyncValidator

CustomAsyncValidator creates an async validator with a custom validation function.

func ExistsValidator

func ExistsValidator(checkFn func(ctx context.Context, value any) (bool, error), entityName string) AsyncValidator

ExistsValidator returns an async validator that checks if a resource exists.

func ExternalAPIValidator

func ExternalAPIValidator(checkURL string, timeout time.Duration) AsyncValidator

ExternalAPIValidator returns an async validator that calls an external API.

func NewAsyncValidator

func NewAsyncValidator(name string, fn func(ctx context.Context, fieldID string, value any) error) AsyncValidator

NewAsyncValidator creates a new async validator from a function.

func NotExistsValidator

func NotExistsValidator(checkFn func(ctx context.Context, value any) (bool, error), message string) AsyncValidator

NotExistsValidator returns an async validator that checks if a resource does NOT exist.

func ParallelAsyncValidator

func ParallelAsyncValidator(validators ...AsyncValidator) AsyncValidator

ParallelAsyncValidator runs multiple async validators in parallel and returns all errors.

func RateLimitedValidator

func RateLimitedValidator(validator AsyncValidator, maxRequests int, window time.Duration) AsyncValidator

RateLimitedValidator wraps an async validator with rate limiting.

func RetryValidator

func RetryValidator(validator AsyncValidator, maxRetries int, backoff time.Duration) AsyncValidator

RetryValidator wraps an async validator with retry logic.

func TimeoutValidator

func TimeoutValidator(validator AsyncValidator, timeout time.Duration) AsyncValidator

TimeoutValidator wraps an async validator with a specific timeout.

func UniqueValidator

func UniqueValidator(checkFn UniqueCheckFunc) AsyncValidator

UniqueValidator returns an async validator that checks for uniqueness.

func UniqueValidatorWithMessage

func UniqueValidatorWithMessage(checkFn UniqueCheckFunc, message string) AsyncValidator

UniqueValidatorWithMessage returns a unique validator with a custom message.

type AsyncValidatorConfig

type AsyncValidatorConfig struct {
	Type    string         `json:"type"`
	Params  map[string]any `json:"params,omitempty"`
	Message string         `json:"message,omitempty"`
}

AsyncValidatorConfig is a serializable async validator configuration.

type AsyncValidatorFunc

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

AsyncValidatorFunc is a function type that implements AsyncValidator.

func (AsyncValidatorFunc) Name

func (v AsyncValidatorFunc) Name() string

Name returns the validator name.

func (AsyncValidatorFunc) ValidateAsync

func (v AsyncValidatorFunc) ValidateAsync(ctx context.Context, fieldID string, value any) error

ValidateAsync implements the AsyncValidator interface.

type CachedAsyncValidator

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

CachedAsyncValidator caches validation results for identical values.

func NewCachedAsyncValidator

func NewCachedAsyncValidator(validator AsyncValidator, ttl time.Duration) *CachedAsyncValidator

NewCachedAsyncValidator creates a cached async validator.

func (*CachedAsyncValidator) Name

func (c *CachedAsyncValidator) Name() string

Name returns the validator name.

func (*CachedAsyncValidator) ValidateAsync

func (c *CachedAsyncValidator) ValidateAsync(ctx context.Context, fieldID string, value any) error

ValidateAsync implements AsyncValidator with caching.

type Condition

type Condition struct {
	// Field is the ID of the field to check
	Field string `json:"field"`
	// Operator is the comparison operator
	Operator ConditionOperator `json:"operator"`
	// Value is the target value for comparison
	Value any `json:"value,omitempty"`
	// Action specifies what happens when condition is met
	Action ConditionAction `json:"action"`
}

Condition represents a conditional visibility/requirement rule.

type ConditionAction

type ConditionAction string

ConditionAction specifies the action to take when a condition is met.

const (
	// ActionShow shows the field when condition is met.
	ActionShow ConditionAction = "show"
	// ActionHide hides the field when condition is met.
	ActionHide ConditionAction = "hide"
	// ActionRequire makes the field required when condition is met.
	ActionRequire ConditionAction = "require"
	// ActionDisable disables the field when condition is met.
	ActionDisable ConditionAction = "disable"
	// ActionEnable enables the field when condition is met.
	ActionEnable ConditionAction = "enable"
)

type ConditionOperator

type ConditionOperator string

ConditionOperator defines the comparison operator for conditions.

const (
	// ConditionEquals checks if the field value equals the target.
	ConditionEquals ConditionOperator = "eq"
	// ConditionNotEquals checks if the field value does not equal the target.
	ConditionNotEquals ConditionOperator = "neq"
	// ConditionContains checks if the field value contains the target.
	ConditionContains ConditionOperator = "contains"
	// ConditionGreaterThan checks if the field value is greater than the target.
	ConditionGreaterThan ConditionOperator = "gt"
	// ConditionLessThan checks if the field value is less than the target.
	ConditionLessThan ConditionOperator = "lt"
	// ConditionEmpty checks if the field value is empty.
	ConditionEmpty ConditionOperator = "empty"
	// ConditionNotEmpty checks if the field value is not empty.
	ConditionNotEmpty ConditionOperator = "not_empty"
)

type DynamicSettingsProvider

type DynamicSettingsProvider interface {
	SettingsProvider
	// GetDynamicSections returns sections that may vary based on context
	GetDynamicSections(ctx context.Context, appID string) ([]*Section, error)
}

DynamicSettingsProvider is an extended interface for providers that generate schemas dynamically based on context (e.g., per-app configuration).

type Field

type Field struct {
	// ID is the unique identifier for this field within the section
	ID string `json:"id"`
	// Type is the field type
	Type FieldType `json:"type"`
	// Label is the display label for the field
	Label string `json:"label"`
	// Description provides additional context for the field
	Description string `json:"description,omitempty"`
	// Placeholder is the placeholder text for input fields
	Placeholder string `json:"placeholder,omitempty"`
	// DefaultValue is the initial value for the field
	DefaultValue any `json:"defaultValue,omitempty"`
	// Required indicates if the field is required
	Required bool `json:"required,omitempty"`
	// Disabled indicates if the field is disabled (read-only)
	Disabled bool `json:"disabled,omitempty"`
	// Hidden indicates if the field is hidden from view
	Hidden bool `json:"hidden,omitempty"`
	// ReadOnly indicates if the field is read-only but visible
	ReadOnly bool `json:"readOnly,omitempty"`
	// Validators are the synchronous validators for this field
	Validators []Validator `json:"-"`
	// ValidatorConfigs are serializable validator configurations
	ValidatorConfigs []ValidatorConfig `json:"validators,omitempty"`
	// AsyncValidators are async validators (uniqueness checks, etc.)
	AsyncValidators []AsyncValidator `json:"-"`
	// AsyncValidatorConfigs are serializable async validator configurations
	AsyncValidatorConfigs []AsyncValidatorConfig `json:"asyncValidators,omitempty"`
	// Options are the available options for select/multiselect fields
	Options []SelectOption `json:"options,omitempty"`
	// Conditions define conditional visibility/requirements
	Conditions []Condition `json:"conditions,omitempty"`
	// Metadata contains additional field-level configuration
	Metadata map[string]any `json:"metadata,omitempty"`
	// Order determines the display order within the section
	Order int `json:"order,omitempty"`
	// Width specifies the field width (e.g., "full", "half", "third")
	Width string `json:"width,omitempty"`
	// HelpText provides additional help information
	HelpText string `json:"helpText,omitempty"`
	// Prefix is an optional prefix for the input (e.g., "$", "https://")
	Prefix string `json:"prefix,omitempty"`
	// Suffix is an optional suffix for the input (e.g., "px", "%")
	Suffix string `json:"suffix,omitempty"`
	// Min is the minimum value for number/slider fields
	Min *float64 `json:"min,omitempty"`
	// Max is the maximum value for number/slider fields
	Max *float64 `json:"max,omitempty"`
	// Step is the step increment for number/slider fields
	Step *float64 `json:"step,omitempty"`
	// MinLength is the minimum string length
	MinLength *int `json:"minLength,omitempty"`
	// MaxLength is the maximum string length
	MaxLength *int `json:"maxLength,omitempty"`
	// Pattern is a regex pattern for validation
	Pattern string `json:"pattern,omitempty"`
	// PatternMessage is the error message for pattern validation failure
	PatternMessage string `json:"patternMessage,omitempty"`
}

Field represents a single form field with its configuration.

func (*Field) Clone

func (f *Field) Clone() *Field

Clone creates a deep copy of the field.

func (*Field) GetDefaultValue

func (f *Field) GetDefaultValue() any

GetDefaultValue returns the field's default value, considering the field type.

type FieldBuilder

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

FieldBuilder provides a fluent API for building fields.

func NewField

func NewField(id string, fieldType FieldType) *FieldBuilder

NewField creates a new field builder.

func (*FieldBuilder) Build

func (b *FieldBuilder) Build() *Field

Build finalizes and returns the field.

func (*FieldBuilder) Condition

func (b *FieldBuilder) Condition(cond Condition) *FieldBuilder

Condition adds a condition.

func (*FieldBuilder) DefaultValue

func (b *FieldBuilder) DefaultValue(value any) *FieldBuilder

DefaultValue sets the default value.

func (*FieldBuilder) DependsOn

func (b *FieldBuilder) DependsOn(fieldID string, value any) *FieldBuilder

DependsOn adds a condition that shows the field when another field equals a value.

func (*FieldBuilder) Description

func (b *FieldBuilder) Description(desc string) *FieldBuilder

Description sets the field description.

func (*FieldBuilder) Disabled

func (b *FieldBuilder) Disabled() *FieldBuilder

Disabled marks the field as disabled.

func (*FieldBuilder) HelpText

func (b *FieldBuilder) HelpText(text string) *FieldBuilder

HelpText sets the help text.

func (*FieldBuilder) Hidden

func (b *FieldBuilder) Hidden() *FieldBuilder

Hidden marks the field as hidden.

func (*FieldBuilder) HideWhen

func (b *FieldBuilder) HideWhen(fieldID string, value any) *FieldBuilder

HideWhen adds a condition that hides the field when another field equals a value.

func (*FieldBuilder) Label

func (b *FieldBuilder) Label(label string) *FieldBuilder

Label sets the field label.

func (*FieldBuilder) LabeledOptions

func (b *FieldBuilder) LabeledOptions(pairs ...string) *FieldBuilder

LabeledOptions creates options with value-label pairs.

func (*FieldBuilder) Max

func (b *FieldBuilder) Max(max float64) *FieldBuilder

Max sets the maximum value for number fields.

func (*FieldBuilder) MaxLength

func (b *FieldBuilder) MaxLength(max int) *FieldBuilder

MaxLength sets the maximum string length.

func (*FieldBuilder) Min

func (b *FieldBuilder) Min(min float64) *FieldBuilder

Min sets the minimum value for number fields.

func (*FieldBuilder) MinLength

func (b *FieldBuilder) MinLength(min int) *FieldBuilder

MinLength sets the minimum string length.

func (*FieldBuilder) Options

func (b *FieldBuilder) Options(options ...SelectOption) *FieldBuilder

Options sets the options for select fields.

func (*FieldBuilder) Order

func (b *FieldBuilder) Order(order int) *FieldBuilder

Order sets the display order.

func (*FieldBuilder) Pattern

func (b *FieldBuilder) Pattern(pattern, message string) *FieldBuilder

Pattern sets a regex validation pattern.

func (*FieldBuilder) Placeholder

func (b *FieldBuilder) Placeholder(placeholder string) *FieldBuilder

Placeholder sets the placeholder text.

func (*FieldBuilder) Prefix

func (b *FieldBuilder) Prefix(prefix string) *FieldBuilder

Prefix sets the input prefix.

func (*FieldBuilder) ReadOnly

func (b *FieldBuilder) ReadOnly() *FieldBuilder

ReadOnly marks the field as read-only.

func (*FieldBuilder) RequireWhen

func (b *FieldBuilder) RequireWhen(fieldID string, value any) *FieldBuilder

RequireWhen adds a condition that requires the field when another field equals a value.

func (*FieldBuilder) Required

func (b *FieldBuilder) Required() *FieldBuilder

Required marks the field as required.

func (*FieldBuilder) Step

func (b *FieldBuilder) Step(step float64) *FieldBuilder

Step sets the step value for number fields.

func (*FieldBuilder) StringOptions

func (b *FieldBuilder) StringOptions(values ...string) *FieldBuilder

StringOptions creates options from string values.

func (*FieldBuilder) Suffix

func (b *FieldBuilder) Suffix(suffix string) *FieldBuilder

Suffix sets the input suffix.

func (*FieldBuilder) Width

func (b *FieldBuilder) Width(width string) *FieldBuilder

Width sets the field width.

func (*FieldBuilder) WithAsyncValidator

func (b *FieldBuilder) WithAsyncValidator(v AsyncValidator) *FieldBuilder

WithAsyncValidator adds an async validator.

func (*FieldBuilder) WithMetadata

func (b *FieldBuilder) WithMetadata(key string, value any) *FieldBuilder

WithMetadata adds metadata to the field.

func (*FieldBuilder) WithValidator

func (b *FieldBuilder) WithValidator(v Validator) *FieldBuilder

WithValidator adds a validator.

type FieldType

type FieldType string

FieldType represents the type of a form field.

const (
	// FieldTypeText represents a text input field.
	FieldTypeText FieldType = "text"
	// FieldTypeNumber represents a number input field.
	FieldTypeNumber FieldType = "number"
	// FieldTypeBoolean represents a boolean toggle/checkbox field.
	FieldTypeBoolean FieldType = "boolean"
	// FieldTypeSelect represents a single-select dropdown.
	FieldTypeSelect FieldType = "select"
	// FieldTypeMultiSelect represents a multi-select dropdown.
	FieldTypeMultiSelect FieldType = "multiselect"
	// FieldTypePassword represents a password input field.
	FieldTypePassword FieldType = "password"
	// FieldTypeEmail represents an email input field.
	FieldTypeEmail FieldType = "email"
	// FieldTypeURL represents a URL input field.
	FieldTypeURL FieldType = "url"
	// FieldTypeTextArea represents a multi-line text area.
	FieldTypeTextArea FieldType = "textarea"
	// FieldTypeJSON represents a JSON editor field.
	FieldTypeJSON FieldType = "json"
	// FieldTypeDate represents a date picker field.
	FieldTypeDate FieldType = "date"
	// FieldTypeDateTime represents a date-time picker field.
	FieldTypeDateTime FieldType = "datetime"
	// FieldTypeColor represents a color picker field.
	FieldTypeColor FieldType = "color"
	// FieldTypeFile represents a file upload field.
	FieldTypeFile FieldType = "file"
	// FieldTypeSlider represents a slider/range input.
	FieldTypeSlider FieldType = "slider"
	// FieldTypeTags represents a tags input field.
	FieldTypeTags FieldType = "tags"
)

func (FieldType) IsValid

func (ft FieldType) IsValid() bool

IsValid checks if the field type is a recognized type.

func (FieldType) String

func (ft FieldType) String() string

String returns the string representation of the field type.

type Registry

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

Registry manages schema sections and providers.

func Global

func Global() *Registry

Global returns the global registry instance.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new schema registry.

func (*Registry) Clear

func (r *Registry) Clear()

Clear removes all sections and providers from the registry.

func (*Registry) Clone

func (r *Registry) Clone() *Registry

Clone creates a deep copy of the registry.

func (*Registry) GetDefaults

func (r *Registry) GetDefaults() map[string]map[string]any

GetDefaults returns default values for all sections.

func (*Registry) GetDynamicSchema

func (r *Registry) GetDynamicSchema(ctx context.Context, appID, schemaID, schemaName string) (*Schema, error)

GetDynamicSchema builds a schema including dynamic sections from providers.

func (*Registry) GetProvider

func (r *Registry) GetProvider(providerID string) SettingsProvider

GetProvider returns a provider by ID.

func (*Registry) GetSchema

func (r *Registry) GetSchema(schemaID, schemaName string) *Schema

GetSchema builds a complete schema from all registered sections.

func (*Registry) GetSection

func (r *Registry) GetSection(sectionID string) *Section

GetSection returns a section by ID.

func (*Registry) GetSectionDefaults

func (r *Registry) GetSectionDefaults(sectionID string) map[string]any

GetSectionDefaults returns default values for a specific section.

func (*Registry) GetSortedSections

func (r *Registry) GetSortedSections() []*Section

GetSortedSections returns sections sorted by order.

func (*Registry) ListProviders

func (r *Registry) ListProviders() []SettingsProvider

ListProviders returns all registered providers.

func (*Registry) ListSections

func (r *Registry) ListSections() []*Section

ListSections returns all registered sections.

func (*Registry) MergeWithDefaults

func (r *Registry) MergeWithDefaults(data map[string]map[string]any) map[string]map[string]any

MergeWithDefaults merges provided data with default values.

func (*Registry) RegisterProvider

func (r *Registry) RegisterProvider(provider SettingsProvider) error

RegisterProvider registers a settings provider.

func (*Registry) RegisterSection

func (r *Registry) RegisterSection(section *Section) error

RegisterSection registers a standalone section.

func (*Registry) RegisterSections

func (r *Registry) RegisterSections(sections ...*Section) error

RegisterSections registers multiple sections at once.

func (*Registry) Stats

func (r *Registry) Stats() RegistryStats

Stats returns registry statistics.

func (*Registry) UnregisterProvider

func (r *Registry) UnregisterProvider(providerID string)

UnregisterProvider removes a provider and its sections from the registry.

func (*Registry) UnregisterSection

func (r *Registry) UnregisterSection(sectionID string)

UnregisterSection removes a section from the registry.

func (*Registry) ValidateSchema

func (r *Registry) ValidateSchema(ctx context.Context, data map[string]map[string]any) *ValidationResult

ValidateSchema validates data for the entire schema.

func (*Registry) ValidateSection

func (r *Registry) ValidateSection(ctx context.Context, sectionID string, data map[string]any) *ValidationResult

ValidateSection validates data for a specific section.

func (*Registry) ValidateWithProviders

func (r *Registry) ValidateWithProviders(ctx context.Context, appID, sectionID string, data map[string]any) *ValidationResult

ValidateWithProviders runs provider-specific validation.

type RegistryStats

type RegistryStats struct {
	SectionCount  int `json:"sectionCount"`
	ProviderCount int `json:"providerCount"`
	FieldCount    int `json:"fieldCount"`
}

RegistryStats contains registry statistics.

type RenderOption

type RenderOption func(*renderOptions)

RenderOption is a functional option for rendering.

func WithReadOnly

func WithReadOnly() RenderOption

WithReadOnly makes all fields read-only.

func WithSaveButton

func WithSaveButton() RenderOption

WithSaveButton includes a save button in the rendered form.

type Renderer

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

Renderer renders schema elements to ForgeUI components.

func NewRenderer

func NewRenderer() *Renderer

NewRenderer creates a new renderer with default settings.

func (*Renderer) RenderField

func (r *Renderer) RenderField(field *Field, options ...RenderOption) g.Node

RenderField renders a single field based on its type.

func (*Renderer) RenderSchema

func (r *Renderer) RenderSchema(schema *Schema, options ...RenderOption) g.Node

RenderSchema renders a complete schema as a form.

func (*Renderer) RenderSection

func (r *Renderer) RenderSection(section *Section, options ...RenderOption) g.Node

RenderSection renders a section with all its fields.

func (*Renderer) WithDataPrefix

func (r *Renderer) WithDataPrefix(prefix string) *Renderer

WithDataPrefix sets the Alpine.js data prefix.

func (*Renderer) WithErrorPrefix

func (r *Renderer) WithErrorPrefix(prefix string) *Renderer

WithErrorPrefix sets the Alpine.js error prefix.

func (*Renderer) WithOnSave

func (r *Renderer) WithOnSave(fn string) *Renderer

WithOnSave sets the save function name.

func (*Renderer) WithTheme

func (r *Renderer) WithTheme(theme string) *Renderer

WithTheme sets the theme.

type Schema

type Schema struct {
	// ID is the unique identifier for this schema
	ID string `json:"id"`
	// Name is the display name of the schema
	Name string `json:"name"`
	// Description provides additional context about the schema
	Description string `json:"description,omitempty"`
	// Sections are the logical groupings of fields
	Sections []*Section `json:"sections"`
	// Version is the schema version for migration support
	Version int `json:"version"`
	// Metadata contains additional schema-level configuration
	Metadata map[string]any `json:"metadata,omitempty"`
}

Schema represents a complete settings schema with multiple sections.

func DefaultAppSettingsSchema

func DefaultAppSettingsSchema() *Schema

DefaultAppSettingsSchema returns the default schema for app settings.

func FromJSON

func FromJSON(data []byte) (*Schema, error)

FromJSON deserializes a schema from JSON.

func GetGlobalSchema

func GetGlobalSchema(schemaID, schemaName string) *Schema

GetGlobalSchema returns the complete schema from the global registry.

func NewSchema

func NewSchema(id, name string) *Schema

NewSchema creates a new schema with the given ID and name.

func (*Schema) AddSection

func (s *Schema) AddSection(section *Section) *Schema

AddSection adds a section to the schema.

func (*Schema) Clone

func (s *Schema) Clone() *Schema

Clone creates a deep copy of the schema.

func (*Schema) GetDefaults

func (s *Schema) GetDefaults() map[string]map[string]any

GetDefaults returns the default values for all fields in the schema.

func (*Schema) GetField

func (s *Schema) GetField(sectionID, fieldID string) *Field

GetField returns a field by section and field ID.

func (*Schema) GetSection

func (s *Schema) GetSection(sectionID string) *Section

GetSection returns a section by ID.

func (*Schema) ToJSON

func (s *Schema) ToJSON() ([]byte, error)

ToJSON serializes the schema to JSON.

type SchemaError

type SchemaError struct {
	Type    string `json:"type"`
	Message string `json:"message"`
	Details string `json:"details,omitempty"`
}

SchemaError represents an error in schema definition.

func NewSchemaError

func NewSchemaError(errType, message, details string) *SchemaError

NewSchemaError creates a new schema error with optional details.

func (*SchemaError) Error

func (e *SchemaError) Error() string

Error implements the error interface.

type Section

type Section struct {
	// ID is the unique identifier for this section
	ID string `json:"id"`
	// Title is the display title for the section
	Title string `json:"title"`
	// Description provides additional context
	Description string `json:"description,omitempty"`
	// Icon is an optional icon identifier (e.g., lucide icon name)
	Icon string `json:"icon,omitempty"`
	// Order determines the display order
	Order int `json:"order,omitempty"`
	// Fields are the form fields in this section
	Fields []*Field `json:"fields"`
	// Collapsible indicates if the section can be collapsed
	Collapsible bool `json:"collapsible,omitempty"`
	// DefaultCollapsed indicates if the section is collapsed by default
	DefaultCollapsed bool `json:"defaultCollapsed,omitempty"`
	// Permissions are the permissions required to view/edit this section
	Permissions []string `json:"permissions,omitempty"`
	// Metadata contains additional section-level configuration
	Metadata map[string]any `json:"metadata,omitempty"`
	// ReadOnly indicates if the entire section is read-only
	ReadOnly bool `json:"readOnly,omitempty"`
	// HelpURL is an optional link to documentation
	HelpURL string `json:"helpUrl,omitempty"`
}

Section represents a logical grouping of fields.

func AuthenticationSettingsSection

func AuthenticationSettingsSection() *Section

AuthenticationSettingsSection returns the authentication settings section.

func BrandingSettingsSection

func BrandingSettingsSection() *Section

BrandingSettingsSection returns the branding settings section.

func GeneralSettingsSection

func GeneralSettingsSection() *Section

GeneralSettingsSection returns the general settings section.

func GetGlobalSection

func GetGlobalSection(sectionID string) *Section

GetGlobalSection returns a section from the global registry.

func NewSection

func NewSection(id, title string) *Section

NewSection creates a new section with the given ID and title.

func NotificationSettingsSection

func NotificationSettingsSection() *Section

NotificationSettingsSection returns the notification settings section.

func SecuritySettingsSection

func SecuritySettingsSection() *Section

SecuritySettingsSection returns the security settings section.

func SessionSettingsSection

func SessionSettingsSection() *Section

SessionSettingsSection returns the session settings section.

func (*Section) AddField

func (s *Section) AddField(field *Field) *Section

AddField adds a field to the section.

func (*Section) AddFields

func (s *Section) AddFields(fields ...*Field) *Section

AddFields adds multiple fields to the section.

func (*Section) Clone

func (s *Section) Clone() *Section

Clone creates a deep copy of the section.

func (*Section) ExtractData

func (s *Section) ExtractData(data map[string]any) map[string]any

ExtractData extracts only the fields defined in this section from the data.

func (*Section) GetDefaults

func (s *Section) GetDefaults() map[string]any

GetDefaults returns the default values for all fields in the section.

func (*Section) GetField

func (s *Section) GetField(fieldID string) *Field

GetField returns a field by ID.

func (*Section) GetSortedFields

func (s *Section) GetSortedFields() []*Field

GetSortedFields returns fields sorted by order.

func (*Section) Patch

func (s *Section) Patch(existing, patch map[string]any) (map[string]any, error)

Patch merges patch data into existing data for this section.

func (*Section) Validate

func (s *Section) Validate(ctx context.Context, data map[string]any) *ValidationResult

Validate validates data against the section's field definitions.

func (*Section) ValidateAsync

func (s *Section) ValidateAsync(ctx context.Context, data map[string]any) *ValidationResult

ValidateAsync runs async validators on the section data.

func (*Section) ValidateFull

func (s *Section) ValidateFull(ctx context.Context, data map[string]any) *ValidationResult

ValidateFull runs both sync and async validation.

type SectionBuilder

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

SectionBuilder provides a fluent API for building sections.

func NewSectionBuilder

func NewSectionBuilder(id, title string) *SectionBuilder

NewSectionBuilder creates a new section builder.

func (*SectionBuilder) AddField

func (b *SectionBuilder) AddField(field *Field) *SectionBuilder

AddField adds a field to the section.

func (*SectionBuilder) AddFields

func (b *SectionBuilder) AddFields(fields ...*Field) *SectionBuilder

AddFields adds multiple fields.

func (*SectionBuilder) Build

func (b *SectionBuilder) Build() *Section

Build finalizes and returns the section.

func (*SectionBuilder) Collapsible

func (b *SectionBuilder) Collapsible() *SectionBuilder

Collapsible makes the section collapsible.

func (*SectionBuilder) DefaultCollapsed

func (b *SectionBuilder) DefaultCollapsed() *SectionBuilder

DefaultCollapsed makes the section collapsed by default.

func (*SectionBuilder) Description

func (b *SectionBuilder) Description(desc string) *SectionBuilder

Description sets the section description.

func (*SectionBuilder) HelpURL

func (b *SectionBuilder) HelpURL(url string) *SectionBuilder

HelpURL sets the help documentation URL.

func (*SectionBuilder) Icon

func (b *SectionBuilder) Icon(icon string) *SectionBuilder

Icon sets the section icon.

func (*SectionBuilder) Order

func (b *SectionBuilder) Order(order int) *SectionBuilder

Order sets the display order.

func (*SectionBuilder) ReadOnly

func (b *SectionBuilder) ReadOnly() *SectionBuilder

ReadOnly makes the entire section read-only.

func (*SectionBuilder) WithMetadata

func (b *SectionBuilder) WithMetadata(key string, value any) *SectionBuilder

WithMetadata adds metadata to the section.

func (*SectionBuilder) WithPermissions

func (b *SectionBuilder) WithPermissions(perms ...string) *SectionBuilder

WithPermissions sets the required permissions.

type SelectOption

type SelectOption struct {
	// Value is the actual value stored
	Value any `json:"value"`
	// Label is the display text
	Label string `json:"label"`
	// Description is optional additional context
	Description string `json:"description,omitempty"`
	// Disabled indicates if this option is disabled
	Disabled bool `json:"disabled,omitempty"`
	// Icon is an optional icon identifier
	Icon string `json:"icon,omitempty"`
	// Group is used to group options in the dropdown
	Group string `json:"group,omitempty"`
}

SelectOption represents an option for select/multiselect fields.

type SettingsMigrator

type SettingsMigrator interface {
	// MigrateSettings migrates settings from one version to another
	MigrateSettings(ctx context.Context, appID string, data map[string]any, fromVersion, toVersion int) (map[string]any, error)
}

SettingsMigrator is an optional interface for providers that need to migrate settings.

type SettingsProvider

type SettingsProvider interface {
	// ProviderID returns the unique identifier for this provider
	ProviderID() string
	// GetSettingsSections returns the settings sections provided by this plugin
	GetSettingsSections() []*Section
	// GetSettingsSchema returns the complete schema (optional, can return nil)
	GetSettingsSchema() *Schema
}

SettingsProvider is the interface for plugins that provide settings sections.

type SettingsValidator

type SettingsValidator interface {
	// ValidateSettings validates settings data for this provider
	ValidateSettings(ctx context.Context, appID string, sectionID string, data map[string]any) *ValidationResult
}

SettingsValidator is an optional interface for providers that need async validation.

type UniqueCheckFunc

type UniqueCheckFunc func(ctx context.Context, value any) (bool, error)

UniqueCheckFunc is a function that checks if a value is unique.

type ValidationError

type ValidationError struct {
	FieldID     string `json:"fieldId"`
	ValidatorID string `json:"validatorId"`
	Message     string `json:"message"`
}

ValidationError represents a validation error for a specific field.

func NewValidationError

func NewValidationError(fieldID, validatorID, format string, args ...any) *ValidationError

NewValidationError creates a new validation error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type ValidationResult

type ValidationResult struct {
	Valid        bool                          `json:"valid"`
	FieldErrors  map[string][]*ValidationError `json:"fieldErrors,omitempty"`
	GlobalErrors []string                      `json:"globalErrors,omitempty"`
}

ValidationResult holds the result of validating a section or schema.

func NewValidationResult

func NewValidationResult() *ValidationResult

NewValidationResult creates a new valid validation result.

func (*ValidationResult) AddFieldError

func (r *ValidationResult) AddFieldError(fieldID, validatorID, message string)

AddFieldError adds a field-level error.

func (*ValidationResult) AddGlobalError

func (r *ValidationResult) AddGlobalError(message string)

AddGlobalError adds a schema-level error.

func (*ValidationResult) AllErrors

func (r *ValidationResult) AllErrors() []*ValidationError

AllErrors returns all errors as a flat slice.

func (*ValidationResult) Error

func (r *ValidationResult) Error() string

Error returns a combined error string.

func (*ValidationResult) ErrorMessages

func (r *ValidationResult) ErrorMessages() []string

ErrorMessages returns all error messages as strings.

func (*ValidationResult) GetFieldErrors

func (r *ValidationResult) GetFieldErrors(fieldID string) []*ValidationError

GetFieldErrors returns all errors for a specific field.

func (*ValidationResult) GetFirstFieldError

func (r *ValidationResult) GetFirstFieldError(fieldID string) *ValidationError

GetFirstFieldError returns the first error for a specific field.

func (*ValidationResult) HasErrors

func (r *ValidationResult) HasErrors() bool

HasErrors returns true if there are any errors.

func (*ValidationResult) HasFieldError

func (r *ValidationResult) HasFieldError(fieldID string) bool

HasFieldError checks if a specific field has errors.

func (*ValidationResult) Merge

func (r *ValidationResult) Merge(other *ValidationResult)

Merge combines another validation result into this one.

func (*ValidationResult) ToMap

func (r *ValidationResult) ToMap() map[string]any

ToMap converts the validation result to a map for JSON responses.

type Validator

type Validator interface {
	// Validate validates the given value
	Validate(value any) error
	// Name returns the validator name for identification
	Name() string
}

Validator is the interface for synchronous field validators.

func AlphanumericValidator

func AlphanumericValidator() Validator

AlphanumericValidator returns a validator for alphanumeric strings.

func ArrayMaxLengthValidator

func ArrayMaxLengthValidator(max int) Validator

ArrayMaxLengthValidator returns a validator for maximum array length.

func ArrayMinLengthValidator

func ArrayMinLengthValidator(min int) Validator

ArrayMinLengthValidator returns a validator for minimum array length.

func CIDRValidator

func CIDRValidator() Validator

CIDRValidator returns a validator for CIDR notation.

func CompositeValidator

func CompositeValidator(validators ...Validator) Validator

CompositeValidator combines multiple validators.

func CustomValidator

func CustomValidator(name string, message string, fn func(value any) bool) Validator

CustomValidator creates a validator with a custom validation function.

func EmailValidator

func EmailValidator() Validator

EmailValidator returns a validator that ensures a valid email format.

func EnumValidator

func EnumValidator(allowed []any) Validator

EnumValidator returns a validator that ensures a value is one of the allowed values.

func HexColorValidator

func HexColorValidator() Validator

HexColorValidator returns a validator for hex color codes.

func IPAddressValidator

func IPAddressValidator() Validator

IPAddressValidator returns a validator for IP addresses.

func JSONValidator

func JSONValidator() Validator

JSONValidator returns a validator that ensures valid JSON.

func MaxLengthValidator

func MaxLengthValidator(max int) Validator

MaxLengthValidator returns a validator that ensures a string has maximum length.

func MaxValueValidator

func MaxValueValidator(max float64) Validator

MaxValueValidator returns a validator that ensures a number is at most max.

func MinLengthValidator

func MinLengthValidator(min int) Validator

MinLengthValidator returns a validator that ensures a string has minimum length.

func MinValueValidator

func MinValueValidator(min float64) Validator

MinValueValidator returns a validator that ensures a number is at least min.

func NewValidator

func NewValidator(name string, fn func(value any) error) Validator

NewValidator creates a new validator from a function.

func NotEmptyValidator

func NotEmptyValidator() Validator

NotEmptyValidator returns a validator that ensures a value is not empty.

func PasswordStrengthValidator

func PasswordStrengthValidator(minLength int, requireUppercase, requireLowercase, requireNumbers, requireSpecial bool) Validator

PasswordStrengthValidator returns a validator for password strength.

func PatternValidator

func PatternValidator(pattern string, message string) Validator

PatternValidator returns a validator that ensures a string matches a regex pattern.

func PhoneValidator

func PhoneValidator() Validator

PhoneValidator returns a validator for phone numbers.

func RangeValidator

func RangeValidator(min, max float64) Validator

RangeValidator returns a validator that ensures a number is within a range.

func RequiredValidator

func RequiredValidator() Validator

RequiredValidator returns a validator that ensures a value is not empty.

func SlugValidator

func SlugValidator() Validator

SlugValidator returns a validator for URL-safe slugs.

func StringEnumValidator

func StringEnumValidator(allowed ...string) Validator

StringEnumValidator returns a validator for string enums.

func URLValidator

func URLValidator() Validator

URLValidator returns a validator that ensures a valid URL format.

func URLWithSchemeValidator

func URLWithSchemeValidator(schemes ...string) Validator

URLWithSchemeValidator returns a validator that ensures a valid URL with specific schemes.

type ValidatorConfig

type ValidatorConfig struct {
	Type    string         `json:"type"`
	Params  map[string]any `json:"params,omitempty"`
	Message string         `json:"message,omitempty"`
}

ValidatorConfig is a serializable validator configuration.

type ValidatorFunc

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

ValidatorFunc is a function type that implements Validator.

func (ValidatorFunc) Name

func (v ValidatorFunc) Name() string

Name returns the validator name.

func (ValidatorFunc) Validate

func (v ValidatorFunc) Validate(value any) error

Validate implements the Validator interface.

Jump to

Keyboard shortcuts

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