@effected/jsonc

中文文档
0.25.0发布于 2026/11/10MITTypeScriptES Module构建来源已验证近 30 天下载 1.1万

Zero-dependency JSONC parsing, editing and formatting as Effect schemas.

原始使用文档
文档目录8 节
  1. Why @effected/jsonc
  2. Install
  3. Quick start
  4. Editing without losing comments
  5. Comments and round-trips
  6. Canonical JSON and content fingerprints
  7. Features
  8. License

@effected/jsonc

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

Zero-dependency JSONC parsing, editing and formatting expressed as Effect schemas and pure functions. Parse JSONC into plain values or an offset-preserving AST, strip comments, compute byte-minimal edits, format, modify by path, walk a document as a Stream, and decode straight into a validated domain schema.

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/jsonc

JSONC is JSON with comments and trailing commas: the format behind tsconfig.json, VS Code settings and much of the JavaScript toolchain. Those files are written by humans, and humans leave comments in them. A JSON.parse then JSON.stringify round-trip destroys every one of them, so any tool that rewrites a tsconfig.json that way hands the user back a file they did not recognize.

This package treats the source text as the document. Modifications are computed as edits against the original bytes rather than re-serialized from a parsed object, so a change to one key leaves every comment, blank line and indentation choice untouched. Parsing recovers from errors and aggregates every diagnostic into one JsoncParseError carrying code, offset, length, line and character per error, instead of throwing on the first. And Jsonc.schema composes with a domain schema so a JSONC string decodes into a validated value in a single step.

Everything is a pure function or a schema. No IO, no owned services and no runtime dependency other than effect itself: the scanner, parser and navigator are vendored into the package with attribution rather than pulled in as a dependency. The one effectful edge is fingerprint hashing, and the package ships no backend for it: JsoncFingerprint.hash and hashText require core's Digest.Digest service (effect/crypto) in R, provided by the consumer at the application edge, while their hashResult / hashTextResult twins take the digest as a plain function argument so a synchronous caller can fingerprint with no runtime at all.

Install

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

Requires Node.js >=24.11.0. effect v4 is a peer dependency; the package itself adds no other runtime dependencies.

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.

Quick start

Compose your schema with Jsonc.schema to decode JSONC straight into a validated domain value:

import { Jsonc } from "@effected/jsonc";
import { Effect, Schema } from "effect";

const Config = Schema.Struct({ port: Schema.Number });
const ConfigFromJsonc = Jsonc.schema(Config);

const program = Effect.gen(function* () {
  return yield* Schema.decodeUnknownEffect(ConfigFromJsonc)(`{
    // dev server
    "port": 3000
  }`);
});

Effect.runPromise(program).then(console.log);
// { port: 3000 }

Malformed input fails through the typed channel, never as a throw:

import { Jsonc } from "@effected/jsonc";
import { Effect } from "effect";

Effect.runPromise(Effect.result(Jsonc.parse('{ "a": }'))).then(console.log);
// Failure with JsoncParseError:
// "JSONC parse failed with 1 error: ValueExpected at 1:8"
// The `errors` field carries one JsoncParseErrorDetail per recovered error,
// each with code, offset, length, line and character.

Synchronous boundaries that cannot run an Effect (a plain config loader, a build script) call Jsonc.parseResult, the same parse returning a Result directly instead of wrapping it in Effect.runSync(Effect.result(...)):

import { Jsonc } from "@effected/jsonc";
import { Result } from "effect";

const result = Jsonc.parseResult('{ "port": 3000 // dev\n}');
console.log(Result.isSuccess(result) ? result.success : result.failure);
// { port: 3000 }

Jsonc.parse is defined in terms of parseResult, and Jsonc.parseTree in terms of Jsonc.parseTreeResult, so the pairs never diverge. Prefer the Effect variants inside Effect code, where they carry their tracing spans.

Editing without losing comments

JsoncModifier.modify returns a JsoncEdit array — offset, length and replacement content — that JsoncEdit.applyAll splices into the original text. Only the bytes covered by an edit change:

import { JsoncEdit, JsoncModifier } from "@effected/jsonc";
import { Effect } from "effect";

const source = `{
  // dev server
  "port": 3000
}`;

const program = Effect.gen(function* () {
  const edits = yield* JsoncModifier.modify(source, ["port"], 8080);
  return JsoncEdit.applyAll(source, edits);
});

Effect.runPromise(program).then(console.log);
// {
//   // dev server
//   "port": 8080
// }

