Documentation
¶
Index ¶
- Constants
- func Check(rootDir string, log func(...any)) ([]string, error)
- func FileWrite(pathFile string, data bytes.Buffer) error
- func GenerateExtractorMain(outputFile string, modules []module, scanner *scanner, assetLibraries []string, ...) error
- func NewFaviconSvgHandler(ac *Config, filename string) *asset
- func NewHtmlHandler(ac *Config, outputName, cssURL, jsURL, faviconURL string) *asset
- func NewSvgHandler(ac *Config, filename string) *asset
- func ParseExistingHtmlContent(content string) (openContent, closeContent string)
- func RewriteAssetUrls(htmlStr string, newRoot string) string
- func StripLeadingUseStrict(b []byte) []byte
- func ValidateProject(dir string) error
- func VerifyTinyGoCompatible(dir string) error
- type Artifact
- type AssetMin
- func (c *AssetMin) ContainsCSS(substr string) bool
- func (c *AssetMin) ContainsHTML(substr string) bool
- func (c *AssetMin) ContainsJS(substr string) bool
- func (c *AssetMin) ContainsSVG(substr string) bool
- func (c *AssetMin) EnableSSRMode()
- func (c *AssetMin) EnsureOutputDirectoryExists()
- func (c *AssetMin) FlushToDisk() error
- func (c *AssetMin) GetCSSURLPath() string
- func (c *AssetMin) GetCachedHTML() []byte
- func (c *AssetMin) GetFaviconURLPath() string
- func (c *AssetMin) GetInitCodeJS() (string, error)
- func (c *AssetMin) GetJSURLPath() string
- func (c *AssetMin) GetMainCssPath() string
- func (c *AssetMin) GetMainHtmlPath() string
- func (c *AssetMin) GetMainJsPath() string
- func (c *AssetMin) GetMainSvgPath() string
- func (c *AssetMin) GetMinifiedCSS() ([]byte, error)
- func (c *AssetMin) GetMinifiedJS() ([]byte, error)
- func (c *AssetMin) GetSVGURLPath() string
- func (c *AssetMin) HasIcon(id string) bool
- func (c *AssetMin) InjectCSS(name string, content string)
- func (c *AssetMin) InjectHTML(html string)
- func (c *AssetMin) InjectJS(name string, content string)
- func (c *AssetMin) InjectSpriteIcon(id, svg, viewBox string) error
- func (c *AssetMin) IsSSRMode() bool
- func (c *AssetMin) List() []Artifact
- func (c *AssetMin) LoadSSRModules()
- func (c *AssetMin) LoadStaticAssets() error
- func (c *AssetMin) Logger(messages ...any)
- func (c *AssetMin) MinifyEnabled() bool
- func (c *AssetMin) Name() string
- func (c *AssetMin) NewFileEvent(fileName, extension, filePath, event string) error
- func (c *AssetMin) PublishImages() error
- func (c *AssetMin) Read(p string) ([]byte, string, bool)
- func (c *AssetMin) RefreshJSAssets()
- func (c *AssetMin) RegenerateHTMLCache() error
- func (c *AssetMin) RegisterComponents(providers ...any) error
- func (c *AssetMin) ReloadSSRModule(moduleDir string) error
- func (c *AssetMin) RouteExtractedAssets(all []*Assets) error
- func (c *AssetMin) SetFS(fs FS)
- func (c *AssetMin) SetImageProcessor(ip ImageProcessor)
- func (c *AssetMin) SetLog(f func(message ...any))
- func (c *AssetMin) SetMinifyEnabled(enabled bool)
- func (c *AssetMin) SetSSRCompiler(fn func() error)
- func (c *AssetMin) SetSSRExtractor(e SSRExtractor)
- func (c *AssetMin) SetWasm(filename string, runtime string)
- func (c *AssetMin) SupportedExtensions() []string
- func (c *AssetMin) UnobservedFiles() []string
- func (c *AssetMin) UpdateFileContentInMemory(filePath, extension, event string, content []byte) (*asset, error)
- func (c *AssetMin) UpdateSSRModule(name string, css string, scripts []*js.Script, html string, ...) error
- func (c *AssetMin) UpdateSSRModuleInSlot(name string, css string, scripts []*js.Script, html string, ...) error
- func (c *AssetMin) WaitForSSRLoad(timeout time.Duration)
- func (c *AssetMin) Write(outPath string, content []byte, mediatype string) error
- type Assets
- type BuildConfig
- type CollectorOutput
- type Config
- type ContentFile
- type Extractor
- func (e *Extractor) ExtractAll() ([]*Assets, error)
- func (e *Extractor) ExtractModule(moduleDir string) (*Assets, error)
- func (e *Extractor) Finder() *modfind.Finder
- func (e *Extractor) SetAssetLibraries(libs []string)
- func (e *Extractor) SetFinder(f *modfind.Finder)
- func (e *Extractor) SetGraphLister(l GraphLister)
- func (e *Extractor) SetLog(fn func(...any))
- func (e *Extractor) SetToolchain(t Toolchain)
- func (e *Extractor) SetWasmBuilder(wb WasmBuilder)
- func (e *Extractor) WasmBuilder() WasmBuilder
- type FS
- type FaviconWire
- type GraphLister
- type ImageProcessor
- type Mode
- type Output
- type SSRExtractor
- type ScriptOutput
- type Site
- type Toolchain
- type WasmBuildOptions
- type WasmBuilder
- type WasmOutput
Constants ¶
const ( DefaultOutputDir = "web/public" DefaultDevOutputDir = ".tinywasm/public" DefaultImageQuality = 82 )
Variables ¶
This section is empty.
Functions ¶
func Check ¶ added in v0.1.0
Check validates the project extraction and returns the list of extracted module names.
func FileWrite ¶
pathFile e.g., "theme/htmlMainFileName" data e.g., *bytes.Buffer NOTE: The buffer data will be cleared after writing the file
func GenerateExtractorMain ¶
func GenerateExtractorMain(outputFile string, modules []module, scanner *scanner, assetLibraries []string, startDir string, lister GraphLister, log func(...any)) error
GenerateExtractorMain writes a main.go file that imports all modules and collects their assets.
func NewFaviconSvgHandler ¶
func NewHtmlHandler ¶
NewHtmlHandler creates an HTML asset handler using the provided output filename
func NewSvgHandler ¶
func ParseExistingHtmlContent ¶
ParseExistingHtmlContent is a public wrapper for tests.
func RewriteAssetUrls ¶
RewriteAssetUrls is a public wrapper for tests.
func StripLeadingUseStrict ¶
StripLeadingUseStrict is a public wrapper for tests.
func ValidateProject ¶
ValidateProject checks if the given directory contains a valid sitec project.
func VerifyTinyGoCompatible ¶
VerifyTinyGoCompatible checks if the source tree is compatible with TinyGo compilation. It reports why the source tree would not compile with TinyGo, or nil if compatible.
Types ¶
type Artifact ¶
Artifact se autodescribe: la ruta ES la URL. No hay una segunda tabla de rutas que mantener en sincronía.
type AssetMin ¶
type AssetMin struct {
*Config
InitialLoadFailed bool // true tras agotar los reintentos de ExtractAll; el próximo evento SSR debe reintentar el escaneo completo
// contains filtered or unexported fields
}
func NewAssetMin ¶
func (*AssetMin) ContainsCSS ¶
ContainsCSS checks if the CSS bundle contains the given substring.
func (*AssetMin) ContainsHTML ¶
ContainsHTML checks if the HTML bundle contains the given substring.
func (*AssetMin) ContainsJS ¶
ContainsJS checks if the JS bundle contains the given substring.
func (*AssetMin) ContainsSVG ¶
ContainsSVG checks if the SVG sprite contains the given substring.
func (*AssetMin) EnableSSRMode ¶
func (c *AssetMin) EnableSSRMode()
EnableSSRMode activates the SSR event branch unconditionally. Pure setter.
func (*AssetMin) EnsureOutputDirectoryExists ¶
func (c *AssetMin) EnsureOutputDirectoryExists()
func (*AssetMin) FlushToDisk ¶
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 ¶
GetCSSURLPath returns the URL path for the main CSS file.
func (*AssetMin) GetCachedHTML ¶
GetCachedHTML returns the cached minified HTML content.
func (*AssetMin) GetFaviconURLPath ¶
GetFaviconURLPath returns the URL path for the favicon file.
func (*AssetMin) GetInitCodeJS ¶
GetInitCodeJS returns the init code for the JS bundle.
func (*AssetMin) GetJSURLPath ¶
GetJSURLPath returns the URL path for the main JS file.
func (*AssetMin) GetMainCssPath ¶
GetMainCssPath returns the output path of the main CSS file.
func (*AssetMin) GetMainHtmlPath ¶
GetMainHtmlPath returns the output path of the main HTML file.
func (*AssetMin) GetMainJsPath ¶
GetMainJsPath returns the output path of the main JS file.
func (*AssetMin) GetMainSvgPath ¶
GetMainSvgPath returns the output path of the main SVG file.
func (*AssetMin) GetMinifiedCSS ¶
GetMinifiedCSS returns the minified content of the CSS bundle.
func (*AssetMin) GetMinifiedJS ¶
GetMinifiedJS returns the minified content of the JS bundle.
func (*AssetMin) GetSVGURLPath ¶
GetSVGURLPath returns the URL path for the SVG sprite file.
func (*AssetMin) InjectCSS ¶
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 ¶
InjectHTML appends HTML to the body
func (*AssetMin) InjectJS ¶
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 ¶
AddIcon adds icons from providers to the bundle InjectSpriteIcon adds an icon to the sprite bundle. id: unique icon ID. svg: raw SVG content (the symbol body, e.g. `<path d="..."/>`). viewBox: the coordinate system the content was drawn in, e.g. "0 0 24 24".
func (*AssetMin) IsSSRMode ¶
IsSSRMode returns true if the package is being used as a dependency (SSR mode).
func (*AssetMin) LoadSSRModules ¶
func (c *AssetMin) LoadSSRModules()
func (*AssetMin) LoadStaticAssets ¶ added in v0.1.5
LoadStaticAssets copia a la salida los activos declarados por RenderSite(). Separado de RouteExtractedAssets porque un activo estático no participa en la cascada de CSS ni en el sprite: solo se copia.
Es el camino que usa el demonio de desarrollo: AssetMin conoce el sitio del raíz y puede copiar lo que declara sin pasar por Build(). Build() la usa igualmente, unida a BuildConfig.StaticAssets y sin duplicados.
func (*AssetMin) MinifyEnabled ¶ added in v0.0.54
MinifyEnabled reports whether minification is currently on.
func (*AssetMin) NewFileEvent ¶
func (*AssetMin) PublishImages ¶ added in v0.1.3
PublishImages mete las imágenes ya procesadas en el conjunto de artefactos en memoria (Artifacts()), que es lo único que el servidor de desarrollo consulta y lo que el release vuelca con WriteTo.
Sin esto una imagen solo existía como archivo en el caché de conversión, así que la única manera de servirla era que el demonio creara un directorio de salida dentro del proyecto del usuario —una segunda salida del sitio, con bytes distintos a los del entregable de release.
NO escribe en disco: escribir es responsabilidad de quien decide volcar (Site/Output.WriteTo, FlushToDisk), no un efecto secundario de publicar. El contenido sale idéntico porque el pipeline es determinista.
Es idempotente: reescribe cada ruta con el contenido actual.
func (*AssetMin) RefreshJSAssets ¶
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 ¶
RegenerateHTMLCache forces regeneration of the HTML cache.
func (*AssetMin) RegisterComponents ¶
RegisterComponents registra structs que implementan las interfaces SSR.
func (*AssetMin) ReloadSSRModule ¶
func (*AssetMin) RouteExtractedAssets ¶ added in v0.0.55
RouteExtractedAssets applies a batch of already-extracted module assets — deciding which module's RootCSS wins, appending every module's RenderCSS to its slot, and copying declared fonts — then resolves the final root stylesheet. It is the routing half of LoadSSRModules, exported so a caller that needs its own retry/backoff policy around ExtractAll (app's AssetsHandler does) can still reach routing: routeAssets and resolveAndApplyRootCSS are unexported, and Go does not promote them through embedding across package boundaries.
func (*AssetMin) SetImageProcessor ¶
func (c *AssetMin) SetImageProcessor(ip ImageProcessor)
func (*AssetMin) SetMinifyEnabled ¶ added in v0.0.54
SetMinifyEnabled toggles minification on or off. The consumer (app's TUI minify toggle) owns the UI; this is the only way to reach the flag, which was private before — activeMinifier() is the sole reader.
func (*AssetMin) SetSSRCompiler ¶
SetSSRCompiler registers a Go compiler callback. Pure setter — does NOT invoke fn. Pass nil to unregister.
func (*AssetMin) SetSSRExtractor ¶
func (c *AssetMin) SetSSRExtractor(e SSRExtractor)
func (*AssetMin) SupportedExtensions ¶
func (*AssetMin) UnobservedFiles ¶
func (*AssetMin) UpdateFileContentInMemory ¶
func (*AssetMin) UpdateSSRModule ¶
func (c *AssetMin) UpdateSSRModule(name string, css string, scripts []*js.Script, html string, icons *sprite.Sprite) error
UpdateSSRModule inyecta o reemplaza los assets de un módulo por nombre en el slot por defecto (middle).
func (*AssetMin) UpdateSSRModuleInSlot ¶
func (c *AssetMin) UpdateSSRModuleInSlot(name string, css string, scripts []*js.Script, html string, icons *sprite.Sprite, slot string) error
UpdateSSRModuleInSlot inyecta o reemplaza los assets de un módulo en el slot especificado.
func (*AssetMin) WaitForSSRLoad ¶
func (*AssetMin) Write ¶
Write writes a pre-built artifact (e.g. the compiled WASM binary) straight to the configured FS sink, bypassing the ContentFile-assembly and minification pipeline used for CSS/JS/HTML fragments.
A compiled binary is a finished artifact, not a text fragment to concatenate: WriteContent joins fragments with "\n" between them, which corrupts a binary. And no minifier is registered for arbitrary binary mediatypes (only text/css, javascript, image/svg+xml, text/html are), so routing it through RegenerateCache made minifier.Bytes return ErrNotExist — an error that FlushToDisk's loop silently discarded, leaving the artifact's cache empty and the file written to disk at 0 bytes.
type Assets ¶
type Assets struct {
ModuleName string
RootCSS string
CSS string
JS []*js.Script
HTML string
Icons *sprite.Sprite
Fonts font.Declaration // family declared by the module; zero value = none
Pages []html.Page
Site *Site // declarado por RenderSite(); solo el raíz puede; nil = no declarado
Favicon *FaviconWire // declarado por Favicon(); solo el raíz puede; nil = no declarado
IsRoot bool
IsFramework bool
}
Assets is what compiling one module yields: the raw output its producers emitted, before minification and before anything is written to disk.
This type is the contract between the compiler and whoever consumes its output. It lives here, with the producer. It used to live in github.com/tinywasm/assetmin — the consumer — which forced the producer to import the minifier, and with it an HTTP router and a terminal UI, just to name its own result.
type BuildConfig ¶ added in v0.1.0
type BuildConfig struct {
RootDir string // Root directory of the module (where go.mod lives). Required.
Mode Mode
OutputDir string // Relative to RootDir. Empty => DefaultOutputDir (Release) or DefaultDevOutputDir (Dev).
SiteURL string // Enables sitemap.xml and absolute canonical URLs.
AppName string
StaticAssets []string // Declared static assets relative to RootDir copied verbatim.
ImageQuality int // 0 => DefaultImageQuality
AssetLibraries []string // Style libraries whose importers must declare a producer.
Log func(...any)
}
BuildConfig contains the site build settings.
type CollectorOutput ¶
type CollectorOutput struct {
Root string `json:"root"`
Render string `json:"render"`
HTML string `json:"html"`
Scripts []ScriptOutput `json:"scripts"`
Icons *sprite.Sprite `json:"icons"`
Fonts font.Declaration `json:"fonts"`
Pages []html.Page `json:"pages"`
Site *Site `json:"site"`
Favicon *FaviconWire `json:"favicon"`
}
CollectorOutput is the structure produced by the generated main.go
func MergeResultsFor ¶
func MergeResultsFor(modulePath string, results map[string]CollectorOutput) (CollectorOutput, bool, error)
MergeResultsFor gathers the module's own assets plus those of every package under it, in a stable order so the emitted CSS does not shuffle between runs.
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)
SiteURL string // Optional: canonical base URL (e.g. "https://example.com"), used for sitemap.xml and canonical URL resolution
}
type ContentFile ¶
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
type Extractor ¶
type Extractor struct {
AssetLibraries []string
// contains filtered or unexported fields
}
func (*Extractor) ExtractAll ¶
func (*Extractor) ExtractModule ¶
func (*Extractor) SetAssetLibraries ¶
func (*Extractor) SetGraphLister ¶
func (e *Extractor) SetGraphLister(l GraphLister)
func (*Extractor) SetToolchain ¶
func (*Extractor) SetWasmBuilder ¶
func (e *Extractor) SetWasmBuilder(wb WasmBuilder)
func (*Extractor) WasmBuilder ¶
func (e *Extractor) WasmBuilder() WasmBuilder
type FS ¶
type FS interface {
Write(path string, content []byte, mediatype string) error
Read(path string) ([]byte, string, bool)
List() []Artifact
}
FS es el sumidero de la etapa emit. memFS no toca disco; osFS escribe.
type FaviconWire ¶ added in v0.2.0
type GraphLister ¶
GraphLister devuelve las rutas de importación transitivas de pattern para el GOOS/GOARCH dado. Se inyecta para que los tests no necesiten toolchain.
type ImageProcessor ¶
type Output ¶ added in v0.1.5
type Output struct {
// contains filtered or unexported fields
}
Output es el resultado de un Build COMPLETO: los artefactos producidos, listos para volcarse a un FS (WriteTo) o servirse desde Artifacts().
func Build ¶ added in v0.1.0
func Build(cfg BuildConfig) (*Output, error)
Build executes the entire build pipeline in memory. It does not write to the output disk.
type SSRExtractor ¶
type ScriptOutput ¶
type Site ¶ added in v0.1.0
type Site struct {
// URL es la URL pública del sitio. Habilita sitemap.xml y las URL
// canónicas absolutas. Vacía ⇒ no se emite sitemap.
URL string `json:"url"`
// StaticAssets son rutas relativas a la raíz del módulo que se copian
// verbatim a la salida. Para lo que NO pasa por el pipeline de imágenes:
// SVG de marca, PDF, robots.txt.
//
// Un archivo o directorio declarado y ausente es un ERROR de build, no un
// aviso: un logo que falta en producción se descubre demasiado tarde.
StaticAssets []string `json:"static_assets"`
}
Site es lo que un módulo RAÍZ declara sobre el sitio que produce.
Declararla convierte al proyecto en un sitio estático: el entregable es el directorio de salida y RenderPages() es el dueño del index.html. Un proyecto sin RenderSite() es una aplicación y su index.html es el shell de arranque del WASM.
Lo que declara RenderSite() manda sobre lo que traiga BuildConfig. El proyecto es la autoridad sobre sí mismo; BuildConfig es el afinado del llamador. Cuando ambos traen valor y difieren, se registra un aviso con los dos valores y se aplica el del proyecto.
type Toolchain ¶
type Toolchain interface {
List(dir string, args ...string) ([]byte, error)
ListEnv(dir string, env []string, args ...string) ([]byte, error)
Run(dir string, args ...string) ([]byte, error)
}
Toolchain ejecuta el toolchain de Go. Todo go list / go run / go build del compilador pasa por este puerto, para que el cacheo, el manejo de GOOS y la clasificación de errores existan en exactamente un lugar.
func NewExecToolchain ¶
func NewExecToolchain() Toolchain
type WasmBuildOptions ¶ added in v0.0.58
type WasmBuildOptions struct {
// Entry is the input file, relative to the directory passed to Build.
// Empty means "web/client.go".
Entry string
// OutputName is the artifact name without the .wasm extension.
// Empty means "client".
OutputName string
}
WasmBuildOptions selects what to compile and what to call the result.
The zero value builds a site frontend: web/client.go → client.wasm. Set the fields to compile something else — an edge worker entry point, for example, which is main.go and must come out named for the platform that serves it.
type WasmBuilder ¶
type WasmBuilder interface {
Build(dir string) (WasmOutput, error)
}
WasmBuilder produce el binario del cliente Y el runtime JS que lo carga. sitec decide sus rutas, sus nombres y su sink; CÓMO compilarlo (TinyGo vs Go, flags) es del adaptador.
func NewDefaultWasmBuilder ¶
func NewDefaultWasmBuilder(stdlib bool) WasmBuilder
NewDefaultWasmBuilder builds a site frontend from web/client.go.
func NewWasmBuilder ¶ added in v0.0.58
func NewWasmBuilder(stdlib bool, opts WasmBuildOptions) WasmBuilder
NewWasmBuilder builds an arbitrary entry point, for callers that are not compiling a site frontend.
type WasmOutput ¶
type WasmOutput struct {
Binary []byte // el .wasm
Filename string // su nombre, que el shell HTML referencia
Runtime string // el glue JS correspondiente al modo usado
}
WasmOutput son los DOS artefactos de una compilación. Van juntos a propósito: TinyGo y Go estándar emiten runtimes wasm_exec distintos, así que un binario servido con el loader del otro modo no arranca. Devolverlos por separado permitiría emparejarlos mal.
Source Files
¶
- assets.go
- build.go
- cache.go
- emit_asset.go
- emit_core.go
- emit_events.go
- emit_favicon.go
- emit_filewrite.go
- emit_flush.go
- emit_fonts.go
- emit_html.go
- emit_images.go
- emit_injection.go
- emit_inspect.go
- emit_route.go
- emit_ssr_register.go
- emit_svg.go
- extract.go
- fs.go
- merge.go
- pipeline.go
- reach.go
- scanner.go
- select.go
- select_tinygo_verify.go
- toolchain.go
- toolchain_exec.go
- wasm_builder_exec.go