Files
SnapOtter/tests/integration/tools/image/compose.test.ts
T
SnapOtterandGitHub b37faed95f fix: QA sweep - tool routes, security, i18n, a11y, + AI bundle install hardening (#393)
* fix(api): correct format/filename/container handling across tool routes

Found during a comprehensive QA sweep exercising every tool against its
full accepted-format matrix:

- watermark-image, compose: preserve the requested output format and a
  matching download filename/extension instead of always emitting the
  source format
- compose: crop oversized overlays to the visible base area instead of
  crashing Sharp's composite, and reject only overlays fully outside the
  base image instead of any oversized one
- compare, vectorize: switch to the shared image input handler so
  filenames and formats like .svgz/.tga/RAW survive validation instead
  of being rejected pre-processing
- tool-factory, images-to-video: normalize frames through Sharp before
  handing them to FFmpeg, fixing GIF/AVIF/RAW image-to-video jobs that
  previously failed or hung
- media-tool, replace-audio, embed-subtitles: fix legacy container
  MIME/codec handling for MPEG sources and subtitle remux cases
- files: expand download MIME mapping for text/data/document/video/audio
  outputs that were falling back to a generic content type
- convert-document/presentation/spreadsheet: same-format conversions now
  return the original validated file instead of erroring or producing
  corrupt tiny output

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(web): dropzone a11y, stale localStorage getter, dead code

- dropzone: stop making the whole drop-zone section clickable/focusable.
  A section acting as an interactive element around a real upload button
  is a nested-interactive-element anti-pattern that confuses screen
  readers; drag-and-drop doesn't need focus semantics, only the button
  fallback does. Keeps that button semantic and keyboard-reachable.
  Updates the two e2e call sites that clicked the section directly.
- api, use-auth: read through window.localStorage via the existing API
  storage helper instead of the bare global, which resolves to Node's
  experimental localStorage getter under Vitest and threw
- find-duplicates-settings, info-settings, login-page: remove dead code
  (unused zip-download handler, a stale mount-only effect dependency
  that left cached info stuck at reused indices, an unused response
  variable)

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(i18n): pt-BR, zh-CN, zh-TW were silently falling back to English

The locale loader looked up dynamic-import exports by the raw locale
code (mod["pt-BR"], mod["zh-CN"], mod["zh-TW"]), but those three modules
export camelCased bindings (ptBR, zhCN, zhTW) since identifiers can't
contain hyphens. The lookup returned undefined and every consumer
silently fell back to English for these three locales. Replaces the
generic lookup with explicit per-locale loaders so the mapping can't
drift out of sync again.

Also updates the dropzone helper copy across all 21 locales to match
the drag-only dropzone wording from the previous commit.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(docs): clear build warnings in the VitePress site

- config.mts: add an onwarn handler for the @vueuse INVALID_ANNOTATION
  warnings emitted during the docs build
- deployment.md: the caddyfile code fence language isn't a shiki grammar
  VitePress ships with, so it warned on every build; use txt instead

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* test(qa): update QA harness for the drag-only dropzone and regen metadata

- api-sweep, qa-helpers, verify-ai: add JSON-body tools, multi-input
  secondary fixtures, async polling for slow valid jobs, 501
  FEATURE_NOT_INSTALLED skip handling, and safer per-tool settings
- input-preview, pipeline-ui specs: update upload flow for the
  drag-only dropzone surface
- add tests/fixtures/data/valid/chart.json, a valid chart fixture the
  updated helpers route to
- regenerate tools-meta.json against current TOOLS[]

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(security): close a login timing side-channel, harden zip-slip tests

Found during a black-box security sweep of the real auth-enabled
production container: a nonexistent username returned 401 in ~3-10ms,
while a wrong password for a real user took ~35-42ms, because scrypt
verification only ran when a user row existed. That timing gap lets an
attacker enumerate valid usernames without ever guessing a password.
Now runs verification against a cached dummy hash on the unknown-user
path too, so both cases cost the same regardless of outcome.

extract-zip already had a relative-traversal regression test
(../evil.txt), but its absolute-path rejection branches
(name.startsWith("/") / startsWith("\\")) had none. Added the three
missing cases: deep relative traversal, absolute Unix path, and
Windows-style absolute path.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* test(qa): add UI-driven AI bundle install scripts

QA_PROMPT.md's Phase 2 requires installing AI models the way a user
does -- through the UI, on demand from HuggingFace -- and treats the
curl-based admin install endpoint as fallback-only. Nothing in the
harness actually drove that flow; tests/qa/seed-ai-models.sh installs
via docker exec + pip, which is further from a real user than even the
API fallback.

install-ai-bundles-ui.mts logs in, opens Settings > AI Features,
screenshots the pre-install state, clicks Install All, and screenshots
progress -- then exits, since installs continue server-side once
triggered. verify-ai-install-complete.mts polls bundle status,
screenshots the completed state, and runs one real tool per installed
bundle to prove the freshly-downloaded model actually executes.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(qa): correct the apiToolPath import in the AI verify script

Dynamic import of the package name failed under tsx's module resolution
from apps/api's node_modules context; use the same relative-path import
api-sweep.mts already uses successfully.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(web): correct AI bundle size estimates shown before install

Measured real downloads during GPU-node QA verification: photo-restoration
pulls ~4.4GB (was advertised as 800MB-1GB, off by 4-5x) and ocr pulls
~5.5GB (was advertised as 3-4GB). Both estimates only accounted for model
weights, not the pip dependencies (torch/paddle) that come down with them.
Updated to reflect actual total download size, since that's what a user
deciding whether they have the disk/bandwidth actually needs to know.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(web): make desktop Settings reachable when auth is disabled

AvatarDropdown (the only desktop entry point to Settings) was gated
behind `!isMobile && authEnabled`. With AUTH_ENABLED=false the synthetic
anonymous admin user should have full Settings access per how auth.ts
documents this mode -- and the mobile bottom nav already worked this way,
showing Settings unconditionally. Desktop just had a stray extra gate the
component doesn't need: AvatarDropdown already resolves its own username
internally (falling back to "admin") and reads authEnabled itself where
it actually matters (hiding the Logout button). Removed the outer gate;
verified end-to-end against a fresh AUTH_ENABLED=false instance -- avatar
now renders, Settings opens, shows the anonymous/Admin identity correctly.

Also documents (not changes) a related finding in install_feature.py:
detect_arch() always resolves amd64 hosts to the GPU-bundled archive
variant regardless of actual GPU presence, since no CPU-only amd64
archive is published to the bundle repo yet. Left as a code comment
rather than a behavior change, since requesting an unpublished archive
key would hard-fail installs entirely -- worse than the current
oversized-but-working download. Full detail in the QA report.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(ai): stop logging expected dispatcher reloads as crashes

After each AI bundle install the Python dispatcher reloads because the
venv changed, and after every app shutdown it's SIGTERMed. Both took the
close handler's `code !== 0` branch (SIGTERM makes the exit code null),
so they were counted as crashes -- producing an alarming "crash" line in
the logs and a pointless ~1s recovery backoff after each of 7 installs.
A `stopping` flag set in shutdown() lets the close handler tell an
intentional stop apart from a real crash. The request-timeout kill path
deliberately does not set it, so a genuinely hung script still records a
crash and the 5-in-60s permanent-disable threshold is untouched.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(api): return a clean message when content-aware resize times out

Carving a very high-resolution image down to a tiny target could exceed
the caire subprocess timeout, and the raw error forwarded to the user was
caire's terminal output -- ANSI color codes and progress-spinner control
characters -- instead of anything actionable. Now: the timeout path
throws a clear "timed out; try a smaller image or larger target" message
(keeping the raw stderr as `cause` for server logs); friendlyError()
strips ANSI/control chars centrally so any subprocess dump surfaced
through the shared sanitizer is plain text; and the content-aware-resize
route (a custom route that bypassed the sanitizer) now routes its error
paths through friendlyError like every other tool.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(ai): stop bundle installs from exhausting host disk

Installing an AI bundle on a tight-disk host could push the root
filesystem to zero bytes free after the preflight check had already
passed. Two root causes:

- move_tree used copytree+rmtree, so during the move the extracted
  payload existed in both staging and the venv at once -- a full
  transient doubling on disk. Rewrote it to rename entries (a cheap
  metadata op on the same filesystem, no copy), falling back to a copy
  only across filesystems.
- the preflight budget used the manifest's extractedSize verbatim, which
  is 0 for several archives, collapsing the estimate to just the
  compressed size. Added a conservative fallback (3x compressed) so a
  missing value can't under-reserve.

Also added a real-on-disk re-check immediately before the first
destructive venv write (measuring the actual extracted payload and
whether the move needs extra space for a cross-filesystem copy), which
also now covers the offline-import path that previously skipped the disk
check entirely; wrapped the moves so an out-of-space failure returns a
clean actionable error instead of a traceback; and made the disk check
resolve the nearest existing ancestor so it never throws on a
not-yet-created venv path.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* feat(web): show the real per-arch AI bundle download size

The bundle cards and install prompt showed a hardcoded, architecture-blind
estimatedSize string. That's misleading: amd64 hosts always pull the
CUDA-inclusive archive (there's no CPU-only amd64 variant published), so a
bundle labelled "1-2 GB" can actually download several times that, while
arm64 pulls a much smaller archive for the same label. The manifest
already carries the real per-arch compressedSize (and extractedSize where
measured), so surface those: a new optional downloadBytes/installedBytes
on FeatureBundleState, populated in getFeatureStates() for this host's
arch (resolver mirrors install_feature.py detect_arch), shown by the UI
when present with estimatedSize kept as the fallback label. Also nudged
upscale-enhance's fallback string (4-5 -> 5-6 GB) to match its real
compressed size, consistent with the earlier photo-restoration/ocr fixes.

Fields are optional so demo/mock and existing tests stay compiling; the
manifest's extractedSize is 0 for a few archives, which now surfaces as
null rather than a bogus 0.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(web): move the AI install queue to the server so it survives tab close

Installing multiple bundles could silently lose all but the first. The
server rejected a concurrent install with 409, so the client worked
around it by queueing the rest in browser-local state and only POSTing
each once it saw the previous finish. A single POSTed install is durable
(the installer child is detached from the request), but a queued one had
zero server footprint -- close the tab mid-queue and those installs
vanished with no error, while the UI still showed them "Queued". The
client "mutex" didn't even serialize: the queued bundles' local waits all
resolved at once and raced into concurrent POSTs that 409'd each other.

Now the queue lives on the server (a small in-memory FIFO leaf module).
The install endpoint enqueues instead of 409-ing and returns
202 {jobId, queued}; a pump starts the next bundle when the current one's
child exits (and after an offline import releases the lock), all behind
the existing venv + file locks, which are unchanged. The client just
POSTs every bundle immediately and reflects the server-reported
queued/installing status; Install All fires all POSTs and lets the server
serialize them, keeping the one-shot retry-on-failure. Adds "queued" to
FeatureStatus (the bundle card already rendered that state) and surfaces
it from getFeatureStates. In-memory is deliberate: it matches the
existing contract (survives a tab close, not a server restart, which
already clears the lock on boot).

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG

* fix(qa): don't log env-derived credentials in the AI-install script

CodeQL flagged clear-text logging of sensitive information: the login
status line interpolated the QA base URL and username (both read from
the process environment) into a console.log. Replaced with a static
message. QA helper only, but it's a real hygiene issue and cleared the
high-severity code-scanning alert on the PR.

Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG
2026-07-03 09:54:02 +08:00

1360 lines
46 KiB
TypeScript

/**
* Integration tests for the compose tool (/api/v1/tools/image/compose).
*
* Compose overlays one image on top of another with position, opacity,
* and blend mode controls. It uses field names "file" for the base image
* and "overlay" for the overlay image.
*/
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import {
buildTestApp,
createMultipartPayload,
loginAsAdmin,
type TestApp,
} from "../../test-server.js";
const PNG = readFixture(fixtures.image.base.png200);
const JPG = readFixture(fixtures.image.base.jpg100);
let testApp: TestApp;
let app: TestApp["app"];
let adminToken: string;
beforeAll(async () => {
testApp = await buildTestApp();
app = testApp.app;
adminToken = await loginAsAdmin(app);
}, 30_000);
afterAll(async () => {
await testApp.cleanup();
}, 10_000);
describe("Compose", () => {
it("overlays a small image onto a base image at default position", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
expect(result.processedSize).toBeGreaterThan(0);
// Output should preserve base image dimensions
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(200);
expect(meta.height).toBe(150);
});
it("positions overlay at a specific x,y offset", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: 50, y: 25 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
// Dimensions should still match the base image
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(200);
expect(meta.height).toBe(150);
});
it("applies opacity to the overlay", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ opacity: 50 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.processedSize).toBeGreaterThan(0);
});
it("uses multiply blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "multiply" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
it("uses screen blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "screen" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("combines position, opacity, and blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{
name: "settings",
content: JSON.stringify({
x: 10,
y: 10,
opacity: 75,
blendMode: "overlay",
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
expect(result.processedSize).toBeGreaterThan(0);
});
// ── Validation ──────────────────────────────────────────────────────
it("rejects requests without a base image", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
const result = JSON.parse(res.body);
expect(result.error).toMatch(/no base image/i);
});
it("rejects requests without an overlay image", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
const result = JSON.parse(res.body);
expect(result.error).toMatch(/no overlay image/i);
});
it("rejects invalid blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "bogus" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
const result = JSON.parse(res.body);
expect(result.error).toMatch(/invalid settings/i);
});
it("rejects opacity out of range", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ opacity: 150 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
});
it("rejects unauthenticated requests", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: { "content-type": contentType },
body,
});
expect(res.statusCode).toBe(401);
});
// ── Extended coverage: blend modes, edge positions, HEIC ───────────
it("uses overlay blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "overlay" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
it("uses darken blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "darken" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("uses lighten blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "lighten" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("uses hard-light blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "hard-light" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("uses soft-light blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "soft-light" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("uses difference blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "difference" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("uses exclusion blend mode", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "exclusion" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("positions overlay at bottom-right edge", async () => {
// Overlay is 100x100, base is 200x150 -> place at (100, 50)
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: 100, y: 50 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
// Output should still be base dimensions
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(200);
expect(meta.height).toBe(150);
});
it("applies zero opacity (completely transparent overlay)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ opacity: 0 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("applies full opacity (default, 100%)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ opacity: 100 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
});
it("handles HEIC base image", { timeout: 120_000 }, async () => {
const HEIC = readFixture(fixtures.image.base.heic200);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.heic", contentType: "image/heic", content: HEIC },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
it("handles HEIC overlay image", { timeout: 120_000 }, async () => {
const HEIC = readFixture(fixtures.image.base.heic200);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.heic", contentType: "image/heic", content: HEIC },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
it("uses WebP overlay on PNG base", async () => {
const WEBP = readFixture(fixtures.image.base.webp50);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.webp", contentType: "image/webp", content: WEBP },
{ name: "settings", content: JSON.stringify({ x: 10, y: 10 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
// Output should preserve base filename
expect(result.downloadUrl).toBeDefined();
});
it("preserves original filename in download URL", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "my-photo.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "watermark.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toContain("my-photo_composed.png");
});
it("rejects negative x position", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: -10 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
});
it("rejects invalid JSON in settings", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: "{not valid" },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
const result = JSON.parse(res.body);
expect(result.error).toMatch(/json/i);
});
// ── Branch coverage: multipart parse error (lines 60-64) ────────────
it("returns 400 for corrupt base image rejected by input validation", async () => {
// Send a corrupt buffer that passes multipart parsing but fails image validation.
const corruptBuffer = Buffer.from("not a real image content at all!!!");
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: corruptBuffer },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
const result = JSON.parse(res.body);
expect(result.error).toMatch(/invalid image/i);
});
// ── Branch coverage: overlay larger than base is cropped to fit ─────
it("crops overlay when it is larger than the base image", async () => {
// Overlay (200x150) is larger than base (100x100), so compose crops
// the overlay to the visible base area.
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.jpg", contentType: "image/jpeg", content: JPG },
{ name: "overlay", filename: "overlay.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ x: 0, y: 0 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(100);
expect(meta.height).toBe(100);
});
// ── Branch coverage: 1x1 tiny image handling ────────────────────────
it("crops overlay when 1x1 base is smaller than overlay", async () => {
const TINY = readFixture(fixtures.image.edge.px1);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: TINY },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
// Overlay (100x100) extends beyond 1x1 base and should be cropped.
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(1);
expect(meta.height).toBe(1);
});
it("handles 1x1 pixel overlay image", async () => {
const TINY = readFixture(fixtures.image.edge.px1);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.png", contentType: "image/png", content: TINY },
{ name: "settings", content: JSON.stringify({ x: 50, y: 50 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(200);
expect(meta.height).toBe(150);
});
// ── Branch coverage: large file handling ────────────────────────────
it("handles a large content image as base", async () => {
const LARGE = readFixture(fixtures.image.stressLarge);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.jpg", contentType: "image/jpeg", content: LARGE },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: 10, y: 10, opacity: 80 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.processedSize).toBeGreaterThan(0);
});
// ── Branch coverage: HEIC overlay with opacity ──────────────────────
it("applies opacity with HEIC overlay", { timeout: 120_000 }, async () => {
const HEIC = readFixture(fixtures.image.base.heic200);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.heic", contentType: "image/heic", content: HEIC },
{ name: "settings", content: JSON.stringify({ opacity: 60, blendMode: "multiply" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
// ── Branch coverage: both images empty → 400 ───────────────────────
it("rejects when no files are provided at all", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
const result = JSON.parse(res.body);
expect(result.error).toMatch(/no base image/i);
});
// ── Branch coverage: negative y position rejects ───────────────────
it("rejects negative y position", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ y: -5 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
});
// ── Branch coverage: opacity at boundary (1%) ──────────────────────
it("applies minimal opacity (1%)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ opacity: 1 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.processedSize).toBeGreaterThan(0);
});
// ── Branch coverage: HEIF content format input ─────────────────────
it("handles portrait HEIC base image", { timeout: 120_000 }, async () => {
const HEIC_PORTRAIT = readFixture(fixtures.image.portraitHeic);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.heic", contentType: "image/heic", content: HEIC_PORTRAIT },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: 10, y: 10 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
// ── Branch coverage: overlay at (0,0) position ─────────────────────
it("positions overlay at origin (0,0)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: 0, y: 0 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(200);
expect(meta.height).toBe(150);
});
// ── Branch coverage: over blend mode (default) ─────────────────────
it("uses default over blend mode explicitly", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "over" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
// ── Branch coverage: same-size overlay and base ────────────────────
it("overlays same-size images successfully", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ opacity: 50, blendMode: "screen" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(200);
expect(meta.height).toBe(150);
});
// ── Branch coverage: corrupt overlay ───────────────────────────────
it("returns 400 for corrupt overlay image rejected by input validation", async () => {
const corruptBuffer = Buffer.from("not a valid image at all");
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{
name: "overlay",
filename: "overlay.png",
contentType: "image/png",
content: corruptBuffer,
},
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
const result = JSON.parse(res.body);
expect(result.error).toMatch(/invalid image/i);
});
// ── HEIF format input ─────────────────────────────────────────────
it("handles HEIF base image", { timeout: 120_000 }, async () => {
const HEIF = readFixture(fixtures.image.motorcycle);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.heif", contentType: "image/heif", content: HEIF },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: 10, y: 10 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
expect(result.processedSize).toBeGreaterThan(0);
});
// ── Animated GIF input ────────────────────────────────────────────
it("handles animated GIF as base image", async () => {
const GIF = readFixture(fixtures.image.animated.gif);
const TINY = readFixture(fixtures.image.edge.px1);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.gif", contentType: "image/gif", content: GIF },
{ name: "overlay", filename: "overlay.png", contentType: "image/png", content: TINY },
{ name: "settings", content: JSON.stringify({ x: 0, y: 0 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
expect(result.processedSize).toBeGreaterThan(0);
});
// ── SVG input ─────────────────────────────────────────────────────
it("handles SVG as overlay image", async () => {
const SVG = readFixture(fixtures.image.base.svg100);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.svg", contentType: "image/svg+xml", content: SVG },
{ name: "settings", content: JSON.stringify({ x: 10, y: 10 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
expect(result.processedSize).toBeGreaterThan(0);
});
// ── SVG as base image ─────────────────────────────────────────────
it("handles SVG as base image with small overlay", async () => {
const SVG = readFixture(fixtures.image.base.svg100);
const TINY = readFixture(fixtures.image.edge.px1);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.svg", contentType: "image/svg+xml", content: SVG },
{ name: "overlay", filename: "overlay.png", contentType: "image/png", content: TINY },
{ name: "settings", content: JSON.stringify({ x: 0, y: 0 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
expect(result.processedSize).toBeGreaterThan(0);
});
// ── Multiple blend modes with opacity ─────────────────────────────
it("combines difference blend mode with low opacity", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ blendMode: "difference", opacity: 30 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.processedSize).toBeGreaterThan(0);
});
// ── Large x,y positioning ─────────────────────────────────────────
it("positions overlay at extreme right edge of base", async () => {
// Base 200x150, overlay 100x100. Place at x=99 so 1px overlap
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: 99, y: 49 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(200);
expect(meta.height).toBe(150);
});
// ── X exceeding max rejects ───────────────────────────────────────
it("rejects x position outside the base image", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({ x: 70000 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
const result = JSON.parse(res.body);
expect(result.error).toMatch(/outside the base image/i);
});
// ── AVIF format input ─────────────────────────────────────────────
it("handles AVIF base image", async () => {
const AVIF = readFixture(fixtures.image.formats("avif"));
const TINY = readFixture(fixtures.image.edge.px1);
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.avif", contentType: "image/avif", content: AVIF },
{ name: "overlay", filename: "overlay.png", contentType: "image/png", content: TINY },
{ name: "settings", content: JSON.stringify({ x: 0, y: 0 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
expect(result.processedSize).toBeGreaterThan(0);
});
// ── SVGZ overlay (compose uses decodeBuffer which validates first) ──
it("handles SVGZ overlay: succeeds or returns 422 for unsupported format", async () => {
const SVGZ = readFixture(fixtures.image.formats("svgz"));
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.svgz", contentType: "image/svg+xml", content: SVGZ },
{ name: "settings", content: JSON.stringify({ x: 10, y: 10 }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
// SVGZ (gzip-compressed SVG) may not be recognized by validateImageBuffer
// depending on the validation pipeline; either succeeds or fails gracefully
expect([200, 422]).toContain(res.statusCode);
if (res.statusCode === 200) {
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
}
});
// ── Opacity at exactly 50% with multiple blend modes ────────────
it("combines hard-light blend mode with 50% opacity at position", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{
name: "settings",
content: JSON.stringify({ x: 25, y: 25, opacity: 50, blendMode: "hard-light" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.processedSize).toBeGreaterThan(0);
});
// ── Exclusion blend with low opacity at edge position ───────────
it("combines exclusion blend mode with 10% opacity at edge", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.jpg", contentType: "image/jpeg", content: JPG },
{
name: "settings",
content: JSON.stringify({ x: 99, y: 0, opacity: 10, blendMode: "exclusion" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.processedSize).toBeGreaterThan(0);
});
// ── Overlay exactly matches base dimensions at (0,0) ────────────
it("overlays same-dimension images at origin with multiply blend", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "base.png", contentType: "image/png", content: PNG },
{ name: "overlay", filename: "overlay.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({ x: 0, y: 0, opacity: 80, blendMode: "multiply" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/compose",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.width).toBe(200);
expect(meta.height).toBe(150);
});
});