assetmin

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: MIT Imports: 23 Imported by: 2

README

AssetMin

AssetMin is a thread-safe, concurrent asset pipeline and bundler for Go web applications. It manages CSS, JavaScript, SVG sprites, and HTML templates, providing minification and caching.

Features

  • Bundling & Minification: CSS, JS, HTML, and SVG.
  • SSR Support: Automatic discovery and extraction of assets from Go modules.
  • Component Registration: Extract assets from live Go structs.
  • Typed CSS: Native support for github.com/tinywasm/css stylesheets.
  • Memory & Disk Modes: Serve directly from RAM or build to disk.
  • Hot Reload: Instant thread-safe cache regeneration.

Documentation

  1. Architecture
  2. Assets
  3. Component Registration
  4. SSR & Module Extraction
  5. API Reference
  6. HTTP Handlers
Diagrams

Performance

The compile-and-invoke SSR extraction mechanism provides:

  • Fast cold extraction: ~450ms for typical projects.
  • Hash-based caching: Instant warm extractions (~1ms).
  • Full typed CSS support without performance penalty.

See Benchmark Suite for detailed performance measurements.

Installation

go get github.com/tinywasm/assetmin

Get Started

package main

import (
	"log"
	"github.com/tinywasm/assetmin"
)

func main() {
	config := &assetmin.Config{
		OutputDir:       "./public",
		RootDir:         ".",
		AppName:         "MyApp",
		AssetsURLPrefix: "/static/",
	}

	am := assetmin.NewAssetMin(config)

	// Load assets from imported Go modules asynchronously
	am.LoadSSRModules()
	
	log.Println("Asset bundler is ready!")
}

For more advanced use cases, such as registration of components or setting up file watchers, please refer to the documentation.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FileWrite

func FileWrite(pathFile string, data bytes.Buffer) error

pathFile e.g., "theme/htmlMainFileName" data e.g., *bytes.Buffer NOTE: The buffer data will be cleared after writing the file

func NewFaviconSvgHandler

func NewFaviconSvgHandler(ac *Config, filename string) *asset

func NewHtmlHandler

func NewHtmlHandler(ac *Config, outputName, cssURL, jsURL, faviconURL string) *asset

NewHtmlHandler creates an HTML asset handler using the provided output filename

func NewSvgHandler

func NewSvgHandler(ac *Config, filename string) *asset

func ParseExistingHtmlContent added in v0.2.2

func ParseExistingHtmlContent(content string) (openContent, closeContent string)

ParseExistingHtmlContent is a public wrapper for tests.

func RewriteAssetUrls added in v0.2.2

func RewriteAssetUrls(htmlStr string, newRoot string) string

RewriteAssetUrls is a public wrapper for tests.

func StripLeadingUseStrict added in v0.2.2

func StripLeadingUseStrict(b []byte) []byte

StripLeadingUseStrict is a public wrapper for tests.

Types

type AssetMin

type AssetMin struct {
	*Config
	// contains filtered or unexported fields
}

func NewAssetMin

func NewAssetMin(ac *Config) *AssetMin

func (*AssetMin) ContainsCSS added in v0.2.2

func (c *AssetMin) ContainsCSS(substr string) bool

ContainsCSS checks if the CSS bundle contains the given substring.

func (*AssetMin) ContainsHTML added in v0.2.2

func (c *AssetMin) ContainsHTML(substr string) bool

ContainsHTML checks if the HTML bundle contains the given substring.

func (*AssetMin) ContainsJS added in v0.2.2

func (c *AssetMin) ContainsJS(substr string) bool

ContainsJS checks if the JS bundle contains the given substring.

func (*AssetMin) ContainsSVG added in v0.2.2

func (c *AssetMin) ContainsSVG(substr string) bool

ContainsSVG checks if the SVG sprite contains the given substring.

func (*AssetMin) EnableSSRMode added in v0.3.3

func (c *AssetMin) EnableSSRMode()

