├── .gitignore ├── COPYING ├── LICENSE ├── Makefile ├── README.md ├── integrations └── backbone-simperium.js ├── libs ├── diff_match_patch_uncompressed.js ├── jsondiff-1.0.js └── sockjs-0.3.4.js └── sync.coffee /.gitignore: -------------------------------------------------------------------------------- 1 | simperium.js 2 | simperium-dev.js 3 | sync.js 4 | sync-nolog.js -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | This project contains code from various open source projects. 2 | 3 | diffmatchpatch (http://code.google.com/p/google-diff-match-patch/) under Apache License, 2.0 4 | 5 | sockjs (https://github.com/sockjs/sockjs-client/) under MIT License 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013, Automattic Inc. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ifndef CLOSURE_COMPILER 2 | CLOSURE_COMPILER = closure-compiler 3 | endif 4 | 5 | CLOSURE_OPTS = --compilation_level SIMPLE_OPTIMIZATIONS --warning_level QUIET 6 | 7 | LIBS = libs/jsondiff-1.0.js libs/diff_match_patch_uncompressed.js libs/sockjs-0.3.4.js 8 | 9 | TARGETS = simperium.js simperium-dev.js 10 | 11 | all: $(TARGETS) 12 | 13 | simperium.js: $(LIBS) sync-nolog.js 14 | $(CLOSURE_COMPILER) $(addprefix --js ,$^) --js_output_file $@ $(CLOSURE_OPTS) 15 | 16 | simperium-dev.js: $(LIBS) sync.js 17 | $(CLOSURE_COMPILER) $(addprefix --js ,$^) --js_output_file $@ $(CLOSURE_OPTS) 18 | 19 | sync-nolog.js: sync.js 20 | # redefine console.log to strip out log calls for production 21 | @sed -e 's/console\.log/false\ \&\&\ console\.log/' $^ > $@ 22 | 23 | sync.js: sync.coffee 24 | coffee -c $^ 25 | 26 | clean: 27 | rm -f *.js 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | simperium-js 2 | ============== 3 | Simperium is a simple way for developers to move data as it changes, instantly and automatically. This is the Javascript library. You can [browse the documentation](https://simperium.com/docs/js/). 4 | 5 | You can [sign up](https://simperium.com) for a hosted version of Simperium. There are Simperium libraries for [other languages](https://simperium.com/overview/) too. 6 | 7 | ### License 8 | The Simperium Javascript library is available for free and commercial use under the MIT license. 9 | 10 | ### Building 11 | 12 | You'll need [coffeescript](http://coffeescript.org/) to build this project. 13 | 14 | To use the included Makefile, set the environment variable `CLOSURE_COMPILER` to 15 | execute Google's [Closure Compiler](http://code.google.com/p/closure-compiler/) jar: 16 | 17 | export CLOSURE_COMPILER="java -jar 18 | ~/usr/local/closure-compiler/build/compiler.jar" 19 | 20 | By default it will try to run the command `closure-compiler` which should be 21 | available if you use [Homebrew](https://github.com/mxcl/homebrew) to install 22 | Google Closure Compiler. 23 | 24 | 25 | ### Getting Started 26 | 27 | See the [introduction](https://simperium.com/docs/js/) or the [API 28 | reference](https://simperium.com/docs/reference/js/). 29 | -------------------------------------------------------------------------------- /integrations/backbone-simperium.js: -------------------------------------------------------------------------------- 1 | (function (factory) { 2 | if (typeof define === 'function' && define.amd) { 3 | // AMD. Register as an anonymous module. 4 | define('backbone-simperium', ['backbone'], factory); 5 | } else { 6 | // Browser globals 7 | factory(Backbone); 8 | } 9 | }(function( Backbone ) { 10 | Backbone.SimperiumModel = Backbone.Model.extend({ 11 | initialize: function(attributes, options) { 12 | _.bindAll(this, "remote_update", "local_data"); 13 | this.bucket = options.bucket; 14 | this.id = options.id; 15 | this.bucket.on('notify', this.remote_update); 16 | this.bucket.on('local', this.local_data); 17 | this.bucket.start(); 18 | }, 19 | 20 | remote_update: function(id, data, version) { 21 | if (id != this.id) return; 22 | if (data == null) { 23 | this.clear(); 24 | } else { 25 | this.set(data); 26 | this.version = version; 27 | } 28 | }, 29 | 30 | local_data: function(id) { 31 | if (id != this.id) return; 32 | 33 | return this.toJSON(); 34 | }, 35 | }); 36 | 37 | Backbone.SimperiumCollection = Backbone.Collection.extend({ 38 | initialize: function(models, options) { 39 | _.bindAll(this, "remote_update", "local_data"); 40 | this.bucket = options.bucket; 41 | this.bucket.on('notify', this.remote_update); 42 | this.bucket.on('local', this.local_data); 43 | this.bucket.start(); 44 | }, 45 | 46 | remote_update: function(id, data, version) { 47 | var model = this.get(id); 48 | if (data == null) { 49 | if (model) { 50 | model.destroy(); 51 | } 52 | } else { 53 | if (model) { 54 | model.version = version; 55 | model.set(data); 56 | } else { 57 | model = new this.model(data); 58 | model.id = id; 59 | model.version = version; 60 | this.add(model); 61 | } 62 | } 63 | }, 64 | 65 | local_data: function(id) { 66 | var model = this.get(id); 67 | if (model) { 68 | return model.toJSON(); 69 | } 70 | return null; 71 | }, 72 | }); 73 | 74 | Backbone.sync = function(method, model, options) { 75 | if (!model) return; 76 | var S4 = function() { 77 | return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); 78 | }; 79 | 80 | var bucket = model.collection && model.collection.bucket || model.bucket; 81 | if (!bucket) return; 82 | 83 | var isModel = !(typeof model.isNew === 'undefined'); 84 | if (isModel) { 85 | if (model.isNew()) { 86 | model.id = S4()+S4()+S4()+S4()+S4(); 87 | if (model.collection) { 88 | model.trigger("change:id", model, model.collection, {}); 89 | } 90 | } 91 | 92 | switch (method) { 93 | case "create" : 94 | case "update" : bucket.update(model.id, model.toJSON()); options && options.success(); break; 95 | case "delete" : bucket.update(model.id, null); options && options.success(); break; 96 | } 97 | } 98 | }; 99 | 100 | return Backbone; 101 | } 102 | )); 103 | -------------------------------------------------------------------------------- /libs/diff_match_patch_uncompressed.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Diff Match and Patch 3 | * 4 | * Copyright 2006 Google Inc. 5 | * http://code.google.com/p/google-diff-match-patch/ 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @fileoverview Computes the difference between two texts to create a patch. 22 | * Applies the patch onto another text, allowing for errors. 23 | * @author fraser@google.com (Neil Fraser) 24 | */ 25 | 26 | /** 27 | * Class containing the diff, match and patch methods. 28 | * @constructor 29 | */ 30 | function diff_match_patch() { 31 | 32 | // Defaults. 33 | // Redefine these in your program to override the defaults. 34 | 35 | // Number of seconds to map a diff before giving up (0 for infinity). 36 | this.Diff_Timeout = 1.0; 37 | // Cost of an empty edit operation in terms of edit characters. 38 | this.Diff_EditCost = 4; 39 | // At what point is no match declared (0.0 = perfection, 1.0 = very loose). 40 | this.Match_Threshold = 0.5; 41 | // How far to search for a match (0 = exact location, 1000+ = broad match). 42 | // A match this many characters away from the expected location will add 43 | // 1.0 to the score (0.0 is a perfect match). 44 | this.Match_Distance = 1000; 45 | // When deleting a large block of text (over ~64 characters), how close do 46 | // the contents have to be to match the expected contents. (0.0 = perfection, 47 | // 1.0 = very loose). Note that Match_Threshold controls how closely the 48 | // end points of a delete need to match. 49 | this.Patch_DeleteThreshold = 0.5; 50 | // Chunk size for context length. 51 | this.Patch_Margin = 4; 52 | 53 | // The number of bits in an int. 54 | this.Match_MaxBits = 32; 55 | } 56 | 57 | 58 | // DIFF FUNCTIONS 59 | 60 | 61 | /** 62 | * The data structure representing a diff is an array of tuples: 63 | * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] 64 | * which means: delete 'Hello', add 'Goodbye' and keep ' world.' 65 | */ 66 | var DIFF_DELETE = -1; 67 | var DIFF_INSERT = 1; 68 | var DIFF_EQUAL = 0; 69 | 70 | /** @typedef {{0: number, 1: string}} */ 71 | diff_match_patch.Diff; 72 | 73 | 74 | /** 75 | * Find the differences between two texts. Simplifies the problem by stripping 76 | * any common prefix or suffix off the texts before diffing. 77 | * @param {string} text1 Old string to be diffed. 78 | * @param {string} text2 New string to be diffed. 79 | * @param {boolean=} opt_checklines Optional speedup flag. If present and false, 80 | * then don't run a line-level diff first to identify the changed areas. 81 | * Defaults to true, which does a faster, slightly less optimal diff. 82 | * @param {number} opt_deadline Optional time when the diff should be complete 83 | * by. Used internally for recursive calls. Users should set DiffTimeout 84 | * instead. 85 | * @return {!Array.} Array of diff tuples. 86 | */ 87 | diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines, 88 | opt_deadline) { 89 | // Set a deadline by which time the diff must be complete. 90 | if (typeof opt_deadline == 'undefined') { 91 | if (this.Diff_Timeout <= 0) { 92 | opt_deadline = Number.MAX_VALUE; 93 | } else { 94 | opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000; 95 | } 96 | } 97 | var deadline = opt_deadline; 98 | 99 | // Check for null inputs. 100 | if (text1 == null || text2 == null) { 101 | throw new Error('Null input. (diff_main)'); 102 | } 103 | 104 | // Check for equality (speedup). 105 | if (text1 == text2) { 106 | if (text1) { 107 | return [[DIFF_EQUAL, text1]]; 108 | } 109 | return []; 110 | } 111 | 112 | if (typeof opt_checklines == 'undefined') { 113 | opt_checklines = true; 114 | } 115 | var checklines = opt_checklines; 116 | 117 | // Trim off common prefix (speedup). 118 | var commonlength = this.diff_commonPrefix(text1, text2); 119 | var commonprefix = text1.substring(0, commonlength); 120 | text1 = text1.substring(commonlength); 121 | text2 = text2.substring(commonlength); 122 | 123 | // Trim off common suffix (speedup). 124 | commonlength = this.diff_commonSuffix(text1, text2); 125 | var commonsuffix = text1.substring(text1.length - commonlength); 126 | text1 = text1.substring(0, text1.length - commonlength); 127 | text2 = text2.substring(0, text2.length - commonlength); 128 | 129 | // Compute the diff on the middle block. 130 | var diffs = this.diff_compute_(text1, text2, checklines, deadline); 131 | 132 | // Restore the prefix and suffix. 133 | if (commonprefix) { 134 | diffs.unshift([DIFF_EQUAL, commonprefix]); 135 | } 136 | if (commonsuffix) { 137 | diffs.push([DIFF_EQUAL, commonsuffix]); 138 | } 139 | this.diff_cleanupMerge(diffs); 140 | return diffs; 141 | }; 142 | 143 | 144 | /** 145 | * Find the differences between two texts. Assumes that the texts do not 146 | * have any common prefix or suffix. 147 | * @param {string} text1 Old string to be diffed. 148 | * @param {string} text2 New string to be diffed. 149 | * @param {boolean} checklines Speedup flag. If false, then don't run a 150 | * line-level diff first to identify the changed areas. 151 | * If true, then run a faster, slightly less optimal diff. 152 | * @param {number} deadline Time when the diff should be complete by. 153 | * @return {!Array.} Array of diff tuples. 154 | * @private 155 | */ 156 | diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines, 157 | deadline) { 158 | var diffs; 159 | 160 | if (!text1) { 161 | // Just add some text (speedup). 162 | return [[DIFF_INSERT, text2]]; 163 | } 164 | 165 | if (!text2) { 166 | // Just delete some text (speedup). 167 | return [[DIFF_DELETE, text1]]; 168 | } 169 | 170 | /** @type {?string} */ 171 | var longtext = text1.length > text2.length ? text1 : text2; 172 | /** @type {?string} */ 173 | var shorttext = text1.length > text2.length ? text2 : text1; 174 | var i = longtext.indexOf(shorttext); 175 | if (i != -1) { 176 | // Shorter text is inside the longer text (speedup). 177 | diffs = [[DIFF_INSERT, longtext.substring(0, i)], 178 | [DIFF_EQUAL, shorttext], 179 | [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; 180 | // Swap insertions for deletions if diff is reversed. 181 | if (text1.length > text2.length) { 182 | diffs[0][0] = diffs[2][0] = DIFF_DELETE; 183 | } 184 | return diffs; 185 | } 186 | 187 | if (shorttext.length == 1) { 188 | // Single character string. 189 | // After the previous speedup, the character can't be an equality. 190 | return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; 191 | } 192 | longtext = shorttext = null; // Garbage collect. 193 | 194 | // Check to see if the problem can be split in two. 195 | var hm = this.diff_halfMatch_(text1, text2); 196 | if (hm) { 197 | // A half-match was found, sort out the return data. 198 | var text1_a = hm[0]; 199 | var text1_b = hm[1]; 200 | var text2_a = hm[2]; 201 | var text2_b = hm[3]; 202 | var mid_common = hm[4]; 203 | // Send both pairs off for separate processing. 204 | var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); 205 | var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); 206 | // Merge the results. 207 | return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); 208 | } 209 | 210 | if (checklines && text1.length > 100 && text2.length > 100) { 211 | return this.diff_lineMode_(text1, text2, deadline); 212 | } 213 | 214 | return this.diff_bisect_(text1, text2, deadline); 215 | }; 216 | 217 | 218 | /** 219 | * Do a quick line-level diff on both strings, then rediff the parts for 220 | * greater accuracy. 221 | * This speedup can produce non-minimal diffs. 222 | * @param {string} text1 Old string to be diffed. 223 | * @param {string} text2 New string to be diffed. 224 | * @param {number} deadline Time when the diff should be complete by. 225 | * @return {!Array.} Array of diff tuples. 226 | * @private 227 | */ 228 | diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) { 229 | // Scan the text on a line-by-line basis first. 230 | var a = this.diff_linesToChars_(text1, text2); 231 | text1 = a.chars1; 232 | text2 = a.chars2; 233 | var linearray = a.lineArray; 234 | 235 | var diffs = this.diff_main(text1, text2, false, deadline); 236 | 237 | // Convert the diff back to original text. 238 | this.diff_charsToLines_(diffs, linearray); 239 | // Eliminate freak matches (e.g. blank lines) 240 | this.diff_cleanupSemantic(diffs); 241 | 242 | // Rediff any replacement blocks, this time character-by-character. 243 | // Add a dummy entry at the end. 244 | diffs.push([DIFF_EQUAL, '']); 245 | var pointer = 0; 246 | var count_delete = 0; 247 | var count_insert = 0; 248 | var text_delete = ''; 249 | var text_insert = ''; 250 | while (pointer < diffs.length) { 251 | switch (diffs[pointer][0]) { 252 | case DIFF_INSERT: 253 | count_insert++; 254 | text_insert += diffs[pointer][1]; 255 | break; 256 | case DIFF_DELETE: 257 | count_delete++; 258 | text_delete += diffs[pointer][1]; 259 | break; 260 | case DIFF_EQUAL: 261 | // Upon reaching an equality, check for prior redundancies. 262 | if (count_delete >= 1 && count_insert >= 1) { 263 | // Delete the offending records and add the merged ones. 264 | diffs.splice(pointer - count_delete - count_insert, 265 | count_delete + count_insert); 266 | pointer = pointer - count_delete - count_insert; 267 | var a = this.diff_main(text_delete, text_insert, false, deadline); 268 | for (var j = a.length - 1; j >= 0; j--) { 269 | diffs.splice(pointer, 0, a[j]); 270 | } 271 | pointer = pointer + a.length; 272 | } 273 | count_insert = 0; 274 | count_delete = 0; 275 | text_delete = ''; 276 | text_insert = ''; 277 | break; 278 | } 279 | pointer++; 280 | } 281 | diffs.pop(); // Remove the dummy entry at the end. 282 | 283 | return diffs; 284 | }; 285 | 286 | 287 | /** 288 | * Find the 'middle snake' of a diff, split the problem in two 289 | * and return the recursively constructed diff. 290 | * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. 291 | * @param {string} text1 Old string to be diffed. 292 | * @param {string} text2 New string to be diffed. 293 | * @param {number} deadline Time at which to bail if not yet complete. 294 | * @return {!Array.} Array of diff tuples. 295 | * @private 296 | */ 297 | diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) { 298 | // Cache the text lengths to prevent multiple calls. 299 | var text1_length = text1.length; 300 | var text2_length = text2.length; 301 | var max_d = Math.ceil((text1_length + text2_length) / 2); 302 | var v_offset = max_d; 303 | var v_length = 2 * max_d; 304 | var v1 = new Array(v_length); 305 | var v2 = new Array(v_length); 306 | // Setting all elements to -1 is faster in Chrome & Firefox than mixing 307 | // integers and undefined. 308 | for (var x = 0; x < v_length; x++) { 309 | v1[x] = -1; 310 | v2[x] = -1; 311 | } 312 | v1[v_offset + 1] = 0; 313 | v2[v_offset + 1] = 0; 314 | var delta = text1_length - text2_length; 315 | // If the total number of characters is odd, then the front path will collide 316 | // with the reverse path. 317 | var front = (delta % 2 != 0); 318 | // Offsets for start and end of k loop. 319 | // Prevents mapping of space beyond the grid. 320 | var k1start = 0; 321 | var k1end = 0; 322 | var k2start = 0; 323 | var k2end = 0; 324 | for (var d = 0; d < max_d; d++) { 325 | // Bail out if deadline is reached. 326 | if ((new Date()).getTime() > deadline) { 327 | break; 328 | } 329 | 330 | // Walk the front path one step. 331 | for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { 332 | var k1_offset = v_offset + k1; 333 | var x1; 334 | if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) { 335 | x1 = v1[k1_offset + 1]; 336 | } else { 337 | x1 = v1[k1_offset - 1] + 1; 338 | } 339 | var y1 = x1 - k1; 340 | while (x1 < text1_length && y1 < text2_length && 341 | text1.charAt(x1) == text2.charAt(y1)) { 342 | x1++; 343 | y1++; 344 | } 345 | v1[k1_offset] = x1; 346 | if (x1 > text1_length) { 347 | // Ran off the right of the graph. 348 | k1end += 2; 349 | } else if (y1 > text2_length) { 350 | // Ran off the bottom of the graph. 351 | k1start += 2; 352 | } else if (front) { 353 | var k2_offset = v_offset + delta - k1; 354 | if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { 355 | // Mirror x2 onto top-left coordinate system. 356 | var x2 = text1_length - v2[k2_offset]; 357 | if (x1 >= x2) { 358 | // Overlap detected. 359 | return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); 360 | } 361 | } 362 | } 363 | } 364 | 365 | // Walk the reverse path one step. 366 | for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { 367 | var k2_offset = v_offset + k2; 368 | var x2; 369 | if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) { 370 | x2 = v2[k2_offset + 1]; 371 | } else { 372 | x2 = v2[k2_offset - 1] + 1; 373 | } 374 | var y2 = x2 - k2; 375 | while (x2 < text1_length && y2 < text2_length && 376 | text1.charAt(text1_length - x2 - 1) == 377 | text2.charAt(text2_length - y2 - 1)) { 378 | x2++; 379 | y2++; 380 | } 381 | v2[k2_offset] = x2; 382 | if (x2 > text1_length) { 383 | // Ran off the left of the graph. 384 | k2end += 2; 385 | } else if (y2 > text2_length) { 386 | // Ran off the top of the graph. 387 | k2start += 2; 388 | } else if (!front) { 389 | var k1_offset = v_offset + delta - k2; 390 | if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { 391 | var x1 = v1[k1_offset]; 392 | var y1 = v_offset + x1 - k1_offset; 393 | // Mirror x2 onto top-left coordinate system. 394 | x2 = text1_length - x2; 395 | if (x1 >= x2) { 396 | // Overlap detected. 397 | return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); 398 | } 399 | } 400 | } 401 | } 402 | } 403 | // Diff took too long and hit the deadline or 404 | // number of diffs equals number of characters, no commonality at all. 405 | return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; 406 | }; 407 | 408 | 409 | /** 410 | * Given the location of the 'middle snake', split the diff in two parts 411 | * and recurse. 412 | * @param {string} text1 Old string to be diffed. 413 | * @param {string} text2 New string to be diffed. 414 | * @param {number} x Index of split point in text1. 415 | * @param {number} y Index of split point in text2. 416 | * @param {number} deadline Time at which to bail if not yet complete. 417 | * @return {!Array.} Array of diff tuples. 418 | * @private 419 | */ 420 | diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y, 421 | deadline) { 422 | var text1a = text1.substring(0, x); 423 | var text2a = text2.substring(0, y); 424 | var text1b = text1.substring(x); 425 | var text2b = text2.substring(y); 426 | 427 | // Compute both diffs serially. 428 | var diffs = this.diff_main(text1a, text2a, false, deadline); 429 | var diffsb = this.diff_main(text1b, text2b, false, deadline); 430 | 431 | return diffs.concat(diffsb); 432 | }; 433 | 434 | 435 | /** 436 | * Split two texts into an array of strings. Reduce the texts to a string of 437 | * hashes where each Unicode character represents one line. 438 | * @param {string} text1 First string. 439 | * @param {string} text2 Second string. 440 | * @return {{chars1: string, chars2: string, lineArray: !Array.}} 441 | * An object containing the encoded text1, the encoded text2 and 442 | * the array of unique strings. 443 | * The zeroth element of the array of unique strings is intentionally blank. 444 | * @private 445 | */ 446 | diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) { 447 | var lineArray = []; // e.g. lineArray[4] == 'Hello\n' 448 | var lineHash = {}; // e.g. lineHash['Hello\n'] == 4 449 | 450 | // '\x00' is a valid character, but various debuggers don't like it. 451 | // So we'll insert a junk entry to avoid generating a null character. 452 | lineArray[0] = ''; 453 | 454 | /** 455 | * Split a text into an array of strings. Reduce the texts to a string of 456 | * hashes where each Unicode character represents one line. 457 | * Modifies linearray and linehash through being a closure. 458 | * @param {string} text String to encode. 459 | * @return {string} Encoded string. 460 | * @private 461 | */ 462 | function diff_linesToCharsMunge_(text) { 463 | var chars = ''; 464 | // Walk the text, pulling out a substring for each line. 465 | // text.split('\n') would would temporarily double our memory footprint. 466 | // Modifying text would create many large strings to garbage collect. 467 | var lineStart = 0; 468 | var lineEnd = -1; 469 | // Keeping our own length variable is faster than looking it up. 470 | var lineArrayLength = lineArray.length; 471 | while (lineEnd < text.length - 1) { 472 | lineEnd = text.indexOf('\n', lineStart); 473 | if (lineEnd == -1) { 474 | lineEnd = text.length - 1; 475 | } 476 | var line = text.substring(lineStart, lineEnd + 1); 477 | lineStart = lineEnd + 1; 478 | 479 | if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : 480 | (lineHash[line] !== undefined)) { 481 | chars += String.fromCharCode(lineHash[line]); 482 | } else { 483 | chars += String.fromCharCode(lineArrayLength); 484 | lineHash[line] = lineArrayLength; 485 | lineArray[lineArrayLength++] = line; 486 | } 487 | } 488 | return chars; 489 | } 490 | 491 | var chars1 = diff_linesToCharsMunge_(text1); 492 | var chars2 = diff_linesToCharsMunge_(text2); 493 | return {chars1: chars1, chars2: chars2, lineArray: lineArray}; 494 | }; 495 | 496 | 497 | /** 498 | * Rehydrate the text in a diff from a string of line hashes to real lines of 499 | * text. 500 | * @param {!Array.} diffs Array of diff tuples. 501 | * @param {!Array.} lineArray Array of unique strings. 502 | * @private 503 | */ 504 | diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) { 505 | for (var x = 0; x < diffs.length; x++) { 506 | var chars = diffs[x][1]; 507 | var text = []; 508 | for (var y = 0; y < chars.length; y++) { 509 | text[y] = lineArray[chars.charCodeAt(y)]; 510 | } 511 | diffs[x][1] = text.join(''); 512 | } 513 | }; 514 | 515 | 516 | /** 517 | * Determine the common prefix of two strings. 518 | * @param {string} text1 First string. 519 | * @param {string} text2 Second string. 520 | * @return {number} The number of characters common to the start of each 521 | * string. 522 | */ 523 | diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) { 524 | // Quick check for common null cases. 525 | if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { 526 | return 0; 527 | } 528 | // Binary search. 529 | // Performance analysis: http://neil.fraser.name/news/2007/10/09/ 530 | var pointermin = 0; 531 | var pointermax = Math.min(text1.length, text2.length); 532 | var pointermid = pointermax; 533 | var pointerstart = 0; 534 | while (pointermin < pointermid) { 535 | if (text1.substring(pointerstart, pointermid) == 536 | text2.substring(pointerstart, pointermid)) { 537 | pointermin = pointermid; 538 | pointerstart = pointermin; 539 | } else { 540 | pointermax = pointermid; 541 | } 542 | pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); 543 | } 544 | return pointermid; 545 | }; 546 | 547 | 548 | /** 549 | * Determine the common suffix of two strings. 550 | * @param {string} text1 First string. 551 | * @param {string} text2 Second string. 552 | * @return {number} The number of characters common to the end of each string. 553 | */ 554 | diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) { 555 | // Quick check for common null cases. 556 | if (!text1 || !text2 || 557 | text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { 558 | return 0; 559 | } 560 | // Binary search. 561 | // Performance analysis: http://neil.fraser.name/news/2007/10/09/ 562 | var pointermin = 0; 563 | var pointermax = Math.min(text1.length, text2.length); 564 | var pointermid = pointermax; 565 | var pointerend = 0; 566 | while (pointermin < pointermid) { 567 | if (text1.substring(text1.length - pointermid, text1.length - pointerend) == 568 | text2.substring(text2.length - pointermid, text2.length - pointerend)) { 569 | pointermin = pointermid; 570 | pointerend = pointermin; 571 | } else { 572 | pointermax = pointermid; 573 | } 574 | pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); 575 | } 576 | return pointermid; 577 | }; 578 | 579 | 580 | /** 581 | * Determine if the suffix of one string is the prefix of another. 582 | * @param {string} text1 First string. 583 | * @param {string} text2 Second string. 584 | * @return {number} The number of characters common to the end of the first 585 | * string and the start of the second string. 586 | * @private 587 | */ 588 | diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) { 589 | // Cache the text lengths to prevent multiple calls. 590 | var text1_length = text1.length; 591 | var text2_length = text2.length; 592 | // Eliminate the null case. 593 | if (text1_length == 0 || text2_length == 0) { 594 | return 0; 595 | } 596 | // Truncate the longer string. 597 | if (text1_length > text2_length) { 598 | text1 = text1.substring(text1_length - text2_length); 599 | } else if (text1_length < text2_length) { 600 | text2 = text2.substring(0, text1_length); 601 | } 602 | var text_length = Math.min(text1_length, text2_length); 603 | // Quick check for the worst case. 604 | if (text1 == text2) { 605 | return text_length; 606 | } 607 | 608 | // Start by looking for a single character match 609 | // and increase length until no match is found. 610 | // Performance analysis: http://neil.fraser.name/news/2010/11/04/ 611 | var best = 0; 612 | var length = 1; 613 | while (true) { 614 | var pattern = text1.substring(text_length - length); 615 | var found = text2.indexOf(pattern); 616 | if (found == -1) { 617 | return best; 618 | } 619 | length += found; 620 | if (found == 0 || text1.substring(text_length - length) == 621 | text2.substring(0, length)) { 622 | best = length; 623 | length++; 624 | } 625 | } 626 | }; 627 | 628 | 629 | /** 630 | * Do the two texts share a substring which is at least half the length of the 631 | * longer text? 632 | * This speedup can produce non-minimal diffs. 633 | * @param {string} text1 First string. 634 | * @param {string} text2 Second string. 635 | * @return {Array.} Five element Array, containing the prefix of 636 | * text1, the suffix of text1, the prefix of text2, the suffix of 637 | * text2 and the common middle. Or null if there was no match. 638 | * @private 639 | */ 640 | diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) { 641 | if (this.Diff_Timeout <= 0) { 642 | // Don't risk returning a non-optimal diff if we have unlimited time. 643 | return null; 644 | } 645 | var longtext = text1.length > text2.length ? text1 : text2; 646 | var shorttext = text1.length > text2.length ? text2 : text1; 647 | if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { 648 | return null; // Pointless. 649 | } 650 | var dmp = this; // 'this' becomes 'window' in a closure. 651 | 652 | /** 653 | * Does a substring of shorttext exist within longtext such that the substring 654 | * is at least half the length of longtext? 655 | * Closure, but does not reference any external variables. 656 | * @param {string} longtext Longer string. 657 | * @param {string} shorttext Shorter string. 658 | * @param {number} i Start index of quarter length substring within longtext. 659 | * @return {Array.} Five element Array, containing the prefix of 660 | * longtext, the suffix of longtext, the prefix of shorttext, the suffix 661 | * of shorttext and the common middle. Or null if there was no match. 662 | * @private 663 | */ 664 | function diff_halfMatchI_(longtext, shorttext, i) { 665 | // Start with a 1/4 length substring at position i as a seed. 666 | var seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); 667 | var j = -1; 668 | var best_common = ''; 669 | var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; 670 | while ((j = shorttext.indexOf(seed, j + 1)) != -1) { 671 | var prefixLength = dmp.diff_commonPrefix(longtext.substring(i), 672 | shorttext.substring(j)); 673 | var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i), 674 | shorttext.substring(0, j)); 675 | if (best_common.length < suffixLength + prefixLength) { 676 | best_common = shorttext.substring(j - suffixLength, j) + 677 | shorttext.substring(j, j + prefixLength); 678 | best_longtext_a = longtext.substring(0, i - suffixLength); 679 | best_longtext_b = longtext.substring(i + prefixLength); 680 | best_shorttext_a = shorttext.substring(0, j - suffixLength); 681 | best_shorttext_b = shorttext.substring(j + prefixLength); 682 | } 683 | } 684 | if (best_common.length * 2 >= longtext.length) { 685 | return [best_longtext_a, best_longtext_b, 686 | best_shorttext_a, best_shorttext_b, best_common]; 687 | } else { 688 | return null; 689 | } 690 | } 691 | 692 | // First check if the second quarter is the seed for a half-match. 693 | var hm1 = diff_halfMatchI_(longtext, shorttext, 694 | Math.ceil(longtext.length / 4)); 695 | // Check again based on the third quarter. 696 | var hm2 = diff_halfMatchI_(longtext, shorttext, 697 | Math.ceil(longtext.length / 2)); 698 | var hm; 699 | if (!hm1 && !hm2) { 700 | return null; 701 | } else if (!hm2) { 702 | hm = hm1; 703 | } else if (!hm1) { 704 | hm = hm2; 705 | } else { 706 | // Both matched. Select the longest. 707 | hm = hm1[4].length > hm2[4].length ? hm1 : hm2; 708 | } 709 | 710 | // A half-match was found, sort out the return data. 711 | var text1_a, text1_b, text2_a, text2_b; 712 | if (text1.length > text2.length) { 713 | text1_a = hm[0]; 714 | text1_b = hm[1]; 715 | text2_a = hm[2]; 716 | text2_b = hm[3]; 717 | } else { 718 | text2_a = hm[0]; 719 | text2_b = hm[1]; 720 | text1_a = hm[2]; 721 | text1_b = hm[3]; 722 | } 723 | var mid_common = hm[4]; 724 | return [text1_a, text1_b, text2_a, text2_b, mid_common]; 725 | }; 726 | 727 | 728 | /** 729 | * Reduce the number of edits by eliminating semantically trivial equalities. 730 | * @param {!Array.} diffs Array of diff tuples. 731 | */ 732 | diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) { 733 | var changes = false; 734 | var equalities = []; // Stack of indices where equalities are found. 735 | var equalitiesLength = 0; // Keeping our own length var is faster in JS. 736 | /** @type {?string} */ 737 | var lastequality = null; 738 | // Always equal to diffs[equalities[equalitiesLength - 1]][1] 739 | var pointer = 0; // Index of current position. 740 | // Number of characters that changed prior to the equality. 741 | var length_insertions1 = 0; 742 | var length_deletions1 = 0; 743 | // Number of characters that changed after the equality. 744 | var length_insertions2 = 0; 745 | var length_deletions2 = 0; 746 | while (pointer < diffs.length) { 747 | if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. 748 | equalities[equalitiesLength++] = pointer; 749 | length_insertions1 = length_insertions2; 750 | length_deletions1 = length_deletions2; 751 | length_insertions2 = 0; 752 | length_deletions2 = 0; 753 | lastequality = diffs[pointer][1]; 754 | } else { // An insertion or deletion. 755 | if (diffs[pointer][0] == DIFF_INSERT) { 756 | length_insertions2 += diffs[pointer][1].length; 757 | } else { 758 | length_deletions2 += diffs[pointer][1].length; 759 | } 760 | // Eliminate an equality that is smaller or equal to the edits on both 761 | // sides of it. 762 | if (lastequality && (lastequality.length <= 763 | Math.max(length_insertions1, length_deletions1)) && 764 | (lastequality.length <= Math.max(length_insertions2, 765 | length_deletions2))) { 766 | // Duplicate record. 767 | diffs.splice(equalities[equalitiesLength - 1], 0, 768 | [DIFF_DELETE, lastequality]); 769 | // Change second copy to insert. 770 | diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; 771 | // Throw away the equality we just deleted. 772 | equalitiesLength--; 773 | // Throw away the previous equality (it needs to be reevaluated). 774 | equalitiesLength--; 775 | pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; 776 | length_insertions1 = 0; // Reset the counters. 777 | length_deletions1 = 0; 778 | length_insertions2 = 0; 779 | length_deletions2 = 0; 780 | lastequality = null; 781 | changes = true; 782 | } 783 | } 784 | pointer++; 785 | } 786 | 787 | // Normalize the diff. 788 | if (changes) { 789 | this.diff_cleanupMerge(diffs); 790 | } 791 | this.diff_cleanupSemanticLossless(diffs); 792 | 793 | // Find any overlaps between deletions and insertions. 794 | // e.g: abcxxxxxxdef 795 | // -> abcxxxdef 796 | // e.g: xxxabcdefxxx 797 | // -> defxxxabc 798 | // Only extract an overlap if it is as big as the edit ahead or behind it. 799 | pointer = 1; 800 | while (pointer < diffs.length) { 801 | if (diffs[pointer - 1][0] == DIFF_DELETE && 802 | diffs[pointer][0] == DIFF_INSERT) { 803 | var deletion = diffs[pointer - 1][1]; 804 | var insertion = diffs[pointer][1]; 805 | var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); 806 | var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); 807 | if (overlap_length1 >= overlap_length2) { 808 | if (overlap_length1 >= deletion.length / 2 || 809 | overlap_length1 >= insertion.length / 2) { 810 | // Overlap found. Insert an equality and trim the surrounding edits. 811 | diffs.splice(pointer, 0, 812 | [DIFF_EQUAL, insertion.substring(0, overlap_length1)]); 813 | diffs[pointer - 1][1] = 814 | deletion.substring(0, deletion.length - overlap_length1); 815 | diffs[pointer + 1][1] = insertion.substring(overlap_length1); 816 | pointer++; 817 | } 818 | } else { 819 | if (overlap_length2 >= deletion.length / 2 || 820 | overlap_length2 >= insertion.length / 2) { 821 | // Reverse overlap found. 822 | // Insert an equality and swap and trim the surrounding edits. 823 | diffs.splice(pointer, 0, 824 | [DIFF_EQUAL, deletion.substring(0, overlap_length2)]); 825 | diffs[pointer - 1][0] = DIFF_INSERT; 826 | diffs[pointer - 1][1] = 827 | insertion.substring(0, insertion.length - overlap_length2); 828 | diffs[pointer + 1][0] = DIFF_DELETE; 829 | diffs[pointer + 1][1] = 830 | deletion.substring(overlap_length2); 831 | pointer++; 832 | } 833 | } 834 | pointer++; 835 | } 836 | pointer++; 837 | } 838 | }; 839 | 840 | 841 | /** 842 | * Look for single edits surrounded on both sides by equalities 843 | * which can be shifted sideways to align the edit to a word boundary. 844 | * e.g: The cat came. -> The cat came. 845 | * @param {!Array.} diffs Array of diff tuples. 846 | */ 847 | diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) { 848 | /** 849 | * Given two strings, compute a score representing whether the internal 850 | * boundary falls on logical boundaries. 851 | * Scores range from 6 (best) to 0 (worst). 852 | * Closure, but does not reference any external variables. 853 | * @param {string} one First string. 854 | * @param {string} two Second string. 855 | * @return {number} The score. 856 | * @private 857 | */ 858 | function diff_cleanupSemanticScore_(one, two) { 859 | if (!one || !two) { 860 | // Edges are the best. 861 | return 6; 862 | } 863 | 864 | // Each port of this function behaves slightly differently due to 865 | // subtle differences in each language's definition of things like 866 | // 'whitespace'. Since this function's purpose is largely cosmetic, 867 | // the choice has been made to use each language's native features 868 | // rather than force total conformity. 869 | var char1 = one.charAt(one.length - 1); 870 | var char2 = two.charAt(0); 871 | var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_); 872 | var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_); 873 | var whitespace1 = nonAlphaNumeric1 && 874 | char1.match(diff_match_patch.whitespaceRegex_); 875 | var whitespace2 = nonAlphaNumeric2 && 876 | char2.match(diff_match_patch.whitespaceRegex_); 877 | var lineBreak1 = whitespace1 && 878 | char1.match(diff_match_patch.linebreakRegex_); 879 | var lineBreak2 = whitespace2 && 880 | char2.match(diff_match_patch.linebreakRegex_); 881 | var blankLine1 = lineBreak1 && 882 | one.match(diff_match_patch.blanklineEndRegex_); 883 | var blankLine2 = lineBreak2 && 884 | two.match(diff_match_patch.blanklineStartRegex_); 885 | 886 | if (blankLine1 || blankLine2) { 887 | // Five points for blank lines. 888 | return 5; 889 | } else if (lineBreak1 || lineBreak2) { 890 | // Four points for line breaks. 891 | return 4; 892 | } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { 893 | // Three points for end of sentences. 894 | return 3; 895 | } else if (whitespace1 || whitespace2) { 896 | // Two points for whitespace. 897 | return 2; 898 | } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { 899 | // One point for non-alphanumeric. 900 | return 1; 901 | } 902 | return 0; 903 | } 904 | 905 | var pointer = 1; 906 | // Intentionally ignore the first and last element (don't need checking). 907 | while (pointer < diffs.length - 1) { 908 | if (diffs[pointer - 1][0] == DIFF_EQUAL && 909 | diffs[pointer + 1][0] == DIFF_EQUAL) { 910 | // This is a single edit surrounded by equalities. 911 | var equality1 = diffs[pointer - 1][1]; 912 | var edit = diffs[pointer][1]; 913 | var equality2 = diffs[pointer + 1][1]; 914 | 915 | // First, shift the edit as far left as possible. 916 | var commonOffset = this.diff_commonSuffix(equality1, edit); 917 | if (commonOffset) { 918 | var commonString = edit.substring(edit.length - commonOffset); 919 | equality1 = equality1.substring(0, equality1.length - commonOffset); 920 | edit = commonString + edit.substring(0, edit.length - commonOffset); 921 | equality2 = commonString + equality2; 922 | } 923 | 924 | // Second, step character by character right, looking for the best fit. 925 | var bestEquality1 = equality1; 926 | var bestEdit = edit; 927 | var bestEquality2 = equality2; 928 | var bestScore = diff_cleanupSemanticScore_(equality1, edit) + 929 | diff_cleanupSemanticScore_(edit, equality2); 930 | while (edit.charAt(0) === equality2.charAt(0)) { 931 | equality1 += edit.charAt(0); 932 | edit = edit.substring(1) + equality2.charAt(0); 933 | equality2 = equality2.substring(1); 934 | var score = diff_cleanupSemanticScore_(equality1, edit) + 935 | diff_cleanupSemanticScore_(edit, equality2); 936 | // The >= encourages trailing rather than leading whitespace on edits. 937 | if (score >= bestScore) { 938 | bestScore = score; 939 | bestEquality1 = equality1; 940 | bestEdit = edit; 941 | bestEquality2 = equality2; 942 | } 943 | } 944 | 945 | if (diffs[pointer - 1][1] != bestEquality1) { 946 | // We have an improvement, save it back to the diff. 947 | if (bestEquality1) { 948 | diffs[pointer - 1][1] = bestEquality1; 949 | } else { 950 | diffs.splice(pointer - 1, 1); 951 | pointer--; 952 | } 953 | diffs[pointer][1] = bestEdit; 954 | if (bestEquality2) { 955 | diffs[pointer + 1][1] = bestEquality2; 956 | } else { 957 | diffs.splice(pointer + 1, 1); 958 | pointer--; 959 | } 960 | } 961 | } 962 | pointer++; 963 | } 964 | }; 965 | 966 | // Define some regex patterns for matching boundaries. 967 | diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; 968 | diff_match_patch.whitespaceRegex_ = /\s/; 969 | diff_match_patch.linebreakRegex_ = /[\r\n]/; 970 | diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/; 971 | diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/; 972 | 973 | /** 974 | * Reduce the number of edits by eliminating operationally trivial equalities. 975 | * @param {!Array.} diffs Array of diff tuples. 976 | */ 977 | diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) { 978 | var changes = false; 979 | var equalities = []; // Stack of indices where equalities are found. 980 | var equalitiesLength = 0; // Keeping our own length var is faster in JS. 981 | /** @type {?string} */ 982 | var lastequality = null; 983 | // Always equal to diffs[equalities[equalitiesLength - 1]][1] 984 | var pointer = 0; // Index of current position. 985 | // Is there an insertion operation before the last equality. 986 | var pre_ins = false; 987 | // Is there a deletion operation before the last equality. 988 | var pre_del = false; 989 | // Is there an insertion operation after the last equality. 990 | var post_ins = false; 991 | // Is there a deletion operation after the last equality. 992 | var post_del = false; 993 | while (pointer < diffs.length) { 994 | if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. 995 | if (diffs[pointer][1].length < this.Diff_EditCost && 996 | (post_ins || post_del)) { 997 | // Candidate found. 998 | equalities[equalitiesLength++] = pointer; 999 | pre_ins = post_ins; 1000 | pre_del = post_del; 1001 | lastequality = diffs[pointer][1]; 1002 | } else { 1003 | // Not a candidate, and can never become one. 1004 | equalitiesLength = 0; 1005 | lastequality = null; 1006 | } 1007 | post_ins = post_del = false; 1008 | } else { // An insertion or deletion. 1009 | if (diffs[pointer][0] == DIFF_DELETE) { 1010 | post_del = true; 1011 | } else { 1012 | post_ins = true; 1013 | } 1014 | /* 1015 | * Five types to be split: 1016 | * ABXYCD 1017 | * AXCD 1018 | * ABXC 1019 | * AXCD 1020 | * ABXC 1021 | */ 1022 | if (lastequality && ((pre_ins && pre_del && post_ins && post_del) || 1023 | ((lastequality.length < this.Diff_EditCost / 2) && 1024 | (pre_ins + pre_del + post_ins + post_del) == 3))) { 1025 | // Duplicate record. 1026 | diffs.splice(equalities[equalitiesLength - 1], 0, 1027 | [DIFF_DELETE, lastequality]); 1028 | // Change second copy to insert. 1029 | diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; 1030 | equalitiesLength--; // Throw away the equality we just deleted; 1031 | lastequality = null; 1032 | if (pre_ins && pre_del) { 1033 | // No changes made which could affect previous entry, keep going. 1034 | post_ins = post_del = true; 1035 | equalitiesLength = 0; 1036 | } else { 1037 | equalitiesLength--; // Throw away the previous equality. 1038 | pointer = equalitiesLength > 0 ? 1039 | equalities[equalitiesLength - 1] : -1; 1040 | post_ins = post_del = false; 1041 | } 1042 | changes = true; 1043 | } 1044 | } 1045 | pointer++; 1046 | } 1047 | 1048 | if (changes) { 1049 | this.diff_cleanupMerge(diffs); 1050 | } 1051 | }; 1052 | 1053 | 1054 | /** 1055 | * Reorder and merge like edit sections. Merge equalities. 1056 | * Any edit section can move as long as it doesn't cross an equality. 1057 | * @param {!Array.} diffs Array of diff tuples. 1058 | */ 1059 | diff_match_patch.prototype.diff_cleanupMerge = function(diffs) { 1060 | diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end. 1061 | var pointer = 0; 1062 | var count_delete = 0; 1063 | var count_insert = 0; 1064 | var text_delete = ''; 1065 | var text_insert = ''; 1066 | var commonlength; 1067 | while (pointer < diffs.length) { 1068 | switch (diffs[pointer][0]) { 1069 | case DIFF_INSERT: 1070 | count_insert++; 1071 | text_insert += diffs[pointer][1]; 1072 | pointer++; 1073 | break; 1074 | case DIFF_DELETE: 1075 | count_delete++; 1076 | text_delete += diffs[pointer][1]; 1077 | pointer++; 1078 | break; 1079 | case DIFF_EQUAL: 1080 | // Upon reaching an equality, check for prior redundancies. 1081 | if (count_delete + count_insert > 1) { 1082 | if (count_delete !== 0 && count_insert !== 0) { 1083 | // Factor out any common prefixies. 1084 | commonlength = this.diff_commonPrefix(text_insert, text_delete); 1085 | if (commonlength !== 0) { 1086 | if ((pointer - count_delete - count_insert) > 0 && 1087 | diffs[pointer - count_delete - count_insert - 1][0] == 1088 | DIFF_EQUAL) { 1089 | diffs[pointer - count_delete - count_insert - 1][1] += 1090 | text_insert.substring(0, commonlength); 1091 | } else { 1092 | diffs.splice(0, 0, [DIFF_EQUAL, 1093 | text_insert.substring(0, commonlength)]); 1094 | pointer++; 1095 | } 1096 | text_insert = text_insert.substring(commonlength); 1097 | text_delete = text_delete.substring(commonlength); 1098 | } 1099 | // Factor out any common suffixies. 1100 | commonlength = this.diff_commonSuffix(text_insert, text_delete); 1101 | if (commonlength !== 0) { 1102 | diffs[pointer][1] = text_insert.substring(text_insert.length - 1103 | commonlength) + diffs[pointer][1]; 1104 | text_insert = text_insert.substring(0, text_insert.length - 1105 | commonlength); 1106 | text_delete = text_delete.substring(0, text_delete.length - 1107 | commonlength); 1108 | } 1109 | } 1110 | // Delete the offending records and add the merged ones. 1111 | if (count_delete === 0) { 1112 | diffs.splice(pointer - count_insert, 1113 | count_delete + count_insert, [DIFF_INSERT, text_insert]); 1114 | } else if (count_insert === 0) { 1115 | diffs.splice(pointer - count_delete, 1116 | count_delete + count_insert, [DIFF_DELETE, text_delete]); 1117 | } else { 1118 | diffs.splice(pointer - count_delete - count_insert, 1119 | count_delete + count_insert, [DIFF_DELETE, text_delete], 1120 | [DIFF_INSERT, text_insert]); 1121 | } 1122 | pointer = pointer - count_delete - count_insert + 1123 | (count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1; 1124 | } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { 1125 | // Merge this equality with the previous one. 1126 | diffs[pointer - 1][1] += diffs[pointer][1]; 1127 | diffs.splice(pointer, 1); 1128 | } else { 1129 | pointer++; 1130 | } 1131 | count_insert = 0; 1132 | count_delete = 0; 1133 | text_delete = ''; 1134 | text_insert = ''; 1135 | break; 1136 | } 1137 | } 1138 | if (diffs[diffs.length - 1][1] === '') { 1139 | diffs.pop(); // Remove the dummy entry at the end. 1140 | } 1141 | 1142 | // Second pass: look for single edits surrounded on both sides by equalities 1143 | // which can be shifted sideways to eliminate an equality. 1144 | // e.g: ABAC -> ABAC 1145 | var changes = false; 1146 | pointer = 1; 1147 | // Intentionally ignore the first and last element (don't need checking). 1148 | while (pointer < diffs.length - 1) { 1149 | if (diffs[pointer - 1][0] == DIFF_EQUAL && 1150 | diffs[pointer + 1][0] == DIFF_EQUAL) { 1151 | // This is a single edit surrounded by equalities. 1152 | if (diffs[pointer][1].substring(diffs[pointer][1].length - 1153 | diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { 1154 | // Shift the edit over the previous equality. 1155 | diffs[pointer][1] = diffs[pointer - 1][1] + 1156 | diffs[pointer][1].substring(0, diffs[pointer][1].length - 1157 | diffs[pointer - 1][1].length); 1158 | diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; 1159 | diffs.splice(pointer - 1, 1); 1160 | changes = true; 1161 | } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == 1162 | diffs[pointer + 1][1]) { 1163 | // Shift the edit over the next equality. 1164 | diffs[pointer - 1][1] += diffs[pointer + 1][1]; 1165 | diffs[pointer][1] = 1166 | diffs[pointer][1].substring(diffs[pointer + 1][1].length) + 1167 | diffs[pointer + 1][1]; 1168 | diffs.splice(pointer + 1, 1); 1169 | changes = true; 1170 | } 1171 | } 1172 | pointer++; 1173 | } 1174 | // If shifts were made, the diff needs reordering and another shift sweep. 1175 | if (changes) { 1176 | this.diff_cleanupMerge(diffs); 1177 | } 1178 | }; 1179 | 1180 | 1181 | /** 1182 | * loc is a location in text1, compute and return the equivalent location in 1183 | * text2. 1184 | * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 1185 | * @param {!Array.} diffs Array of diff tuples. 1186 | * @param {number} loc Location within text1. 1187 | * @return {number} Location within text2. 1188 | */ 1189 | diff_match_patch.prototype.diff_xIndex = function(diffs, loc) { 1190 | var chars1 = 0; 1191 | var chars2 = 0; 1192 | var last_chars1 = 0; 1193 | var last_chars2 = 0; 1194 | var x; 1195 | for (x = 0; x < diffs.length; x++) { 1196 | if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion. 1197 | chars1 += diffs[x][1].length; 1198 | } 1199 | if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion. 1200 | chars2 += diffs[x][1].length; 1201 | } 1202 | if (chars1 > loc) { // Overshot the location. 1203 | break; 1204 | } 1205 | last_chars1 = chars1; 1206 | last_chars2 = chars2; 1207 | } 1208 | // Was the location was deleted? 1209 | if (diffs.length != x && diffs[x][0] === DIFF_DELETE) { 1210 | return last_chars2; 1211 | } 1212 | // Add the remaining character length. 1213 | return last_chars2 + (loc - last_chars1); 1214 | }; 1215 | 1216 | 1217 | /** 1218 | * Convert a diff array into a pretty HTML report. 1219 | * @param {!Array.} diffs Array of diff tuples. 1220 | * @return {string} HTML representation. 1221 | */ 1222 | diff_match_patch.prototype.diff_prettyHtml = function(diffs) { 1223 | var html = []; 1224 | var pattern_amp = /&/g; 1225 | var pattern_lt = //g; 1227 | var pattern_para = /\n/g; 1228 | for (var x = 0; x < diffs.length; x++) { 1229 | var op = diffs[x][0]; // Operation (insert, delete, equal) 1230 | var data = diffs[x][1]; // Text of change. 1231 | var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<') 1232 | .replace(pattern_gt, '>').replace(pattern_para, '¶
'); 1233 | switch (op) { 1234 | case DIFF_INSERT: 1235 | html[x] = '' + text + ''; 1236 | break; 1237 | case DIFF_DELETE: 1238 | html[x] = '' + text + ''; 1239 | break; 1240 | case DIFF_EQUAL: 1241 | html[x] = '' + text + ''; 1242 | break; 1243 | } 1244 | } 1245 | return html.join(''); 1246 | }; 1247 | 1248 | 1249 | /** 1250 | * Compute and return the source text (all equalities and deletions). 1251 | * @param {!Array.} diffs Array of diff tuples. 1252 | * @return {string} Source text. 1253 | */ 1254 | diff_match_patch.prototype.diff_text1 = function(diffs) { 1255 | var text = []; 1256 | for (var x = 0; x < diffs.length; x++) { 1257 | if (diffs[x][0] !== DIFF_INSERT) { 1258 | text[x] = diffs[x][1]; 1259 | } 1260 | } 1261 | return text.join(''); 1262 | }; 1263 | 1264 | 1265 | /** 1266 | * Compute and return the destination text (all equalities and insertions). 1267 | * @param {!Array.} diffs Array of diff tuples. 1268 | * @return {string} Destination text. 1269 | */ 1270 | diff_match_patch.prototype.diff_text2 = function(diffs) { 1271 | var text = []; 1272 | for (var x = 0; x < diffs.length; x++) { 1273 | if (diffs[x][0] !== DIFF_DELETE) { 1274 | text[x] = diffs[x][1]; 1275 | } 1276 | } 1277 | return text.join(''); 1278 | }; 1279 | 1280 | 1281 | /** 1282 | * Compute the Levenshtein distance; the number of inserted, deleted or 1283 | * substituted characters. 1284 | * @param {!Array.} diffs Array of diff tuples. 1285 | * @return {number} Number of changes. 1286 | */ 1287 | diff_match_patch.prototype.diff_levenshtein = function(diffs) { 1288 | var levenshtein = 0; 1289 | var insertions = 0; 1290 | var deletions = 0; 1291 | for (var x = 0; x < diffs.length; x++) { 1292 | var op = diffs[x][0]; 1293 | var data = diffs[x][1]; 1294 | switch (op) { 1295 | case DIFF_INSERT: 1296 | insertions += data.length; 1297 | break; 1298 | case DIFF_DELETE: 1299 | deletions += data.length; 1300 | break; 1301 | case DIFF_EQUAL: 1302 | // A deletion and an insertion is one substitution. 1303 | levenshtein += Math.max(insertions, deletions); 1304 | insertions = 0; 1305 | deletions = 0; 1306 | break; 1307 | } 1308 | } 1309 | levenshtein += Math.max(insertions, deletions); 1310 | return levenshtein; 1311 | }; 1312 | 1313 | 1314 | /** 1315 | * Crush the diff into an encoded string which describes the operations 1316 | * required to transform text1 into text2. 1317 | * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. 1318 | * Operations are tab-separated. Inserted text is escaped using %xx notation. 1319 | * @param {!Array.} diffs Array of diff tuples. 1320 | * @return {string} Delta text. 1321 | */ 1322 | diff_match_patch.prototype.diff_toDelta = function(diffs) { 1323 | var text = []; 1324 | for (var x = 0; x < diffs.length; x++) { 1325 | switch (diffs[x][0]) { 1326 | case DIFF_INSERT: 1327 | text[x] = '+' + encodeURI(diffs[x][1]); 1328 | break; 1329 | case DIFF_DELETE: 1330 | text[x] = '-' + diffs[x][1].length; 1331 | break; 1332 | case DIFF_EQUAL: 1333 | text[x] = '=' + diffs[x][1].length; 1334 | break; 1335 | } 1336 | } 1337 | return text.join('\t').replace(/%20/g, ' '); 1338 | }; 1339 | 1340 | 1341 | /** 1342 | * Given the original text1, and an encoded string which describes the 1343 | * operations required to transform text1 into text2, compute the full diff. 1344 | * @param {string} text1 Source string for the diff. 1345 | * @param {string} delta Delta text. 1346 | * @return {!Array.} Array of diff tuples. 1347 | * @throws {!Error} If invalid input. 1348 | */ 1349 | diff_match_patch.prototype.diff_fromDelta = function(text1, delta) { 1350 | var diffs = []; 1351 | var diffsLength = 0; // Keeping our own length var is faster in JS. 1352 | var pointer = 0; // Cursor in text1 1353 | var tokens = delta.split(/\t/g); 1354 | for (var x = 0; x < tokens.length; x++) { 1355 | // Each token begins with a one character parameter which specifies the 1356 | // operation of this token (delete, insert, equality). 1357 | var param = tokens[x].substring(1); 1358 | switch (tokens[x].charAt(0)) { 1359 | case '+': 1360 | try { 1361 | diffs[diffsLength++] = [DIFF_INSERT, decodeURI(param)]; 1362 | } catch (ex) { 1363 | // Malformed URI sequence. 1364 | throw new Error('Illegal escape in diff_fromDelta: ' + param); 1365 | } 1366 | break; 1367 | case '-': 1368 | // Fall through. 1369 | case '=': 1370 | var n = parseInt(param, 10); 1371 | if (isNaN(n) || n < 0) { 1372 | throw new Error('Invalid number in diff_fromDelta: ' + param); 1373 | } 1374 | var text = text1.substring(pointer, pointer += n); 1375 | if (tokens[x].charAt(0) == '=') { 1376 | diffs[diffsLength++] = [DIFF_EQUAL, text]; 1377 | } else { 1378 | diffs[diffsLength++] = [DIFF_DELETE, text]; 1379 | } 1380 | break; 1381 | default: 1382 | // Blank tokens are ok (from a trailing \t). 1383 | // Anything else is an error. 1384 | if (tokens[x]) { 1385 | throw new Error('Invalid diff operation in diff_fromDelta: ' + 1386 | tokens[x]); 1387 | } 1388 | } 1389 | } 1390 | if (pointer != text1.length) { 1391 | throw new Error('Delta length (' + pointer + 1392 | ') does not equal source text length (' + text1.length + ').'); 1393 | } 1394 | return diffs; 1395 | }; 1396 | 1397 | 1398 | // MATCH FUNCTIONS 1399 | 1400 | 1401 | /** 1402 | * Locate the best instance of 'pattern' in 'text' near 'loc'. 1403 | * @param {string} text The text to search. 1404 | * @param {string} pattern The pattern to search for. 1405 | * @param {number} loc The location to search around. 1406 | * @return {number} Best match index or -1. 1407 | */ 1408 | diff_match_patch.prototype.match_main = function(text, pattern, loc) { 1409 | // Check for null inputs. 1410 | if (text == null || pattern == null || loc == null) { 1411 | throw new Error('Null input. (match_main)'); 1412 | } 1413 | 1414 | loc = Math.max(0, Math.min(loc, text.length)); 1415 | if (text == pattern) { 1416 | // Shortcut (potentially not guaranteed by the algorithm) 1417 | return 0; 1418 | } else if (!text.length) { 1419 | // Nothing to match. 1420 | return -1; 1421 | } else if (text.substring(loc, loc + pattern.length) == pattern) { 1422 | // Perfect match at the perfect spot! (Includes case of null pattern) 1423 | return loc; 1424 | } else { 1425 | // Do a fuzzy compare. 1426 | return this.match_bitap_(text, pattern, loc); 1427 | } 1428 | }; 1429 | 1430 | 1431 | /** 1432 | * Locate the best instance of 'pattern' in 'text' near 'loc' using the 1433 | * Bitap algorithm. 1434 | * @param {string} text The text to search. 1435 | * @param {string} pattern The pattern to search for. 1436 | * @param {number} loc The location to search around. 1437 | * @return {number} Best match index or -1. 1438 | * @private 1439 | */ 1440 | diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) { 1441 | if (pattern.length > this.Match_MaxBits) { 1442 | throw new Error('Pattern too long for this browser.'); 1443 | } 1444 | 1445 | // Initialise the alphabet. 1446 | var s = this.match_alphabet_(pattern); 1447 | 1448 | var dmp = this; // 'this' becomes 'window' in a closure. 1449 | 1450 | /** 1451 | * Compute and return the score for a match with e errors and x location. 1452 | * Accesses loc and pattern through being a closure. 1453 | * @param {number} e Number of errors in match. 1454 | * @param {number} x Location of match. 1455 | * @return {number} Overall score for match (0.0 = good, 1.0 = bad). 1456 | * @private 1457 | */ 1458 | function match_bitapScore_(e, x) { 1459 | var accuracy = e / pattern.length; 1460 | var proximity = Math.abs(loc - x); 1461 | if (!dmp.Match_Distance) { 1462 | // Dodge divide by zero error. 1463 | return proximity ? 1.0 : accuracy; 1464 | } 1465 | return accuracy + (proximity / dmp.Match_Distance); 1466 | } 1467 | 1468 | // Highest score beyond which we give up. 1469 | var score_threshold = this.Match_Threshold; 1470 | // Is there a nearby exact match? (speedup) 1471 | var best_loc = text.indexOf(pattern, loc); 1472 | if (best_loc != -1) { 1473 | score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); 1474 | // What about in the other direction? (speedup) 1475 | best_loc = text.lastIndexOf(pattern, loc + pattern.length); 1476 | if (best_loc != -1) { 1477 | score_threshold = 1478 | Math.min(match_bitapScore_(0, best_loc), score_threshold); 1479 | } 1480 | } 1481 | 1482 | // Initialise the bit arrays. 1483 | var matchmask = 1 << (pattern.length - 1); 1484 | best_loc = -1; 1485 | 1486 | var bin_min, bin_mid; 1487 | var bin_max = pattern.length + text.length; 1488 | var last_rd; 1489 | for (var d = 0; d < pattern.length; d++) { 1490 | // Scan for the best match; each iteration allows for one more error. 1491 | // Run a binary search to determine how far from 'loc' we can stray at this 1492 | // error level. 1493 | bin_min = 0; 1494 | bin_mid = bin_max; 1495 | while (bin_min < bin_mid) { 1496 | if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { 1497 | bin_min = bin_mid; 1498 | } else { 1499 | bin_max = bin_mid; 1500 | } 1501 | bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); 1502 | } 1503 | // Use the result from this iteration as the maximum for the next. 1504 | bin_max = bin_mid; 1505 | var start = Math.max(1, loc - bin_mid + 1); 1506 | var finish = Math.min(loc + bin_mid, text.length) + pattern.length; 1507 | 1508 | var rd = Array(finish + 2); 1509 | rd[finish + 1] = (1 << d) - 1; 1510 | for (var j = finish; j >= start; j--) { 1511 | // The alphabet (s) is a sparse hash, so the following line generates 1512 | // warnings. 1513 | var charMatch = s[text.charAt(j - 1)]; 1514 | if (d === 0) { // First pass: exact match. 1515 | rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; 1516 | } else { // Subsequent passes: fuzzy match. 1517 | rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | 1518 | (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | 1519 | last_rd[j + 1]; 1520 | } 1521 | if (rd[j] & matchmask) { 1522 | var score = match_bitapScore_(d, j - 1); 1523 | // This match will almost certainly be better than any existing match. 1524 | // But check anyway. 1525 | if (score <= score_threshold) { 1526 | // Told you so. 1527 | score_threshold = score; 1528 | best_loc = j - 1; 1529 | if (best_loc > loc) { 1530 | // When passing loc, don't exceed our current distance from loc. 1531 | start = Math.max(1, 2 * loc - best_loc); 1532 | } else { 1533 | // Already passed loc, downhill from here on in. 1534 | break; 1535 | } 1536 | } 1537 | } 1538 | } 1539 | // No hope for a (better) match at greater error levels. 1540 | if (match_bitapScore_(d + 1, loc) > score_threshold) { 1541 | break; 1542 | } 1543 | last_rd = rd; 1544 | } 1545 | return best_loc; 1546 | }; 1547 | 1548 | 1549 | /** 1550 | * Initialise the alphabet for the Bitap algorithm. 1551 | * @param {string} pattern The text to encode. 1552 | * @return {!Object} Hash of character locations. 1553 | * @private 1554 | */ 1555 | diff_match_patch.prototype.match_alphabet_ = function(pattern) { 1556 | var s = {}; 1557 | for (var i = 0; i < pattern.length; i++) { 1558 | s[pattern.charAt(i)] = 0; 1559 | } 1560 | for (var i = 0; i < pattern.length; i++) { 1561 | s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1); 1562 | } 1563 | return s; 1564 | }; 1565 | 1566 | 1567 | // PATCH FUNCTIONS 1568 | 1569 | 1570 | /** 1571 | * Increase the context until it is unique, 1572 | * but don't let the pattern expand beyond Match_MaxBits. 1573 | * @param {!diff_match_patch.patch_obj} patch The patch to grow. 1574 | * @param {string} text Source text. 1575 | * @private 1576 | */ 1577 | diff_match_patch.prototype.patch_addContext_ = function(patch, text) { 1578 | if (text.length == 0) { 1579 | return; 1580 | } 1581 | var pattern = text.substring(patch.start2, patch.start2 + patch.length1); 1582 | var padding = 0; 1583 | 1584 | // Look for the first and last matches of pattern in text. If two different 1585 | // matches are found, increase the pattern length. 1586 | while (text.indexOf(pattern) != text.lastIndexOf(pattern) && 1587 | pattern.length < this.Match_MaxBits - this.Patch_Margin - 1588 | this.Patch_Margin) { 1589 | padding += this.Patch_Margin; 1590 | pattern = text.substring(patch.start2 - padding, 1591 | patch.start2 + patch.length1 + padding); 1592 | } 1593 | // Add one chunk for good luck. 1594 | padding += this.Patch_Margin; 1595 | 1596 | // Add the prefix. 1597 | var prefix = text.substring(patch.start2 - padding, patch.start2); 1598 | if (prefix) { 1599 | patch.diffs.unshift([DIFF_EQUAL, prefix]); 1600 | } 1601 | // Add the suffix. 1602 | var suffix = text.substring(patch.start2 + patch.length1, 1603 | patch.start2 + patch.length1 + padding); 1604 | if (suffix) { 1605 | patch.diffs.push([DIFF_EQUAL, suffix]); 1606 | } 1607 | 1608 | // Roll back the start points. 1609 | patch.start1 -= prefix.length; 1610 | patch.start2 -= prefix.length; 1611 | // Extend the lengths. 1612 | patch.length1 += prefix.length + suffix.length; 1613 | patch.length2 += prefix.length + suffix.length; 1614 | }; 1615 | 1616 | 1617 | /** 1618 | * Compute a list of patches to turn text1 into text2. 1619 | * Use diffs if provided, otherwise compute it ourselves. 1620 | * There are four ways to call this function, depending on what data is 1621 | * available to the caller: 1622 | * Method 1: 1623 | * a = text1, b = text2 1624 | * Method 2: 1625 | * a = diffs 1626 | * Method 3 (optimal): 1627 | * a = text1, b = diffs 1628 | * Method 4 (deprecated, use method 3): 1629 | * a = text1, b = text2, c = diffs 1630 | * 1631 | * @param {string|!Array.} a text1 (methods 1,3,4) or 1632 | * Array of diff tuples for text1 to text2 (method 2). 1633 | * @param {string|!Array.} opt_b text2 (methods 1,4) or 1634 | * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). 1635 | * @param {string|!Array.} opt_c Array of diff tuples 1636 | * for text1 to text2 (method 4) or undefined (methods 1,2,3). 1637 | * @return {!Array.} Array of Patch objects. 1638 | */ 1639 | diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) { 1640 | var text1, diffs; 1641 | if (typeof a == 'string' && typeof opt_b == 'string' && 1642 | typeof opt_c == 'undefined') { 1643 | // Method 1: text1, text2 1644 | // Compute diffs from text1 and text2. 1645 | text1 = /** @type {string} */(a); 1646 | diffs = this.diff_main(text1, /** @type {string} */(opt_b), true); 1647 | if (diffs.length > 2) { 1648 | this.diff_cleanupSemantic(diffs); 1649 | this.diff_cleanupEfficiency(diffs); 1650 | } 1651 | } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' && 1652 | typeof opt_c == 'undefined') { 1653 | // Method 2: diffs 1654 | // Compute text1 from diffs. 1655 | diffs = /** @type {!Array.} */(a); 1656 | text1 = this.diff_text1(diffs); 1657 | } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' && 1658 | typeof opt_c == 'undefined') { 1659 | // Method 3: text1, diffs 1660 | text1 = /** @type {string} */(a); 1661 | diffs = /** @type {!Array.} */(opt_b); 1662 | } else if (typeof a == 'string' && typeof opt_b == 'string' && 1663 | opt_c && typeof opt_c == 'object') { 1664 | // Method 4: text1, text2, diffs 1665 | // text2 is not used. 1666 | text1 = /** @type {string} */(a); 1667 | diffs = /** @type {!Array.} */(opt_c); 1668 | } else { 1669 | throw new Error('Unknown call format to patch_make.'); 1670 | } 1671 | 1672 | if (diffs.length === 0) { 1673 | return []; // Get rid of the null case. 1674 | } 1675 | var patches = []; 1676 | var patch = new diff_match_patch.patch_obj(); 1677 | var patchDiffLength = 0; // Keeping our own length var is faster in JS. 1678 | var char_count1 = 0; // Number of characters into the text1 string. 1679 | var char_count2 = 0; // Number of characters into the text2 string. 1680 | // Start with text1 (prepatch_text) and apply the diffs until we arrive at 1681 | // text2 (postpatch_text). We recreate the patches one by one to determine 1682 | // context info. 1683 | var prepatch_text = text1; 1684 | var postpatch_text = text1; 1685 | for (var x = 0; x < diffs.length; x++) { 1686 | var diff_type = diffs[x][0]; 1687 | var diff_text = diffs[x][1]; 1688 | 1689 | if (!patchDiffLength && diff_type !== DIFF_EQUAL) { 1690 | // A new patch starts here. 1691 | patch.start1 = char_count1; 1692 | patch.start2 = char_count2; 1693 | } 1694 | 1695 | switch (diff_type) { 1696 | case DIFF_INSERT: 1697 | patch.diffs[patchDiffLength++] = diffs[x]; 1698 | patch.length2 += diff_text.length; 1699 | postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + 1700 | postpatch_text.substring(char_count2); 1701 | break; 1702 | case DIFF_DELETE: 1703 | patch.length1 += diff_text.length; 1704 | patch.diffs[patchDiffLength++] = diffs[x]; 1705 | postpatch_text = postpatch_text.substring(0, char_count2) + 1706 | postpatch_text.substring(char_count2 + 1707 | diff_text.length); 1708 | break; 1709 | case DIFF_EQUAL: 1710 | if (diff_text.length <= 2 * this.Patch_Margin && 1711 | patchDiffLength && diffs.length != x + 1) { 1712 | // Small equality inside a patch. 1713 | patch.diffs[patchDiffLength++] = diffs[x]; 1714 | patch.length1 += diff_text.length; 1715 | patch.length2 += diff_text.length; 1716 | } else if (diff_text.length >= 2 * this.Patch_Margin) { 1717 | // Time for a new patch. 1718 | if (patchDiffLength) { 1719 | this.patch_addContext_(patch, prepatch_text); 1720 | patches.push(patch); 1721 | patch = new diff_match_patch.patch_obj(); 1722 | patchDiffLength = 0; 1723 | // Unlike Unidiff, our patch lists have a rolling context. 1724 | // http://code.google.com/p/google-diff-match-patch/wiki/Unidiff 1725 | // Update prepatch text & pos to reflect the application of the 1726 | // just completed patch. 1727 | prepatch_text = postpatch_text; 1728 | char_count1 = char_count2; 1729 | } 1730 | } 1731 | break; 1732 | } 1733 | 1734 | // Update the current character count. 1735 | if (diff_type !== DIFF_INSERT) { 1736 | char_count1 += diff_text.length; 1737 | } 1738 | if (diff_type !== DIFF_DELETE) { 1739 | char_count2 += diff_text.length; 1740 | } 1741 | } 1742 | // Pick up the leftover patch if not empty. 1743 | if (patchDiffLength) { 1744 | this.patch_addContext_(patch, prepatch_text); 1745 | patches.push(patch); 1746 | } 1747 | 1748 | return patches; 1749 | }; 1750 | 1751 | 1752 | /** 1753 | * Given an array of patches, return another array that is identical. 1754 | * @param {!Array.} patches Array of Patch objects. 1755 | * @return {!Array.} Array of Patch objects. 1756 | */ 1757 | diff_match_patch.prototype.patch_deepCopy = function(patches) { 1758 | // Making deep copies is hard in JavaScript. 1759 | var patchesCopy = []; 1760 | for (var x = 0; x < patches.length; x++) { 1761 | var patch = patches[x]; 1762 | var patchCopy = new diff_match_patch.patch_obj(); 1763 | patchCopy.diffs = []; 1764 | for (var y = 0; y < patch.diffs.length; y++) { 1765 | patchCopy.diffs[y] = patch.diffs[y].slice(); 1766 | } 1767 | patchCopy.start1 = patch.start1; 1768 | patchCopy.start2 = patch.start2; 1769 | patchCopy.length1 = patch.length1; 1770 | patchCopy.length2 = patch.length2; 1771 | patchesCopy[x] = patchCopy; 1772 | } 1773 | return patchesCopy; 1774 | }; 1775 | 1776 | 1777 | /** 1778 | * Merge a set of patches onto the text. Return a patched text, as well 1779 | * as a list of true/false values indicating which patches were applied. 1780 | * @param {!Array.} patches Array of Patch objects. 1781 | * @param {string} text Old text. 1782 | * @return {!Array.>} Two element Array, containing the 1783 | * new text and an array of boolean values. 1784 | */ 1785 | diff_match_patch.prototype.patch_apply = function(patches, text) { 1786 | if (patches.length == 0) { 1787 | return [text, []]; 1788 | } 1789 | 1790 | // Deep copy the patches so that no changes are made to originals. 1791 | patches = this.patch_deepCopy(patches); 1792 | 1793 | var nullPadding = this.patch_addPadding(patches); 1794 | text = nullPadding + text + nullPadding; 1795 | 1796 | this.patch_splitMax(patches); 1797 | // delta keeps track of the offset between the expected and actual location 1798 | // of the previous patch. If there are patches expected at positions 10 and 1799 | // 20, but the first patch was found at 12, delta is 2 and the second patch 1800 | // has an effective expected position of 22. 1801 | var delta = 0; 1802 | var results = []; 1803 | for (var x = 0; x < patches.length; x++) { 1804 | var expected_loc = patches[x].start2 + delta; 1805 | var text1 = this.diff_text1(patches[x].diffs); 1806 | var start_loc; 1807 | var end_loc = -1; 1808 | if (text1.length > this.Match_MaxBits) { 1809 | // patch_splitMax will only provide an oversized pattern in the case of 1810 | // a monster delete. 1811 | start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits), 1812 | expected_loc); 1813 | if (start_loc != -1) { 1814 | end_loc = this.match_main(text, 1815 | text1.substring(text1.length - this.Match_MaxBits), 1816 | expected_loc + text1.length - this.Match_MaxBits); 1817 | if (end_loc == -1 || start_loc >= end_loc) { 1818 | // Can't find valid trailing context. Drop this patch. 1819 | start_loc = -1; 1820 | } 1821 | } 1822 | } else { 1823 | start_loc = this.match_main(text, text1, expected_loc); 1824 | } 1825 | if (start_loc == -1) { 1826 | // No match found. :( 1827 | results[x] = false; 1828 | // Subtract the delta for this failed patch from subsequent patches. 1829 | delta -= patches[x].length2 - patches[x].length1; 1830 | } else { 1831 | // Found a match. :) 1832 | results[x] = true; 1833 | delta = start_loc - expected_loc; 1834 | var text2; 1835 | if (end_loc == -1) { 1836 | text2 = text.substring(start_loc, start_loc + text1.length); 1837 | } else { 1838 | text2 = text.substring(start_loc, end_loc + this.Match_MaxBits); 1839 | } 1840 | if (text1 == text2) { 1841 | // Perfect match, just shove the replacement text in. 1842 | text = text.substring(0, start_loc) + 1843 | this.diff_text2(patches[x].diffs) + 1844 | text.substring(start_loc + text1.length); 1845 | } else { 1846 | // Imperfect match. Run a diff to get a framework of equivalent 1847 | // indices. 1848 | var diffs = this.diff_main(text1, text2, false); 1849 | if (text1.length > this.Match_MaxBits && 1850 | this.diff_levenshtein(diffs) / text1.length > 1851 | this.Patch_DeleteThreshold) { 1852 | // The end points match, but the content is unacceptably bad. 1853 | results[x] = false; 1854 | } else { 1855 | this.diff_cleanupSemanticLossless(diffs); 1856 | var index1 = 0; 1857 | var index2; 1858 | for (var y = 0; y < patches[x].diffs.length; y++) { 1859 | var mod = patches[x].diffs[y]; 1860 | if (mod[0] !== DIFF_EQUAL) { 1861 | index2 = this.diff_xIndex(diffs, index1); 1862 | } 1863 | if (mod[0] === DIFF_INSERT) { // Insertion 1864 | text = text.substring(0, start_loc + index2) + mod[1] + 1865 | text.substring(start_loc + index2); 1866 | } else if (mod[0] === DIFF_DELETE) { // Deletion 1867 | text = text.substring(0, start_loc + index2) + 1868 | text.substring(start_loc + this.diff_xIndex(diffs, 1869 | index1 + mod[1].length)); 1870 | } 1871 | if (mod[0] !== DIFF_DELETE) { 1872 | index1 += mod[1].length; 1873 | } 1874 | } 1875 | } 1876 | } 1877 | } 1878 | } 1879 | // Strip the padding off. 1880 | text = text.substring(nullPadding.length, text.length - nullPadding.length); 1881 | return [text, results]; 1882 | }; 1883 | 1884 | 1885 | /** 1886 | * Add some padding on text start and end so that edges can match something. 1887 | * Intended to be called only from within patch_apply. 1888 | * @param {!Array.} patches Array of Patch objects. 1889 | * @return {string} The padding string added to each side. 1890 | */ 1891 | diff_match_patch.prototype.patch_addPadding = function(patches) { 1892 | var paddingLength = this.Patch_Margin; 1893 | var nullPadding = ''; 1894 | for (var x = 1; x <= paddingLength; x++) { 1895 | nullPadding += String.fromCharCode(x); 1896 | } 1897 | 1898 | // Bump all the patches forward. 1899 | for (var x = 0; x < patches.length; x++) { 1900 | patches[x].start1 += paddingLength; 1901 | patches[x].start2 += paddingLength; 1902 | } 1903 | 1904 | // Add some padding on start of first diff. 1905 | var patch = patches[0]; 1906 | var diffs = patch.diffs; 1907 | if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) { 1908 | // Add nullPadding equality. 1909 | diffs.unshift([DIFF_EQUAL, nullPadding]); 1910 | patch.start1 -= paddingLength; // Should be 0. 1911 | patch.start2 -= paddingLength; // Should be 0. 1912 | patch.length1 += paddingLength; 1913 | patch.length2 += paddingLength; 1914 | } else if (paddingLength > diffs[0][1].length) { 1915 | // Grow first equality. 1916 | var extraLength = paddingLength - diffs[0][1].length; 1917 | diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1]; 1918 | patch.start1 -= extraLength; 1919 | patch.start2 -= extraLength; 1920 | patch.length1 += extraLength; 1921 | patch.length2 += extraLength; 1922 | } 1923 | 1924 | // Add some padding on end of last diff. 1925 | patch = patches[patches.length - 1]; 1926 | diffs = patch.diffs; 1927 | if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) { 1928 | // Add nullPadding equality. 1929 | diffs.push([DIFF_EQUAL, nullPadding]); 1930 | patch.length1 += paddingLength; 1931 | patch.length2 += paddingLength; 1932 | } else if (paddingLength > diffs[diffs.length - 1][1].length) { 1933 | // Grow last equality. 1934 | var extraLength = paddingLength - diffs[diffs.length - 1][1].length; 1935 | diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength); 1936 | patch.length1 += extraLength; 1937 | patch.length2 += extraLength; 1938 | } 1939 | 1940 | return nullPadding; 1941 | }; 1942 | 1943 | 1944 | /** 1945 | * Look through the patches and break up any which are longer than the maximum 1946 | * limit of the match algorithm. 1947 | * Intended to be called only from within patch_apply. 1948 | * @param {!Array.} patches Array of Patch objects. 1949 | */ 1950 | diff_match_patch.prototype.patch_splitMax = function(patches) { 1951 | var patch_size = this.Match_MaxBits; 1952 | for (var x = 0; x < patches.length; x++) { 1953 | if (patches[x].length1 <= patch_size) { 1954 | continue; 1955 | } 1956 | var bigpatch = patches[x]; 1957 | // Remove the big old patch. 1958 | patches.splice(x--, 1); 1959 | var start1 = bigpatch.start1; 1960 | var start2 = bigpatch.start2; 1961 | var precontext = ''; 1962 | while (bigpatch.diffs.length !== 0) { 1963 | // Create one of several smaller patches. 1964 | var patch = new diff_match_patch.patch_obj(); 1965 | var empty = true; 1966 | patch.start1 = start1 - precontext.length; 1967 | patch.start2 = start2 - precontext.length; 1968 | if (precontext !== '') { 1969 | patch.length1 = patch.length2 = precontext.length; 1970 | patch.diffs.push([DIFF_EQUAL, precontext]); 1971 | } 1972 | while (bigpatch.diffs.length !== 0 && 1973 | patch.length1 < patch_size - this.Patch_Margin) { 1974 | var diff_type = bigpatch.diffs[0][0]; 1975 | var diff_text = bigpatch.diffs[0][1]; 1976 | if (diff_type === DIFF_INSERT) { 1977 | // Insertions are harmless. 1978 | patch.length2 += diff_text.length; 1979 | start2 += diff_text.length; 1980 | patch.diffs.push(bigpatch.diffs.shift()); 1981 | empty = false; 1982 | } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 && 1983 | patch.diffs[0][0] == DIFF_EQUAL && 1984 | diff_text.length > 2 * patch_size) { 1985 | // This is a large deletion. Let it pass in one chunk. 1986 | patch.length1 += diff_text.length; 1987 | start1 += diff_text.length; 1988 | empty = false; 1989 | patch.diffs.push([diff_type, diff_text]); 1990 | bigpatch.diffs.shift(); 1991 | } else { 1992 | // Deletion or equality. Only take as much as we can stomach. 1993 | diff_text = diff_text.substring(0, 1994 | patch_size - patch.length1 - this.Patch_Margin); 1995 | patch.length1 += diff_text.length; 1996 | start1 += diff_text.length; 1997 | if (diff_type === DIFF_EQUAL) { 1998 | patch.length2 += diff_text.length; 1999 | start2 += diff_text.length; 2000 | } else { 2001 | empty = false; 2002 | } 2003 | patch.diffs.push([diff_type, diff_text]); 2004 | if (diff_text == bigpatch.diffs[0][1]) { 2005 | bigpatch.diffs.shift(); 2006 | } else { 2007 | bigpatch.diffs[0][1] = 2008 | bigpatch.diffs[0][1].substring(diff_text.length); 2009 | } 2010 | } 2011 | } 2012 | // Compute the head context for the next patch. 2013 | precontext = this.diff_text2(patch.diffs); 2014 | precontext = 2015 | precontext.substring(precontext.length - this.Patch_Margin); 2016 | // Append the end context for this patch. 2017 | var postcontext = this.diff_text1(bigpatch.diffs) 2018 | .substring(0, this.Patch_Margin); 2019 | if (postcontext !== '') { 2020 | patch.length1 += postcontext.length; 2021 | patch.length2 += postcontext.length; 2022 | if (patch.diffs.length !== 0 && 2023 | patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) { 2024 | patch.diffs[patch.diffs.length - 1][1] += postcontext; 2025 | } else { 2026 | patch.diffs.push([DIFF_EQUAL, postcontext]); 2027 | } 2028 | } 2029 | if (!empty) { 2030 | patches.splice(++x, 0, patch); 2031 | } 2032 | } 2033 | } 2034 | }; 2035 | 2036 | 2037 | /** 2038 | * Take a list of patches and return a textual representation. 2039 | * @param {!Array.} patches Array of Patch objects. 2040 | * @return {string} Text representation of patches. 2041 | */ 2042 | diff_match_patch.prototype.patch_toText = function(patches) { 2043 | var text = []; 2044 | for (var x = 0; x < patches.length; x++) { 2045 | text[x] = patches[x]; 2046 | } 2047 | return text.join(''); 2048 | }; 2049 | 2050 | 2051 | /** 2052 | * Parse a textual representation of patches and return a list of Patch objects. 2053 | * @param {string} textline Text representation of patches. 2054 | * @return {!Array.} Array of Patch objects. 2055 | * @throws {!Error} If invalid input. 2056 | */ 2057 | diff_match_patch.prototype.patch_fromText = function(textline) { 2058 | var patches = []; 2059 | if (!textline) { 2060 | return patches; 2061 | } 2062 | var text = textline.split('\n'); 2063 | var textPointer = 0; 2064 | var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; 2065 | while (textPointer < text.length) { 2066 | var m = text[textPointer].match(patchHeader); 2067 | if (!m) { 2068 | throw new Error('Invalid patch string: ' + text[textPointer]); 2069 | } 2070 | var patch = new diff_match_patch.patch_obj(); 2071 | patches.push(patch); 2072 | patch.start1 = parseInt(m[1], 10); 2073 | if (m[2] === '') { 2074 | patch.start1--; 2075 | patch.length1 = 1; 2076 | } else if (m[2] == '0') { 2077 | patch.length1 = 0; 2078 | } else { 2079 | patch.start1--; 2080 | patch.length1 = parseInt(m[2], 10); 2081 | } 2082 | 2083 | patch.start2 = parseInt(m[3], 10); 2084 | if (m[4] === '') { 2085 | patch.start2--; 2086 | patch.length2 = 1; 2087 | } else if (m[4] == '0') { 2088 | patch.length2 = 0; 2089 | } else { 2090 | patch.start2--; 2091 | patch.length2 = parseInt(m[4], 10); 2092 | } 2093 | textPointer++; 2094 | 2095 | while (textPointer < text.length) { 2096 | var sign = text[textPointer].charAt(0); 2097 | try { 2098 | var line = decodeURI(text[textPointer].substring(1)); 2099 | } catch (ex) { 2100 | // Malformed URI sequence. 2101 | throw new Error('Illegal escape in patch_fromText: ' + line); 2102 | } 2103 | if (sign == '-') { 2104 | // Deletion. 2105 | patch.diffs.push([DIFF_DELETE, line]); 2106 | } else if (sign == '+') { 2107 | // Insertion. 2108 | patch.diffs.push([DIFF_INSERT, line]); 2109 | } else if (sign == ' ') { 2110 | // Minor equality. 2111 | patch.diffs.push([DIFF_EQUAL, line]); 2112 | } else if (sign == '@') { 2113 | // Start of next patch. 2114 | break; 2115 | } else if (sign === '') { 2116 | // Blank line? Whatever. 2117 | } else { 2118 | // WTF? 2119 | throw new Error('Invalid patch mode "' + sign + '" in: ' + line); 2120 | } 2121 | textPointer++; 2122 | } 2123 | } 2124 | return patches; 2125 | }; 2126 | 2127 | 2128 | /** 2129 | * Class representing one patch operation. 2130 | * @constructor 2131 | */ 2132 | diff_match_patch.patch_obj = function() { 2133 | /** @type {!Array.} */ 2134 | this.diffs = []; 2135 | /** @type {?number} */ 2136 | this.start1 = null; 2137 | /** @type {?number} */ 2138 | this.start2 = null; 2139 | /** @type {number} */ 2140 | this.length1 = 0; 2141 | /** @type {number} */ 2142 | this.length2 = 0; 2143 | }; 2144 | 2145 | 2146 | /** 2147 | * Emmulate GNU diff's format. 2148 | * Header: @@ -382,8 +481,9 @@ 2149 | * Indicies are printed as 1-based, not 0-based. 2150 | * @return {string} The GNU diff string. 2151 | */ 2152 | diff_match_patch.patch_obj.prototype.toString = function() { 2153 | var coords1, coords2; 2154 | if (this.length1 === 0) { 2155 | coords1 = this.start1 + ',0'; 2156 | } else if (this.length1 == 1) { 2157 | coords1 = this.start1 + 1; 2158 | } else { 2159 | coords1 = (this.start1 + 1) + ',' + this.length1; 2160 | } 2161 | if (this.length2 === 0) { 2162 | coords2 = this.start2 + ',0'; 2163 | } else if (this.length2 == 1) { 2164 | coords2 = this.start2 + 1; 2165 | } else { 2166 | coords2 = (this.start2 + 1) + ',' + this.length2; 2167 | } 2168 | var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n']; 2169 | var op; 2170 | // Escape the body of the patch with %xx notation. 2171 | for (var x = 0; x < this.diffs.length; x++) { 2172 | switch (this.diffs[x][0]) { 2173 | case DIFF_INSERT: 2174 | op = '+'; 2175 | break; 2176 | case DIFF_DELETE: 2177 | op = '-'; 2178 | break; 2179 | case DIFF_EQUAL: 2180 | op = ' '; 2181 | break; 2182 | } 2183 | text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n'; 2184 | } 2185 | return text.join('').replace(/%20/g, ' '); 2186 | }; 2187 | 2188 | 2189 | // Export these global variables so that they survive Google's JS compiler. 2190 | // In a browser, 'this' will be 'window'. 2191 | // Users of node.js should 'require' the uncompressed version since Google's 2192 | // JS compiler may break the following exports for non-browser environments. 2193 | this['diff_match_patch'] = diff_match_patch; 2194 | this['DIFF_DELETE'] = DIFF_DELETE; 2195 | this['DIFF_INSERT'] = DIFF_INSERT; 2196 | this['DIFF_EQUAL'] = DIFF_EQUAL; 2197 | -------------------------------------------------------------------------------- /libs/jsondiff-1.0.js: -------------------------------------------------------------------------------- 1 | // Generated by CoffeeScript 1.6.3 2 | (function() { 3 | var jsondiff, 4 | __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, 5 | __hasProp = {}.hasOwnProperty; 6 | 7 | jsondiff = (function() { 8 | var DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT; 9 | 10 | DIFF_INSERT = 1; 11 | 12 | DIFF_DELETE = -1; 13 | 14 | DIFF_EQUAL = 0; 15 | 16 | function jsondiff() { 17 | this.patch_apply_with_offsets = __bind(this.patch_apply_with_offsets, this); 18 | this.transform_object_diff = __bind(this.transform_object_diff, this); 19 | this.transform_list_diff_dmp = __bind(this.transform_list_diff_dmp, this); 20 | this.transform_list_diff = __bind(this.transform_list_diff, this); 21 | this.apply_diff = __bind(this.apply_diff, this); 22 | this.apply_object_diff_with_offsets = __bind(this.apply_object_diff_with_offsets, this); 23 | this.apply_object_diff = __bind(this.apply_object_diff, this); 24 | this.apply_list_diff_dmp = __bind(this.apply_list_diff_dmp, this); 25 | this.apply_list_diff = __bind(this.apply_list_diff, this); 26 | this.diff = __bind(this.diff, this); 27 | this.object_diff = __bind(this.object_diff, this); 28 | this._text_to_array = __bind(this._text_to_array, this); 29 | this._serialize_to_text = __bind(this._serialize_to_text, this); 30 | this.list_diff_dmp = __bind(this.list_diff_dmp, this); 31 | this.list_diff = __bind(this.list_diff, this); 32 | this._common_suffix = __bind(this._common_suffix, this); 33 | this._common_prefix = __bind(this._common_prefix, this); 34 | this.object_equals = __bind(this.object_equals, this); 35 | this.list_equals = __bind(this.list_equals, this); 36 | this.equals = __bind(this.equals, this); 37 | this.deepCopy = __bind(this.deepCopy, this); 38 | this.typeOf = __bind(this.typeOf, this); 39 | this.entries = __bind(this.entries, this); 40 | this.dmp = new diff_match_patch(); 41 | } 42 | 43 | jsondiff.prototype.entries = function(obj) { 44 | var key, n, value; 45 | n = 0; 46 | for (key in obj) { 47 | if (!__hasProp.call(obj, key)) continue; 48 | value = obj[key]; 49 | n++; 50 | } 51 | return n; 52 | }; 53 | 54 | jsondiff.prototype.typeOf = function(value) { 55 | var s; 56 | s = typeof value; 57 | if (s === 'object') { 58 | if (value) { 59 | if (typeof value.length === 'number' && typeof value.splice === 'function' && !value.propertyIsEnumerable('length')) { 60 | s = 'array'; 61 | } 62 | } else { 63 | s = 'null'; 64 | } 65 | } 66 | return s; 67 | }; 68 | 69 | jsondiff.prototype.deepCopy = function(obj) { 70 | return JSON.parse(JSON.stringify(obj)); 71 | }; 72 | 73 | jsondiff.prototype.equals = function(a, b) { 74 | var typea, typeb; 75 | typea = this.typeOf(a); 76 | typeb = this.typeOf(b); 77 | if (typea === 'boolean' && typeb === 'number') { 78 | return Number(a) === b; 79 | } 80 | if (typea === 'number' && typeb === 'boolean') { 81 | return Number(b) === a; 82 | } 83 | if (typea !== typeb) { 84 | return false; 85 | } 86 | if (typea === 'array') { 87 | return this.list_equals(a, b); 88 | } else if (typea === 'object') { 89 | return this.object_equals(a, b); 90 | } else { 91 | return a === b; 92 | } 93 | }; 94 | 95 | jsondiff.prototype.list_equals = function(a, b) { 96 | var alength, i, _i; 97 | alength = a.length; 98 | if (alength !== b.length) { 99 | return false; 100 | } 101 | for (i = _i = 0; 0 <= alength ? _i < alength : _i > alength; i = 0 <= alength ? ++_i : --_i) { 102 | if (!this.equals(a[i], b[i])) { 103 | return false; 104 | } 105 | } 106 | return true; 107 | }; 108 | 109 | jsondiff.prototype.object_equals = function(a, b) { 110 | var key; 111 | for (key in a) { 112 | if (!__hasProp.call(a, key)) continue; 113 | if (!(key in b)) { 114 | return false; 115 | } 116 | if (!this.equals(a[key], b[key])) { 117 | return false; 118 | } 119 | } 120 | for (key in b) { 121 | if (!__hasProp.call(b, key)) continue; 122 | if (!(key in a)) { 123 | return false; 124 | } 125 | } 126 | return true; 127 | }; 128 | 129 | jsondiff.prototype._common_prefix = function(a, b) { 130 | var i, minlen, _i; 131 | minlen = Math.min(a.length, b.length); 132 | for (i = _i = 0; 0 <= minlen ? _i < minlen : _i > minlen; i = 0 <= minlen ? ++_i : --_i) { 133 | if (!this.equals(a[i], b[i])) { 134 | return i; 135 | } 136 | } 137 | return minlen; 138 | }; 139 | 140 | jsondiff.prototype._common_suffix = function(a, b) { 141 | var i, lena, lenb, minlen, _i; 142 | lena = a.length; 143 | lenb = b.length; 144 | minlen = Math.min(a.length, b.length); 145 | if (minlen === 0) { 146 | return 0; 147 | } 148 | for (i = _i = 0; 0 <= minlen ? _i < minlen : _i > minlen; i = 0 <= minlen ? ++_i : --_i) { 149 | if (!this.equals(a[lena - i - 1], b[lenb - i - 1])) { 150 | return i; 151 | } 152 | } 153 | return minlen; 154 | }; 155 | 156 | jsondiff.prototype.list_diff = function(a, b, policy) { 157 | var diffs, i, lena, lenb, maxlen, prefix_len, suffix_len, _i; 158 | if ((policy != null) && 'item' in policy) { 159 | policy = policy['item']; 160 | } else { 161 | policy = null; 162 | } 163 | diffs = {}; 164 | lena = a.length; 165 | lenb = b.length; 166 | prefix_len = this._common_prefix(a, b); 167 | suffix_len = this._common_suffix(a, b); 168 | a = a.slice(prefix_len, lena - suffix_len); 169 | b = b.slice(prefix_len, lenb - suffix_len); 170 | lena = a.length; 171 | lenb = b.length; 172 | maxlen = Math.max(lena, lenb); 173 | for (i = _i = 0; 0 <= maxlen ? _i <= maxlen : _i >= maxlen; i = 0 <= maxlen ? ++_i : --_i) { 174 | if (i < lena && i < lenb) { 175 | if (!this.equals(a[i], b[i])) { 176 | diffs[i + prefix_len] = this.diff(a[i], b[i], policy); 177 | } 178 | } else if (i < lena) { 179 | diffs[i + prefix_len] = { 180 | 'o': '-' 181 | }; 182 | } else if (i < lenb) { 183 | diffs[i + prefix_len] = { 184 | 'o': '+', 185 | 'v': b[i] 186 | }; 187 | } 188 | } 189 | return diffs; 190 | }; 191 | 192 | jsondiff.prototype.list_diff_dmp = function(a, b, policy) { 193 | var atext, btext, delta, diffs, lena, lenb; 194 | lena = a.length; 195 | lenb = b.length; 196 | atext = this._serialize_to_text(a); 197 | btext = this._serialize_to_text(b); 198 | diffs = this.dmp.diff_lineMode_(atext, btext); 199 | this.dmp.diff_cleanupEfficiency(diffs); 200 | delta = this.dmp.diff_toDelta(diffs); 201 | return delta; 202 | }; 203 | 204 | jsondiff.prototype._serialize_to_text = function(a) { 205 | var i, s, _i, _len; 206 | s = ''; 207 | for (_i = 0, _len = a.length; _i < _len; _i++) { 208 | i = a[_i]; 209 | s += "" + (JSON.stringify(i)) + "\n"; 210 | } 211 | return s; 212 | }; 213 | 214 | jsondiff.prototype._text_to_array = function(s) { 215 | var a, sa, x; 216 | a = []; 217 | sa = s.split("\n"); 218 | a = (function() { 219 | var _i, _len, _results; 220 | _results = []; 221 | for (_i = 0, _len = sa.length; _i < _len; _i++) { 222 | x = sa[_i]; 223 | if (x.length > 0) { 224 | _results.push(JSON.parse(x)); 225 | } 226 | } 227 | return _results; 228 | })(); 229 | return a; 230 | }; 231 | 232 | jsondiff.prototype.object_diff = function(a, b, policy) { 233 | var diffs, key, sub_policy; 234 | diffs = {}; 235 | if ((policy != null) && 'attributes' in policy) { 236 | policy = policy['attributes']; 237 | } 238 | if ((a == null) || (b == null)) { 239 | return {}; 240 | } 241 | for (key in a) { 242 | if (!__hasProp.call(a, key)) continue; 243 | if ((policy != null) && key in policy) { 244 | sub_policy = policy[key]; 245 | } else { 246 | sub_policy = null; 247 | } 248 | if (key in b) { 249 | if (!this.equals(a[key], b[key])) { 250 | diffs[key] = this.diff(a[key], b[key], sub_policy); 251 | } 252 | } else { 253 | diffs[key] = { 254 | 'o': '-' 255 | }; 256 | } 257 | } 258 | for (key in b) { 259 | if (!__hasProp.call(b, key)) continue; 260 | if (!(key in a) && (b[key] != null)) { 261 | diffs[key] = { 262 | 'o': '+', 263 | 'v': b[key] 264 | }; 265 | } 266 | } 267 | return diffs; 268 | }; 269 | 270 | jsondiff.prototype.diff = function(a, b, policy) { 271 | var diffs, otype, typea; 272 | if (this.equals(a, b)) { 273 | return {}; 274 | } 275 | if ((policy != null) && 'attributes' in policy) { 276 | policy = policy['attributes']; 277 | } 278 | if ((policy != null) && 'otype' in policy) { 279 | otype = policy['otype']; 280 | switch (otype) { 281 | case 'replace': 282 | return { 283 | 'o': 'r', 284 | 'v': b 285 | }; 286 | case 'list': 287 | return { 288 | 'o': 'L', 289 | 'v': this.list_diff(a, b, policy) 290 | }; 291 | case 'list_dmp': 292 | return { 293 | 'o': 'dL', 294 | 'v': this.list_diff_dmp(a, b, policy) 295 | }; 296 | case 'integer': 297 | return { 298 | 'o': 'I', 299 | 'v': b - a 300 | }; 301 | case 'string': 302 | diffs = this.dmp.diff_main(a, b); 303 | if (diffs.length > 2) { 304 | this.dmp.diff_cleanupEfficiency(diffs); 305 | } 306 | if (diffs.length > 0) { 307 | return { 308 | 'o': 'd', 309 | 'v': this.dmp.diff_toDelta(diffs) 310 | }; 311 | } 312 | } 313 | } 314 | typea = this.typeOf(a); 315 | if (typea !== this.typeOf(b)) { 316 | return { 317 | 'o': 'r', 318 | 'v': b 319 | }; 320 | } 321 | switch (typea) { 322 | case 'boolean': 323 | return { 324 | 'o': 'r', 325 | 'v': b 326 | }; 327 | case 'number': 328 | return { 329 | 'o': 'r', 330 | 'v': b 331 | }; 332 | case 'array': 333 | return { 334 | 'o': 'r', 335 | 'v': b 336 | }; 337 | case 'object': 338 | return { 339 | 'o': 'O', 340 | 'v': this.object_diff(a, b, policy) 341 | }; 342 | case 'string': 343 | diffs = this.dmp.diff_main(a, b); 344 | if (diffs.length > 2) { 345 | this.dmp.diff_cleanupEfficiency(diffs); 346 | } 347 | if (diffs.length > 0) { 348 | return { 349 | 'o': 'd', 350 | 'v': this.dmp.diff_toDelta(diffs) 351 | }; 352 | } 353 | } 354 | return {}; 355 | }; 356 | 357 | jsondiff.prototype.apply_list_diff = function(s, diffs) { 358 | var deleted, dmp_diffs, dmp_patches, dmp_result, index, indexes, key, op, patched, s_index, shift, x, _i, _len, _ref, _ref1; 359 | patched = this.deepCopy(s); 360 | indexes = []; 361 | deleted = []; 362 | for (key in diffs) { 363 | if (!__hasProp.call(diffs, key)) continue; 364 | indexes.push(key); 365 | indexes.sort(); 366 | } 367 | for (_i = 0, _len = indexes.length; _i < _len; _i++) { 368 | index = indexes[_i]; 369 | op = diffs[index]; 370 | shift = ((function() { 371 | var _j, _len1, _results; 372 | _results = []; 373 | for (_j = 0, _len1 = deleted.length; _j < _len1; _j++) { 374 | x = deleted[_j]; 375 | if (x <= index) { 376 | _results.push(x); 377 | } 378 | } 379 | return _results; 380 | })()).length; 381 | s_index = index - shift; 382 | switch (op['o']) { 383 | case '+': 384 | [].splice.apply(patched, [s_index, (s_index - 1) - s_index + 1].concat(_ref = op['v'])), _ref; 385 | break; 386 | case '-': 387 | [].splice.apply(patched, [s_index, s_index - s_index + 1].concat(_ref1 = [])), _ref1; 388 | deleted[deleted.length] = s_index; 389 | break; 390 | case 'r': 391 | patched[s_index] = op['v']; 392 | break; 393 | case 'I': 394 | patched[s_index] += op['v']; 395 | break; 396 | case 'L': 397 | patched[s_index] = this.apply_list_diff(patched[s_index], op['v']); 398 | break; 399 | case 'dL': 400 | patched[s_index] = this.apply_list_diff_dmp(patched[s_index], op['v']); 401 | break; 402 | case 'O': 403 | patched[s_index] = this.apply_object_diff(patched[s_index], op['v']); 404 | break; 405 | case 'd': 406 | dmp_diffs = this.dmp.diff_fromDelta(patched[s_index], op['v']); 407 | dmp_patches = this.dmp.patch_make(patched[s_index], dmp_diffs); 408 | dmp_result = this.dmp.patch_apply(dmp_patches, patched[s_index]); 409 | patched[s_index] = dmp_result[0]; 410 | } 411 | } 412 | return patched; 413 | }; 414 | 415 | jsondiff.prototype.apply_list_diff_dmp = function(s, delta) { 416 | var dmp_diffs, dmp_patches, dmp_result, ptext; 417 | ptext = this._serialize_to_text(s); 418 | dmp_diffs = this.dmp.diff_fromDelta(ptext, delta); 419 | dmp_patches = this.dmp.patch_make(ptext, dmp_diffs); 420 | dmp_result = this.dmp.patch_apply(dmp_patches, ptext); 421 | return this._text_to_array(dmp_result[0]); 422 | }; 423 | 424 | jsondiff.prototype.apply_object_diff = function(s, diffs) { 425 | var key, op, patched; 426 | patched = this.deepCopy(s); 427 | for (key in diffs) { 428 | if (!__hasProp.call(diffs, key)) continue; 429 | op = diffs[key]; 430 | if (op['o'] === '-') { 431 | delete patched[key]; 432 | } else { 433 | patched[key] = this.apply_diff(patched[key], op); 434 | } 435 | } 436 | return patched; 437 | }; 438 | 439 | jsondiff.prototype.apply_object_diff_with_offsets = function(s, diffs, field, offsets) { 440 | var dmp_diffs, dmp_patches, dmp_result, key, op, patched; 441 | patched = this.deepCopy(s); 442 | for (key in diffs) { 443 | if (!__hasProp.call(diffs, key)) continue; 444 | op = diffs[key]; 445 | switch (op['o']) { 446 | case '+': 447 | patched[key] = op['v']; 448 | break; 449 | case '-': 450 | delete patched[key]; 451 | break; 452 | case 'r': 453 | patched[key] = op['v']; 454 | break; 455 | case 'I': 456 | patched[key] += op['v']; 457 | break; 458 | case 'L': 459 | patched[key] = this.apply_list_diff(patched[key], op['v']); 460 | break; 461 | case 'O': 462 | patched[key] = this.apply_object_diff(patched[key], op['v']); 463 | break; 464 | case 'd': 465 | dmp_diffs = this.dmp.diff_fromDelta(patched[key], op['v']); 466 | dmp_patches = this.dmp.patch_make(patched[key], dmp_diffs); 467 | if (key === field) { 468 | patched[key] = this.patch_apply_with_offsets(dmp_patches, patched[key], offsets); 469 | } else { 470 | dmp_result = this.dmp.patch_apply(dmp_patches, patched[key]); 471 | patched[key] = dmp_result[0]; 472 | } 473 | } 474 | } 475 | return patched; 476 | }; 477 | 478 | jsondiff.prototype.apply_diff = function(a, op) { 479 | var dmp_diffs, dmp_patches, dmp_result; 480 | switch (op['o']) { 481 | case '+': 482 | return op['v']; 483 | case '-': 484 | return null; 485 | case 'r': 486 | return op['v']; 487 | case 'I': 488 | return a + op['v']; 489 | case 'L': 490 | return this.apply_list_diff(a, op['v']); 491 | case 'dL': 492 | return this.apply_list_diff_dmp(a, op['v']); 493 | case 'O': 494 | return this.apply_object_diff(a, op['v']); 495 | case 'd': 496 | dmp_diffs = this.dmp.diff_fromDelta(a, op['v']); 497 | dmp_patches = this.dmp.patch_make(a, dmp_diffs); 498 | dmp_result = this.dmp.patch_apply(dmp_patches, a); 499 | return dmp_result[0]; 500 | } 501 | }; 502 | 503 | jsondiff.prototype.transform_list_diff = function(ad, bd, s, policy) { 504 | var ad_new, b_deletes, b_inserts, diff, index, last_index, last_shift, op, other_op, shift_l, shift_r, sindex, target_op, x; 505 | ad_new = {}; 506 | b_inserts = []; 507 | b_deletes = []; 508 | if ((policy != null) && 'item' in policy) { 509 | policy = policy['item']; 510 | } else { 511 | policy = null; 512 | } 513 | for (index in bd) { 514 | if (!__hasProp.call(bd, index)) continue; 515 | op = bd[index]; 516 | index = parseInt(index); 517 | if (op['o'] === '+') { 518 | b_inserts.push(index); 519 | } 520 | if (op['o'] === '-') { 521 | b_deletes.push(index); 522 | } 523 | } 524 | last_index = 0; 525 | last_shift = 0; 526 | for (index in ad) { 527 | if (!__hasProp.call(ad, index)) continue; 528 | op = ad[index]; 529 | index = parseInt(index); 530 | shift_r = ((function() { 531 | var _i, _len, _results; 532 | _results = []; 533 | for (_i = 0, _len = b_inserts.length; _i < _len; _i++) { 534 | x = b_inserts[_i]; 535 | if (x < index) { 536 | _results.push(x); 537 | } 538 | } 539 | return _results; 540 | })()).length; 541 | shift_l = ((function() { 542 | var _i, _len, _results; 543 | _results = []; 544 | for (_i = 0, _len = b_deletes.length; _i < _len; _i++) { 545 | x = b_deletes[_i]; 546 | if (x < index) { 547 | _results.push(x); 548 | } 549 | } 550 | return _results; 551 | })()).length; 552 | if (last_index + 1 === index) { 553 | index = index + last_shift; 554 | } else { 555 | index = index + shift_r - shift_l; 556 | } 557 | last_index = index; 558 | last_shift = shift_r - shift_l; 559 | sindex = String(index); 560 | ad_new[sindex] = op; 561 | if (sindex in bd) { 562 | if (op['o'] === '+' && bd[index]['o'] === '+') { 563 | continue; 564 | } else if (op['o'] === '-') { 565 | if (bd[index]['o'] === '-') { 566 | delete ad_new[sindex]; 567 | } 568 | } else if (bd[index]['o'] === '-') { 569 | if (op['o'] === 'r') { 570 | ad_new[sindex] = { 571 | 'o': '+', 572 | 'v': op['v'] 573 | }; 574 | } 575 | if (op['o'] === !'+') { 576 | ad_new[sindex] = { 577 | 'o': '+', 578 | 'v': this.apply_object_diff(s[sindex], op['v']) 579 | }; 580 | } 581 | } else { 582 | target_op = {}; 583 | target_op[sindex] = op; 584 | other_op = {}; 585 | other_op[sindex] = bd[index]; 586 | diff = this.transform_object_diff(target_op, other_op, s, policy); 587 | ad_new[sindex] = diff[sindex]; 588 | } 589 | } 590 | } 591 | return ad_new; 592 | }; 593 | 594 | jsondiff.prototype.transform_list_diff_dmp = function(ad, bd, s, policy) { 595 | var a_patches, ab_text, b_patches, b_text, dmp_diffs, stext; 596 | stext = this._serialize_to_text(s); 597 | a_patches = this.dmp.patch_make(stext, this.dmp.diff_fromDelta(stext, ad)); 598 | b_patches = this.dmp.patch_make(stext, this.dmp.diff_fromDelta(stext, bd)); 599 | b_text = (this.dmp.patch_apply(b_patches, stext))[0]; 600 | ab_text = (this.dmp.patch_apply(a_patches, b_text))[0]; 601 | if (ab_text !== b_text) { 602 | dmp_diffs = this.dmp.diff_lineMode_(b_text, ab_text); 603 | if (dmp_diffs.length > 2) { 604 | this.dmp.diff_cleanupEfficiency(dmp_diffs); 605 | } 606 | if (dmp_diffs.length > 0) { 607 | return this.dmp.diff_toDelta(dmp_diffs); 608 | } 609 | } 610 | return ""; 611 | }; 612 | 613 | jsondiff.prototype.transform_object_diff = function(ad, bd, s, policy) { 614 | var a_patches, ab_text, ad_new, aop, b_patches, b_text, bop, dmp_diffs, key, sk, _ref; 615 | ad_new = this.deepCopy(ad); 616 | if ((policy != null) && 'attributes' in policy) { 617 | policy = policy['attributes']; 618 | } 619 | for (key in ad) { 620 | if (!__hasProp.call(ad, key)) continue; 621 | aop = ad[key]; 622 | if (!(key in bd)) { 623 | continue; 624 | } 625 | if ((policy != null) && 'attributes' in policy) { 626 | policy = policy['attributes']; 627 | if ((policy != null) && key in policy) { 628 | policy = policy[key]; 629 | } else { 630 | policy = null; 631 | } 632 | } else { 633 | policy = null; 634 | } 635 | sk = s[key]; 636 | bop = bd[key]; 637 | if (aop['o'] === '+' && bop['o'] === '+') { 638 | if (this.equals(aop['v'], bop['v'])) { 639 | delete ad_new[key]; 640 | } else { 641 | ad_new[key] = this.diff(bop['v'], aop['v'], policy); 642 | } 643 | } else if (aop['o'] === '-' && bop['o'] === '-') { 644 | delete ad_new[key]; 645 | } else if (bop['o'] === '-' && ((_ref = aop['o']) !== '+' && _ref !== '-')) { 646 | ad_new[key] = { 647 | 'o': '+' 648 | }; 649 | ad_new[key]['v'] = this.apply_diff(sk, aop); 650 | } else if (aop['o'] === 'O' && bop['o'] === 'O') { 651 | ad_new[key] = { 652 | 'o': 'O', 653 | 'v': this.transform_object_diff(aop['v'], bop['v'], sk, policy) 654 | }; 655 | } else if (aop['o'] === 'L' && bop['o'] === 'L') { 656 | ad_new[key] = { 657 | 'o': 'L', 658 | 'v': this.transform_list_diff(aop['v'], bop['v'], sk, policy) 659 | }; 660 | } else if (aop['o'] === 'dL' && bop['o'] === 'dL') { 661 | ad_new[key] = { 662 | 'o': 'dL', 663 | 'v': this.transform_list_diff_dmp(aop['v'], bop['v'], sk, policy) 664 | }; 665 | } else if (aop['o'] === 'd' && bop['o'] === 'd') { 666 | delete ad_new[key]; 667 | a_patches = this.dmp.patch_make(sk, this.dmp.diff_fromDelta(sk, aop['v'])); 668 | b_patches = this.dmp.patch_make(sk, this.dmp.diff_fromDelta(sk, bop['v'])); 669 | b_text = (this.dmp.patch_apply(b_patches, sk))[0]; 670 | ab_text = (this.dmp.patch_apply(a_patches, b_text))[0]; 671 | if (ab_text !== b_text) { 672 | dmp_diffs = this.dmp.diff_main(b_text, ab_text); 673 | if (dmp_diffs.length > 2) { 674 | this.dmp.diff_cleanupEfficiency(dmp_diffs); 675 | } 676 | if (dmp_diffs.length > 0) { 677 | ad_new[key] = { 678 | 'o': 'd', 679 | 'v': this.dmp.diff_toDelta(dmp_diffs) 680 | }; 681 | } 682 | } 683 | } 684 | return ad_new; 685 | } 686 | }; 687 | 688 | jsondiff.prototype.patch_apply_with_offsets = function(patches, text, offsets) { 689 | var del_end, del_start, delta, diffs, end_loc, expected_loc, i, index1, index2, mod, nullPadding, start_loc, text1, text2, x, y, _i, _j, _k, _l, _ref, _ref1, _ref2, _ref3; 690 | if (patches.length === 0) { 691 | return text; 692 | } 693 | patches = this.dmp.patch_deepCopy(patches); 694 | nullPadding = this.dmp.patch_addPadding(patches); 695 | text = nullPadding + text + nullPadding; 696 | this.dmp.patch_splitMax(patches); 697 | delta = 0; 698 | for (x = _i = 0, _ref = patches.length; 0 <= _ref ? _i < _ref : _i > _ref; x = 0 <= _ref ? ++_i : --_i) { 699 | expected_loc = patches[x].start2 + delta; 700 | text1 = this.dmp.diff_text1(patches[x].diffs); 701 | end_loc = -1; 702 | if (text1.length > this.dmp.Match_MaxBits) { 703 | start_loc = this.dmp.match_main(text, text1.substring(0, this.dmp.Match_MaxBits), expected_loc); 704 | if (start_loc !== -1) { 705 | end_loc = this.dmp.match_main(text, text1.substring(text1.length - this.dmp.Match_MaxBits), expected_loc + text1.length - this.dmp.Match_MaxBits); 706 | if (end_loc === -1 || start_loc >= end_loc) { 707 | start_loc = -1; 708 | } 709 | } 710 | } else { 711 | start_loc = this.dmp.match_main(text, text1, expected_loc); 712 | } 713 | if (start_loc === -1) { 714 | delta -= patches[x].length2 - patches[x].length1; 715 | } else { 716 | delta = start_loc - expected_loc; 717 | if (end_loc === -1) { 718 | text2 = text.substring(start_loc, start_loc + text1.length); 719 | } else { 720 | text2 = text.substring(start_loc, end_loc + this.dmp.Match_MaxBits); 721 | } 722 | diffs = this.dmp.diff_main(text1, text2, false); 723 | if (text1.length > this.dmp.Match_MaxBits && this.dmp.diff_levenshtein(diffs) / text1.length > this.dmp.Patch_DeleteThreshold) { 724 | 725 | } else { 726 | index1 = 0; 727 | for (y = _j = 0, _ref1 = patches[x].diffs.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; y = 0 <= _ref1 ? ++_j : --_j) { 728 | mod = patches[x].diffs[y]; 729 | if (mod[0] !== DIFF_EQUAL) { 730 | index2 = this.dmp.diff_xIndex(diffs, index1); 731 | } 732 | if (mod[0] === DIFF_INSERT) { 733 | text = text.substring(0, start_loc + index2) + mod[1] + text.substring(start_loc + index2); 734 | for (i = _k = 0, _ref2 = offsets.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) { 735 | if (offsets[i] + nullPadding.length > start_loc + index2) { 736 | offsets[i] += mod[1].length; 737 | } 738 | } 739 | } else if (mod[0] === DIFF_DELETE) { 740 | del_start = start_loc + index2; 741 | del_end = start_loc + this.dmp.diff_xIndex(diffs, index1 + mod[1].length); 742 | text = text.substring(0, del_start) + text.substring(del_end); 743 | for (i = _l = 0, _ref3 = offsets.length; 0 <= _ref3 ? _l < _ref3 : _l > _ref3; i = 0 <= _ref3 ? ++_l : --_l) { 744 | if (offsets[i] + nullPadding.length > del_start) { 745 | if (offsets[i] + nullPadding.length < del_end) { 746 | offsets[i] = del_start - nullPadding.length; 747 | } else { 748 | offsets[i] -= del_end - del_start; 749 | } 750 | } 751 | } 752 | } 753 | if (mod[0] !== DIFF_DELETE) { 754 | index1 += mod[1].length; 755 | } 756 | } 757 | } 758 | } 759 | } 760 | text = text.substring(nullPadding.length, text.length - nullPadding.length); 761 | return text; 762 | }; 763 | 764 | return jsondiff; 765 | 766 | })(); 767 | 768 | window['jsondiff'] = jsondiff; 769 | 770 | }).call(this); 771 | -------------------------------------------------------------------------------- /sync.coffee: -------------------------------------------------------------------------------- 1 | class bucket 2 | constructor: (@s, @name, b_opts) -> 3 | @jd = @s.jd 4 | @options = @jd.deepCopy @s.options 5 | for own name, val of b_opts 6 | @options[name] = val 7 | @chan = @options['n'] 8 | @space = "#{@options['app_id']}/#{@name}" 9 | @username = @options['username'] 10 | @namespace = "#{@username}:#{@space}" 11 | 12 | @clientid = null 13 | try 14 | @clientid = localStorage.getItem "#{@namespace}/clientid" 15 | catch error 16 | @clientid = null 17 | if not @clientid? or @clientid.indexOf("sjs") != 0 18 | @clientid = "sjs-#{@s.bversion}-#{@uuid(5)}" 19 | try 20 | localStorage.setItem "#{@namespace}/clientid" 21 | catch error 22 | console.log "#{@name}: couldnt set clientid" 23 | 24 | @cb_events = ['notify', 'notify_init', 'notify_version', 'local', 'get', 'ready', 'notify_pending', 'error'] 25 | @cbs = {} 26 | @cb_e = @cb_l = @cb_ni = @cb_np = null 27 | @cb_n = @cb_nv = @cb_r = -> 28 | 29 | @initialized = false 30 | @authorized = false 31 | @data = 32 | last_cv: 0 33 | ccid: @uuid() 34 | store: {} 35 | send_queue: [] 36 | send_queue_timer: null 37 | 38 | @started = false 39 | 40 | if not ('nostore' of @options) 41 | @_load_meta() 42 | @loaded = @_load_data() 43 | console.log "#{@name}: localstorage loaded #{@loaded} entities" 44 | else 45 | console.log "#{@name}: not loading from localstorage" 46 | @loaded = 0 47 | 48 | @_last_pending = null 49 | @_send_backoff = 15000 50 | @_backoff_max = 120000 51 | @_backoff_min = 15000 52 | 53 | console.log "#{@namespace}: bucket created: opts: #{JSON.stringify(@options)}" 54 | 55 | S4: -> 56 | (((1+Math.random())*0x10000)|0).toString(16).substring(1) 57 | 58 | uuid: (n) -> 59 | n = n || 8 60 | s = @S4() 61 | while n -= 1 62 | s += @S4() 63 | return s 64 | 65 | now: -> 66 | new Date().getTime() 67 | 68 | on: (event, callback) => 69 | if event in @cb_events 70 | @cbs[event] = callback 71 | switch event 72 | when 'get', 'local' 73 | @cb_l = callback 74 | when 'notify' 75 | @cb_n = callback 76 | when 'notify_version' 77 | @cb_nv = callback 78 | when 'notify_pending' 79 | @cb_np = callback 80 | when 'notify_init' 81 | @cb_ni = callback 82 | when 'ready' 83 | @cb_r = callback 84 | when 'error' 85 | @cb_e = callback 86 | else 87 | throw new Error("unsupported callback event") 88 | 89 | show_data: => 90 | if not @s.supports_html5_storage() 91 | return 92 | total = 0 93 | for own key, datastr of localStorage 94 | console.log "[#{key}]: #{datastr}" 95 | total = total + 1 96 | console.log "#{total} total" 97 | 98 | _save_meta: -> 99 | if not @s.supports_html5_storage() 100 | return false 101 | console.log "#{@name}: save_meta ccid:#{@data.ccid} cv:#{@data.last_cv}" 102 | try 103 | localStorage.setItem "#{@namespace}/ccid", @data.ccid 104 | localStorage.setItem "#{@namespace}/last_cv", @data.last_cv 105 | catch error 106 | return false 107 | return true 108 | 109 | _load_meta: => 110 | if not @s.supports_html5_storage() 111 | return 112 | @data.ccid = localStorage.getItem "#{@namespace}/ccid" 113 | @data.ccid ?= 1 114 | @data.last_cv = localStorage.getItem "#{@namespace}/last_cv" 115 | @data.last_cv ?= 0 116 | console.log "#{@name}: load_meta ccid:#{@data.ccid} cv:#{@data.last_cv}" 117 | 118 | _verify: (data) => 119 | if !('object' of data) or !('version' of data) 120 | return false 121 | if @jd.entries(data['object']) == 0 122 | 123 | if 'last' of data and @jd.entries(data['last']) > 0 124 | return true 125 | else 126 | return false 127 | else 128 | if !(data['version']?) 129 | return false 130 | return true 131 | 132 | _load_data: => 133 | if not @s.supports_html5_storage() 134 | return 135 | prefix = "#{@namespace}/e/" 136 | p_len = prefix.length 137 | loaded = 0 138 | if localStorage.length == 0 139 | return 0 140 | for i in [0..localStorage.length-1] 141 | key = localStorage.key(i) 142 | if key? and key.substr(0, p_len) is prefix 143 | id = key.substr(p_len, key.length-p_len) 144 | try 145 | data = JSON.parse localStorage.getItem key 146 | catch error 147 | data = null 148 | if not data? 149 | continue 150 | if @_verify data 151 | data['check'] = null 152 | @data.store[id] = data 153 | loaded = loaded + 1 154 | else 155 | console.log "ignoring CORRUPT data: #{JSON.stringify(data)}" 156 | @_remove_entity id 157 | return loaded 158 | 159 | _save_entity: (id) => 160 | if not @s.supports_html5_storage() 161 | return false 162 | key = "#{@namespace}/e/#{id}" 163 | store_data = @data.store[id] 164 | datastr = JSON.stringify(store_data) 165 | try 166 | localStorage.setItem key, datastr 167 | catch error 168 | return false 169 | ret_data = JSON.parse localStorage.getItem key 170 | if @jd.equals store_data, ret_data 171 | # console.log "saved #{key} len: #{datastr.length}" 172 | return true 173 | else 174 | # console.log "ERROR STORING ENTITY: store: #{JSON.stringify(store_data)}, retrieve: #{JSON.stringify(ret_data)}" 175 | return false 176 | 177 | _remove_entity: (id) => 178 | if not @s.supports_html5_storage() 179 | return false 180 | key = "#{@namespace}/e/#{id}" 181 | try 182 | localStorage.removeItem key 183 | catch error 184 | return false 185 | return true 186 | 187 | start: => 188 | console.log "#{@space}: started initialized: #{@initialized} authorized: #{@authorized}" 189 | @namespace = "#{@username}:#{@space}" 190 | @started = true 191 | @first = false 192 | if not @authorized 193 | if @s.connected 194 | @first = true 195 | if 'limit' of @options 196 | index_query = "i:1:::#{@options['limit']}" 197 | else 198 | index_query = "i:1:::40" 199 | @irequest_time = @now() 200 | @index_request = true 201 | @notify_index = {} 202 | opts = 203 | app_id: @options.app_id 204 | token: @options.token 205 | name: @name 206 | clientid: @clientid 207 | build: @s.bversion 208 | if not @initialized 209 | opts.cmd = index_query 210 | @send("init:#{JSON.stringify(opts)}") 211 | console.log "#{@name}: sent init #{JSON.stringify(opts)} waiting for auth" 212 | else 213 | console.log "#{@name}: waiting for connect" 214 | return 215 | if not @initialized 216 | if not @first 217 | @notify_index = {} 218 | @_refresh_store() 219 | else 220 | console.log "#{@name}: retrieve changes from start" 221 | @retrieve_changes() 222 | 223 | on_data: (data) => 224 | if data.substr(0, 5) == "auth:" 225 | user = data.substr(5) 226 | if user is "expired" 227 | console.log "auth expired" 228 | @started = false 229 | if @cb_e? 230 | @cb_e "auth" 231 | return 232 | else 233 | @username = user 234 | @authorized = true 235 | if @initialized 236 | @start() 237 | else if data.substr(0, 4) == "cv:?" 238 | console.log "#{@name}: cv out of sync, refreshing index" 239 | setTimeout => @_refresh_store() 240 | else if data.substr(0, 2) == "c:" 241 | changes = JSON.parse(data.substr(2)) 242 | if @data.last_cv is "0" and changes.length is 0 and not @cv_check 243 | @cv_check = true 244 | @_refresh_store() 245 | @on_changes changes 246 | else if data.substr(0, 2) == "i:" 247 | console.log "#{@name}: index msg received: #{@now() - @irequest_time}" 248 | @on_index_page JSON.parse(data.substr(2)) 249 | else if data.substr(0, 2) == "e:" 250 | key_end = data.indexOf("\n") 251 | evkey = data.substr(2, key_end-2) 252 | version = evkey.substr(evkey.lastIndexOf('.')+1) 253 | key = evkey.substr(0, evkey.lastIndexOf('.')) 254 | entitydata = data.substr(key_end+1) 255 | if entitydata is "?" 256 | @on_entity_version null, key, version 257 | else 258 | entity = JSON.parse(entitydata) 259 | @on_entity_version entity['data'], key, version 260 | else 261 | console.log "unknown message: #{data}" 262 | 263 | send: (message) => 264 | console.log "sending: #{@chan}:#{message}" 265 | @s.send("#{@chan}:#{message}") 266 | 267 | _refresh_store: => 268 | # load the index 269 | console.log "#{@name}: _refresh_store(): loading index" 270 | if 'limit' of @options 271 | index_query = "i:1:::#{@options['limit']}" 272 | else 273 | index_query = "i:1:::40" 274 | @send(index_query) 275 | @irequest_time = @now() 276 | @index_request = true 277 | return 278 | 279 | on_index_page: (response) => 280 | now = @now() 281 | elapsed = now - @irequest_time 282 | console.log "#{@name}: index response time: #{elapsed}" 283 | console.log "#{@name}: on_index_page(): index page received, current= #{response['current']}" 284 | console.log response 285 | 286 | loaded = 0 287 | for item in response['index'] 288 | @notify_index[item['id']] = false 289 | loaded++ 290 | setTimeout do(item) => 291 | => @on_entity_version(item['d'], item['id'], item['v']) 292 | 293 | if not ('mark' of response) or 'limit' of @options 294 | @index_request = false 295 | if 'current' of response 296 | @data.last_cv = response['current'] 297 | @_save_meta() 298 | else 299 | @data.last_cv = 0 300 | if loaded is 0 301 | @_index_loaded() 302 | else 303 | @index_request = true 304 | console.log "#{@name}: index last process time: #{@now() - now}, page_delay: #{@options['page_delay']}" 305 | mark = response['mark'] 306 | page_req = (mark) => 307 | @send("i:1:#{mark}::100") 308 | @irequest_time = @now() 309 | 310 | setTimeout( (do(mark) => 311 | => page_req(mark)), @options['page_delay']) 312 | 313 | on_index_error: => 314 | console.log "#{@name}: index doesnt exist or other error" 315 | 316 | load_versions: (id, versions) => 317 | if not (id of @data.store) 318 | return false 319 | min = Math.max(@data.store[id]['version'] - (versions+1), 1) 320 | for v in [min..@data.store[id]['version']-1] 321 | console.log "#{@name}: loading version #{id}.#{v}" 322 | @send("e:#{id}.#{v}") 323 | 324 | get_version: (id, version) => 325 | evkey = "#{id}.#{version}" 326 | @send("e:#{evkey}") 327 | 328 | on_entity_version: (data, id, version) => 329 | console.log "#{@name}: on_entity_version(#{data}, #{id}, #{version})" 330 | if data? 331 | data_copy = @jd.deepCopy(data) 332 | else 333 | data_copy = null 334 | if @initialized is false and @cb_ni? 335 | notify_cb = @cb_ni 336 | else 337 | notify_cb = @cb_n 338 | if id of @data.store and 'last' of @data.store[id] and @jd.entries(@data.store[id]['last']) 339 | data_copy = @jd.deepCopy(@data.store[id]['last']) 340 | 341 | notify_cb id, data_copy, null 342 | @notify_index[id] = true 343 | @_check_update(id) 344 | 345 | else if id of @data.store and version < @data.store[id]['version'] 346 | @cb_nv id, data_copy, version 347 | else 348 | if not (id of @data.store) 349 | @data.store[id] = {} 350 | @data.store[id]['id'] = id 351 | @data.store[id]['object'] = data 352 | @data.store[id]['version'] = parseInt(version) 353 | 354 | notify_cb id, data_copy, version 355 | @notify_index[id] = true 356 | to_load = 0 357 | for own nid of @notify_index 358 | if @notify_index[nid] is false 359 | to_load++ 360 | if to_load is 0 and @index_request is false 361 | @_index_loaded() 362 | 363 | _index_loaded: => 364 | console.log "#{@name}: index loaded, initialized: #{@initialized}" 365 | if @initialized is false 366 | @cb_r() 367 | @initialized = true 368 | console.log "#{@name}: retrieve changes from index loaded" 369 | @retrieve_changes() 370 | 371 | # id: id of object 372 | # new_object: latest server version of object (includes latest diff) 373 | # orig_object: the previous server version of object that the client had 374 | # diff: the newly received incoming diff (orig_object + diff = new_object) 375 | _notify_client: (key, new_object, orig_object, diff, version) => 376 | console.log "#{@name}: _notify_client(#{key}, #{new_object}, #{orig_object}, #{JSON.stringify(diff)})" 377 | if not @cb_l? 378 | console.log "#{@name}: no get callback, notifying without transform" 379 | @cb_n key, new_object, version 380 | return 381 | 382 | c_object = @cb_l key 383 | t_object = null 384 | t_diff = null 385 | cursor = null 386 | offsets = [] 387 | 388 | if @jd.typeOf(c_object) is 'array' 389 | element = c_object[2] 390 | fieldname = c_object[1] 391 | c_object = c_object[0] 392 | cursor = @s._captureCursor element 393 | if cursor 394 | offsets[0] = cursor['startOffset'] 395 | if 'endOffset' of cursor 396 | offsets[1] = cursor['endOffset'] 397 | 398 | if c_object? and orig_object? 399 | # console.log "going to do object diff new diff: #{JSON.stringify(diff)}" 400 | 401 | o_diff = @jd.object_diff orig_object, c_object 402 | console.log "client/server version diff: #{JSON.stringify(o_diff)}" 403 | if @jd.entries(o_diff) is 0 404 | console.log "local diff 0 entries" 405 | t_diff = diff 406 | t_object = orig_object 407 | else 408 | console.log "o_diff" 409 | console.log o_diff 410 | console.log "orig_object" 411 | console.log orig_object 412 | console.log "c_object" 413 | console.log c_object 414 | console.log "client modified doing transform" 415 | # client has local modifications, so we need to transform to apply new 416 | # changes to client's data 417 | # this transforms >o_diff< which is the local client modification with 418 | # respect to >diff< which is the new incoming change received from server 419 | # orig_object + diff = new_object 420 | # orig_object + o_diff (clients local modifications) = c_object (current 421 | # client data) 422 | # new client data (that includes both diffs) = orig_object + diff + T(o_diff) 423 | # new client data = (orig_object + diff) + T(o_diff) 424 | # new client data = new_object + T(o_diff) 425 | # new client data = new_object + t_diff 426 | t_diff = @jd.transform_object_diff o_diff, diff, orig_object 427 | t_object = new_object 428 | 429 | if cursor 430 | new_data = @jd.apply_object_diff_with_offsets t_object, t_diff, fieldname, offsets 431 | 432 | if element? and 'value' of element 433 | element['value'] = new_data[fieldname] 434 | 435 | cursor['startOffset'] = offsets[0] 436 | if offsets.length > 1 437 | cursor['endOffset'] = offsets[1] 438 | if cursor['startOffset'] >= cursor['endOffset'] 439 | cursor['collapsed'] = true 440 | @s._restoreCursor element, cursor 441 | else 442 | console.log "in regular apply_object_diff" 443 | console.log "t_object" 444 | console.log t_object 445 | console.log "t_diff" 446 | console.log t_diff 447 | new_data = @jd.apply_object_diff t_object, t_diff 448 | # console.log "transformed diff: #{JSON.stringify(t_diff)}" 449 | # console.log "#{@name}: notifying client of new data for #{key}: #{JSON.stringify(new_data)}" 450 | @cb_n key, new_data, version 451 | else if new_object 452 | @cb_n key, new_object, version 453 | else 454 | @cb_n key, null, null 455 | 456 | _check_update: (id) => 457 | console.log "#{@name}: _check_update(#{id})" 458 | if not (id of @data.store) 459 | return false 460 | s_data = @data.store[id] 461 | 462 | if s_data['change'] 463 | found = false 464 | for change in @data.send_queue 465 | if change['id'] is s_data['change']['id'] and change['ccid'] is s_data['change']['ccid'] 466 | found = true 467 | if !found 468 | @_queue_change s_data['change'] 469 | return true 470 | return false 471 | 472 | if s_data['check']? 473 | return false 474 | 475 | if 'last' of s_data and @jd.equals s_data['object'], s_data['last'] 476 | delete s_data['last'] 477 | @_remove_entity id 478 | return false 479 | 480 | change = @_make_change id 481 | if change? 482 | s_data['change'] = change 483 | @_queue_change change 484 | else 485 | @_remove_entity id 486 | return true 487 | 488 | update: (id, object) => 489 | if arguments.length is 1 490 | if @cb_l? 491 | object = @cb_l id 492 | if @jd.typeOf(object) is 'array' 493 | object = object[0] 494 | else 495 | throw new Error("missing 'local' callback") 496 | console.log "#{@name}: update(#{id})" 497 | 498 | if not id? and not object? 499 | return false 500 | if id? 501 | if id.length is 0 or id.indexOf('/') isnt -1 502 | return false 503 | else 504 | id = @uuid() 505 | if not (id of @data.store) 506 | @data.store[id] = 507 | 'id' : id 508 | 'object' : {} 509 | 'version' : null 510 | 'change' : null 511 | 'check' : null 512 | s_data = @data.store[id] 513 | s_data['last'] = @jd.deepCopy(object) 514 | s_data['modified'] = @s._time() 515 | @_save_entity id 516 | 517 | for change in @data.send_queue 518 | if String(id) is change['id'] 519 | console.log "#{@name}: update(#{id}) found pending change, aborting" 520 | return null 521 | 522 | if s_data['check']? 523 | clearTimeout(s_data['check']) 524 | 525 | s_data['check'] = setTimeout((do(id, s_data) => 526 | => 527 | s_data['check'] = null 528 | s_data['change'] = @_make_change id 529 | delete s_data['last'] 530 | @_save_entity id 531 | @_queue_change s_data['change'] 532 | ), @options['update_delay']) 533 | return id 534 | 535 | # create change objects 536 | _make_change: (id) => 537 | # console.log "#{@name}: _make_change(#{id})" 538 | s_data = @data.store[id] 539 | 540 | change = 541 | 'id' : String(id) 542 | 'ccid' : @uuid() 543 | 544 | if not @initialized 545 | if 'last' of s_data 546 | c_object = s_data['last'] 547 | else 548 | return null 549 | else 550 | if @cb_l? 551 | c_object = @cb_l id 552 | if @jd.typeOf(c_object) is 'array' 553 | c_object = c_object[0] 554 | else 555 | if 'last' of s_data 556 | c_object = s_data['last'] 557 | else 558 | return null 559 | 560 | if s_data['version']? 561 | change['sv'] = s_data['version'] 562 | 563 | if c_object is null and s_data['version']? 564 | change['o'] = '-' 565 | console.log "#{@name}: deletion requested for #{id}" 566 | else if c_object? and s_data['object']? 567 | change['o'] = 'M' 568 | if 'sendfull' of s_data 569 | change['d'] = @jd.deepCopy c_object 570 | delete s_data['sendfull'] 571 | else 572 | change['v'] = @jd.object_diff s_data['object'], c_object 573 | if @jd.entries(change['v']) is 0 574 | change = null 575 | else 576 | change = null 577 | # console.log "_make_change(#{id}) returning: #{JSON.stringify(change)}" 578 | return change 579 | 580 | _queue_change: (change) => 581 | if not change? 582 | return 583 | 584 | console.log "_queue_change(#{change['id']}:#{change['ccid']}): sending" 585 | @data.send_queue.push change 586 | @send("c:#{JSON.stringify(change)}") 587 | @_check_pending() 588 | 589 | if @data.send_queue_timer? 590 | clearTimeout(@data.send_queue_timer) 591 | 592 | @data.send_queue_timer = setTimeout @_send_changes, @_send_backoff 593 | 594 | _send_changes: => 595 | if @data.send_queue.length is 0 596 | console.log "#{@name}: send_queue empty, done" 597 | @data.send_queue_timer = null 598 | return 599 | if not @s.connected 600 | console.log "#{@name}: _send_changes: not connected" 601 | else 602 | for change in @data.send_queue 603 | console.log "#{@name}: sending change: #{JSON.stringify(change)}" 604 | @send("c:#{JSON.stringify(change)}") 605 | 606 | @_send_backoff = @_send_backoff * 2 607 | if @_send_backoff > @_backoff_max 608 | @_send_backoff = @_backoff_max 609 | 610 | @data.send_queue_timer = setTimeout @_send_changes, @_send_backoff 611 | 612 | retrieve_changes: => 613 | console.log "#{@name}: requesting changes since cv:#{@data.last_cv}" 614 | @send("cv:#{@data.last_cv}") 615 | # @sio.send("cv:#{@data.last_cv}") 616 | return 617 | 618 | on_changes: (response) => 619 | check_updates = [] 620 | reload_needed = false 621 | @_send_backoff = @_backoff_min 622 | console.log "#{@name}: on_changes(): response=" 623 | console.log response 624 | for change in response 625 | id = change['id'] 626 | console.log "#{@name}: processing id=#{id}" 627 | pending_to_delete = [] 628 | for pending in @data.send_queue 629 | if change['clientid'] is @clientid and id is pending['id'] 630 | # console.log "#{@name}: deleting change for id #{id}" 631 | change['local'] = true 632 | pending_to_delete.push pending 633 | check_updates.push id 634 | for pd in pending_to_delete 635 | @data.store[pd['id']]['change'] = null 636 | @_save_entity pd['id'] 637 | @data.send_queue = (p for p in @data.send_queue when p isnt pd) 638 | if pending_to_delete.length > 0 639 | @_check_pending() 640 | # console.log "#{@name}: send queue: #{JSON.stringify(@data.send_queue)}" 641 | 642 | if 'error' of change 643 | switch change['error'] 644 | when 412 645 | console.log "#{@name}: on_changes(): empty change, dont check" 646 | idx = check_updates.indexOf(change['id']) 647 | if idx > -1 648 | check_updates.splice(idx, 1) 649 | when 409 650 | console.log "#{@name}: on_changes(): duplicate change, ignoring" 651 | when 405 652 | console.log "#{@name}: on_changes(): bad version" 653 | if change['id'] of @data.store 654 | @data.store[change['id']]['version'] = null 655 | reload_needed = true 656 | when 440 657 | console.log "#{@name}: on_change(): bad diff, sending full object" 658 | @data.store[id]['sendfull'] = true 659 | else 660 | console.log "#{@name}: error for last change, reloading" 661 | if change['id'] of @data.store 662 | @data.store[change['id']]['version'] = null 663 | reload_needed = true 664 | else 665 | op = change['o'] 666 | if op is '-' 667 | delete @data.store[id] 668 | @_remove_entity id 669 | if not ('local' of change) 670 | # setTimeout do(change) => 671 | # => @_notify_client change['id'], null, null, null 672 | @_notify_client change['id'], null, null, null, null 673 | 674 | else if op is 'M' 675 | s_data = @data.store[id] 676 | if ('sv' of change and s_data? and s_data['version']? and s_data['version'] == change['sv']) or !('sv' of change) or (change['ev'] == 1) 677 | if not s_data? 678 | @data.store[id] = 679 | 'id' : id 680 | 'object' : {} 681 | 'version' : null 682 | 'change' : null 683 | 'check' : null 684 | s_data = @data.store[id] 685 | # console.log "#{@name}: processing modify for #{JSON.stringify(s_data)}" 686 | orig_object = @jd.deepCopy s_data['object'] 687 | s_data['object'] = @jd.apply_object_diff s_data['object'], change['v'] 688 | s_data['version'] = change['ev'] 689 | 690 | new_object = @jd.deepCopy s_data['object'] 691 | 692 | if not ('local' of change) 693 | # setTimeout do(change, new_object, orig_object) => 694 | # => @_notify_client change['id'], new_object, orig_object, change['v'] 695 | @_notify_client change['id'], new_object, orig_object, change['v'], change['ev'] 696 | else if s_data? and s_data['version']? and change['ev'] <= s_data['version'] 697 | console.log "#{@name}: old or duplicate change received, ignoring, change.ev=#{change['ev']}, s_data.version:#{s_data['version']}" 698 | else 699 | if s_data? 700 | console.log "#{@name}: version mismatch couldnt apply change, change.ev:#{change['ev']}, s_data.version:#{s_data['version']}" 701 | else 702 | console.log "#{@name}: version mismatch couldnt apply change, change.ev:#{change['ev']}, s_data null" 703 | if s_data? 704 | @data.store[id]['version'] = null 705 | reload_needed = true 706 | else 707 | console.log "#{@name}: no operation found for change" 708 | if not reload_needed 709 | @data.last_cv = change['cv'] 710 | @_save_meta() 711 | console.log "#{@name}: checkpoint cv=#{@data.last_cv} ccid=#{@data.ccid}" 712 | if reload_needed 713 | console.log "#{@name}: reload needed, refreshing store" 714 | setTimeout => @_refresh_store() 715 | else 716 | for id in check_updates 717 | do (id) => setTimeout (=> @_check_update id), @options['update_delay'] 718 | return 719 | 720 | pending: => 721 | x = (change['id'] for change in @data.send_queue) 722 | console.log "#{@name}: pending: #{JSON.stringify(x)}" 723 | (change['id'] for change in @data.send_queue) 724 | 725 | _check_pending: => 726 | if @cb_np? 727 | curr_pending = @pending() 728 | diff = true 729 | if @_last_pending 730 | diff = false 731 | if @_last_pending.length is curr_pending.length 732 | for x in @_last_pending 733 | if curr_pending.indexOf(x) is -1 734 | diff = true 735 | else 736 | diff = true 737 | if diff 738 | @_last_pending = curr_pending 739 | @cb_np curr_pending 740 | 741 | 742 | class simperium 743 | lowerstrip: (s) -> 744 | s = s.toLowerCase() 745 | if String::trim? then s.trim() else s.replace /^\s+|\s+$/g, "" 746 | 747 | _time: -> 748 | d = new Date() 749 | Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds())/1000 750 | 751 | supports_html5_storage: -> 752 | try 753 | return 'localStorage' of window && window['localStorage'] != null 754 | catch error 755 | return false 756 | 757 | constructor: (@app_id, @options) -> 758 | @bversion = 2014030401 759 | @jd = new jsondiff() 760 | @dmp = @jd.dmp 761 | @auth_token = null 762 | @options = @options || {} 763 | 764 | @options['app_id'] = @app_id 765 | @sock_opts = { 'debug' : false } 766 | if 'sockjs' of @options 767 | for own name, val of @options['sockjs'] 768 | @sock_opts[name] = val 769 | 770 | if not ('host' of @options) then @options['host'] = 'api.simperium.com' 771 | if not ('port' of @options) then @options['port'] = 80 772 | if 'token' of @options then @auth_token = @options['token'] 773 | 774 | if @options['host'].indexOf("simperium.com") != -1 775 | scheme = "https" 776 | else 777 | scheme = "http" 778 | 779 | @buckets = {} 780 | @channels = 0 781 | 782 | if not ('update_delay' of @options) 783 | @options['update_delay'] = 0 784 | if not ('page_delay' of @options) 785 | @options['page_delay'] = 0 786 | 787 | @options['prefix'] = "sock/1/#{@app_id}" 788 | 789 | @options['port'] = parseInt(@options['port']) 790 | if @options['port'] != 80 and @options['port'] != 443 791 | @sock_url = "#{scheme}://#{@options['host']}:#{@options['port']}/#{@options['prefix']}" 792 | else 793 | @sock_url = "#{scheme}://#{@options['host']}/#{@options['prefix']}" 794 | 795 | @stopped = false 796 | @_sock_backoff = 3000 797 | @_sock_hb = 1 798 | @_sock_connect() 799 | 800 | bucket: (name, b_opts) => 801 | name = @lowerstrip(name) 802 | b_opts = b_opts || {} 803 | b_opts['n'] = @channels++ 804 | b = new bucket(@, name, b_opts) 805 | @buckets[b_opts['n']] = b 806 | return b 807 | 808 | on: (bucket, event, callback) => 809 | @buckets[bucket].on(event, callback) 810 | 811 | start: => 812 | @stopped = false 813 | for own name, bucket of @buckets 814 | bucket.start() 815 | 816 | stop: => 817 | @stopped = true 818 | if @sock? 819 | @sock.close() 820 | 821 | send: (data) => 822 | @sock.send(data) 823 | 824 | synced: => 825 | for own name, bucket of @buckets 826 | if bucket.pending().length > 0 827 | return false 828 | return true 829 | 830 | _sock_connect: => 831 | console.log "simperium: connecting to #{@sock_url}" 832 | @connected = false 833 | @authorized = false 834 | @sock = new SockJS(@sock_url, undefined, @sock_opts) 835 | @sock.onopen = @_sock_opened 836 | @sock.onmessage = @_sock_message 837 | @sock.onclose = @_sock_closed 838 | 839 | _sock_opened: => 840 | @_sock_backoff = 3000 841 | @connected = true 842 | @_sock_hb_timer = setTimeout @_sock_hb_check, 20000 843 | for own name, bucket of @buckets 844 | if bucket.started 845 | bucket.start() 846 | 847 | _sock_closed: => 848 | @connected = false 849 | for own name, bucket of @buckets 850 | bucket.authorized = false 851 | console.log "simperium: sock js closed" 852 | if @_sock_backoff < 4000 853 | @_sock_backoff = @_sock_backoff + 1 854 | else 855 | @_sock_backoff = 15000 856 | if @_sock_hb_timer 857 | clearTimeout @_sock_hb_timer 858 | @_sock_hb_timer = null 859 | if not @stopped 860 | setTimeout @_sock_connect, @_sock_backoff 861 | 862 | _sock_hb_check: => 863 | delay = new Date().getTime() - @_sock_msg_time 864 | if @connected is false 865 | return 866 | if delay > 40000 867 | console.log "simperium: force conn close" 868 | @sock.close() 869 | else if delay > 15000 870 | console.log "simperium: send hb #{@_sock_hb}" 871 | @sock.send("h:#{@_sock_hb}") 872 | @_sock_hb_timer = setTimeout @_sock_hb_check, 20000 873 | 874 | _sock_message: (e) => 875 | @_sock_msg_time = new Date().getTime() 876 | data = e.data 877 | sep = data.indexOf(":") 878 | chan = null 879 | if sep is 1 and data.charAt(0) is 'h' 880 | @_sock_hb = data.substr(2) 881 | return 882 | try 883 | chan = parseInt(data.substr(0, sep)) 884 | data = data.substr(sep+1) 885 | catch error 886 | chan = null 887 | if chan is null 888 | return 889 | if not (chan of @buckets) 890 | return 891 | @buckets[chan].on_data(data) 892 | 893 | _captureCursor: (element) => 894 | return 895 | _captureCursor: `function(element) { 896 | if ('activeElement' in element && !element.activeElement) { 897 | // Safari specific code. 898 | // Restoring a cursor in an unfocused element causes the focus to jump. 899 | return null; 900 | } 901 | var padLength = this.dmp.Match_MaxBits / 2; // Normally 16. 902 | var text = element.value; 903 | var cursor = {}; 904 | if ('selectionStart' in element) { // W3 905 | try { 906 | var selectionStart = element.selectionStart; 907 | var selectionEnd = element.selectionEnd; 908 | } catch (e) { 909 | // No cursor; the element may be "display:none". 910 | return null; 911 | } 912 | cursor.startPrefix = text.substring(selectionStart - padLength, selectionStart); 913 | cursor.startSuffix = text.substring(selectionStart, selectionStart + padLength); 914 | cursor.startOffset = selectionStart; 915 | cursor.collapsed = (selectionStart == selectionEnd); 916 | if (!cursor.collapsed) { 917 | cursor.endPrefix = text.substring(selectionEnd - padLength, selectionEnd); 918 | cursor.endSuffix = text.substring(selectionEnd, selectionEnd + padLength); 919 | cursor.endOffset = selectionEnd; 920 | } 921 | } else { // IE 922 | // Walk up the tree looking for this textarea's document node. 923 | var doc = element; 924 | while (doc.parentNode) { 925 | doc = doc.parentNode; 926 | } 927 | if (!doc.selection || !doc.selection.createRange) { 928 | // Not IE? 929 | return null; 930 | } 931 | var range = doc.selection.createRange(); 932 | if (range.parentElement() != element) { 933 | // Cursor not in this textarea. 934 | return null; 935 | } 936 | var newRange = doc.body.createTextRange(); 937 | 938 | cursor.collapsed = (range.text == ''); 939 | newRange.moveToElementText(element); 940 | if (!cursor.collapsed) { 941 | newRange.setEndPoint('EndToEnd', range); 942 | cursor.endPrefix = newRange.text; 943 | cursor.endOffset = cursor.endPrefix.length; 944 | cursor.endPrefix = cursor.endPrefix.substring(cursor.endPrefix.length - padLength); 945 | } 946 | newRange.setEndPoint('EndToStart', range); 947 | cursor.startPrefix = newRange.text; 948 | cursor.startOffset = cursor.startPrefix.length; 949 | cursor.startPrefix = cursor.startPrefix.substring(cursor.startPrefix.length - padLength); 950 | 951 | newRange.moveToElementText(element); 952 | newRange.setEndPoint('StartToStart', range); 953 | cursor.startSuffix = newRange.text.substring(0, padLength); 954 | if (!cursor.collapsed) { 955 | newRange.setEndPoint('StartToEnd', range); 956 | cursor.endSuffix = newRange.text.substring(0, padLength); 957 | } 958 | } 959 | 960 | // Record scrollbar locations 961 | if ('scrollTop' in element) { 962 | cursor.scrollTop = element.scrollTop / element.scrollHeight; 963 | cursor.scrollLeft = element.scrollLeft / element.scrollWidth; 964 | } 965 | 966 | // alert(cursor.startPrefix + '|' + cursor.startSuffix + ' ' + 967 | // cursor.startOffset + '\n' + cursor.endPrefix + '|' + 968 | // cursor.endSuffix + ' ' + cursor.endOffset + '\n' + 969 | // cursor.scrollTop + ' x ' + cursor.scrollLeft); 970 | return cursor; 971 | }` 972 | 973 | _restoreCursor: (element, cursor) => 974 | return 975 | _restoreCursor: `function(element, cursor) { 976 | // Set some constants which tweak the matching behaviour. 977 | // Maximum distance to search from expected location. 978 | this.dmp.Match_Distance = 1000; 979 | // At what point is no match declared (0.0 = perfection, 1.0 = very loose) 980 | this.dmp.Match_Threshold = 0.9; 981 | 982 | var padLength = this.dmp.Match_MaxBits / 2; // Normally 16. 983 | var newText = element.value; 984 | 985 | // Find the start of the selection in the new text. 986 | var pattern1 = cursor.startPrefix + cursor.startSuffix; 987 | var pattern2, diff; 988 | var cursorStartPoint = this.dmp.match_main(newText, pattern1, 989 | cursor.startOffset - padLength); 990 | if (cursorStartPoint !== null) { 991 | pattern2 = newText.substring(cursorStartPoint, 992 | cursorStartPoint + pattern1.length); 993 | //alert(pattern1 + '\nvs\n' + pattern2); 994 | // Run a diff to get a framework of equivalent indicies. 995 | diff = this.dmp.diff_main(pattern1, pattern2, false); 996 | cursorStartPoint += this.dmp.diff_xIndex(diff, cursor.startPrefix.length); 997 | } 998 | 999 | var cursorEndPoint = null; 1000 | if (!cursor.collapsed) { 1001 | // Find the end of the selection in the new text. 1002 | pattern1 = cursor.endPrefix + cursor.endSuffix; 1003 | cursorEndPoint = this.dmp.match_main(newText, pattern1, 1004 | cursor.endOffset - padLength); 1005 | if (cursorEndPoint !== null) { 1006 | pattern2 = newText.substring(cursorEndPoint, 1007 | cursorEndPoint + pattern1.length); 1008 | //alert(pattern1 + '\nvs\n' + pattern2); 1009 | // Run a diff to get a framework of equivalent indicies. 1010 | diff = this.dmp.diff_main(pattern1, pattern2, false); 1011 | cursorEndPoint += this.dmp.diff_xIndex(diff, cursor.endPrefix.length); 1012 | } 1013 | } 1014 | 1015 | // Deal with loose ends 1016 | if (cursorStartPoint === null && cursorEndPoint !== null) { 1017 | // Lost the start point of the selection, but we have the end point. 1018 | // Collapse to end point. 1019 | cursorStartPoint = cursorEndPoint; 1020 | } else if (cursorStartPoint === null && cursorEndPoint === null) { 1021 | // Lost both start and end points. 1022 | // Jump to the offset of start. 1023 | cursorStartPoint = cursor.startOffset; 1024 | } 1025 | if (cursorEndPoint === null) { 1026 | // End not known, collapse to start. 1027 | cursorEndPoint = cursorStartPoint; 1028 | } 1029 | 1030 | // Restore selection. 1031 | if ('selectionStart' in element) { // W3 1032 | element.selectionStart = cursorStartPoint; 1033 | element.selectionEnd = cursorEndPoint; 1034 | } else { // IE 1035 | // Walk up the tree looking for this textarea's document node. 1036 | var doc = element; 1037 | while (doc.parentNode) { 1038 | doc = doc.parentNode; 1039 | } 1040 | if (!doc.selection || !doc.selection.createRange) { 1041 | // Not IE? 1042 | return; 1043 | } 1044 | // IE's TextRange.move functions treat '\r\n' as one character. 1045 | var snippet = element.value.substring(0, cursorStartPoint); 1046 | var ieStartPoint = snippet.replace(/\r\n/g, '\n').length; 1047 | 1048 | var newRange = doc.body.createTextRange(); 1049 | newRange.moveToElementText(element); 1050 | newRange.collapse(true); 1051 | newRange.moveStart('character', ieStartPoint); 1052 | if (!cursor.collapsed) { 1053 | snippet = element.value.substring(cursorStartPoint, cursorEndPoint); 1054 | var ieMidLength = snippet.replace(/\r\n/g, '\n').length; 1055 | newRange.moveEnd('character', ieMidLength); 1056 | } 1057 | newRange.select(); 1058 | } 1059 | 1060 | // Restore scrollbar locations 1061 | if ('scrollTop' in cursor) { 1062 | element.scrollTop = cursor.scrollTop * element.scrollHeight; 1063 | element.scrollLeft = cursor.scrollLeft * element.scrollWidth; 1064 | } 1065 | }` 1066 | 1067 | 1068 | window['Simperium'] = simperium 1069 | bucket.prototype['on'] = bucket.prototype.on 1070 | bucket.prototype['start'] = bucket.prototype.start 1071 | bucket.prototype['load_versions'] = bucket.prototype.load_versions 1072 | bucket.prototype['pending'] = bucket.prototype.pending 1073 | simperium.prototype['on'] = simperium.prototype.on 1074 | simperium.prototype['start'] = simperium.prototype.start 1075 | simperium.prototype['bucket'] = simperium.prototype.bucket 1076 | simperium.prototype['synced'] = simperium.prototype.synced 1077 | --------------------------------------------------------------------------------