| 115 | exports.generate = generate; |
| 116 | // Dirty check if obj is different from mirror, generate patches and update mirror |
| 117 | function _generate(mirror, obj, patches, path, invertible) { |
| 118 | if (obj === mirror) { |
| 119 | return; |
| 120 | } |
| 121 | if (typeof obj.toJSON === "function") { |
| 122 | obj = obj.toJSON(); |
| 123 | } |
| 124 | var newKeys = helpers_js_1._objectKeys(obj); |
| 125 | var oldKeys = helpers_js_1._objectKeys(mirror); |
| 126 | var changed = false; |
| 127 | var deleted = false; |
| 128 | //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" |
| 129 | for (var t = oldKeys.length - 1; t >= 0; t--) { |
| 130 | var key = oldKeys[t]; |
| 131 | var oldVal = mirror[key]; |
| 132 | if (helpers_js_1.hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) { |
| 133 | var newVal = obj[key]; |
| 134 | if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) { |
| 135 | _generate(oldVal, newVal, patches, path + "/" + helpers_js_1.escapePathComponent(key), invertible); |
| 136 | } |
| 137 | else { |
| 138 | if (oldVal !== newVal) { |
| 139 | changed = true; |
| 140 | if (invertible) { |
| 141 | patches.push({ op: "test", path: path + "/" + helpers_js_1.escapePathComponent(key), value: helpers_js_1._deepClone(oldVal) }); |
| 142 | } |
| 143 | patches.push({ op: "replace", path: path + "/" + helpers_js_1.escapePathComponent(key), value: helpers_js_1._deepClone(newVal) }); |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | else if (Array.isArray(mirror) === Array.isArray(obj)) { |
| 148 | if (invertible) { |
| 149 | patches.push({ op: "test", path: path + "/" + helpers_js_1.escapePathComponent(key), value: helpers_js_1._deepClone(oldVal) }); |
| 150 | } |
| 151 | patches.push({ op: "remove", path: path + "/" + helpers_js_1.escapePathComponent(key) }); |
| 152 | deleted = true; // property has been deleted |
| 153 | } |
| 154 | else { |
| 155 | if (invertible) { |
| 156 | patches.push({ op: "test", path: path, value: mirror }); |
| 157 | } |
| 158 | patches.push({ op: "replace", path: path, value: obj }); |
| 159 | changed = true; |
| 160 | } |
| 161 | } |
| 162 | if (!deleted && newKeys.length == oldKeys.length) { |
| 163 | return; |
| 164 | } |
| 165 | for (var t = 0; t < newKeys.length; t++) { |
| 166 | var key = newKeys[t]; |
| 167 | if (!helpers_js_1.hasOwnProperty(mirror, key) && obj[key] !== undefined) { |
| 168 | patches.push({ op: "add", path: path + "/" + helpers_js_1.escapePathComponent(key), value: helpers_js_1._deepClone(obj[key]) }); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | /** |
| 173 | * Create an array of patches from the differences in two objects |
| 174 | */ |