npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ferrow/json-patch-ts

v1.0.0

Published

RFC 6902 JSON Patch and RFC 6901 JSON Pointer: apply, generate, and validate patches with zero dependencies

Readme

json-patch-ts

CI

RFC 6902 JSON Patch and RFC 6901 JSON Pointer: apply, generate, and validate patches with zero dependencies.

Strict TypeScript, zero runtime dependencies, immutable operations (structural sharing — untouched branches of the document are reused, not copied), and a runnable demo covering the RFC 6902 Appendix A examples plus pointer escaping and round-trip diffing.

Install

This is a standalone repo, not (yet) published to npm. Clone it and build, or copy src/ into your project:

git clone https://github.com/FerrowAI/json-patch-ts.git
cd json-patch-ts
npm install
npm run build   # emits dist/ (CommonJS + .d.ts)
npm run demo    # runs examples/demo.js against dist/

Quickstart

import { apply, generate, validatePatch, get } from "json-patch-ts";

const doc = { name: "Ada", tags: ["math"] };

// Apply a patch (RFC 6902). Returns a NEW document; `doc` is never mutated.
const patched = apply(doc, [
  { op: "add", path: "/tags/-", value: "computing" },
  { op: "replace", path: "/name", value: "Ada Lovelace" },
]);
// patched = { name: "Ada Lovelace", tags: ["math", "computing"] }

// Generate a patch between two documents.
const patch = generate(doc, patched);
// apply(doc, patch) deep-equals patched

// Validate patch structure before applying it.
const result = validatePatch(patch);
if (!result.valid) {
  console.error(result.errors); // [{ index, reason }, ...]
}

// Read a value by JSON Pointer (RFC 6901).
get(patched, "/tags/0"); // "math"

API

JSON Pointer (RFC 6901)

  • parsePointer(pointer: string): string[] — split a pointer into unescaped reference tokens ("" -> []).
  • compilePointer(tokens: string[]): string — join raw tokens into an escaped pointer string.
  • escapeToken(token: string): string / unescapeToken(token: string): string — apply/reverse the ~0/~1 escaping rules for a single token.
  • get(doc: unknown, pointer: string): unknown — resolve a pointer; throws JsonPointerError if it doesn't resolve.
  • exists(doc: unknown, pointer: string): boolean — like get, but returns false instead of throwing.
  • set(doc: unknown, pointer: string, value: unknown, mode?: "insert" | "overwrite"): unknown — return a new document with value written at pointer, without mutating doc. mode controls array target behavior: "insert" (default) shifts elements right (JSON Patch add semantics), "overwrite" replaces the element in place (JSON Patch replace semantics). Supports the array "-" append token.
  • remove(doc: unknown, pointer: string): unknown — return a new document with the value at pointer removed (array elements are spliced out).

JSON Patch (RFC 6902)

  • apply<T>(doc: T, patch: JsonPatchOp[]): T — apply a patch, returning a new document. Throws JsonPatchError (with .index and .op) on the first failing operation; the patch is applied atomically — if any op fails (including a test mismatch), no partial result escapes and doc itself was never mutated.
  • tryApply<T>(doc: T, patch: JsonPatchOp[]): { ok: true; doc: T } | { ok: false; error: JsonPatchError } — same as apply, without throwing.
  • Supported ops: add, remove, replace, move, copy, test — full RFC 6902 semantics, including array "-" append, move-into-own-child rejection, and atomic abort on a failing test.
  • JsonPatchError{ message, index, op }.

Generate

  • generate(a: unknown, b: unknown): JsonPatchOp[] — produce a patch such that apply(a, generate(a, b)) deep-equals b. See Limits below.

Validate

  • validatePatch(patch: unknown): { valid: true; errors: [] } | { valid: false; errors: { index: number; reason: string }[] } — structural validation only (well-formed ops, required members present, valid pointers). It does not check a patch against a target document — a structurally valid patch can still fail to apply (e.g. a replace on a path that doesn't exist).

Limits

  • generate() is index-based, not a true LCS/diff, for arrays. Elements are compared position-by-position. Appending or removing from the end of an array produces minimal add/remove ops; an insertion or deletion in the middle will generally produce a replace for every shifted element instead of a single add/remove. The output is always correct (apply(a, generate(a, b)) deep-equals b) but is not guaranteed minimal. If you need a minimal middle-of-array diff, diff with an LCS algorithm yourself and hand the result to apply directly — generate()'s contract is correctness, not minimality.
  • deepEqual (used internally by generate and the test op) treats undefined object values and missing keys as different from each other, matches JSON semantics (no support for Date, Map, Set, etc. — this library operates on plain JSON-compatible values only).
  • No streaming / no support for JSON Patch's optional application/json-patch+json content-type framing — this is a pure data-structure library, not an HTTP layer.

Testing

npm run build && npm run demo

examples/demo.js is a runnable smoke test (not a test-framework suite) that asserts RFC 6902 Appendix A cases, pointer escaping, atomic-abort-on-test-failure, move-into-own-child rejection, and generate() round-trips, exiting non-zero on any assertion failure.

License

MIT


Part of the ferrow-toolkit collection · Sponsored by Ferrow