-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathjsonpatch.coffee
423 lines (348 loc) · 15.4 KB
/
jsonpatch.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# jsonpatch.js 0.6.1
# (c) 2011-2017 Byron Ruth
# jsonpatch may be freely distributed under the BSD license
((factory) ->
# Detect global object for browser, node, and worker
root = if window? then window else if global? then global else @;
if typeof exports isnt 'undefined'
# Node/CommonJS
factory(exports)
else if typeof define is 'function' and define.amd
# AMD
define ['exports'], (exports) ->
root.jsonpatch = factory(exports)
else
# Browser globals
root.jsonpatch = factory({})
) (exports) ->
# Utilities
toString = Object.prototype.toString
hasOwnProperty = Object.prototype.hasOwnProperty
# Define a few helper functions taken from the awesome underscore library
isArray = (obj) -> toString.call(obj) is '[object Array]'
isObject = (obj) -> toString.call(obj) is '[object Object]'
isString = (obj) -> toString.call(obj) is '[object String]'
# Limited Underscore.js implementation, internal recursive comparison function.
_isEqual = (a, b, stack) ->
# Identical objects are equal. `0 === -0`, but they aren't identical.
# See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if a is b then return a isnt 0 or 1 / a == 1 / b
# A strict comparison is necessary because `null == undefined`.
if a == null or b == null then return a is b
# Compare `[[Class]]` names.
className = toString.call(a)
if className isnt toString.call(b) then return false
switch className
# Strings, numbers, and booleans are compared by value.
when '[object String]'
# Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
# equivalent to `new String("5")`.
String(a) is String(b)
when '[object Number]'
a = +a
b = +b
# `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
# other numeric values.
if a isnt a
b isnt b
else
if a is 0
1 / a is 1 / b
else
a is b
when '[object Boolean]'
# Coerce dates and booleans to numeric primitive values. Dates are compared by their
# millisecond representations. Note that invalid dates with millisecond representations
# of `NaN` are not equivalent.
+a is +b
if typeof a isnt 'object' or typeof b isnt 'object' then return false
# Assume equality for cyclic structures. The algorithm for detecting cyclic
# structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
length = stack.length
while length--
# Linear search. Performance is inversely proportional to the number of
# unique nested structures.
if stack[length] is a then return true
# Add the first object to the stack of traversed objects.
stack.push(a)
size = 0
result = true
# Recursively compare objects and arrays.
if className is '[object Array]'
# Compare array lengths to determine if a deep comparison is necessary.
size = a.length
result = size is b.length
if result
# Deep compare the contents, ignoring non-numeric properties.
while size--
# Ensure commutative equality for sparse arrays.
if not (result = size in a is size in b and _isEqual(a[size], b[size], stack)) then break
else
# Objects with different constructors are not equivalent.
if "constructor" in a isnt "constructor" in b or a.constructor isnt b.constructor then return false
# Deep compare objects.
for key of a
if hasOwnProperty.call(a, key)
# Count the expected number of properties.
size++
# Deep compare each member.
if not (result = hasOwnProperty.call(b, key) and _isEqual(a[key], b[key], stack)) then break
# Ensure that both objects contain the same number of properties.
if result
for key of b
if hasOwnProperty.call(b, key) and not size-- then break
result = not size
# Remove the first object from the stack of traversed objects.
stack.pop()
return result
# Perform a deep comparison to check if two objects are equal.
isEqual = (a, b) -> _isEqual(a, b, [])
# Various error constructors
class JSONPatchError extends Error
constructor: (@message='JSON patch error') ->
@name = 'JSONPatchError'
class InvalidPointerError extends Error
constructor: (@message='Invalid pointer') ->
@name = 'InvalidPointer'
class InvalidPatchError extends JSONPatchError
constructor: (@message='Invalid patch') ->
@name = 'InvalidPatch'
class PatchConflictError extends JSONPatchError
constructor: (@message='Patch conflict') ->
@name = 'PatchConflictError'
class PatchTestFailed extends Error
constructor: (@message='Patch test failed') ->
@name = 'PatchTestFailed'
escapedSlash = /~1/g
escapedTilde = /~0/g
accessorMatch = /^[-+]?\d+$/
# Spec: http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-05
class JSONPointer
constructor: (path) ->
steps = []
# If a path is specified, it must start with a /
if path and (steps = path.split '/').shift() isnt ''
throw new InvalidPointerError()
# Decode each component, decode JSON Pointer specific syntax ~0 and ~1
for step, i in steps
steps[i] = step.replace(escapedSlash, '/')
.replace(escapedTilde, '~')
# The final segment is the accessor (property/index) of the object
# the pointer ultimately references
@accessor = steps.pop()
@steps = steps
@path = path
# Returns an object with the object reference and the accessor
getReference: (parent) ->
for step in @steps
if isArray parent then step = parseInt(step, 10)
if step not of parent
throw new PatchConflictError('Array location out of
bounds or not an instance property')
parent = parent[step]
return parent
# Checks and coerces the accessor relative to the reference
# object it will be applied to.
coerce: (reference, accessor) ->
if isArray(reference)
if isString(accessor)
if accessor is '-'
accessor = reference.length
else if accessorMatch.test(accessor)
accessor = parseInt(accessor, 10)
else
throw new InvalidPointerError('Invalid array index number')
return accessor
# Interface for patch operation classes
class JSONPatch
constructor: (patch) ->
# All patches required a 'path' member
if 'path' not of patch
throw new InvalidPatchError()
# Validates the patch based on the requirements of this operation
@validate(patch)
@patch = patch
# Create the primary pointer for this operation
@path = new JSONPointer(patch.path)
# Call for operation-specific setup
@initialize(patch)
initialize: ->
validate: (patch) ->
apply: (document) -> throw new Error('Method not implemented')
class AddPatch extends JSONPatch
validate: (patch) ->
if 'value' not of patch then throw new InvalidPatchError()
apply: (document) ->
reference = @path.getReference(document)
accessor = @path.accessor
value = @patch.value
if isArray(reference)
accessor = @path.coerce(reference, accessor)
if accessor < 0 or accessor > reference.length
throw new PatchConflictError("Index #{accessor} out of bounds")
reference.splice(accessor, 0, value)
else if not accessor?
document = value
else
reference[accessor] = value
return document
class RemovePatch extends JSONPatch
apply: (document) ->
reference = @path.getReference(document)
accessor = @path.accessor
if isArray(reference)
accessor = @path.coerce(reference, accessor)
if accessor >= reference.length
throw new PatchConflictError("Value at #{accessor} does not exist")
reference.splice(accessor, 1)
else
if accessor not of reference
throw new PatchConflictError("Value at #{accessor} does not exist")
delete reference[accessor]
return document
class ReplacePatch extends JSONPatch
validate: (patch) ->
if 'value' not of patch then throw new InvalidPatchError()
apply: (document) ->
reference = @path.getReference(document)
accessor = @path.accessor
value = @patch.value
# Replace whole document
if not accessor?
return value
if isArray(reference)
accessor = @path.coerce(reference, accessor)
if accessor >= reference.length
throw new PatchConflictError("Value at #{accessor} does not exist")
reference.splice(accessor, 1, value)
else
if accessor not of reference
throw new PatchConflictError("Value at #{accessor} does not exist")
reference[accessor] = value
return document
class TestPatch extends JSONPatch
validate: (patch) ->
if 'value' not of patch
throw new InvalidPatchError("'value' member is required")
apply: (document) ->
reference = @path.getReference(document)
accessor = @path.accessor
value = @patch.value
if isArray(reference)
accessor = @path.coerce(reference, accessor)
if not isEqual(reference[accessor], value)
throw new PatchTestFailed()
return document
class MovePatch extends JSONPatch
initialize: (patch) ->
@from = new JSONPointer(patch.from)
len = @from.steps.length
within = true
for i in [0..len]
if @from.steps[i] isnt @path.steps[i]
within = false
break
if within
if @path.steps.length isnt len
throw new InvalidPatchError("'to' member cannot be a descendent of 'path'")
if @from.accessor is @path.accessor
# The path and to pointers reference the same location,
# therefore apply can be a no-op
@apply = (document) -> document
validate: (patch) ->
if 'from' not of patch
throw new InvalidPatchError("'from' member is required")
apply: (document) ->
reference = @from.getReference(document)
accessor = @from.accessor
if isArray(reference)
accessor = @from.coerce(reference, accessor)
if accessor >= reference.length
throw new PatchConflictError("Value at #{accessor} does not exist")
value = reference.splice(accessor, 1)[0]
else
if accessor not of reference
throw new PatchConflictError("Value at #{accessor} does not exist")
value = reference[accessor]
delete reference[accessor]
reference = @path.getReference(document)
accessor = @path.accessor
# Add to object
if isArray(reference)
accessor = @path.coerce(reference, accessor)
if accessor < 0 or accessor > reference.length
throw new PatchConflictError("Index #{accessor} out of bounds")
reference.splice(accessor, 0, value)
else
if accessor of reference
throw new PatchConflictError("Value at #{accessor} exists")
reference[accessor] = value
return document
class CopyPatch extends MovePatch
apply: (document) ->
reference = @from.getReference(document)
accessor = @from.accessor
if isArray(reference)
accessor = @from.coerce(reference, accessor)
if accessor >= reference.length
throw new PatchConflictError("Value at #{accessor} does not exist")
value = reference.slice(accessor, accessor + 1)[0]
else
if accessor not of reference
throw new PatchConflictError("Value at #{accessor} does not exist")
value = reference[accessor]
reference = @path.getReference(document)
accessor = @path.accessor
# Add to object
if isArray(reference)
accessor = @path.coerce(reference, accessor)
if accessor < 0 or accessor > reference.length
throw new PatchConflictError("Index #{accessor} out of bounds")
reference.splice(accessor, 0, value)
else
if accessor of reference
throw new PatchConflictError("Value at #{accessor} exists")
reference[accessor] = value
return document
# Map of operation classes
operationMap =
add: AddPatch
remove: RemovePatch
replace: ReplacePatch
move: MovePatch
copy: CopyPatch
test: TestPatch
# Validates and compiles a patch document and returns a function to apply
# to multiple documents
compile = (patch) ->
if not isArray(patch)
if isObject(patch)
patch = [patch]
else
throw new InvalidPatchError('patch must be an object or array')
ops = []
for p in patch
# Not a valid operation
if not (klass = operationMap[p.op])
throw new InvalidPatchError('invalid operation: ' + p.op)
ops.push new klass(p)
return (document) ->
result = document
for op in ops
result = op.apply(result)
return result
# Applies a patch to a document
apply = (document, patch) ->
compile(patch)(document)
# Export to exports
exports.version = '0.7.0'
exports.apply = apply
exports.compile = compile
exports.JSONPointer = JSONPointer
exports.JSONPatch = JSONPatch
exports.JSONPatchError = JSONPatchError
exports.InvalidPointerError = InvalidPointerError
exports.InvalidPatchError = InvalidPatchError
exports.PatchConflictError = PatchConflictError
exports.PatchTestFailed = PatchTestFailed
return exports