Documentation
¶
Overview ¶
color.go provides ANSI color output helpers. It exposes Success / Warning / Error / Info helpers and automatically falls back to plain text when color is unavailable.
progress.go provides progress output for build steps. It supports step counting, status markers, and colored output.
Index ¶
- Constants
- Variables
- func Blue(text string) string
- func Bold(text string) string
- func CJKFontInstallHint() string
- func CacheDisabled() bool
- func CacheRootDir() string
- func CheckURLNotPrivate(u *url.URL) error
- func ContainsCJK(text string) bool
- func CopyFile(src, dst string) error
- func Cyan(text string) string
- func DetectImageMIME(path string, data []byte) string
- func Dim(text string) string
- func DisableSSRFCheck()
- func DownloadImage(urlStr string, destDir string) (string, error)
- func EnableSSRFCheck()
- func EnsureDir(path string) error
- func Error(format string, args ...any)
- func EscapeAttr(s string) string
- func EscapeHTML(s string) string
- func EscapeXML(s string) string
- func ExtractTitleFromFile(path string) string
- func FileExists(path string) bool
- func Green(text string) string
- func Header(title string)
- func ImageExtForMIME(mimeType string) (string, bool)
- func ImageToBase64(path string) (string, error)
- func Info(format string, args ...any)
- func IsCJKRune(r rune) bool
- func IsColorEnabled() bool
- func IsRemoteURL(path string) bool
- func ParseVersionPart(s string) (int, error)
- func ProcessImages(htmlContent string, baseDir string, embedAsBase64 bool, logger ...*slog.Logger) (string, error)
- func ProcessImagesWithOptions(htmlContent string, baseDir string, options ImageProcessingOptions) (string, error)
- func ReadFile(path string) ([]byte, error)
- func Red(text string) string
- func RelPath(basePath, targetPath string) string
- func ResolveCDNPlaceholders(tmpl string) string
- func SSRFSafeTransport() *http.Transport
- func SafeJoin(baseDir, untrusted string) (string, error)
- func SanitizeCSS(css string) string
- func SetColorEnabled(enabled bool)
- func StableHash(parts ...string) string
- func StripHTMLTags(s string) string
- func Success(format string, args ...any)
- func Warning(format string, args ...any)
- func WriteFile(path string, data []byte) error
- func Yellow(text string) string
- type CJKFontStatus
- type ImageProcessingOptions
- type LimitedWriter
- type PageDimensions
- type ProgressTracker
- func (p *ProgressTracker) Done()
- func (p *ProgressTracker) DoneWithDetail(detail string)
- func (p *ProgressTracker) Fail()
- func (p *ProgressTracker) Finish()
- func (p *ProgressTracker) FinishWithError(err error)
- func (p *ProgressTracker) Skip(reason string)
- func (p *ProgressTracker) Start(description string)
Constants ¶
const ( // KaTeXCSSURL is the CDN URL for the KaTeX stylesheet. KaTeXCSSURL = "https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.css" // KaTeXJSURL is the CDN URL for the KaTeX core JavaScript library. KaTeXJSURL = "https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.js" // KaTeXAutoRenderURL is the CDN URL for the KaTeX auto-render extension, which scans for $...$ and $$...$$ in the document and renders them. KaTeXAutoRenderURL = "https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/contrib/auto-render.min.js" )
KaTeX CDN URLs. Centralized here to keep the version consistent across the codebase.
const ( // MaxImageSize is the maximum allowed size for a downloaded image (50 MB). MaxImageSize = 50 * 1024 * 1024 // DefaultMaxConcurrentDownloads is the default number of concurrent image downloads. DefaultMaxConcurrentDownloads = 4 )
const MaxHTTPRedirects = 10
MaxHTTPRedirects is the maximum number of HTTP redirects to follow. Shared across image downloads, upgrade checks, and PlantUML rendering.
const MermaidCDNURL = "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"
MermaidCDNURL is the CDN URL for the Mermaid diagram library. Centralized here so every part of the codebase uses the same version.
Variables ¶
var HTMLTagPattern = regexp.MustCompile(`<[^>]*>`)
HTMLTagPattern matches any HTML tag. Useful for stripping tags to obtain plain text. Shared across cmd and internal/output packages.
var ImgSrcRegex = regexp.MustCompile(`<img\s+([^>]*\s+)?src=["']([^"']+)["']([^>]*)>`)
ImgSrcRegex matches HTML <img> tags and captures the src attribute. Exported so that other packages (e.g. internal/output/epub) can reuse the same compiled pattern instead of declaring a duplicate.
Functions ¶
func CJKFontInstallHint ¶ added in v0.3.1
func CJKFontInstallHint() string
CJKFontInstallHint returns platform-specific instructions for installing CJK fonts.
func CacheDisabled ¶ added in v0.3.1
func CacheDisabled() bool
CacheDisabled reports whether runtime caches are disabled for this process.
func CacheRootDir ¶ added in v0.3.1
func CacheRootDir() string
CacheRootDir returns the root directory used for mdpress runtime caches. MDPRESS_CACHE_DIR overrides the default location when set.
func CheckURLNotPrivate ¶ added in v0.7.0
CheckURLNotPrivate checks that a URL's hostname does not resolve to a private, loopback, or link-local IP address (SSRF prevention). Exported so that other packages (e.g. internal/plantuml) can reuse the same validation instead of duplicating the logic.
func ContainsCJK ¶ added in v0.3.1
ContainsCJK reports whether the text contains any CJK (Chinese, Japanese, Korean) characters.
func DetectImageMIME ¶
DetectImageMIME determines the MIME type from content when possible. This is more reliable than extension-only detection for remote assets whose URLs do not include a file suffix, such as Shields badges.
func DisableSSRFCheck ¶ added in v0.6.2
func DisableSSRFCheck()
DisableSSRFCheck disables the SSRF prevention check. Intended for testing only.
func DownloadImage ¶
DownloadImage downloads an image from a URL and returns the local path.
func EnableSSRFCheck ¶ added in v0.6.2
func EnableSSRFCheck()
EnableSSRFCheck re-enables the SSRF prevention check.
func EnsureDir ¶
EnsureDir creates a directory when it does not already exist. MkdirAll is idempotent, so we call it directly to avoid a TOCTOU race.
func EscapeHTML ¶
EscapeHTML escapes HTML special characters including single quotes. This is the canonical HTML escaping function used throughout mdpress.
func EscapeXML ¶
EscapeXML escapes XML special characters. Similar to EscapeHTML but uses ' for single quotes per the XML specification.
func ExtractTitleFromFile ¶ added in v0.5.2
ExtractTitleFromFile scans a Markdown file and returns the first H1 heading. For performance, scanning stops after 50 lines.
func FileExists ¶
FileExists reports whether a file or directory exists.
func ImageExtForMIME ¶ added in v0.7.0
ImageExtForMIME returns the file extension for a given image MIME type. Returns the extension and true if found, or "" and false otherwise.
func ImageToBase64 ¶
ImageToBase64 converts an image file to a base64 data URI.
func IsColorEnabled ¶
func IsColorEnabled() bool
IsColorEnabled reports whether color output is enabled.
func IsRemoteURL ¶
IsRemoteURL reports whether a path is an HTTP(S) URL.
func ParseVersionPart ¶ added in v0.6.0
ParseVersionPart parses a version number component (e.g., "25" from "1.25.0").
func ProcessImages ¶
func ProcessImages(htmlContent string, baseDir string, embedAsBase64 bool, logger ...*slog.Logger) (string, error)
ProcessImages resolves image paths in HTML and optionally embeds them as base64. An optional logger can be provided to record warnings when image processing fails. Pass nil to silently skip failures (legacy behavior).
func ProcessImagesWithOptions ¶ added in v0.3.1
func ProcessImagesWithOptions(htmlContent string, baseDir string, options ImageProcessingOptions) (string, error)
ProcessImagesWithOptions resolves image paths in HTML with explicit control over embedding, remote downloads, and file URL rewriting.
func ReadFile ¶
ReadFile reads a file and returns clearer errors. It rejects files larger than 100 MB as a safety net against OOM.
The size check uses Fstat on the open file descriptor to avoid a TOCTOU race between a separate Stat call and the subsequent read.
func ResolveCDNPlaceholders ¶ added in v0.7.0
ResolveCDNPlaceholders replaces CDN URL placeholders in a template string with the actual CDN URLs defined in this package.
func SSRFSafeTransport ¶ added in v0.7.4
SSRFSafeTransport returns a clone of the SSRF-safe HTTP transport that validates resolved IP addresses at dial time to prevent DNS rebinding attacks. Callers should use this when building HTTP clients for user-controlled URLs.
func SafeJoin ¶ added in v0.6.4
SafeJoin joins a base directory with an untrusted relative path and verifies the result stays within the base directory. It returns an error if the resolved path escapes the base via ".." or absolute-path tricks.
func SanitizeCSS ¶ added in v0.7.0
SanitizeCSS removes sequences from CSS content that could break out of a <style> block or perform injection attacks. This prevents: - </style> tag breakout - @import-based data exfiltration - expression()-based script execution (legacy IE) - url() references to external HTTP(S) origins - javascript:/vbscript: URIs inside url() values
Note: @font-face rules are allowed because external url() references are already blocked by cssExternalURLPattern. This permits legitimate local font declarations (e.g. src: local("...") or src: url("fonts/my.woff")) while still preventing data exfiltration via external URLs.
func SetColorEnabled ¶
func SetColorEnabled(enabled bool)
SetColorEnabled overrides color output for tests or forced modes.
func StableHash ¶ added in v0.3.1
StableHash returns a stable SHA-256 hex digest for the given strings.
func StripHTMLTags ¶ added in v0.6.4
StripHTMLTags removes all HTML tags from s, returning plain text.
Types ¶
type CJKFontStatus ¶ added in v0.3.1
type CJKFontStatus struct {
Available bool // Whether any CJK font is installed.
Fonts []string // Names of detected CJK fonts (up to 5).
}
CJKFontStatus describes the availability of CJK fonts on the system.
func CheckCJKFonts ¶ added in v0.3.1
func CheckCJKFonts() CJKFontStatus
CheckCJKFonts checks whether CJK fonts are installed on the system. It uses platform-specific methods: fc-list on Linux, system_profiler on macOS.
type ImageProcessingOptions ¶ added in v0.3.1
type ImageProcessingOptions struct {
EmbedLocalAsBase64 bool
EmbedRemoteAsBase64 bool
RewriteLocalToFileURL bool
RewriteRemoteToFileURL bool
DownloadRemote bool
CacheDir string
MaxConcurrentDownloads int
Logger *slog.Logger
}
ImageProcessingOptions controls how image references are rewritten.
type LimitedWriter ¶ added in v0.7.0
LimitedWriter wraps an io.Writer and silently discards writes that would exceed the configured byte limit. This prevents unbounded memory growth when capturing output from external processes.
After the limit is reached, Write still reports consuming all bytes so that callers such as io.Copy do not treat a truncated write as io.ErrShortWrite.
type PageDimensions ¶ added in v0.7.0
PageDimensions holds page width and height in millimeters.
func GetPageDimensions ¶ added in v0.7.0
func GetPageDimensions(size string) PageDimensions
GetPageDimensions returns the page dimensions for a named page size. If the size is unknown, A4 dimensions are returned.
func (PageDimensions) HeightMM ¶ added in v0.7.0
func (d PageDimensions) HeightMM() string
HeightMM returns the height as a Typst-compatible "Xmm" string.
func (PageDimensions) WidthMM ¶ added in v0.7.0
func (d PageDimensions) WidthMM() string
WidthMM returns the width as a Typst-compatible "Xmm" string.
type ProgressTracker ¶
type ProgressTracker struct {
// contains filtered or unexported fields
}
ProgressTracker tracks build progress.
func NewProgressTracker ¶
func NewProgressTracker(total int) *ProgressTracker
NewProgressTracker creates a new progress tracker.
func (*ProgressTracker) Done ¶
func (p *ProgressTracker) Done()
Done marks the current step as completed.
func (*ProgressTracker) DoneWithDetail ¶
func (p *ProgressTracker) DoneWithDetail(detail string)
DoneWithDetail marks the current step as completed with extra detail.
func (*ProgressTracker) Fail ¶
func (p *ProgressTracker) Fail()
Fail marks the current step as failed.
func (*ProgressTracker) Finish ¶
func (p *ProgressTracker) Finish()
Finish prints the build-complete summary.
func (*ProgressTracker) FinishWithError ¶
func (p *ProgressTracker) FinishWithError(err error)
FinishWithError prints the build-failed summary.
func (*ProgressTracker) Skip ¶
func (p *ProgressTracker) Skip(reason string)
Skip marks the current step as skipped.
func (*ProgressTracker) Start ¶
func (p *ProgressTracker) Start(description string)
Start marks the beginning of a new step and prints the pending state.