Generated text follows the document it lands in. A new member lines up with its last sibling, a multi-line value is indented to its member, and every generated line takes the file's line ending, so a tab-indented CRLF file stays one. Pass formattingOptions to set the indentation unit or line ending yourself. Deleting an entry takes its line with it and collapses an emptied container to {} or [], unless a comment is still in there.

A new member goes last unless insertAfter names the sibling it should follow, and that sibling keeps a comment trailing it. createParents builds missing object ancestors instead of failing; it never overwrites a value of the wrong type and never invents an array.

JsoncFormatter.format produces the same kind of edit array for whitespace normalization, so a formatter pass is a diff rather than a rewrite.

Migrating from jsonc-effect 0.3.x? That library's value spans over-reached trailing content (jsonc-effect#62), so edits could swallow whitespace or comments after a value. @effected/jsonc 0.1.0 fixes this: value spans cover exactly the value, format-preserving edits are byte-exact, and any downstream AST-plus-trimEnd workarounds can be deleted.

Comments and round-trips

There is no comment-preserving stringify in this package, and that is deliberate rather than an oversight. Jsonc.stringify and its synchronous twin Jsonc.stringifyResult emit plain JSON — comments live in the document and edit layer (JsoncNode, JsoncEdit, JsoncFormatter), never in a plain JavaScript value. The encode direction of Jsonc.schema, Jsonc.fromString and Jsonc.JsoncFromString is that same emission. Comments do not survive a decode then encode round trip — once a document has been reduced to a plain JavaScript value, the comments are already gone and no honest encoder can put them back.

Values JSON cannot represent fail through a typed channel rather than throwing:

import { Jsonc } from "@effected/jsonc";
import { Result } from "effect";

const ok = Jsonc.stringifyResult({ port: 3000 });
console.log(Result.isSuccess(ok) ? ok.success : ok.failure);
// {
//   "port": 3000
// }

const bad = Jsonc.stringifyResult(0n);
console.log(Result.isFailure(bad) ? bad.failure.code : "");
// BigIntValue

Preserving comments requires the original source text, which is exactly what JsoncModifier and JsoncFormatter take. If you need to write a JSONC file back out with its comments intact, edit the text: parse for reading, and modify for writing.

Canonical JSON and content fingerprints

JsoncFingerprint produces RFC 8785 canonical JSON (the JSON Canonicalization Scheme) and SHA-256 fingerprints over it: compact output, object keys sorted by UTF-16 code units, ECMAScript number serialization. Two values that differ only in key order canonicalize — and fingerprint — identically. Unlike Jsonc.stringify, which follows JSON.stringify's drop/null semantics for nested unrepresentables, canonicalization refuses to alter the document: an undefined, a function, a symbol, a bigint, a non-finite number, a string or member key containing an unpaired surrogate, or a non-plain object (a Date, a Map, a class instance) fails typed with a JsoncCanonicalizeError naming the JSON-pointer path to fix, rather than being silently dropped or nulled. toJSON methods are ignored on purpose — encode Schema classes and Dates to plain JSON first (the same error carries one code that is not about the document, InvalidDigest, for a synchronous caller's own digest function — see below):

import { JsoncFingerprint } from "@effected/jsonc";
import { Result } from "effect";

const ok = JsoncFingerprint.canonicalizeResult({ b: 2, a: 1 });
console.log(Result.isSuccess(ok) ? ok.success : "");
// {"a":1,"b":2}

const bad = JsoncFingerprint.canonicalizeResult({ a: { b: undefined } });
console.log(Result.isFailure(bad) ? `${bad.failure.code} at "${bad.failure.path}"` : "");
// UnrepresentableValue at "/a/b"

hash and hashText carry that canonicalization through to a content digest: the lowercase-hex SHA-256 of the UTF-8 bytes of the canonical text (hash) or of raw text as given (hashText). Both require core's Digest.Digest service (effect/crypto) in R — this package owns no backend, so provide Digest.layerWebCrypto (any runtime with WebCrypto) or a platform family layer such as @effect/platform-node's NodeCrypto.layerDigest at the application edge:

import { JsoncFingerprint } from "@effected/jsonc";
import { Effect } from "effect";
import { Digest } from "effect/crypto";

const program = Effect.gen(function* () {
  const a = yield* JsoncFingerprint.hash({ b: 2, a: 1 });
  const b = yield* JsoncFingerprint.hash({ a: 1, b: 2 });
  return a === b;
});

Effect.runPromise(program.pipe(Effect.provide(Digest.layerWebCrypto))).then(console.log);
// true