EnableSSRMode activates the SSR event branch unconditionally. Pure setter.

func (*AssetMin) EnsureOutputDirectoryExists

func (c *AssetMin) EnsureOutputDirectoryExists()

func (*AssetMin) Execute added in v0.2.3

func (c *AssetMin) Execute()

Execute toggles minification and regenerates all assets.

func (*AssetMin) FlushToDisk added in v0.3.3

func (c *AssetMin) FlushToDisk() error

FlushToDisk snapshots all registered assets, writes them to disk (overwrite), and sets diskMirrored = true only on full success. Returns the first write error.

func (*AssetMin) GetCSSURLPath added in v0.2.2

func (c *AssetMin) GetCSSURLPath() string

GetCSSURLPath returns the URL path for the main CSS file.

func (*AssetMin) GetCachedHTML added in v0.2.2

func (c *AssetMin) GetCachedHTML() []byte

GetCachedHTML returns the cached minified HTML content.

func (*AssetMin) GetFaviconURLPath added in v0.2.2

func (c *AssetMin) GetFaviconURLPath() string

GetFaviconURLPath returns the URL path for the favicon file.

func (*AssetMin) GetInitCodeJS added in v0.2.2

func (c *AssetMin) GetInitCodeJS() (string, error)

GetInitCodeJS returns the init code for the JS bundle.

func (*AssetMin) GetJSURLPath added in v0.2.2

func (c *AssetMin) GetJSURLPath() string

GetJSURLPath returns the URL path for the main JS file.

func (*AssetMin) GetMainCssPath added in v0.2.2

func (c *AssetMin) GetMainCssPath() string

GetMainCssPath returns the output path of the main CSS file.

func (*AssetMin) GetMainHtmlPath added in v0.2.2

func (c *AssetMin) GetMainHtmlPath() string

GetMainHtmlPath returns the output path of the main HTML file.

func (*AssetMin) GetMainJsPath added in v0.2.2

func (c *AssetMin) GetMainJsPath() string

GetMainJsPath returns the output path of the main JS file.

func (*AssetMin) GetMainSvgPath added in v0.2.2

func (c *AssetMin) GetMainSvgPath() string

GetMainSvgPath returns the output path of the main SVG file.

func (*AssetMin) GetMinifiedCSS added in v0.2.2

func (c *AssetMin) GetMinifiedCSS() ([]byte, error)

GetMinifiedCSS returns the minified content of the CSS bundle.

func (*AssetMin) GetMinifiedJS added in v0.2.2

func (c *AssetMin) GetMinifiedJS() ([]byte, error)

GetMinifiedJS returns the minified content of the JS bundle.

func (*AssetMin) GetSVGURLPath added in v0.2.2

func (c *AssetMin) GetSVGURLPath() string

GetSVGURLPath returns the URL path for the SVG sprite file.

func (*AssetMin) HasIcon added in v0.2.2

func (c *AssetMin) HasIcon(id string) bool

HasIcon checks if an icon with the given ID is registered.

func (*AssetMin) InjectCSS added in v0.0.81

func (c *AssetMin) InjectCSS(name string, content string)

AddCSS appends CSS content from providers to the bundle InjectCSS appends CSS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.css"). AddCSS appends CSS content from providers to the bundle InjectCSS appends CSS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.css").

func (*AssetMin) InjectHTML added in v0.0.81

func (c *AssetMin) InjectHTML(html string)

InjectHTML appends HTML to the body

func (*AssetMin) InjectJS added in v0.0.81

func (c *AssetMin) InjectJS(name string, content string)

AddJS appends JS content from providers to the bundle InjectJS appends JS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.js").

func (*AssetMin) InjectSpriteIcon added in v0.0.81

func (c *AssetMin) InjectSpriteIcon(id, svg string) error

AddIcon adds icons from providers to the bundle InjectSpriteIcon adds an icon to the sprite bundle. id: unique icon ID. svg: raw SVG content.

