@effected/semver

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

Strict SemVer 2.0.0 versions, ranges and comparators as Effect schemas.

原始使用文档
文档目录10 节
  1. Why @effected/semver
  2. Install
  3. Quick start
  4. Versions
  5. Ranges and comparators
  6. Comparing two versions
  7. Version cache
  8. Errors
  9. Features
  10. License

@effected/semver

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

Strict SemVer 2.0.0 versions, ranges and comparators as Effect schemas. SemVer, Comparator and Range are Schema.Classes, so a version is a validated value with methods on it rather than a string you re-parse at every call site, and each one carries a FromString codec that decodes the canonical form and encodes back to it. Parsing is strict: no v prefix, no = prefix, no leading zeros on numeric identifiers, no partially consumed input. Every failure is a tagged error carrying the offending string and the character position where the grammar gave up. Zero runtime dependencies, no IO.

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.

Why @effected/semver

The version parsers most projects reach for are lenient by default. They coerce v1.2.3 and =1.2.3 into a version, then hand back null — or throw — when they finally decide something is wrong, leaving you to reconstruct what failed and where. Once parsed, the result is a bag of numbers you stringify to store and re-parse to compare. This package inverts that. The class is the schema, so a version field anywhere in your own schemas decodes to a real SemVer and re-encodes to its canonical string with no glue code, and the operations you want live on the value you already have.

Failures are Schema.TaggedError values you route with Effect.catchTag, each one structured rather than stringly: InvalidVersionError carries input and position, UnsatisfiedRangeError carries the range and every version that was available to match against it. The strictness is deliberate. Coercion is a decision about your data taken inside a library you did not write, and it is where version bugs hide. Range.intersect holds the same line: intersecting ^1.0.0 with ^2.0.0 does not quietly hand back a range that matches nothing, it fails with UnsatisfiableConstraintError carrying both constraints. Nothing here repairs your input behind your back.

Install

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

Requires Node.js >=24.11.0.