hashResult and hashTextResult are the synchronous twins of those two, for callers with no fiber to run an Effect in — a bundler plugin's synchronous hook, a cache read/write invoked from inside a host callback. They agree byte for byte with the Effect forms. Since a Digest layer cannot be provided from inside a synchronous callback, the digest itself is the argument: pass a JsoncDigest, (bytes: Uint8Array) => Uint8Array. This package still imports nothing from node:* and assumes no runtime, so a Node consumer binds the platform in one line:

import { createHash } from "node:crypto";
import { JsoncFingerprint, type JsoncDigest } from "@effected/jsonc";
import { Result } from "effect";

const digest: JsoncDigest = (bytes) => createHash("sha256").update(bytes).digest();

const fingerprint = JsoncFingerprint.hashResult({ b: 2, a: 1 }, digest);
console.log(Result.isSuccess(fingerprint) ? fingerprint.success : "");
// 64 lowercase hex characters — the same answer `hash` gives

A digest that throws, or that returns anything other than 32 bytes, fails typed with JsoncCanonicalizeError's InvalidDigest code at path "" rather than escaping into the host or emitting a plausible-looking digest of the wrong width — a SHA-1 binding would otherwise have produced 40 hex characters. No check can catch a different 32-byte algorithm; that much is the caller's to get right.

Digests are always exactly 64 lowercase hexadecimal characters, with no sha256: or other algorithm prefix — the same format @effected/sbom's Sha256Digest schema decodes, so a fingerprint flows straight into an attestation subject without this package taking a dependency edge on sbom. hashText's (and hashTextResult's) normalizeEol: true option normalizes \r\n and bare \r to \n before hashing — reach for it when the same file content must fingerprint identically across checkouts with different line-ending settings; JsoncFingerprint.normalizeEol exposes the same normalization as a pure, total function.

Features

  • Jsonc.parse / Jsonc.parseTree — error-recovery parsing to a plain value or an offset-preserving JsoncNode AST, aggregating every recovered error into one JsoncParseError rather than failing on the first.
  • Jsonc.parseResult / Jsonc.parseTreeResult — the synchronous Result variants of parse and parseTree for callers outside an Effect runtime; the Effect forms are defined in terms of them, so the pairs never diverge.
  • Jsonc.stringify / Jsonc.stringifyResult — value-level JSON emission with configurable indent, failing with a typed JsoncStringifyError whose code names the mode: CircularReference, BigIntValue or TopLevelUnrepresentable.
  • Jsonc.stripComments — pure comment removal yielding valid JSON; pass a replacement character to keep every byte offset stable.
  • Jsonc.equals / Jsonc.equalsValue — semantic equality that ignores comments, whitespace, formatting and object key order, while keeping array order significant.
  • Jsonc.schema / Jsonc.fromString / Jsonc.JsoncFromString — string→domain schema factories that decode JSONC directly into a validated Effect Schema value.
  • JsoncFormatter / JsoncModifier — compute byte-minimal JsoncEdit arrays for formatting and path-based modification, so callers apply the smallest possible diff instead of re-serializing the document.
  • JsoncVisitor — walk a parsed document as a Stream of visitor events, with Stream.take early termination on large inputs.
  • JsoncFingerprint — RFC 8785 canonical JSON (canonicalize / canonicalizeResult) and SHA-256 content fingerprints over it (hash, hashText), failing typed with JsoncCanonicalizeError rather than silently dropping or altering non-JSON values; hash/hashText require core's Digest.Digest service.
  • JsoncFingerprint.hashResult / JsoncFingerprint.hashTextResult — the synchronous Result variants of hash and hashText for callers outside an Effect runtime, taking the caller's own JsoncDigest instead of a Digest layer so a synchronous host hook can fingerprint at all.
  • JsoncParseError / JsoncModificationError — tagged errors carrying structured, positional payloads rather than opaque messages. Hostile input (deep nesting, unterminated literals) fails through the error channel, never as a stack overflow.

License

MIT

版本与发布记录

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

版本发布日期距今
0.25.0latest2026/11/102 天前
0.24.02026/11/067 天前
0.23.02026/11/0310 天前
0.22.02026/11/0112 天前
0.21.02026/10/2915 天前
0.20.12026/10/2716 天前

关于 @effected/jsonc 的常见问题

@effected/jsonc 是什么?

Zero-dependency JSONC parsing, editing and formatting as Effect schemas.

如何安装 @effected/jsonc?

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

@effected/jsonc 支持 TypeScript 吗?

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

@effected/jsonc 支持 ESM 还是 CommonJS?

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

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

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

@effected/jsonc 可以商用吗?

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

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

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

@effected/jsonc 还在维护吗?

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