func (*AssetMin) IsSSRMode added in v0.2.2

func (c *AssetMin) IsSSRMode() bool

IsSSRMode returns true if the package is being used as a dependency (SSR mode).

func (*AssetMin) Label added in v0.2.3

func (c *AssetMin) Label() string

Label returns the TUI button label reflecting current minification state.

func (*AssetMin) LoadSSRModules added in v0.2.2

func (c *AssetMin) LoadSSRModules()

LoadSSRModules descubre todos los módulos e inyecta sus assets (asíncrono).

func (*AssetMin) Logger added in v0.0.71

func (c *AssetMin) Logger(messages ...any)

func (*AssetMin) MainInputFileRelativePath added in v0.0.70

func (c *AssetMin) MainInputFileRelativePath() string

MainInputFileRelativePath returns the main input file path. AssetMin manages multiple assets, so returns empty. Used by DevWatch for specific file watching logic.

func (*AssetMin) MainOutputFileAbsolutePath added in v0.0.70

func (c *AssetMin) MainOutputFileAbsolutePath() string

MainOutputFileAbsolutePath returns the main output file path. AssetMin manages multiple outputs, so returns empty. Used by DevWatch for exclusion logic (handled by UnobservedFiles instead)

func (*AssetMin) Name added in v0.0.71

func (c *AssetMin) Name() string

func (*AssetMin) NewFileEvent

func (c *AssetMin) NewFileEvent(fileName, extension, filePath, event string) error

event: create, remove, write, rename

func (*AssetMin) NewSSRFileWatcher added in v0.4.0

func (am *AssetMin) NewSSRFileWatcher(onBrowserReload func() error) *SSRFileWatcher

NewSSRFileWatcher creates an SSRFileWatcher bound to this AssetMin instance.

func (*AssetMin) RefreshJSAssets added in v0.2.7

func (c *AssetMin) RefreshJSAssets()

RefreshJSAssets triggers a refresh of JS assets. Call this when the WASM binary changes to ensure they are up to date.

func (*AssetMin) RegenerateHTMLCache added in v0.2.2

func (c *AssetMin) RegenerateHTMLCache() error

RegenerateHTMLCache forces regeneration of the HTML cache.

func (*AssetMin) RegisterComponents added in v0.2.2

func (c *AssetMin) RegisterComponents(providers ...any) error

RegisterComponents registra structs que implementan las interfaces SSR.

func (*AssetMin) RegisterRoutes

func (c *AssetMin) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers the HTTP handlers for all assets.

func (*AssetMin) ReloadSSRModule added in v0.2.2

func (c *AssetMin) ReloadSSRModule(moduleDir string) error

func (*AssetMin) ScheduleSSRLoad added in v0.2.4

func (c *AssetMin) ScheduleSSRLoad()

ScheduleSSRLoad inicia la carga de módulos SSR en segundo plano de forma segura.

func (*AssetMin) SetImageProcessor added in v0.4.0

func (c *AssetMin) SetImageProcessor(p ImageProcessor)

SetImageProcessor inyecta el pipeline de imágenes. Pasar nil lo desactiva.

func (*AssetMin) SetLog added in v0.0.71

func (c *AssetMin) SetLog(f func(message ...any))

func (*AssetMin) SetSSRCompiler added in v0.3.3

func (c *AssetMin) SetSSRCompiler(fn func() error)

SetSSRCompiler registers a Go compiler callback. Pure setter — does NOT invoke fn. Pass nil to unregister.

func (*AssetMin) SetSSRExtractor added in v0.4.0

func (c *AssetMin) SetSSRExtractor(e SSRExtractor)

func (*AssetMin) ShouldCompileToWasm added in v0.0.70

func (c *AssetMin) ShouldCompileToWasm(fileName, filePath string) bool

ShouldCompileToWasm checks if the file triggers WASM compilation. AssetMin handles assets, not WASM, so always returns false.

func (*AssetMin) SupportedExtensions

