DevelopMedia
@holtkeeper/assets
Asset budgets for games and frontends: inventories the images, audio, video, fonts, atlases and models a repository ships, reads their headers, checks them against budgets, suggests smaller formats and compares with the previous record.
Analyzer
Section titled “Analyzer”assetsAnalyzer — kind assets, scope repo, needs a checkout; refreshed when the default branch changes (at most daily, heavy). Options (assetsOptionsSchema):
| Option | Default | Meaning |
|---|---|---|
roots |
defaultRoots |
Globs to scan: public/**, assets/**, static/**, src/**/assets/**, res/** |
dist |
— | Build output folder, scanned as well with origin: 'build' (flag --dist) |
policy |
defaultAssetsPolicy |
The asset policy (see Policy); the server fills it from the assets.policy setting, never from analyzers.assets |
convert |
sharp if it loads, else estimate |
sharp (real variants and changes), estimate (ratios), tools (measure with converters), off (flag --convert) |
optimizeTop |
20 |
With sharp: images (raster and SVG together) optimized, largest first (flag --optimize-top) |
svgPreset |
safe |
With sharp: svgo preset of SVG changes (flag --svg-preset) |
naming |
— | With sharp: { width?, density? } variant file templates, default {name}-{width}w.{ext} / {name}@{density}x.{ext} |
inlineSvg |
true |
Check inline <svg>/<path> in markup and components (flag --inline-svg); off with convert: 'off' |
Repositories that ship no assets (backends, infrastructure, contracts) turn it off with repo.analyzers ({ off: ['assets'] }, Analyzers turned off): it is never queued automatically there, the hub’s Assets card reads Off and the repository leaves Quality › Assets.
From the policy the analyzer takes ignore (left out of the inventory), minSaving.bytes (smallest suggested saving), AVIF when formats.raster asks for it, and passes the whole policy to analyzeAssets, which records policy and its violations in the data, drops suggestions below minSaving (percent and bytes), drops format changes and missing-modern-formats findings under formats.raster: 'keep', and leaves SVG files and inline SVGs alone under formats.svg: 'keep'.
Policy
Section titled “Policy”assets.policy is a structured setting (assetsPolicySetting, key assetsPolicyKey), scoped like every setting (all → group → repository, the most specific entry wins as a whole). assetsPolicySchema fills every field:
| Field | Default | Meaning |
|---|---|---|
formats.raster |
webp |
Modern format every PNG, JPEG and GIF from 8 kB needs next to it: webp, avif, avif+webp or keep |
formats.svg |
optimize |
optimize suggests svgo rewrites; keep leaves SVGs alone |
formats.allowed |
— | Extensions allowed at all; files of others are errors |
maxBytes |
{ warn: 500000, error: 1000000 } |
Per file; perKind replaces warn/error for one kind |
maxDimension |
2560 |
Largest width or height of raster images and videos |
minSaving |
{ pct: 5, bytes: 1024 } |
Conversions saving less than both are not suggested |
ignore |
vendor/**, **/*.min.*, fixtures/** |
Globs left out of everything |
budgets |
{} |
total bytes of every asset, perKind bytes per kind |
mode |
comment |
suggest-mr: reviews also offer a merge request with the variants from the panel |
policyViolations(assets, policy)→PolicyViolation { id, rule, severity, path?, kind?, format?, actual?, limit?, message }[], errors first then by path. Rules:format(error),max-bytes(warning abovewarn, error aboveerror),max-dimension(warning; SVGs are not checked),modern-format(warning: a source PNG/JPEG/GIF family from 8 kB without the required siblings),budget(error, per kind or total). Ignored files are skipped and build files identical to a source file are checked once.parseAssetsPolicy(value)— a stored value as a full policy; invalid or missing givesdefaultAssetsPolicy.isIgnored,byteLimits(policy, kind),formatAllowed,kindOfPath,requiredFormats(raster)— single questions the reviewer and agent tools ask.assetsPolicyFacts(policy)— the policy as Markdown bullets; the Guide adds them to the Assets section when an entry covers the repository, andasset_policyand theassetstopic ofrepo_rulesreturn them.
Prose rules (which component renders images, where files go) belong in the Guide’s Assets section, not in the policy.
Summary
Section titled “Summary”assetsSummary(data, limit = 200) → AssetsSummary { files, totalBytes, totals, errors, warnings, budgets, savings, duplicateBytes, rows, more }: per file (AssetRow { path, kind, format, bytes, width?, height?, severity, problems, suggestion? }) the policy violations, extra copies (duplicate, info) and the best suggestion (a file with only a suggestion gets a saving info problem), errors first, then by size. The repository Assets tab and the repo_assets tool show it.
assetsMetrics(data, { previous? }) is the kind’s metrics, stored with every record as AssetsMetrics: files, bytes and kinds (bytes per kind), policy errors and warnings, exceeded budgets, savings, duplicateBytes, delta (bytes minus the previous record’s), rows (the first 50 assetsSummary rows, errors first, then by size) and moreRows (rows left out). The fleet Assets table reads rows from the newest records’ metrics, so it never loads record data; files past the first 50 of a repository show only in that repository’s summary. parseAssetsMetrics(value) reads stored metrics back (undefined when they are not in that shape; metrics stored before rows existed read as having none). assetProblemRules lists every AssetProblem['rule']: the policy rules, duplicate and saving.
analyzeAssets(options) runs the same pipeline without the analyzer wrapper; it never writes to the checkout. options.cache (the analyzer passes context.cache) is handed to encodeVariants, so images whose bytes did not change since an earlier run — on any machine sharing the store — are not encoded again.
Pipeline
Section titled “Pipeline”-
Inventory (
inventory,scanFiles) — known formats of any size and unknown binaries from 256 kB (OTHER_MIN_BYTES); code, styles and documents are skipped. EachAssethaspath,kind(image,audio,video,font,atlas,model,data,other),format,bytes,gzip(text formats),hash(SHA-256 prefix) andorigin. -
Headers — pure parsers, no native dependencies; malformed files just get no metadata.
- Images (
image): PNG/APNG (IHDR, tRNS, acTL), JPEG (SOF), GIF (frames, transparency), WebP (VP8, VP8L, VP8X/ANMF), AVIF (ispe,pixi, auxiliary alpha,avis), SVG (width/height,viewBox), BMP, ICO. - Audio (
audio): WAV (fmt/data), MP3 (frame header, Xing/Info/VBRI, else CBR), Ogg Vorbis/Opus (headers + last granule), FLAC (STREAMINFO), M4A (mvhd,mp4a). Video (video): MP4 duration and track size. - Fonts (
font): TrueType/OpenType/WOFF glyph count frommaxp; WOFF2 and collections report the format only. - Atlases (
atlas): TexturePacker / Pixi / Phaser JSON, libGDX/Spine.atlas, AngelCode.fnt— frame count and texture names.
- Images (
-
References (
collectTokens,isReferenced) — tokens of every source and config file (generated folders skipped) plus atlas/glTF texts. An asset is referenced when its file name, a path suffix, or its stem (3+ chars, e.g. loader keys) appears. Favicons and similar are implicit. Build outputs are not checked. -
Engines (
detectEngines) — pixi, phaser, three, babylon, cocos, playcanvas frompackage.jsonfiles up to two levels deep. -
Checks —
evaluateBudgets(per-asset and per-kind total),findIssues(huge-dimensionsabove 4096 px,non-power-of-twofor raster images ≥ 64 px when an engine is found,unused, and withfamiliesthe delivery checks below),findDuplicates(by hash within an origin).- Families (
imageFamilies): source rasters grouped by folder and base name, sohero.png,hero.webp,hero-640w.avifandhero@2x.pngare one family; the original is the PNG/JPEG/GIF (before WebP, before AVIF; the widest when several). A bare-{n}suffix (bg-720.webp,bg-1080.webp) is a size only whennis the file’s width or height, solevel-2.pngstays its own image.variantPaths,modernFormats,hasModernFormats,hasSizesanswer what a family already ships. - Delivery (
deliveryIssues):missing-modern-formatsfor PNG/JPEG/GIF originals fromminBytes(8 kB) without WebP in the family — withavif, without AVIF or WebP (warning when both are missing, info when one is),single-resolutionfor originals wider thanHIGH_RES_WIDTH(1280 px) without width or density variants (info in game projects). - Inline SVG (
scanInlineSvgs,inlineSvgFile):.html/.htm/.jsx/.tsx/.vue/.svelte/.astrofiles (generated folders skipped, up to 2 MB) throughoptimizeInlineSvgs; oneinline-svgfinding (withline) and one changeassets:inline-svg:<file>per file, with areplaceedit per fragment —safewhen every fragment is a static svgo rewrite,reviewwhen path data in JSX or bound SVGs is rewritten.
- Families (
-
Suggestions (
candidates,estimateSuggestions,measureSuggestions) — family members and formats a family already has are skipped; opaque PNG → WebP lossy, PNG with alpha → WebP lossless, JPEG → WebP lossy (AVIF withavif), animated GIF → animated WebP, WAV/FLAC → Ogg Vorbis, TTF/OTF → WOFF2.estimateRatiosholds the conservative ratios with their sources.convert: 'tools'copies each candidate to a temp dir and runscwebp,avifenc,ffmpegorwoff2_compressthrough theCommandRunner; a missing tool or failed conversion falls back to the estimate. Assets under 8 kB and savings under 2 kB are dropped. -
Optimization (
convert: 'sharp',optimizationCandidates,optimizeAssets) — theoptimizeToplargest source images: PNG/APNG/JPEG/GIF/WebP fromminBytes(8 kB) and SVGs from 512 bytes, except generated family members and originals that already ship WebP (and AVIF withavif) and smaller sizes. Built on@holtkeeper/media:- Usages (
usageSources,findReferences,imgReferences,cssReferences,resolveImage):<img src="…">with a literal src in.html/.htm/.jsx/.tsx/.vueandbackground/background-image: url(…)in.css/.scss/.less./x.pngresolves againstpublic/,static/and the root, relative URLs against the file,@//~/againstsrc/. Tags withsrcset, inside<picture>, with dynamic src, and declarations already usingimage-set()are left alone. - Usage kind (
usageOf):fixedwhen every<img>gives the samewidth(density ladder),texturein game projects (an engine found) without markup usages, otherwiseresponsive. - Rasters are probed, planned and encoded with sharp as WebP and the original format re-encoded, plus AVIF with
avif; a format is proposed when its full-size variant saves at leastminSaving(2 kB) (proposedVariants). The change (assets:image:<path>) haswrite-binaryedits for the proposed variants —artifactis the variant SHA-256, no base64; the full-size re-encode in the original format overwrites the original withpreviousSha256— plus, when usages were found,replaceedits swapping each<img>for a<picture>snippet (React/Vue/HTML by file type, keeping other attributes such asclassName) and each CSS declaration for itself plus animage-set()declaration. Confidencereviewwith swaps or a lossy overwrite of the original,safeotherwise. - SVGs are optimized with svgo; a saving of at least 2% (min 64 bytes, at most
minSaving) becomes a whole-filereplacechange (assets:svg:<path>),safefor thesafepreset andreviewotherwise. SVGs over 512 kB are reported but get no change. - Measured results replace the estimated image suggestions (
method: 'measured', SVGs as rulesvg);toolslistssharpandsvgowhen they measured something. Undecodable images are kept witherror.
- Usages (
Artifacts contract
Section titled “Artifacts contract”Analysis data stays JSON-serializable: variants are stored as sizes and hashes only. The encoded bytes of every proposed variant are kept in memory for the returned data object: collectArtifacts(data) → { sha256, bytes, data }[], one per distinct artifact of the write-binary edits. It works only on the exact object analyzeAssets (or assetsAnalyzer.run) returned, in the same process — a copy, a parsed record or a run without sharp yields []. assetsAnalyzer.run returns them as analyzer artifacts (runArtifacts(data): id = sha256, contentType, name = target path), which the job engine stores tagged with the analysis, so the changes can be applied later.
Build files with the same hash as a source file are the same shipped asset: they count once in totals, get no suggestion and are not duplicates.
AssetsData { roots, engines, convert, tools, assets, totals, budgets, findings, suggestions, duplicates, optimized?, svgs?, changes? }, validated by assetsDataSchema.
optimized:ImageOptimization { path, format, bytes, width, height, usage, variants, skipped, best?, references, changeId?, error? }; eachImageVariant { id, format, width, height, density?, bytes, quality, ssim?, sha256, file, replacesOriginal?, proposed }.svgs:SvgOptimizationData { path, preset, bytes, gzip, breakdown, changeId?, error? }— the svgo breakdown without the optimized text, which lives in the change.inlineSvgs:InlineSvgData { file, line, endLine, kind, bytes, digits, paths, changeId }per fragment worth rewriting.changes:CodeChange[], also returned byassetsAnalysis.changes(data).
Comparison and report
Section titled “Comparison and report”compareAssets(previous, current) matches assets by path; an unmatched new path with the hash of a removed one is renamed. It returns per-kind totals, asset changes (added, removed, grown, shrunk, changed, renamed) and new/resolved budget violation ids.
assetsAnalysis (or createAssetsAnalysis({ largest, treemapFiles, imageCards })) reports:
- Metrics: total bytes, bytes per kind, policy violations (with budgets), proposed changes (when there are changes), potential savings — each with a delta against the previous record.
- Overview: bytes by kind chart, folder → file treemap.
- Policy: policy violations (new ones tagged), per-pattern budget violations of
analyzeAssetscallers, resolved ones, huge and non-power-of-two textures. - Suggestions: asset, current, suggested format, how, expected size, saving, estimated/measured; possibly unused assets.
- Image optimization (with
sharp): per image original, full-size WebP/re-encoded sizes (AVIF too when it was encoded), best saving, Δ of the best size against the previous record, proposed/total variants and usages; per-image cards (imageCards, default 10) with every format’s widths or densities, full-size and smallest bytes, saving, quality and status; images that could not be decoded; an applicablechangesblock with the variants and image swaps (binary files listed without hunks). - SVG optimization: before/after bytes and gzip, saving, Δ against the previous record, what was removed; path data (paths, commands, coordinates, digits, longest path before → after); viewBox/size/embedded-raster issues; an applicable
changesblock. - Largest assets: size, gzip, dimensions/duration/glyphs, tags.
- Changes since previous: per kind and per asset (only with a previous record).
- Duplicates: copies and wasted bytes.
- Image delivery:
missing-modern-formats,single-resolutionandinline-svgfindings, a table of inline SVGs (file, lines, svgo or path-data rewrite, bytes, path digits) and an applicablechangesblock with the inline rewrites.
File columns are path columns and the report sets exclude to assets.policy with ignore, so the panel can add a glob for a file or folder from any row.
Limitations
Section titled “Limitations”- Default roots are relative to the repository root; monorepos with
apps/*/publicneedroots. - WebM, AAC (ADTS) and KTX/Basis textures are inventoried without metadata.
- Reference search is token based: assets loaded by computed names look unused.
- Usage rewriting is regex based:
<img>attributes with nested braces,<Image>components and imported image modules (src={hero}) are not rewritten; variants are written next to the original, so URLs keep the original folder. sharpmode encodes up tooptimizeTopimages with every ladder width and format; large images take seconds each.