web

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 40 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 web is the `serve` command's localhost web UI.

Server-rendered html/template pages over the same internal/app functions the CLI and the TUI call, with a little vanilla JavaScript and Tabler's CSS, all embedded in the binary: the page makes no network request beyond this server. It never imports internal/cli, internal/ui or internal/tui, which hold process-wide state a long-lived server cannot share.

Index

Constants

View Source
const (
	KindRegistry = "registry"
	KindPack     = "pack"
	KindManifest = "manifest"
	KindGlobal   = "global"
)

Config file kinds the editor knows how to validate.

View Source
const ContentSecurityPolicy = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; " +
	"connect-src 'self'; font-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"

ContentSecurityPolicy is sent on every response. Everything is same-origin; nothing is inline. img-src allows data: because Tabler's CSS draws its checkboxes and selects with data: SVG URLs.

View Source
const DefaultPort = 7878

DefaultPort is where serve listens unless told otherwise.

View Source
const DefaultPortAttempts = 20

DefaultPortAttempts bounds how far past a taken default port Listen looks.

View Source
const GlobalName = "global"

GlobalName is the editor's name for the global config file.

View Source
const SessionCookie = "iss_session"

SessionCookie is the cookie a valid token is exchanged for.

Variables

View Source
var ErrConflict = errors.New("the file changed on disk after it was opened")

ErrConflict is returned when a file changed on disk after it was opened.

Functions

func AllowedHosts

func AllowedHosts(bindHost string, port int, extra []string) []string

AllowedHosts is the set of Host header values the server answers to.

For a loopback bind that is the three spellings of this machine at the bound port. Anything else is refused, which is the DNS-rebinding defence: a page on evil.example that rebinds its name to 127.0.0.1 still sends Host: evil.example. With a remote bind the bound host and any explicitly allowed names are added.

func DefaultHistoryDir

func DefaultHistoryDir(lookup func(string) (string, bool)) string

DefaultHistoryDir is where finished runs are kept: XDG state, on every platform but Windows, per the house layout ($XDG_STATE_HOME, else ~/.local/state; %LocalAppData% on Windows).

func IsAddrInUse

func IsAddrInUse(err error) bool

IsAddrInUse reports whether a listen error means the port is taken.

func IsLoopback

func IsLoopback(host string) bool

IsLoopback reports whether host only accepts connections from this machine: localhost, or an address in 127.0.0.0/8 or ::1.

func Listen

func Listen(listen ListenFunc, host string, port int, pinned bool, attempts int) (net.Listener, error)

Listen binds host:port.

When pinned is false and the port is in use, it tries the next port up, up to attempts ports in all, and returns the first that binds: the default port being taken by another process is ordinary, and the caller prints the URL actually bound. When pinned is true -- the user asked for this port -- a taken port is an error, because silently serving elsewhere would leave whatever they pointed at this port talking to something else. Any error other than "address in use" stops the search at once.

func NewToken

func NewToken() string

NewToken returns 32 random bytes, base64url-encoded.

func ReadNotes

func ReadNotes(path string) map[string]string

ReadNotes returns a config file's top-level annotation keys: those starting with "_". Unreadable or non-JSON files yield none.

func RecipeName

func RecipeName(p *config.PackConfig) string

RecipeName names the recipe a pack runs, for display.

func WithRunFlags

func WithRunFlags(stack settings.Stack, req RunRequest) (settings.Stack, error)

WithRunFlags copies stack's flag layer and sets dry_run and force on it -- always, so the form's choice is the effective one -- and concurrency when given.

Types

type AppEngine

type AppEngine struct {
	ConfigDir  string
	Workspace  string
	GlobalPath string
	// GlobalHome is $XDG_CONFIG_HOME (or ~/.config): where the editor creates
	// a global config when none exists yet.
	GlobalHome string
	Stack      settings.Stack
	Git        *gitx.Git
	// contains filtered or unexported fields
}

AppEngine is the production Engine over internal/app.

func (*AppEngine) AuditBundled deprecated

func (e *AppEngine) AuditBundled(ctx context.Context, req AuditRequest, h AuditHooks) ([]manifestpack.Resolution, error)

AuditBundled is AuditManifestPack's former name, and forwards to it. The Engine interface names only AuditManifestPack.

Deprecated: use AuditManifestPack. Earliest removal: 0.2.0.

func (*AppEngine) AuditManifestPack added in v0.1.2

func (e *AppEngine) AuditManifestPack(ctx context.Context, req AuditRequest, h AuditHooks) ([]manifestpack.Resolution, error)

AuditManifestPack implements Engine.

func (*AppEngine) Check