func (c *AssetMin) SupportedExtensions() []string

func (*AssetMin) UnobservedFiles

func (c *AssetMin) UnobservedFiles() []string

func (*AssetMin) UpdateFileContentInMemory

func (c *AssetMin) UpdateFileContentInMemory(filePath, extension, event string, content []byte) (*asset, error)

func (*AssetMin) UpdateSSRModule added in v0.2.2

func (c *AssetMin) UpdateSSRModule(name string, css string, scripts []*js.Script, html string, icons *svg.Sprite) error

UpdateSSRModule inyecta o reemplaza los assets de un módulo por nombre en el slot por defecto (middle).

func (*AssetMin) UpdateSSRModuleInSlot added in v0.2.2

func (c *AssetMin) UpdateSSRModuleInSlot(name string, css string, scripts []*js.Script, html string, icons *svg.Sprite, slot string) error

UpdateSSRModuleInSlot inyecta o reemplaza los assets de un módulo en el slot especificado.

func (*AssetMin) WaitForSSRLoad added in v0.2.2

func (c *AssetMin) WaitForSSRLoad(timeout time.Duration)

WaitForSSRLoad espera a que LoadSSRModules termine, hasta el timeout dado.

type Config

type Config struct {
	OutputDir       string // eg: web/static, web/public, web/assets
	RootDir         string // Root directory of the project where go.mod exists
	AppName         string // Application name for templates (default: "MyApp")
	AssetsURLPrefix string // New: for HTTP routes
	DevMode         bool   // If true, disables caching (default: false)
}

type ContentFile added in v0.2.2

type ContentFile struct {
	Path    string // eg: modules/module1/file.js
	Content []byte /// eg: "console.log('hello world')"
}

ContentFile represents a file with its path and content

func (*ContentFile) WriteToDisk added in v0.2.2

func (f *ContentFile) WriteToDisk() error

WriteToDisk writes the content file to disk at the specified path It creates parent directories if they don't exist

type ImageProcessor added in v0.4.0

type ImageProcessor interface {
	LoadImages() error                   // escaneo completo inicial (startup)
	ReloadModule(moduleDir string) error // reproceso de un módulo (image.go cambió)
	UnobservedFiles() []string           // outputs .webp a excluir del watcher
}

ImageProcessor procesa imágenes declaradas en los image.go de los módulos. Implementado por github.com/tinywasm/image/min; inyectado por el composition root (app).

type SSRAssets added in v0.2.2

type SSRAssets struct {
	ModuleName  string
	RootCSS     string
	CSS         string
	JS          []*js.Script
	HTML        string
	Icons       *svg.Sprite
	IsRoot      bool
	IsFramework bool
}

SSRAssets es el DTO de assets crudos por módulo (lo produce tinywasm/ssr).

type SSRExtractor added in v0.4.0

type SSRExtractor interface {
	ExtractModule(moduleDir string) (*SSRAssets, error)
	ExtractAll() ([]*SSRAssets, error)
}

SSRExtractor lo implementa github.com/tinywasm/ssr; lo inyecta app.

type SSRFileWatcher added in v0.4.0

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

SSRFileWatcher implements devwatch.FilesEventHandlers. Watches .go events; routes only recognized asset-source files.

func (*SSRFileWatcher) MainInputFileRelativePath added in v0.4.0

func (w *SSRFileWatcher) MainInputFileRelativePath() string

func (*SSRFileWatcher) NewFileEvent added in v0.4.0

func (w *SSRFileWatcher) NewFileEvent(fileName, extension, filePath, event string) error

NewFileEvent routes a .go event to the correct action.

func (*SSRFileWatcher) SupportedExtensions added in v0.4.0

func (w *SSRFileWatcher) SupportedExtensions() []string

func (*SSRFileWatcher) UnobservedFiles added in v0.4.0

func (w *SSRFileWatcher) UnobservedFiles() []string

Jump to

Keyboard shortcuts

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