When a shared document changes, sending the whole document again wastes bandwidth and overwrites other people's edits. Instead, servers and editors send a JSON Patch (RFC 6902): a list of small operations such as "add this value at /items/2" or "remove /draft". Paths are JSON Pointers (RFC 6901). The client applies the list in order to its copy, and either every operation succeeds or the document stays as it was.
Write applyPatch(document, patch) in json-patch.js.
The result is a new document: the input is never changed and shares no objects with the result, even for an empty patch.
Operations run in order, each on the result of the one before.
All or nothing: if any operation fails, applyPatch throws an Error, and the input is unchanged.
Pointers."" is the whole document. Any other pointer starts with / and is split into tokens on /. In each token, ~1 means / and ~0 means ~, decoded in that order (so ~01 is the key ~1). A ~ followed by anything else, or a pointer not starting with /, is an error. "/" is the member named "".
Array tokens are 0 or digits without a leading zero. For add, the index may equal the array's length, and - means the end. For every other use, the element must exist. On an object, a digit token is an ordinary member name.
Every token but the last must lead to an existing object or array; nothing is created on the way, and stepping into a number, string, boolean or null is an error.
add: on an array, inserts and shifts the rest; on an object, sets the member. Path "" replaces the whole document.
remove and replace need the target to exist. replace with path "" replaces the whole document.
move: from must exist, and must not be a proper prefix of path (a value cannot move into one of its own children). A move to the same place (from equal to path, "" to "" included) changes nothing.
copy adds a deep copy: a later change to one does not change the other.
test passes when the values are equal as JSON: same type; arrays with the same elements in the same order; objects with the same members in any order. Otherwise, or when nothing is at path, it is an error.
A missing path, from (for move and copy) or value (for add, replace and test) is an error. value: null is a valid value. An unknown or missing op is an error.
A member named __proto__ is an ordinary member: adding it never changes a prototype.
Plain JavaScript in a browser page; the tests call the global applyPatch from json-patch.js. The tests freeze the input document.
Documents and values are JSON: no undefined, functions, Dates, Maps or array holes. Removing the whole document (remove with path "") is not part of this problem; moving it to itself is.
JSON.parse(JSON.stringify(...)) and structuredClone are allowed, but think about what they do with a member named __proto__.