All @effected/* packages are ESM-only: the exports maps publish only import conditions, so require() — including tools that resolve in CJS mode — fails with Node's ERR_PACKAGE_PATH_NOT_EXPORTED rather than loading a CJS build that does not exist. Import from an ES module.

effect v4 is the only peer dependency, and it is the only dependency of any kind — no parser, no polyfill, no platform package rides in behind it. There is no IO here, so there is nothing to provide at the edge either: the whole surface runs under Effect.runSync, apart from VersionCache, which brings its own layer.

Quick start

Parse, bump, compare, and test a version against a range:

import { Range, SemVer } from "@effected/semver";
import { Effect } from "effect";

const program = Effect.gen(function* () {
  const version = yield* SemVer.parse("1.2.3");
  const next = version.bump.minor();
  const range = yield* Range.parse("^1.0.0");
  return [next.toString(), range.test(version), version.gt(next)] as const;
});

console.log(Effect.runSync(program));
// => ["1.3.0", true, false]

Instance methods are the canonical API: compare with a.gt(b), a.compare(b), range.filter(versions). Operations with no instance counterpart are dual statics on the owning class, so Range.satisfies(version, range) and version.pipe(Range.satisfies(range)) both typecheck and mean the same thing. For a data-last comparison, derive one from SemVer.Order: Arr.filter(versions, Order.isGreaterThan(SemVer.Order)(floor)).

Versions

SemVer's fields are validated in the schema — non-negative safe integers for the components, well-formed prerelease and build identifiers — so SemVer.make cannot produce an invalid version. Use SemVer.parse for a string and SemVer.of(1, 2, 3) for the positional form.

import { SemVer } from "@effected/semver";
import { Effect } from "effect";

const program = Effect.gen(function* () {
  const stable = yield* SemVer.parse("1.0.0");
  const rc = yield* SemVer.parse("2.0.0-rc.1");
  return [
    stable.bump.prerelease("beta").toString(),
    rc.bump.prerelease().toString(),
    rc.isPrerelease,
    SemVer.truncate(rc, "prerelease").toString(),
  ] as const;
});

console.log(Effect.runSync(program));
// => ["1.0.1-beta.0", "2.0.0-rc.2", true, "2.0.0"]

Bumping is node-semver compatible: a stable version starts a prerelease of the next patch, switching identifiers resets the counter, and the right-most numeric identifier increments wherever it sits (1.0.0-1.beta becomes 1.0.0-2.beta), with 0 appended only when there is none. Build metadata never survives a bump.

Equality follows the spec rather than the string. Equal.equals ignores build metadata (§10) and includes prerelease identifiers (§11), and SemVer overrides [Hash.symbol] to agree with that, so two versions differing only in build metadata are one value in a HashSet and one slot in VersionCache. SemVer.Order sorts by precedence; SemVer.OrderWithBuild adds a lexical tiebreak on build metadata when you need a total order over distinct version strings.

Collection operations are statics: sort, rsort, max, min, groupBy (by major, minor or patch), latestByMajor and latestByMinor.

Ranges and comparators

A Range is a union (OR) of comparator sets (AND). Parsing accepts the node-semver dialect — hyphen ranges, X-ranges, tilde, caret and || — desugars it into primitive comparators and normalizes the result. A Comparator is one operator applied to one complete version, with no wildcards and no sugar; that vocabulary belongs to Range.

import { Range, SemVer } from "@effected/semver";
import { Effect } from "effect";

const program = Effect.gen(function* () {
  const caret = yield* Range.parse("^1.0.0");
  const floor = yield* Range.parse(">=1.5.0");
  const both = yield* Range.intersect(caret, floor);
  const versions = [SemVer.of(1, 2, 0), SemVer.of(1, 6, 0), SemVer.of(2, 0, 0)];
  return [both.test(SemVer.of(1, 6, 0)), caret.filter(versions).map((v) => v.toString())] as const;
});

console.log(Effect.runSync(program));
// => [true, ["1.2.0", "1.6.0"]]

Matching implements node-semver's prerelease restriction: a prerelease version satisfies a set only when some comparator in that set carries a prerelease on the same major.minor.patch tuple. That is what keeps ^1.2.3 from unexpectedly matching 1.2.4-alpha. Pass Range.parse(input, { includePrerelease: true }) (also accepted by Range.parseResult and VersionCache.resolveString) to lift that rule: wildcard floors are lowered to their first prerelease (^1.2 becomes >=1.2.0-0 <2.0.0-0) and the parsed Range records the choice in its includePrerelease field, so every matcher built on it honours it. Range.FromString cannot carry the flag; the struct form round-trips it.

The range algebra is union, intersect, isSubset, equivalent and simplify. isSubset is a deliberate conservative approximation: it can report false for a range that is technically a subset, when the sub-range straddles comparator-set boundaries in the sup-range. False negatives are safe, because all they do is decline a simplification.

Comparing two versions

VersionDiff.between(a, b) classifies a change and carries the signed component deltas. It is a Schema.TaggedClass, so a diff serializes as cleanly as it computes.

import { SemVer, VersionDiff } from "@effected/semver";
import { Effect } from "effect";

const program = Effect.gen(function* () {
  const from = yield* SemVer.parse("1.2.3");
  const to = yield* SemVer.parse("2.0.0");
  const diff = VersionDiff.between(from, to);
  return [diff.type, diff.major, diff.toString()] as const;
});

console.log(Effect.runSync(program));
// => ["major", 1, "major (1.2.3 → 2.0.0)"]

type names the highest-precedence field that differs: "major", "minor", "patch", "prerelease", "build" or "none".

Version cache

VersionCache is a Context.Service over a sorted, deduplicated set of versions — pure state in a Ref, no IO. Reach for it when you hold a list of published versions and a range to resolve against them.

import { SemVer, VersionCache } from "@effected/semver";
import { Effect } from "effect";

const program = Effect.gen(function* () {
  const cache = yield* VersionCache;
  yield* cache.load([SemVer.of(1, 0, 0), SemVer.of(1, 4, 2), SemVer.of(2, 0, 0)]);
  const latest = yield* cache.latest();
  const resolved = yield* cache.resolveString("^1.0.0");
  return [latest.toString(), resolved.toString()] as const;
}).pipe(Effect.provide(VersionCache.layer));

console.log(Effect.runSync(program));
// => ["2.0.0", "1.4.2"]

The two kinds of absence stay apart. next and prev fail with VersionNotFoundError when the pivot version is not in the cache, and succeed with Option.none() when the pivot sits at a boundary. Queries over the whole cache (versions, filter) never fail and return [].

Errors

Every failure is a Schema.TaggedError routed with Effect.catchTag, carrying structured fields. The message getter is derived from those fields, never stored.

TagRaised byCarries
InvalidVersionErrorSemVer.parseinput, and the position where the grammar failed
InvalidComparatorErrorComparator.parseinput, position
InvalidRangeErrorRange.parse, VersionCache.resolveStringinput, position
UnsatisfiableConstraintErrorRange.intersectconstraints, the ranges whose intersection is empty
EmptyCacheErrorVersionCache.latest, VersionCache.oldestnothing; the cache is empty
VersionNotFoundErrorVersionCache.diff, next, prevversion, the pivot that is not cached
UnsatisfiedRangeErrorVersionCache.resolve, resolveStringrange, plus available, the versions that were there to match

The FromString codecs report the same failures through a generic Schema parse error carrying the same message, so schema decoding and the parse statics never disagree about what is valid.

import { SemVer } from "@effected/semver";
import { Effect } from "effect";

// A leading `v` is not a version, and nothing here coerces it into one.
const program = SemVer.parse("v1.2.3").pipe(Effect.catch((error) => Effect.succeed(`${error._tag}: ${error.input}`)));

console.log(Effect.runSync(program));
// => "InvalidVersionError: v1.2.3"

Features

  • SemVer — the version model: schema-validated fields, parse / of / make construction, bumping through version.bump, comparison as instance methods and dual statics, spec-correct Equal and Hash, and the collection statics (sort, max, groupBy, latestByMajor, …).
  • Comparator — a single operator-plus-version constraint, and the primitive that range sugar desugars into.
  • Range — the node-semver range dialect parsed into normalized comparator sets, with matching (test, filter, maxSatisfying, minSatisfying) and algebra (union, intersect, isSubset, equivalent, simplify).
  • VersionDiff — the classified difference between two versions with signed component deltas, serializable as a tagged class.
  • VersionCache — a sorted in-memory version set with range resolution and neighbor navigation, provided by VersionCache.layer.
  • SemVer.FromString, Comparator.FromString, Range.FromString — codecs between the canonical strings and the models, usable as fields inside your own schemas.
  • Seven tagged errors, each carrying the structured payload a caller needs to report what actually went wrong.

License

MIT

版本与发布记录

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

版本发布日期距今
0.24.0latest2026/11/103 天前
0.23.02026/11/103 天前
0.22.02026/11/067 天前
0.21.02026/11/0310 天前
0.20.02026/11/0112 天前
0.19.02026/10/2915 天前

关于 @effected/semver 的常见问题

@effected/semver 是什么?

Strict SemVer 2.0.0 versions, ranges and comparators as Effect schemas.

如何安装 @effected/semver?

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

@effected/semver 支持 TypeScript 吗?

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

@effected/semver 支持 ESM 还是 CommonJS?

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

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

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

@effected/semver 可以商用吗?

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

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

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

@effected/semver 还在维护吗?

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