Documentation
¶
Index ¶
- Constants
- Variables
- func IsValidTarget(target string) bool
- func NewCSS(config CSSConfig) middleware.Middleware
- func NewTypeScript(config TypeScriptConfig) middleware.Middleware
- func ParseConfigFileURLRewrites(configPath string, fs platform.FileSystem) ([]cfg.URLRewrite, []string, error)
- func ParseTsConfig(path string, fs platform.FileSystem) ([]cfg.URLRewrite, []string, error)
- func RewriteImportAttributes(source []byte) ([]byte, error)
- func TransformCSS(source []byte, path string) string
- func ValidateURLRewrites(urlRewrites []config.URLRewrite) error
- type CSSConfig
- type Cache
- type CacheEntry
- type CacheKey
- type CacheStats
- type ImportAttribute
- type ImportRewrite
- type Loader
- type PathResolver
- type Pool
- type SourceMapMode
- type Target
- type TransformOptions
- type TransformResult
- type TsConfig
- type TsConfigCompilerOptions
- type TypeScriptConfig
Constants ¶
const DefaultTarget = "ES2022"
DefaultTarget is the default TypeScript transformation target.
Variables ¶
var ( // ErrPoolQueueFull is returned when the work queue is at capacity ErrPoolQueueFull = errors.New("transform pool queue is full") // ErrPoolClosed is returned when attempting to submit to a closed pool ErrPoolClosed = errors.New("transform pool is closed") )
Functions ¶
func IsValidTarget ¶
IsValidTarget checks if a target string is valid
func NewCSS ¶
func NewCSS(config CSSConfig) middleware.Middleware
NewCSS creates a middleware that transforms CSS files to JavaScript modules
func NewTypeScript ¶
func NewTypeScript(config TypeScriptConfig) middleware.Middleware
NewTypeScript creates a middleware that transforms TypeScript files to JavaScript
func ParseConfigFileURLRewrites ¶ added in v0.8.0
func ParseConfigFileURLRewrites(configPath string, fs platform.FileSystem) ([]cfg.URLRewrite, []string, error)
ParseConfigFileURLRewrites reads a cem.yaml config file and extracts URL rewrites. Returns URL rewrites and the absolute path of the config file (for change tracking). Returns empty slice if config file doesn't exist or has no URL rewrites.
Example config file:
serve:
urlRewrites:
- urlPattern: "/dist/:path*"
urlTemplate: "/src/{{.path}}"
func ParseTsConfig ¶ added in v0.8.0
func ParseTsConfig(path string, fs platform.FileSystem) ([]cfg.URLRewrite, []string, error)
ParseTsConfig reads a tsconfig.json file and extracts URL rewrites. Returns a slice of URLRewrite objects for src/dist separation and a list of all visited tsconfig files (for dependency tracking).
Handles tsconfig inheritance via the "extends" field (max depth: 5). Missing rootDir or outDir default to ".". Relative paths are normalized to the tsconfig directory.
Example: rootDir="./src", outDir="./dist" produces:
URLRewrite{URLPattern: "/dist/:path*", URLTemplate: "/src/{{.path}}"}
func RewriteImportAttributes ¶
RewriteImportAttributes rewrites TypeScript/JavaScript source to convert import attributes into query parameters that can be preserved through esbuild transformation.
Example transformation:
import styles from './foo.css' with { type: 'css' }
becomes:
import styles from './foo.css?__cem-import-attrs[type]=css'
This allows the dev server to detect and handle these imports appropriately.
func TransformCSS ¶
TransformCSS transforms CSS to a JavaScript module exporting a CSSStyleSheet
func ValidateURLRewrites ¶ added in v0.8.0
func ValidateURLRewrites(urlRewrites []config.URLRewrite) error
ValidateURLRewrites validates all URL rewrites to ensure they can be compiled. This should be called during server initialization to fail fast on invalid patterns/templates.
Types ¶
type CSSConfig ¶
type CSSConfig struct {
WatchDirFunc func() string // Function to get current watch directory
Logger types.Logger
ErrorBroadcaster types.ErrorBroadcaster // Sends errors to browser error overlay
ConfigFile string // Path to config file (for error reporting)
Enabled bool // Enable/disable CSS transformation
Include []string // Glob patterns to include (empty means all .css files)
Exclude []string // Glob patterns to exclude
FS platform.FileSystem // Filesystem abstraction for testability
PathResolver middleware.PathResolver // Cached path resolver for efficient URL rewriting
}
CSSConfig holds configuration for CSS transformation
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache provides thread-safe caching of transformed files with LRU eviction
func NewCacheWithLogger ¶
NewCacheWithLogger creates a new transform cache with a logger
func (*Cache) Get ¶
func (c *Cache) Get(key CacheKey) (*CacheEntry, bool)
Get retrieves a cached entry if it exists
func (*Cache) Invalidate ¶
Invalidate removes a file and all its transitive dependents from cache Returns list of invalidated paths
func (*Cache) LogStats ¶
func (c *Cache) LogStats()
LogStats logs cache statistics if a logger is configured
type CacheEntry ¶
CacheEntry stores transformed code and its dependencies
type CacheStats ¶
type CacheStats struct {
Hits int64
Misses int64
Evictions int64
Entries int
SizeBytes int64
MaxSize int64
HitRate float64
}
CacheStats represents cache metrics
type ImportAttribute ¶
ImportAttribute represents a single import attribute key-value pair
type ImportRewrite ¶
type ImportRewrite struct {
OriginalSource string // The original import path (e.g., './foo.css')
Attributes []ImportAttribute // The import attributes
SourceNode *ts.Node // The source string node for rewriting
StartByte uint // Start byte of the source string
EndByte uint // End byte of the source string
}
ImportRewrite represents a detected import with attributes that needs rewriting
type PathResolver ¶ added in v0.8.0
type PathResolver struct {
// contains filtered or unexported fields
}
PathResolver resolves TypeScript source files from JavaScript request paths. It handles both in-place compilation (co-located .ts/.js files) and pattern-based path mappings (e.g., /elements/:slug/:rest* -> /elements/rh-{{.slug}}/{{.rest}}).
func NewPathResolver ¶ added in v0.8.0
func NewPathResolver(watchDir string, urlRewrites []config.URLRewrite, fs platform.FileSystem, logger types.Logger) *PathResolver
NewPathResolver creates a new PathResolver with the given configuration. All URL rewrites are compiled as URLPattern + template pairs during initialization.
func (*PathResolver) ResolveSourcePath ¶ added in v0.8.0
func (pr *PathResolver) ResolveSourcePath(requestPath string, sourceExt string, requestExt string) string
ResolveSourcePath resolves a source file path using path mappings. This is the generic path resolution logic shared by TypeScript and CSS resolvers.
Parameters:
- requestPath: The requested path (e.g., "/dist/components/button.js")
- sourceExt: The source file extension to look for (e.g., ".ts" or ".css")
- requestExt: The request extension to replace (e.g., ".js" or ".css")
Returns the resolved source path, or empty string if not found.
For extensionless files (requestExt == ""), the path is used as-is without modification. This allows pattern matching on paths like /README or /docs/guide.
Resolution strategy: 1. Try co-located file (in-place compilation) 2. Try pattern-based path mappings (URLPattern + templates)
func (*PathResolver) ResolveTsSource ¶ added in v0.8.0
func (pr *PathResolver) ResolveTsSource(requestedJsPath string) string
ResolveTsSource finds the .ts source file for a requested .js file. Returns the request path to the .ts file (relative to watchDir with leading slash), or empty string if not found.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool manages concurrent transform operations with backpressure
func NewPool ¶
NewPool creates a worker pool with specified concurrency and queue depth maxWorkers: maximum number of concurrent transform operations queueDepth: maximum number of queued tasks before rejecting new submissions
func (*Pool) Submit ¶
Submit adds a task to the pool (non-blocking) Returns an error if the queue is full or the pool is closed Task execution errors are not returned (handle within task function)
func (*Pool) SubmitSync ¶ added in v0.7.2
SubmitSync adds a task to the pool and waits for completion Returns the result of the task function or a pool error This is a synchronous wrapper around Submit for HTTP handler use cases
type SourceMapMode ¶
type SourceMapMode string
SourceMapMode specifies how source maps are generated
const ( SourceMapInline SourceMapMode = "inline" SourceMapExternal SourceMapMode = "external" SourceMapNone SourceMapMode = "none" )
type TransformOptions ¶
type TransformOptions struct {
Loader Loader
Target Target
Sourcemap SourceMapMode
TsconfigRaw string // Optional tsconfig.json content as JSON string
Sourcefile string // Original source file path for source maps
}
TransformOptions configures the transformation
type TransformResult ¶
TransformResult contains the transformed code and dependencies
func TransformTypeScript ¶
func TransformTypeScript(source []byte, opts TransformOptions) (*TransformResult, error)
TransformTypeScript transforms TypeScript source code to JavaScript using esbuild
type TsConfig ¶ added in v0.8.0
type TsConfig struct {
CompilerOptions *TsConfigCompilerOptions `json:"compilerOptions"`
Extends string `json:"extends"`
}
TsConfig represents the structure of a tsconfig.json file. We only parse the fields we need for path resolution.
type TsConfigCompilerOptions ¶ added in v0.8.0
type TsConfigCompilerOptions struct {
RootDir string `json:"rootDir"`
OutDir string `json:"outDir"`
}
TsConfigCompilerOptions represents compiler options we care about
type TypeScriptConfig ¶
type TypeScriptConfig struct {
WatchDirFunc func() string // Function to get current watch directory
TsconfigRawFunc func() string // Function to get current tsconfig.json content
Cache *Cache
Pool *Pool // Worker pool for limiting concurrent transforms
Logger types.Logger
ErrorBroadcaster types.ErrorBroadcaster
Target string
Enabled bool // Enable/disable TypeScript transformation
FS platform.FileSystem // Filesystem abstraction for testability
PathResolver middleware.PathResolver // Cached path resolver for efficient URL rewriting
}
TypeScriptConfig holds configuration for TypeScript transformation