Skip to content
GitHub

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.

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'.

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 above warn, error above error), 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 gives defaultAssetsPolicy.
  • 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, and asset_policy and the assets topic of repo_rules return them.

Prose rules (which component renders images, where files go) belong in the Guide’s Assets section, not in the policy.

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.

  1. Inventory (inventory, scanFiles) — known formats of any size and unknown binaries from 256 kB (OTHER_MIN_BYTES); code, styles and documents are skipped. Each Asset has path, kind (image, audio, video, font, atlas, model, data, other), format, bytes, gzip (text formats), hash (SHA-256 prefix) and origin.

  2. 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 from maxp; WOFF2 and collections report the format only.
    • Atlases (atlas): TexturePacker / Pixi / Phaser JSON, libGDX/Spine .atlas, AngelCode .fnt — frame count and texture names.
  3. 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.

  4. Engines (detectEngines) — pixi, phaser, three, babylon, cocos, playcanvas from package.json files up to two levels deep.

  5. Checks — evaluateBudgets (per-asset and per-kind total), findIssues (huge-dimensions above 4096 px, non-power-of-two for raster images ≥ 64 px when an engine is found, unused, and with families the delivery checks below), findDuplicates (by hash within an origin).

    • Families (imageFamilies): source rasters grouped by folder and base name, so hero.png, hero.webp, hero-640w.avif and hero@2x.png are 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 when n is the file’s width or height, so level-2.png stays its own image. variantPaths, modernFormats, hasModernFormats, hasSizes answer what a family already ships.
    • Delivery (deliveryIssues): missing-modern-formats for PNG/JPEG/GIF originals from minBytes (8 kB) without WebP in the family — with avif, without AVIF or WebP (warning when both are missing, info when one is), single-resolution for originals wider than HIGH_RES_WIDTH (1280 px) without width or density variants (info in game projects).
    • Inline SVG (scanInlineSvgs, inlineSvgFile): .html/.htm/.jsx/.tsx/.vue/.svelte/.astro files (generated folders skipped, up to 2 MB) through optimizeInlineSvgs; one inline-svg finding (with line) and one change assets:inline-svg:<file> per file, with a replace edit per fragment — safe when every fragment is a static svgo rewrite, review when path data in JSX or bound SVGs is rewritten.
  6. 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 with avif), animated GIF → animated WebP, WAV/FLAC → Ogg Vorbis, TTF/OTF → WOFF2. estimateRatios holds the conservative ratios with their sources. convert: 'tools' copies each candidate to a temp dir and runs cwebp, avifenc, ffmpeg or woff2_compress through the CommandRunner; a missing tool or failed conversion falls back to the estimate. Assets under 8 kB and savings under 2 kB are dropped.

  7. Optimization (convert: 'sharp', optimizationCandidates, optimizeAssets) — the optimizeTop largest source images: PNG/APNG/JPEG/GIF/WebP from minBytes (8 kB) and SVGs from 512 bytes, except generated family members and originals that already ship WebP (and AVIF with avif) and smaller sizes. Built on @holtkeeper/media:

    • Usages (usageSources, findReferences, imgReferences, cssReferences, resolveImage): <img src="…"> with a literal src in .html/.htm/.jsx/.tsx/.vue and background/background-image: url(…) in .css/.scss/.less. /x.png resolves against public/, static/ and the root, relative URLs against the file, @//~/ against src/. Tags with srcset, inside <picture>, with dynamic src, and declarations already using image-set() are left alone.
    • Usage kind (usageOf): fixed when every <img> gives the same width (density ladder), texture in game projects (an engine found) without markup usages, otherwise responsive.
    • 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 least minSaving (2 kB) (proposedVariants). The change (assets:image:<path>) has write-binary edits for the proposed variants — artifact is the variant SHA-256, no base64; the full-size re-encode in the original format overwrites the original with previousSha256 — plus, when usages were found, replace edits swapping each <img> for a <picture> snippet (React/Vue/HTML by file type, keeping other attributes such as className) and each CSS declaration for itself plus an image-set() declaration. Confidence review with swaps or a lossy overwrite of the original, safe otherwise.
    • SVGs are optimized with svgo; a saving of at least 2% (min 64 bytes, at most minSaving) becomes a whole-file replace change (assets:svg:<path>), safe for the safe preset and review otherwise. SVGs over 512 kB are reported but get no change.
    • Measured results replace the estimated image suggestions (method: 'measured', SVGs as rule svg); tools lists sharp and svgo when they measured something. Undecodable images are kept with error.

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? }; each ImageVariant { 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 by assetsAnalysis.changes(data).

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 analyzeAssets callers, 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 applicable changes block 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 changes block.
  • 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-resolution and inline-svg findings, a table of inline SVGs (file, lines, svgo or path-data rewrite, bytes, path digits) and an applicable changes block 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.

  • Default roots are relative to the repository root; monorepos with apps/*/public need roots.
  • 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.
  • sharp mode encodes up to optimizeTop images with every ladder width and format; large images take seconds each.