Process, hash, sync, and clean image assets for web projects that keep originals outside git and optionally sync through any rclone remote, with a separate pass for web videos.
Features
- originals may live on an
rcloneremote and be synced locally - optimized outputs should be deterministic and aggressively cacheable
- output filenames should change when either the source file or the transform changes
- old optimized files should be removed locally and remotely
- generates type-safe
imageList.tsandvideoList.tsshould stay in sync with processed assets
Quick link
- code - https://github.com/david1gp/assets-optimizer
- npm - https://www.npmjs.com/package/@adaptive-ds/assets-optimizer
processAssets() orchestrates the full workflow:
- Syncs originals from remote source to local
imagesandvideosfolders using the catalog sync protocol - Pulls existing optimized outputs from R2, then runs
assetsOptimize()locally - Uploads optimized assets to s3-compatible remote destination with caching headers
assetsOptimize() performs the core asset processing:
- Resolves the project name from
package.json.name - If
rcloneRemoteis configured, uses that project name as the base path on the remote - If
rcloneRemoteis configured, syncs originals between the remote andimages - Scans transform folders like
1920x1080_jpg, optionally nested in grouping folders - Processes matching image source files with
sharp - Writes flat optimized images into
public/images - Names image files as
<basename>_<hash>.<ext> - Skips already-generated images
- Deletes stale optimized images locally
- If
rcloneRemoteis configured, uploads missing optimized images to the remote with cache headers - If
rcloneRemoteis configured, deletes stale optimized images from the remote - Runs a separate optional video pass from
videostopublic/videos - Generates a hashed
<basename>_<hash>.webppreview beside each processed video (full resolution,sharp-encoded) - Keeps video filenames unchanged and skips any processed video or preview that already exists
- If
rcloneRemoteis configured, uploads videos with a short cache header and their hashed previews with a long (immutable) cache header - Generates
src/app/assets/imageList.tsandsrc/app/assets/videoList.tsby default - Prints a clear summary of what changed
The hash is derived from:
- source file bytes
- normalized transform spec
That means image cache keys change when the source image changes or when you change the folder rule, even if the output filename format stays short.
Original files belong under one transform folder inside images. Arbitrary grouping folders may appear before and after the transform folder.
Example:
images/
interiors/
homes/
1920x1080_jpg/
hero/
living-room.png
products/
1200x1200_webp/
kitchen.jpg
This produces flat optimized image output like:
public/images/
living-room_9f8e7d6c.jpg
kitchen_7c6b5a4d.webp
Files that are not inside a transform folder are ignored by design. Ignored folder names are configurable: by default, folders whose name contains .git, ignore, discarded, skipped, or staging are skipped entirely.
Add project-specific ignored folder names with ignoredDirNames:
await assetsOptimize({
ignoredDirNames: ["archive", "drafts"],
})Only the first transform folder in a path is used. If another transform-looking folder appears below it, that nested folder is skipped with a warning.
Videos are handled separately and do not use transform folders:
videos/
hero.mp4
intro.webm
public/videos/
hero.mp4
hero_a1b2c3d4.webp
intro.webm
intro_9f8e7d6c.webp
Video behavior:
- if both local
videosand remotevideo-originalsare missing, the video pass does nothing - if
rcloneRemoteis configured, source videos sync throughvideo-originals - if
rcloneRemoteis configured, processed videos sync throughvideo-processed - missing processed videos are created with
ffmpeg - missing preview images are created beside processed videos as
<basename>_<hash>.webp:ffmpegextracts a representative frame at full resolution, thensharpre-encodes it to webp atvideoPreviewQuality(default65, the same encoder/quality scale used for images) - the preview hash is derived from the processed video's content, so the preview filename busts when the video changes; previews can therefore be cached immutably even though video filenames are not hashed
- existing processed videos are skipped and preserved as manual transformations
- existing previews are skipped; stale previews from a previous hash are removed when regenerated
- video filenames and relative paths are kept as-is (optimize them by hand)
- processed videos and generated previews without a corresponding original are deleted; cleanup is skipped if the originals directory is missing
Output filenames are <basename>_<hash>.<ext>, where the hash defaults to 8 hex chars.
Set imageHashLength to use a shorter (or longer) suffix:
await assetsOptimize({
imageHashLength: 3,
})images/1920x1080_webp/ship_PYM.webp -> public/images/ship_PYM_a1b.webp
The hash only busts cache when a single file's content changes — the basename already
distinguishes different images, so cross-file collisions never matter. The only risk of a
short hash is that an edited file re-hashes to the same suffix and its cache is not busted:
roughly 1 / 16^length per edit (≈ 1/4096 at length 3). The generated imageList.ts
strips exactly imageHashLength hex chars to keep stable keys, so keep this value in sync
with the existing list.
imageTypeImportPath sets the import type { ImageType } from "..." line of the
generated imageList.ts (defaults to this package's name).
Folder names can use the full form:
<width>x<height>_<format>
<format> is optional and defaults to webp. <height> is optional and defaults to <width>.
Supported image output formats:
-
jpg -
png -
webpExamples: -
1920x1080_jpg -
1600x900_webp -
1600x900 -
1200_webp -
1200Image processing behavior: -
resize fit:
inside/ max-bounds scaling -
withoutEnlargement: true -
image auto-rotation is applied
-
default quality is
80
Supported video source extensions:
mp4movm4vwebmavimkv
bun add -D @adaptive-ds/assets-optimizerUse assetsOptimize() when the optimizer is part of a project build:
import { assetsOptimize } from "@adaptive-ds/assets-optimizer"
await assetsOptimize()This generates optimized images, processed videos, hashed webp video previews, imageList.ts, and videoList.ts in one run.
Existing image alt text and existing video preview alt text are preserved when the generated files already exist.
Image alt text can also be provided with a same-basename .txt or .md file next to the source image inside a transform folder. If both exist, .txt is used and .md is the fallback.
After installing the package, pass options as typed kebab-case flags:
assets-optimizer optimize --no-process-images --no-process-videos --no-process-fontsString arrays accept repeated flags, for example --ignored-dir-names cache --ignored-dir-names tmp. AI label settings use flattened flags such as --ai-label-mode adaptive and --ai-label-placement bottom-right. Run assets-optimizer optimize --help for the full list.
The optimize command writes one JSON object to stdout. Successful runs use { "success": true, "data": ... }; failures use { "success": false, "error": ... } and exit with status 1. Requested logs are captured in an optional diagnostics field instead of being written as separate lines. Stderr stays empty.
The remote is the source of truth. Each originals tree has a remote .assets-sync/ containing catalog.json (with a global version counter), changelog.jsonl, and trash/<date>/<transfer-id>/; separate transfer IDs preserve repeated same-day backups, and trash is purged after 30 days. Each local tree stores its base catalog and hash cache in its own .assets-sync/. Add these patterns to the consumer project's .gitignore:
.assets-sync/
*.remote-conflict.*Sync compares local and remote against the local base: a local-only change uploads, a remote-only change downloads, and a deletion propagates when the other side is unchanged. Identical changes need no transfer; different edits on both sides conflict rather than overwrite. On a fresh machine without a base, remote files download; differing existing local and remote files conflict.
On a fresh machine, a local-only original is deleted only when a remote tombstone matches its SHA-256. A missing remote file without a matching tombstone is restored from the local original instead.
An edit wins over a deletion: when one side edited a tracked file and the other side deleted it, the edit is applied (uploaded or downloaded) in a single run instead of conflicting.
A conflict quarantines only its own path. Every other path still syncs and commits in the same run; the conflicted local file is left untouched and the remote contents are downloaded as a sibling *.remote-conflict.* copy. syncOriginals() returns normally with summary.conflicts > 0 instead of throwing (note: this is a behaviour change for library callers that relied on the throw). The next run re-reports the path without auto-uploading while the copy exists. To resolve, inspect the conflict and pick a side with resolve, then sync again to apply it:
assets-optimizer resolve --local images
assets-optimizer resolve --local images --keep local conflict/photo.jpg
assets-optimizer resolve --local images --keep remote
assets-optimizer resolve --local images --keep both conflict/photo.jpgWithout --keep, resolve only lists outstanding conflicts and changes nothing, showing both sides (size, date, author, image dimensions, and whether the pixels match). --keep local deletes the copy so the next sync uploads the local file; --keep remote replaces the local file with the copy (restoring it when missing) so the next sync is a no-op for that path; --keep both renames the copy to a *.remote-copy.* sibling, which becomes a normal original that syncs and gets optimized. Pass specific original paths to resolve only those; unknown or non-conflicted paths fail without affecting the others. As a fallback, the same steps can be done manually: keep the local original and delete the copy to upload it, or replace the local file with the copy and delete the copy to keep the remote version. For a remote deletion, delete the local original to accept it.
To resolve edit/edit conflicts without manual steps, pass prefer: "local" (upload local; the remote loser is preserved by the upload backup-dir trash) or prefer: "remote" (move the losing local file to <localDir>/.assets-sync/trash/<YYYY-MM-DD>/<path>, adding a numeric suffix on same-day repeats, then download remote). Outstanding *.remote-conflict.* copies from earlier runs resolve the same way. Warnings name each auto-resolved path.
When migrating from bisync, the first run against an existing remote creates a catalog. Old rclone bisync state in ~/.cache/rclone/bisync can be deleted. The resync option is a deprecated no-op.
assets-optimizer status --local images --remote myremote:project/images
assets-optimizer sync --local images --remote myremote:project/images --dry-run
assets-optimizer sync --local images --remote myremote:project/images --cwd /path/to/project
assets-optimizer sync --local images --remote myremote:project/images --prefer remotestatus and sync --dry-run show the plan without applying it. By default, both commands print a human-readable plan and summary to stdout; errors are printed to stderr and exit nonzero. Add --json to either command for a JSON envelope on stdout, including data.text on success; errors also use the JSON envelope and exit nonzero. Status can show conflicts in its plan; sync exits nonzero when unresolved conflicts remain after a completed partial sync, and its message makes clear the other paths were synced.
This package is built for a workflow with two local directories:
images: original source images, never modifiedpublic/images: generated optimized images, flat output onlyvideos: original source videos, optionalpublic/videos: processed videos, optional
- Source images live below transform folders like
1920x1080_jpginsideimages/ - Grouping folders may appear before and after the transform folder
- Each source file is resized to fit within the specified bounds without enlargement
- Auto-rotation is applied based on EXIF data
- Output quality defaults to 80%
- Files are named using a hash of the source content and transform spec
- Existing optimized files are skipped unless their source changed
- Stale optimized files (from deleted sources or changed transforms) are removed
- A TypeScript list file is generated with all processed image references
- Source videos live directly in
videos/(no transform folders) - Each video is copied to the output directory using
ffmpeg - A hashed, full-resolution webp preview (
sharp-encoded atvideoPreviewQuality, default65) is generated beside each processed video - Video filenames stay unhashed (optimize length/etc. by hand); previews are content-hashed so they cache-bust on change
- Existing processed videos and previews are preserved as-is
- A TypeScript list file is generated with all processed video references
bunrclone>= 1.66 (install from https://rclone.org/install/)ffmpeg- an existing
rcloneremote - write access to the target bucket/path
- Node/Bun environment capable of running
sharp
This package assumes the remote bucket/path already exists or can be created by rclone mkdir.
Optimized output cleanup does not use a manifest.
Instead it derives the expected output set from the current originals and current transform folders, then reconciles that against:
- local
public/images - remote
images/optimizedobjects
That means:
- files no longer produced by the current source set are deleted
- renaming or removing a source file cleans up stale optimized files
- changing a transform folder causes a different hash and a different output filename
- Add or sync originals into
images/<grouping-folders>/<transform-folder>/<grouping-folders>/ - Run your local image pipeline entrypoint
- Regenerate your typed image list
- Reference the generated hashed filenames from app code or derived metadata
By default this package skips source images sitting directly at the root of images, so
only files below explicit transform folders are processed:
images/1920x1080_jpg/
That contract is what makes the output deterministic and safe to clean automatically.
If you'd rather drop loose images at the root (e.g. one-off screenshots or placeholders),
set allowRootImageFiles: true. Each root file is then optimized once at its native
dimensions with the output format derived from its extension — no resizing, no transform
folder required. A root file's alt sidecar (<name>.md / <name>.txt) placed beside it is
picked up too. Transform folders and root files can coexist in the same images tree.
Images identified as AI-generated or AI-modified can automatically receive a visible watermark label during optimization to support EU AI Act labeling workflows. This feature helps incorporate AI disclosure labels into processed image assets; it does not present legal advice or guarantee regulatory compliance.
Classification is determined automatically by checking folder names, file names, or explicit transform folder suffixes:
- Filename detection: Source file names containing an AI pattern as a substring anywhere in the filename (e.g.
hero_Ai_generated.png,chart-ai-modified.jpg). - Directory detection: In-tree directory names inside the
images/source tree containing an AI pattern as a substring anywhere in the folder name (e.g.images/AI generated/1920x1080_jpg/). Detection applies recursively to all images within that directory and its subdirectories; external parent directories outside the source tree are ignored. - Accepted case, delimiter, and following-character forms: The classification pattern is matched as a substring starting with
AI,Ai, orai, followed by a delimiter (,.,_, or-), and ending withgeneratedormodified(e.g.AI generated,Ai_modified,ai-generated,AI.modified). The trailinggeneratedormodifiedmust occur at the end of the name or be followed by a non-letter character (e.g.ai_generated_2.pngmatches, butai-generatednessdoes not). - Transform folder suffix: Transform folders can specify an explicit classification suffix:
<width>x<height>_<format>_ai_<classification>or<width>x<height>_ai_<classification>(e.g.1920x1080_jpg_ai_generated,1200_webp_ai_modified, or1200_ai_generated).
Precedence (highest to lowest):
- Transform folder suffix (
_ai_generated/_ai_modified) - Source filename detection
- Parent directory detection (closest parent folder priority)
Configure label rendering via aiLabelOptions on assetsOptimize():
await assetsOptimize({
aiLabelOptions: {
mode: "adaptive",
simpleColor: "black",
visual: "padding",
opacity: "opaque",
placement: "bottom-right",
height: 32,
offsetX: 0,
offsetY: 0,
},
})Supported options (AiLabelOptions):
mode("simple"|"adaptive", default"simple"): Selects color logic."simple"uses the fixedsimpleColor."adaptive"analyzes pixels under the target region using linear relative luminance with alpha weighting to choose whichever color ("black"or"white") has lower luminance contrast against the background so the label is less conspicuous. Ties or invisible regions default to"black".
simpleColor("black"|"white", default"black"): Label color used in simple mode.visual("padding"|"circle", default"padding"): Visual layout variant (padded badge or circular icon).opacity("opaque"|"50%", default"opaque"): Opacity variant (100% fill or 50% transparency).placement("top-left"|"top-right"|"bottom-left"|"bottom-right", default"bottom-right"): Target corner placement.height(number, default32): Target label height in pixels.offsetX/offsetY(number, default0): Horizontal/vertical offsets in pixels. Positive values inset the label away from the corner into the image interior; negative values shift toward the boundary and clamp to image edges.
Label scaling preserves the SVG aspect ratio based on the target height. If an image is smaller than the requested label dimensions, the label automatically scales down to fit within the image bounds without distortion or overflow. Label positioning and dimensions are clamped to stay entirely within the target image bounds.
The 12 physical pre-rendered vector SVG label assets (mapping to 16 classification/color/visual/opacity option combinations, with circular visual assets shared across classifications) are stored in public/ai/ and included in NPM package distributions alongside dist/ (files: ["dist", "public"]). Label SVGs are loaded using module-relative resolution (import.meta.url), ensuring compatibility across package deployments.
MIT