func (e *AppEngine) Check(ctx context.Context, packs []*config.PackConfig) []checker.Result

Check implements Engine.

func (*AppEngine) ConfigFiles

func (e *AppEngine) ConfigFiles() ([]ConfigFile, error)

ConfigFiles implements Engine.

func (*AppEngine) Pack

func (e *AppEngine) Pack(slug string) (*config.PackConfig, error)

Pack implements Engine.

func (*AppEngine) PackNotes

func (e *AppEngine) PackNotes(pack *config.PackConfig) map[string]string

PackNotes implements Engine.

func (*AppEngine) PackSettings

func (e *AppEngine) PackSettings(pack *config.PackConfig) (SettingsView, error)

PackSettings implements Engine.

func (*AppEngine) PackStats

func (e *AppEngine) PackStats(ctx context.Context, pack *config.PackConfig) PackStats

PackStats implements Engine.

func (*AppEngine) Packs

func (e *AppEngine) Packs() ([]*config.PackConfig, error)

Packs implements Engine.

func (*AppEngine) ReadConfig

func (e *AppEngine) ReadConfig(name string) (ConfigDoc, error)

ReadConfig implements Engine.

func (*AppEngine) Recipe

func (e *AppEngine) Recipe(ctx context.Context, pack *config.PackConfig, version string, req RunRequest, hooks RunHooks) (pipeline.Result, error)

Recipe implements Engine.

func (*AppEngine) Settings

func (e *AppEngine) Settings() SettingsView

Settings implements Engine.

func (*AppEngine) Sync

func (e *AppEngine) Sync(ctx context.Context, packs []*config.PackConfig, req RunRequest, hooks RunHooks) []app.Outcome

Sync implements Engine.

func (*AppEngine) ValidateConfig

func (e *AppEngine) ValidateConfig(name string, data []byte) []app.Finding

ValidateConfig implements Engine: the same loaders and checks the CLI uses, run on bytes that are not yet on disk.

func (*AppEngine) WriteConfig

func (e *AppEngine) WriteConfig(name string, data []byte, base string) error

WriteConfig implements Engine. It refuses a stale base revision and an invalid document, and otherwise replaces the file atomically. Saving the global config also reloads its layer, so the next run sees it.

type AuditHooks

type AuditHooks struct {
	Logger   *slog.Logger
	Starting func(sets int, filesRoot string)
	SetDone  func(manifestpack.Resolution)
}

AuditHooks route an audit's progress into a job.

type AuditRequest

type AuditRequest struct{ Set, Package string }

AuditRequest is the audit form: one set, optionally verified against one named package; empty means every set.

type ConfigDoc

type ConfigDoc struct {
	ConfigFile
	Data   []byte
	Exists bool
	// Rev is the sha256 of the bytes on disk ("" when the file does not
	// exist). A save carries the Rev it was edited from, and is refused if
	// the file has changed since.
	Rev string
	// ReadOnly, with Why, when the directory cannot be written.
	ReadOnly bool
	Why      string
}

ConfigDoc is a file's current contents.

type ConfigFile

type ConfigFile struct {
	Name, Path, Kind, Slug string
}

ConfigFile is one document the editor offers. Name is the only thing a request may name: the editor serves a file only if it is in this list, so no request can reach a path the list did not put there.

type Engine

type Engine interface {
	// Packs loads every registered pack, in registry order.
	Packs() ([]*config.PackConfig, error)

	// Check resolves each pack's upstream status. It polls the registries.
	Check(ctx context.Context, packs []*config.PackConfig) []checker.Result

	// PackStats reads a pack repo's local state: SVG count, branch, dirty.
	PackStats(ctx context.Context, pack *config.PackConfig) PackStats

	// Settings is the effective run-wide settings, with where each came from.
	Settings() SettingsView

	// Pack loads one registered pack.
	Pack(slug string) (*config.PackConfig, error)

	// PackSettings is one pack's effective settings, its own layer merged in.
	PackSettings(pack *config.PackConfig) (SettingsView, error)

	// PackNotes returns the authoring annotations (`_note` and the like) of a
	// pack's config file, which loading strips.
	PackNotes(pack *config.PackConfig) map[string]string

	// Sync refreshes packs that are behind upstream (or all, with Force),
	// exactly as `sync` does, with req applied as the flag layer.
	Sync(ctx context.Context, packs []*config.PackConfig, req RunRequest, hooks RunHooks) []app.Outcome

	// Recipe runs one pack's recipe at a version, as `recipe` does.
	Recipe(ctx context.Context, pack *config.PackConfig, version string, req RunRequest, hooks RunHooks) (pipeline.Result, error)

	// ConfigFiles lists the documents the editor offers.
	ConfigFiles() ([]ConfigFile, error)
	// ReadConfig returns one document's bytes and revision.
	ReadConfig(name string) (ConfigDoc, error)
	// ValidateConfig checks bytes as the loader would, without writing.
	ValidateConfig(name string, data []byte) []app.Finding
	// WriteConfig validates and saves, refusing a stale base revision.
	WriteConfig(name string, data []byte, base string) error

	// AuditManifestPack surveys where each of the manifest pack's sets came
	// from, as `manifest-pack audit` does.
	AuditManifestPack(ctx context.Context, req AuditRequest, hooks AuditHooks) ([]manifestpack.Resolution, error)
}

