Version v26.11.20 Size 1.9 KB gzip Dependencies Zero dependencies
Why Patchwork?
Once two places hold the same document, sending the whole document is the lazy answer that scales worst: bandwidth grows with document size, not with what changed, and blind writes clobber concurrent edits. JSON Patch is the wire format for the honest answer, and Patchwork implements it with the two properties sync code actually needs: apply is immutable with structural sharing (untouched subtrees keep their object identity, so React and every memo layer work for free), and diff is structural (objects diff field-by-field, append-only arrays stay one operation, and inserts land at exactly the right index).
import { apply, diff } from '@vielzeug/patchwork';
const patch = diff(before, after); // [{ op: 'replace', path: '/user/address/zip', value: '1010' }]
const next = apply(before, patch); // before untouched; next.user.address is new, next.user.orders === before.user.ordersA failed test operation is an ordinary answer in protocol code, not an exception: tryApply returns { ok: false, error: { index, path, reason } }, so conflict handling is data you can log and reply to. Zero runtime dependencies, spec-exact pointers (~0/~1 escaping, - append), and a browser-safe build.
Installation
pnpm add @vielzeug/patchworknpm install @vielzeug/patchworkyarn add @vielzeug/patchworkQuick Start
import { apply, diff, tryApply } from '@vielzeug/patchwork';
const doc = { items: ['a'], title: 'Cart' };
const patch = diff(doc, { items: ['a', 'b'], title: 'Wagen' });
// [{ op: 'add', path: '/items/-', value: 'b' }, { op: 'replace', path: '/title', value: 'Wagen' }]
const next = apply(doc, patch); // doc untouched; next.title changed, next.items is a new array (it grew)
tryApply(doc, [{ op: 'test', path: '/title', value: 'Other' }, ...patch]);
// { ok: false, error: { index: 0, reason: 'test', path: '/title', message: … } }Features
apply: immutable RFC 6902 — all six operations, copy-on-write with structural sharing.tryApply: the same engine as data; a failedtestor bad pointer returns a structured rejection with the failing operation index.diff: per-field object patches, prefix/suffix-aligned arrays (appends, prepends, and middle inserts cost a singleadd), pointer-escaped keys.- Pointer API:
parsePointer/formatPointerwith~0/~1escaping andgetInfor reads. - Spec-exact edges:
nullis a value not an absence,replacerequires an existing target, arrayaddinserts,-appends. - Input isolation:
add/copyvalues are cloned in, so the caller's objects can never mutate a document afterwards. - Hard JSON domain: numbers, strings, booleans, null, arrays, objects — no functions, no prototypes, nothing to inherit.
@vielzeug/patchwork/merge: opt-in three-way merge — field-level reconciliation of diverged copies withconflictsas data.