@effected/images

中文文档
0.10.0发布于 2026/11/10MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 4145

Image facts (format, MIME type, dimensions) from bytes, and a generated-image cache, for Effect.

原始使用文档
文档目录8 节
  1. Install
  2. Image facts
  3. The generated-image cache
  4. A Promise-returning renderer
  5. Switching the cache off
  6. Bring your own store
  7. Features
  8. License

@effected/images

npm License: MIT Node.js %3E%3D24.11.0 TypeScript 7.0

Image facts from bytes, and a cache for generated images. ImageFacts reads the format, MIME type and pixel dimensions of a PNG, JPEG, GIF, WebP or AVIF file straight from its header, with one typed failure for bytes that are not a readable image. ImageCache answers "have I already generated an image from these parameters?", so a build stops re-running an expensive renderer such as an Open Graph card generator on every run.

Pre-1.0.0. This package is part of the @effected/* kit, built on stable Effect v4 (effect ~4.1.0) and still in 0.x development. Stable Effect makes a kit 1.0.0 possible, not automatic. To keep your effect and @effect/* versions on the line the kit is built and tested against, install @effected/pnpm-plugin-effected.

Stability: unstable. This package's API surface is not yet considered complete and may change across 0.x releases. Pin an exact version — even a package marked stable before 1.0.0 can introduce a breaking change by accident, and an exact pin turns that into a type-check error rather than a runtime surprise. Full policy: release strategy.

Install

npm install @effected/images effect
pnpm add @effected/images effect

Requires Node.js >=24.11.0. effect v4 is the only peer dependency, and the only dependency of any kind — the format readers are in-house.

All @effected/* packages are ESM-only: the exports maps publish only import conditions, so require() fails with Node's ERR_PACKAGE_PATH_NOT_EXPORTED. Import from an ES module.

Image facts

The root entry is pure: no IO, no services. ImageFacts.fromBytesResult is the synchronous engine, usable from a script with no Effect runtime, and ImageFacts.fromBytes is the same read as an Effect.

import { ImageFacts } from "@effected/images";
import { Effect, Result } from "effect";

declare const bytes: Uint8Array;

// Synchronous: a Result, never a throw.
const result = ImageFacts.fromBytesResult(bytes);
if (Result.isSuccess(result)) {
  const { format, mimeType, width, height } = result.success; // "png", "image/png", 1200, 630
  const file = `card.${result.success.extension}`; // "card.png"; a JPEG is written ".jpg"
}

// Effect: fails with ImageParseError.
const facts = ImageFacts.fromBytes(bytes).pipe(
  Effect.catchTag("ImageParseError", (e) => Effect.logWarning(`not an image: ${e.reason}`)),
);

mimeType is one of the five media types (image/png, image/jpeg, image/gif, image/webp, image/avif), and extension is the conventional file extension: jpg for jpeg, the format name otherwise. extension is a getter derived from format, so it is not part of the encoded form, and a spread such as { ...facts } drops it.

ImageParseError.reason is unrecognized (no known signature), truncated (a recognized file cut short) or malformed (a header that contradicts itself). Readers never throw on any input, bounds-check every length before reading it, and bound the JPEG and AVIF walks with a step budget.

The generated-image cache

@effected/images/cache caches generated bytes under a key derived from the parameters that produced them. ImageCacheKey.fromParams encodes the parameters through your Schema, serializes them canonically and digests them with a salt — the identity of your generator, bumped when its template changes so every old entry misses.

import { ImageBackend, ImageCache, ImageCacheKey } from "@effected/images/cache";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Layer, Schema } from "effect";

const CardParams = Schema.Struct({ title: Schema.String, theme: Schema.String });
declare const renderCard: () => Effect.Effect<Uint8Array>; // your renderer

const CacheLive = ImageCache.layer.pipe(
  Layer.provide(ImageBackend.layerDirectory({ directory: ".cache/og" })),
);

const program = Effect.gen(function* () {
  const cache = yield* ImageCache;
  const key = yield* ImageCacheKey.fromParams(
    CardParams,
    { title: "Hello", theme: "dark" },
    { salt: "og-card-v3", namespace: "og" },
  );
  const { bytes, facts, hit } = yield* cache.getOrGenerate(
    key,
    renderCard, // () => Effect<Uint8Array, E, R> - runs only on a miss
    { accept: ["png"] },
  );
  return { bytes, width: facts.width, hit };
}).pipe(
  Effect.provide(CacheLive),
  Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layerDigest)),
);

getOrGenerate returns the bytes, their ImageFacts and whether it was a hit. With accept, the result's facts.format is typed as the accepted formats, so ["png", "jpeg", "webp"] gives "png" | "jpeg" | "webp"; without it, every format. A stored entry that no longer parses, or whose format is outside accept, is treated as a miss and overwritten. A generator result that is empty, unparseable or outside accept fails with ImageGenerateError and is never stored. Backend failures surface as ImageBackendError; the generator's own error passes through untouched.

A Promise-returning renderer

When the renderer returns a Promise, wrap it with both try and catch so its own error reaches the caller:

import { Effect } from "effect";

declare const render: (info: { readonly title: string }) => Promise<Uint8Array>;
declare const info: { readonly title: string };

const generate = () => Effect.tryPromise({ try: () => render(info), catch: (cause) => cause });

The one-argument Effect.tryPromise(() => render(info)) wraps a rejection in UnknownError, so the generator's own error is lost.

Switching the cache off

ImageBackend.layerNone stores nothing: get always misses and set discards. Provide it when caching is disabled and keep the same getOrGenerate call; every call runs the generator and returns hit: false.

import { ImageBackend } from "@effected/images/cache";

declare const cachingEnabled: boolean;
const backend = cachingEnabled ? ImageBackend.layerDirectory({ directory: ".cache/og" }) : ImageBackend.layerNone;

The key digest uses core Digest.Digest (effect/crypto), and the directory backend uses FileSystem and Path. On Node, NodeServices.layer from @effect/platform-node provides FileSystem and Path, and NodeCrypto.layerDigest provides Digest.Digest; Digest.layerWebCrypto from effect/crypto works on any runtime with WebCrypto.

Bring your own store

ImageBackend is a port, not a dependency. ImageBackend.layerFrom(key) adapts any service whose get and set match structurally — for example the Cache from @effected/store, with no edge between the two packages:

import { Cache } from "@effected/store";
import { ImageBackend } from "@effected/images/cache";

const StoreBacked = ImageBackend.layerFrom(Cache); // provide Cache underneath

The directory backend stores <directory>/<key>.<ext> through a temp file and an atomic rename. It accepts and ignores tags.

Features

  • ImageFacts — format, MIME type, file extension and pixel dimensions as stored in the file; sync fromBytesResult and Effect fromBytes.
  • ImageExtension / ImageMimeType — the extension and media-type unions.
  • ImageFormat — the literal union png | jpeg | gif | webp | avif.
  • ImageParseError — the one parse failure, with a reason and, once a signature matched, the format.
  • ImageCacheKey / ImageCacheKeyError — content-addressed keys from schema-encoded parameters; failure reasons encode, non-json and digest.
  • ImageBackend / ImageBackendError — the storage port, a directory backend, a no-store backend and a structural adapter; failure reasons backend and unsupported-content-type.
  • ImageCache / ImageGenerateError — getOrGenerate with an optional accept format list that narrows the result's format.

SVG, BMP, ICO, TIFF, HEIC, JPEG XL, EXIF orientation, image transformation and cache eviction are out of scope.

License

MIT

版本与发布记录

@effected/images 共发布 15 个版本,首次发布于 2026/10/10;过去 12 个月发布了 15 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.10.0latest2026/11/103 天前
0.9.02026/11/0310 天前
0.8.02026/11/0112 天前
0.7.02026/10/2915 天前
0.6.22026/10/2716 天前
0.6.12026/10/2420 天前

关于 @effected/images 的常见问题

@effected/images 是什么?

Image facts (format, MIME type, dimensions) from bytes, and a generated-image cache, for Effect.

如何安装 @effected/images?

在项目目录运行 npm install @effected/images,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:effect(~4.1.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@effected/images 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@effected/images 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@effected/images 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.11.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@effected/images 可以商用吗?

@effected/images 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@effected/images 的下载量有多少?

根据 npm 官方下载统计,@effected/images 在 2026/10/13 – 2026/11/11 这 30 天内被下载 4,145 次,日均约 138 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@effected/images 还在维护吗?

最新版本 0.10.0 发布于 2026/11/10(3 天前);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2026/10/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。