Engine is everything the web layer asks of the sync engine. Handlers call it and nothing else, so no handler can re-implement a command.

It is the test seam -- the same idea as the CLI's syncChecker/syncRun -- and has one production implementation, AppEngine, a thin adapter over internal/app.

type ListenFunc

type ListenFunc func(network, address string) (net.Listener, error)

ListenFunc is net.Listen's signature, injectable so the port fallback can be tested without binding a socket.

type Options

type Options struct {
	// Engine is the sync engine. Required.
	Engine Engine

	// Token is the launch token printed in the URL. Required.
	Token string

	// AllowedHosts are the Host header values answered (see AllowedHosts).
	AllowedHosts []string

	// AllowRemote records that the bind is not loopback; it lets a TLS
	// reverse proxy's X-Forwarded-Proto mark the session cookie Secure.
	AllowRemote bool

	// ReadOnly registers no route that runs a sync or writes a file.
	ReadOnly bool

	// Version, BindAddr and ConfigDir are shown on the settings page.
	Version  string
	BindAddr string

	// HistoryDir keeps finished jobs as JSON Lines. Empty keeps them in
	// memory only. See DefaultHistoryDir.
	HistoryDir string

	// CheckTTL is how old a cached upstream check may be before a page load
	// starts a new one. Zero means ten minutes.
	CheckTTL time.Duration

	// Now is the clock. Nil means time.Now.
	Now func() time.Time
}

Options configures a Server.

type PackStats

type PackStats struct {
	SVGs   int
	Branch string
	Dirty  bool
	// Err explains why the repo could not be read; the other fields are then
	// zero.
	Err string
}

PackStats is the local state of one pack repository.

func ReadPackStats

func ReadPackStats(ctx context.Context, git *gitx.Git, pack *config.PackConfig) PackStats

ReadPackStats counts a pack's vendored SVGs and reads its git state. A missing checkout is reported, not fatal: the dashboard still renders.

type RunHooks

type RunHooks struct {
	Logger   *slog.Logger
	Observer pipeline.Observer
	Starting func(pack *config.PackConfig, result checker.Result, dryRun bool)
	Done     func(app.Outcome)
}

RunHooks route a run's output into a job.

type RunRequest

type RunRequest struct {
	DryRun      bool
	Force       bool
	Concurrency int // 0 leaves the setting alone
}

RunRequest is what a run form may set. It enters the settings as the flag layer -- the same way the TUI's dry-run choice does -- so nothing below it, not a pack config and not the environment, can turn a dry run into a real commit.

type Server

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

Server is the web UI.

func New

func New(opts Options) (*Server, error)

New builds a Server. It parses every template once, so a template error is a startup error rather than a 500 on first visit.

func (*Server) Close

func (s *Server) Close()

Close stops background work without serving; for tests.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the full middleware chain and routes.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, ln net.Listener) error

Serve answers on ln until ctx is cancelled, then shuts down with a ten-second grace for requests in flight and cancels background work.

type SettingRow

type SettingRow struct {
	Name, Value, Origin, Help string
	PackScoped                bool
}

SettingRow is one line of the settings table.

type SettingsView

type SettingsView struct {
	Rows       []SettingRow
	ConfigDir  string
	GlobalPath string
}

SettingsView is the effective settings and the paths they came from.

func BuildSettingsView

func BuildSettingsView(r settings.Resolved, configDir, globalPath string) SettingsView

BuildSettingsView flattens resolved settings into display rows, in the registry's order, with each key's origin and help.

type ValidationError

type ValidationError struct{ Findings []app.Finding }

ValidationError carries the findings that refused a save.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
Package jobs runs the web UI's long operations -- syncs, recipes, audits -- in the background, records what each one did as a stream of typed events, and keeps a bounded history on disk.
Package jobs runs the web UI's long operations -- syncs, recipes, audits -- in the background, records what each one did as a stream of typed events, and keeps a bounded history on disk.

Jump to

Keyboard shortcuts

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