diff.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  1. /*!
  2. diff v5.1.0
  3. Software License Agreement (BSD License)
  4. Copyright (c) 2009-2015, Kevin Decker <kpdecker@gmail.com>
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms, with or without modification,
  7. are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above
  9. copyright notice, this list of conditions and the
  10. following disclaimer.
  11. * Redistributions in binary form must reproduce the above
  12. copyright notice, this list of conditions and the
  13. following disclaimer in the documentation and/or other
  14. materials provided with the distribution.
  15. * Neither the name of Kevin Decker nor the names of its
  16. contributors may be used to endorse or promote products
  17. derived from this software without specific prior
  18. written permission.
  19. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
  20. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  21. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  22. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  25. IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  26. OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. @license
  28. */
  29. (function (global, factory) {
  30. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  31. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  32. (global = global || self, factory(global.Diff = {}));
  33. }(this, (function (exports) { 'use strict';
  34. function Diff() {}
  35. Diff.prototype = {
  36. diff: function diff(oldString, newString) {
  37. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  38. var callback = options.callback;
  39. if (typeof options === 'function') {
  40. callback = options;
  41. options = {};
  42. }
  43. this.options = options;
  44. var self = this;
  45. function done(value) {
  46. if (callback) {
  47. setTimeout(function () {
  48. callback(undefined, value);
  49. }, 0);
  50. return true;
  51. } else {
  52. return value;
  53. }
  54. } // Allow subclasses to massage the input prior to running
  55. oldString = this.castInput(oldString);
  56. newString = this.castInput(newString);
  57. oldString = this.removeEmpty(this.tokenize(oldString));
  58. newString = this.removeEmpty(this.tokenize(newString));
  59. var newLen = newString.length,
  60. oldLen = oldString.length;
  61. var editLength = 1;
  62. var maxEditLength = newLen + oldLen;
  63. if (options.maxEditLength) {
  64. maxEditLength = Math.min(maxEditLength, options.maxEditLength);
  65. }
  66. var bestPath = [{
  67. newPos: -1,
  68. components: []
  69. }]; // Seed editLength = 0, i.e. the content starts with the same values
  70. var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
  71. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  72. // Identity per the equality and tokenizer
  73. return done([{
  74. value: this.join(newString),
  75. count: newString.length
  76. }]);
  77. } // Main worker method. checks all permutations of a given edit length for acceptance.
  78. function execEditLength() {
  79. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  80. var basePath = void 0;
  81. var addPath = bestPath[diagonalPath - 1],
  82. removePath = bestPath[diagonalPath + 1],
  83. _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  84. if (addPath) {
  85. // No one else is going to attempt to use this value, clear it
  86. bestPath[diagonalPath - 1] = undefined;
  87. }
  88. var canAdd = addPath && addPath.newPos + 1 < newLen,
  89. canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
  90. if (!canAdd && !canRemove) {
  91. // If this path is a terminal then prune
  92. bestPath[diagonalPath] = undefined;
  93. continue;
  94. } // Select the diagonal that we want to branch from. We select the prior
  95. // path whose position in the new string is the farthest from the origin
  96. // and does not pass the bounds of the diff graph
  97. if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
  98. basePath = clonePath(removePath);
  99. self.pushComponent(basePath.components, undefined, true);
  100. } else {
  101. basePath = addPath; // No need to clone, we've pulled it from the list
  102. basePath.newPos++;
  103. self.pushComponent(basePath.components, true, undefined);
  104. }
  105. _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
  106. if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
  107. return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
  108. } else {
  109. // Otherwise track this path as a potential candidate and continue.
  110. bestPath[diagonalPath] = basePath;
  111. }
  112. }
  113. editLength++;
  114. } // Performs the length of edit iteration. Is a bit fugly as this has to support the
  115. // sync and async mode which is never fun. Loops over execEditLength until a value
  116. // is produced, or until the edit length exceeds options.maxEditLength (if given),
  117. // in which case it will return undefined.
  118. if (callback) {
  119. (function exec() {
  120. setTimeout(function () {
  121. if (editLength > maxEditLength) {
  122. return callback();
  123. }
  124. if (!execEditLength()) {
  125. exec();
  126. }
  127. }, 0);
  128. })();
  129. } else {
  130. while (editLength <= maxEditLength) {
  131. var ret = execEditLength();
  132. if (ret) {
  133. return ret;
  134. }
  135. }
  136. }
  137. },
  138. pushComponent: function pushComponent(components, added, removed) {
  139. var last = components[components.length - 1];
  140. if (last && last.added === added && last.removed === removed) {
  141. // We need to clone here as the component clone operation is just
  142. // as shallow array clone
  143. components[components.length - 1] = {
  144. count: last.count + 1,
  145. added: added,
  146. removed: removed
  147. };
  148. } else {
  149. components.push({
  150. count: 1,
  151. added: added,
  152. removed: removed
  153. });
  154. }
  155. },
  156. extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
  157. var newLen = newString.length,
  158. oldLen = oldString.length,
  159. newPos = basePath.newPos,
  160. oldPos = newPos - diagonalPath,
  161. commonCount = 0;
  162. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
  163. newPos++;
  164. oldPos++;
  165. commonCount++;
  166. }
  167. if (commonCount) {
  168. basePath.components.push({
  169. count: commonCount
  170. });
  171. }
  172. basePath.newPos = newPos;
  173. return oldPos;
  174. },
  175. equals: function equals(left, right) {
  176. if (this.options.comparator) {
  177. return this.options.comparator(left, right);
  178. } else {
  179. return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
  180. }
  181. },
  182. removeEmpty: function removeEmpty(array) {
  183. var ret = [];
  184. for (var i = 0; i < array.length; i++) {
  185. if (array[i]) {
  186. ret.push(array[i]);
  187. }
  188. }
  189. return ret;
  190. },
  191. castInput: function castInput(value) {
  192. return value;
  193. },
  194. tokenize: function tokenize(value) {
  195. return value.split('');
  196. },
  197. join: function join(chars) {
  198. return chars.join('');
  199. }
  200. };
  201. function buildValues(diff, components, newString, oldString, useLongestToken) {
  202. var componentPos = 0,
  203. componentLen = components.length,
  204. newPos = 0,
  205. oldPos = 0;
  206. for (; componentPos < componentLen; componentPos++) {
  207. var component = components[componentPos];
  208. if (!component.removed) {
  209. if (!component.added && useLongestToken) {
  210. var value = newString.slice(newPos, newPos + component.count);
  211. value = value.map(function (value, i) {
  212. var oldValue = oldString[oldPos + i];
  213. return oldValue.length > value.length ? oldValue : value;
  214. });
  215. component.value = diff.join(value);
  216. } else {
  217. component.value = diff.join(newString.slice(newPos, newPos + component.count));
  218. }
  219. newPos += component.count; // Common case
  220. if (!component.added) {
  221. oldPos += component.count;
  222. }
  223. } else {
  224. component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
  225. oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
  226. // The diffing algorithm is tied to add then remove output and this is the simplest
  227. // route to get the desired output with minimal overhead.
  228. if (componentPos && components[componentPos - 1].added) {
  229. var tmp = components[componentPos - 1];
  230. components[componentPos - 1] = components[componentPos];
  231. components[componentPos] = tmp;
  232. }
  233. }
  234. } // Special case handle for when one terminal is ignored (i.e. whitespace).
  235. // For this case we merge the terminal into the prior string and drop the change.
  236. // This is only available for string mode.
  237. var lastComponent = components[componentLen - 1];
  238. if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
  239. components[componentLen - 2].value += lastComponent.value;
  240. components.pop();
  241. }
  242. return components;
  243. }
  244. function clonePath(path) {
  245. return {
  246. newPos: path.newPos,
  247. components: path.components.slice(0)
  248. };
  249. }
  250. var characterDiff = new Diff();
  251. function diffChars(oldStr, newStr, options) {
  252. return characterDiff.diff(oldStr, newStr, options);
  253. }
  254. function generateOptions(options, defaults) {
  255. if (typeof options === 'function') {
  256. defaults.callback = options;
  257. } else if (options) {
  258. for (var name in options) {
  259. /* istanbul ignore else */
  260. if (options.hasOwnProperty(name)) {
  261. defaults[name] = options[name];
  262. }
  263. }
  264. }
  265. return defaults;
  266. }
  267. //
  268. // Ranges and exceptions:
  269. // Latin-1 Supplement, 0080–00FF
  270. // - U+00D7 × Multiplication sign
  271. // - U+00F7 ÷ Division sign
  272. // Latin Extended-A, 0100–017F
  273. // Latin Extended-B, 0180–024F
  274. // IPA Extensions, 0250–02AF
  275. // Spacing Modifier Letters, 02B0–02FF
  276. // - U+02C7 ˇ &#711; Caron
  277. // - U+02D8 ˘ &#728; Breve
  278. // - U+02D9 ˙ &#729; Dot Above
  279. // - U+02DA ˚ &#730; Ring Above
  280. // - U+02DB ˛ &#731; Ogonek
  281. // - U+02DC ˜ &#732; Small Tilde
  282. // - U+02DD ˝ &#733; Double Acute Accent
  283. // Latin Extended Additional, 1E00–1EFF
  284. var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
  285. var reWhitespace = /\S/;
  286. var wordDiff = new Diff();
  287. wordDiff.equals = function (left, right) {
  288. if (this.options.ignoreCase) {
  289. left = left.toLowerCase();
  290. right = right.toLowerCase();
  291. }
  292. return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
  293. };
  294. wordDiff.tokenize = function (value) {
  295. // All whitespace symbols except newline group into one token, each newline - in separate token
  296. var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
  297. for (var i = 0; i < tokens.length - 1; i++) {
  298. // If we have an empty string in the next field and we have only word chars before and after, merge
  299. if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
  300. tokens[i] += tokens[i + 2];
  301. tokens.splice(i + 1, 2);
  302. i--;
  303. }
  304. }
  305. return tokens;
  306. };
  307. function diffWords(oldStr, newStr, options) {
  308. options = generateOptions(options, {
  309. ignoreWhitespace: true
  310. });
  311. return wordDiff.diff(oldStr, newStr, options);
  312. }
  313. function diffWordsWithSpace(oldStr, newStr, options) {
  314. return wordDiff.diff(oldStr, newStr, options);
  315. }
  316. var lineDiff = new Diff();
  317. lineDiff.tokenize = function (value) {
  318. var retLines = [],
  319. linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
  320. if (!linesAndNewlines[linesAndNewlines.length - 1]) {
  321. linesAndNewlines.pop();
  322. } // Merge the content and line separators into single tokens
  323. for (var i = 0; i < linesAndNewlines.length; i++) {
  324. var line = linesAndNewlines[i];
  325. if (i % 2 && !this.options.newlineIsToken) {
  326. retLines[retLines.length - 1] += line;
  327. } else {
  328. if (this.options.ignoreWhitespace) {
  329. line = line.trim();
  330. }
  331. retLines.push(line);
  332. }
  333. }
  334. return retLines;
  335. };
  336. function diffLines(oldStr, newStr, callback) {
  337. return lineDiff.diff(oldStr, newStr, callback);
  338. }
  339. function diffTrimmedLines(oldStr, newStr, callback) {
  340. var options = generateOptions(callback, {
  341. ignoreWhitespace: true
  342. });
  343. return lineDiff.diff(oldStr, newStr, options);
  344. }
  345. var sentenceDiff = new Diff();
  346. sentenceDiff.tokenize = function (value) {
  347. return value.split(/(\S.+?[.!?])(?=\s+|$)/);
  348. };
  349. function diffSentences(oldStr, newStr, callback) {
  350. return sentenceDiff.diff(oldStr, newStr, callback);
  351. }
  352. var cssDiff = new Diff();
  353. cssDiff.tokenize = function (value) {
  354. return value.split(/([{}:;,]|\s+)/);
  355. };
  356. function diffCss(oldStr, newStr, callback) {
  357. return cssDiff.diff(oldStr, newStr, callback);
  358. }
  359. function _typeof(obj) {
  360. "@babel/helpers - typeof";
  361. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  362. _typeof = function (obj) {
  363. return typeof obj;
  364. };
  365. } else {
  366. _typeof = function (obj) {
  367. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  368. };
  369. }
  370. return _typeof(obj);
  371. }
  372. function _toConsumableArray(arr) {
  373. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  374. }
  375. function _arrayWithoutHoles(arr) {
  376. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  377. }
  378. function _iterableToArray(iter) {
  379. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  380. }
  381. function _unsupportedIterableToArray(o, minLen) {
  382. if (!o) return;
  383. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  384. var n = Object.prototype.toString.call(o).slice(8, -1);
  385. if (n === "Object" && o.constructor) n = o.constructor.name;
  386. if (n === "Map" || n === "Set") return Array.from(o);
  387. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  388. }
  389. function _arrayLikeToArray(arr, len) {
  390. if (len == null || len > arr.length) len = arr.length;
  391. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  392. return arr2;
  393. }
  394. function _nonIterableSpread() {
  395. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  396. }
  397. var objectPrototypeToString = Object.prototype.toString;
  398. var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
  399. // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
  400. jsonDiff.useLongestToken = true;
  401. jsonDiff.tokenize = lineDiff.tokenize;
  402. jsonDiff.castInput = function (value) {
  403. var _this$options = this.options,
  404. undefinedReplacement = _this$options.undefinedReplacement,
  405. _this$options$stringi = _this$options.stringifyReplacer,
  406. stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
  407. return typeof v === 'undefined' ? undefinedReplacement : v;
  408. } : _this$options$stringi;
  409. return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
  410. };
  411. jsonDiff.equals = function (left, right) {
  412. return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
  413. };
  414. function diffJson(oldObj, newObj, options) {
  415. return jsonDiff.diff(oldObj, newObj, options);
  416. } // This function handles the presence of circular references by bailing out when encountering an
  417. // object that is already on the "stack" of items being processed. Accepts an optional replacer
  418. function canonicalize(obj, stack, replacementStack, replacer, key) {
  419. stack = stack || [];
  420. replacementStack = replacementStack || [];
  421. if (replacer) {
  422. obj = replacer(key, obj);
  423. }
  424. var i;
  425. for (i = 0; i < stack.length; i += 1) {
  426. if (stack[i] === obj) {
  427. return replacementStack[i];
  428. }
  429. }
  430. var canonicalizedObj;
  431. if ('[object Array]' === objectPrototypeToString.call(obj)) {
  432. stack.push(obj);
  433. canonicalizedObj = new Array(obj.length);
  434. replacementStack.push(canonicalizedObj);
  435. for (i = 0; i < obj.length; i += 1) {
  436. canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
  437. }
  438. stack.pop();
  439. replacementStack.pop();
  440. return canonicalizedObj;
  441. }
  442. if (obj && obj.toJSON) {
  443. obj = obj.toJSON();
  444. }
  445. if (_typeof(obj) === 'object' && obj !== null) {
  446. stack.push(obj);
  447. canonicalizedObj = {};
  448. replacementStack.push(canonicalizedObj);
  449. var sortedKeys = [],
  450. _key;
  451. for (_key in obj) {
  452. /* istanbul ignore else */
  453. if (obj.hasOwnProperty(_key)) {
  454. sortedKeys.push(_key);
  455. }
  456. }
  457. sortedKeys.sort();
  458. for (i = 0; i < sortedKeys.length; i += 1) {
  459. _key = sortedKeys[i];
  460. canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
  461. }
  462. stack.pop();
  463. replacementStack.pop();
  464. } else {
  465. canonicalizedObj = obj;
  466. }
  467. return canonicalizedObj;
  468. }
  469. var arrayDiff = new Diff();
  470. arrayDiff.tokenize = function (value) {
  471. return value.slice();
  472. };
  473. arrayDiff.join = arrayDiff.removeEmpty = function (value) {
  474. return value;
  475. };
  476. function diffArrays(oldArr, newArr, callback) {
  477. return arrayDiff.diff(oldArr, newArr, callback);
  478. }
  479. function parsePatch(uniDiff) {
  480. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  481. var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
  482. delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  483. list = [],
  484. i = 0;
  485. function parseIndex() {
  486. var index = {};
  487. list.push(index); // Parse diff metadata
  488. while (i < diffstr.length) {
  489. var line = diffstr[i]; // File header found, end parsing diff metadata
  490. if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
  491. break;
  492. } // Diff index
  493. var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
  494. if (header) {
  495. index.index = header[1];
  496. }
  497. i++;
  498. } // Parse file headers if they are defined. Unified diff requires them, but
  499. // there's no technical issues to have an isolated hunk without file header
  500. parseFileHeader(index);
  501. parseFileHeader(index); // Parse hunks
  502. index.hunks = [];
  503. while (i < diffstr.length) {
  504. var _line = diffstr[i];
  505. if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
  506. break;
  507. } else if (/^@@/.test(_line)) {
  508. index.hunks.push(parseHunk());
  509. } else if (_line && options.strict) {
  510. // Ignore unexpected content unless in strict mode
  511. throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
  512. } else {
  513. i++;
  514. }
  515. }
  516. } // Parses the --- and +++ headers, if none are found, no lines
  517. // are consumed.
  518. function parseFileHeader(index) {
  519. var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
  520. if (fileHeader) {
  521. var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
  522. var data = fileHeader[2].split('\t', 2);
  523. var fileName = data[0].replace(/\\\\/g, '\\');
  524. if (/^".*"$/.test(fileName)) {
  525. fileName = fileName.substr(1, fileName.length - 2);
  526. }
  527. index[keyPrefix + 'FileName'] = fileName;
  528. index[keyPrefix + 'Header'] = (data[1] || '').trim();
  529. i++;
  530. }
  531. } // Parses a hunk
  532. // This assumes that we are at the start of a hunk.
  533. function parseHunk() {
  534. var chunkHeaderIndex = i,
  535. chunkHeaderLine = diffstr[i++],
  536. chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
  537. var hunk = {
  538. oldStart: +chunkHeader[1],
  539. oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
  540. newStart: +chunkHeader[3],
  541. newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
  542. lines: [],
  543. linedelimiters: []
  544. }; // Unified Diff Format quirk: If the chunk size is 0,
  545. // the first number is one lower than one would expect.
  546. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
  547. if (hunk.oldLines === 0) {
  548. hunk.oldStart += 1;
  549. }
  550. if (hunk.newLines === 0) {
  551. hunk.newStart += 1;
  552. }
  553. var addCount = 0,
  554. removeCount = 0;
  555. for (; i < diffstr.length; i++) {
  556. // Lines starting with '---' could be mistaken for the "remove line" operation
  557. // But they could be the header for the next file. Therefore prune such cases out.
  558. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
  559. break;
  560. }
  561. var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
  562. if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
  563. hunk.lines.push(diffstr[i]);
  564. hunk.linedelimiters.push(delimiters[i] || '\n');
  565. if (operation === '+') {
  566. addCount++;
  567. } else if (operation === '-') {
  568. removeCount++;
  569. } else if (operation === ' ') {
  570. addCount++;
  571. removeCount++;
  572. }
  573. } else {
  574. break;
  575. }
  576. } // Handle the empty block count case
  577. if (!addCount && hunk.newLines === 1) {
  578. hunk.newLines = 0;
  579. }
  580. if (!removeCount && hunk.oldLines === 1) {
  581. hunk.oldLines = 0;
  582. } // Perform optional sanity checking
  583. if (options.strict) {
  584. if (addCount !== hunk.newLines) {
  585. throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  586. }
  587. if (removeCount !== hunk.oldLines) {
  588. throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  589. }
  590. }
  591. return hunk;
  592. }
  593. while (i < diffstr.length) {
  594. parseIndex();
  595. }
  596. return list;
  597. }
  598. // Iterator that traverses in the range of [min, max], stepping
  599. // by distance from a given start position. I.e. for [0, 4], with
  600. // start of 2, this will iterate 2, 3, 1, 4, 0.
  601. function distanceIterator (start, minLine, maxLine) {
  602. var wantForward = true,
  603. backwardExhausted = false,
  604. forwardExhausted = false,
  605. localOffset = 1;
  606. return function iterator() {
  607. if (wantForward && !forwardExhausted) {
  608. if (backwardExhausted) {
  609. localOffset++;
  610. } else {
  611. wantForward = false;
  612. } // Check if trying to fit beyond text length, and if not, check it fits
  613. // after offset location (or desired location on first iteration)
  614. if (start + localOffset <= maxLine) {
  615. return localOffset;
  616. }
  617. forwardExhausted = true;
  618. }
  619. if (!backwardExhausted) {
  620. if (!forwardExhausted) {
  621. wantForward = true;
  622. } // Check if trying to fit before text beginning, and if not, check it fits
  623. // before offset location
  624. if (minLine <= start - localOffset) {
  625. return -localOffset++;
  626. }
  627. backwardExhausted = true;
  628. return iterator();
  629. } // We tried to fit hunk before text beginning and beyond text length, then
  630. // hunk can't fit on the text. Return undefined
  631. };
  632. }
  633. function applyPatch(source, uniDiff) {
  634. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  635. if (typeof uniDiff === 'string') {
  636. uniDiff = parsePatch(uniDiff);
  637. }
  638. if (Array.isArray(uniDiff)) {
  639. if (uniDiff.length > 1) {
  640. throw new Error('applyPatch only works with a single input.');
  641. }
  642. uniDiff = uniDiff[0];
  643. } // Apply the diff to the input
  644. var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
  645. delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  646. hunks = uniDiff.hunks,
  647. compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
  648. return line === patchContent;
  649. },
  650. errorCount = 0,
  651. fuzzFactor = options.fuzzFactor || 0,
  652. minLine = 0,
  653. offset = 0,
  654. removeEOFNL,
  655. addEOFNL;
  656. /**
  657. * Checks if the hunk exactly fits on the provided location
  658. */
  659. function hunkFits(hunk, toPos) {
  660. for (var j = 0; j < hunk.lines.length; j++) {
  661. var line = hunk.lines[j],
  662. operation = line.length > 0 ? line[0] : ' ',
  663. content = line.length > 0 ? line.substr(1) : line;
  664. if (operation === ' ' || operation === '-') {
  665. // Context sanity check
  666. if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
  667. errorCount++;
  668. if (errorCount > fuzzFactor) {
  669. return false;
  670. }
  671. }
  672. toPos++;
  673. }
  674. }
  675. return true;
  676. } // Search best fit offsets for each hunk based on the previous ones
  677. for (var i = 0; i < hunks.length; i++) {
  678. var hunk = hunks[i],
  679. maxLine = lines.length - hunk.oldLines,
  680. localOffset = 0,
  681. toPos = offset + hunk.oldStart - 1;
  682. var iterator = distanceIterator(toPos, minLine, maxLine);
  683. for (; localOffset !== undefined; localOffset = iterator()) {
  684. if (hunkFits(hunk, toPos + localOffset)) {
  685. hunk.offset = offset += localOffset;
  686. break;
  687. }
  688. }
  689. if (localOffset === undefined) {
  690. return false;
  691. } // Set lower text limit to end of the current hunk, so next ones don't try
  692. // to fit over already patched text
  693. minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
  694. } // Apply patch hunks
  695. var diffOffset = 0;
  696. for (var _i = 0; _i < hunks.length; _i++) {
  697. var _hunk = hunks[_i],
  698. _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
  699. diffOffset += _hunk.newLines - _hunk.oldLines;
  700. for (var j = 0; j < _hunk.lines.length; j++) {
  701. var line = _hunk.lines[j],
  702. operation = line.length > 0 ? line[0] : ' ',
  703. content = line.length > 0 ? line.substr(1) : line,
  704. delimiter = _hunk.linedelimiters[j];
  705. if (operation === ' ') {
  706. _toPos++;
  707. } else if (operation === '-') {
  708. lines.splice(_toPos, 1);
  709. delimiters.splice(_toPos, 1);
  710. /* istanbul ignore else */
  711. } else if (operation === '+') {
  712. lines.splice(_toPos, 0, content);
  713. delimiters.splice(_toPos, 0, delimiter);
  714. _toPos++;
  715. } else if (operation === '\\') {
  716. var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
  717. if (previousOperation === '+') {
  718. removeEOFNL = true;
  719. } else if (previousOperation === '-') {
  720. addEOFNL = true;
  721. }
  722. }
  723. }
  724. } // Handle EOFNL insertion/removal
  725. if (removeEOFNL) {
  726. while (!lines[lines.length - 1]) {
  727. lines.pop();
  728. delimiters.pop();
  729. }
  730. } else if (addEOFNL) {
  731. lines.push('');
  732. delimiters.push('\n');
  733. }
  734. for (var _k = 0; _k < lines.length - 1; _k++) {
  735. lines[_k] = lines[_k] + delimiters[_k];
  736. }
  737. return lines.join('');
  738. } // Wrapper that supports multiple file patches via callbacks.
  739. function applyPatches(uniDiff, options) {
  740. if (typeof uniDiff === 'string') {
  741. uniDiff = parsePatch(uniDiff);
  742. }
  743. var currentIndex = 0;
  744. function processIndex() {
  745. var index = uniDiff[currentIndex++];
  746. if (!index) {
  747. return options.complete();
  748. }
  749. options.loadFile(index, function (err, data) {
  750. if (err) {
  751. return options.complete(err);
  752. }
  753. var updatedContent = applyPatch(data, index, options);
  754. options.patched(index, updatedContent, function (err) {
  755. if (err) {
  756. return options.complete(err);
  757. }
  758. processIndex();
  759. });
  760. });
  761. }
  762. processIndex();
  763. }
  764. function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  765. if (!options) {
  766. options = {};
  767. }
  768. if (typeof options.context === 'undefined') {
  769. options.context = 4;
  770. }
  771. var diff = diffLines(oldStr, newStr, options);
  772. if (!diff) {
  773. return;
  774. }
  775. diff.push({
  776. value: '',
  777. lines: []
  778. }); // Append an empty value to make cleanup easier
  779. function contextLines(lines) {
  780. return lines.map(function (entry) {
  781. return ' ' + entry;
  782. });
  783. }
  784. var hunks = [];
  785. var oldRangeStart = 0,
  786. newRangeStart = 0,
  787. curRange = [],
  788. oldLine = 1,
  789. newLine = 1;
  790. var _loop = function _loop(i) {
  791. var current = diff[i],
  792. lines = current.lines || current.value.replace(/\n$/, '').split('\n');
  793. current.lines = lines;
  794. if (current.added || current.removed) {
  795. var _curRange;
  796. // If we have previous context, start with that
  797. if (!oldRangeStart) {
  798. var prev = diff[i - 1];
  799. oldRangeStart = oldLine;
  800. newRangeStart = newLine;
  801. if (prev) {
  802. curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
  803. oldRangeStart -= curRange.length;
  804. newRangeStart -= curRange.length;
  805. }
  806. } // Output our changes
  807. (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
  808. return (current.added ? '+' : '-') + entry;
  809. }))); // Track the updated file position
  810. if (current.added) {
  811. newLine += lines.length;
  812. } else {
  813. oldLine += lines.length;
  814. }
  815. } else {
  816. // Identical context lines. Track line changes
  817. if (oldRangeStart) {
  818. // Close out any changes that have been output (or join overlapping)
  819. if (lines.length <= options.context * 2 && i < diff.length - 2) {
  820. var _curRange2;
  821. // Overlapping
  822. (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
  823. } else {
  824. var _curRange3;
  825. // end the range and output
  826. var contextSize = Math.min(lines.length, options.context);
  827. (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
  828. var hunk = {
  829. oldStart: oldRangeStart,
  830. oldLines: oldLine - oldRangeStart + contextSize,
  831. newStart: newRangeStart,
  832. newLines: newLine - newRangeStart + contextSize,
  833. lines: curRange
  834. };
  835. if (i >= diff.length - 2 && lines.length <= options.context) {
  836. // EOF is inside this hunk
  837. var oldEOFNewline = /\n$/.test(oldStr);
  838. var newEOFNewline = /\n$/.test(newStr);
  839. var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
  840. if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
  841. // special case: old has no eol and no trailing context; no-nl can end up before adds
  842. // however, if the old file is empty, do not output the no-nl line
  843. curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
  844. }
  845. if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
  846. curRange.push('\\ No newline at end of file');
  847. }
  848. }
  849. hunks.push(hunk);
  850. oldRangeStart = 0;
  851. newRangeStart = 0;
  852. curRange = [];
  853. }
  854. }
  855. oldLine += lines.length;
  856. newLine += lines.length;
  857. }
  858. };
  859. for (var i = 0; i < diff.length; i++) {
  860. _loop(i);
  861. }
  862. return {
  863. oldFileName: oldFileName,
  864. newFileName: newFileName,
  865. oldHeader: oldHeader,
  866. newHeader: newHeader,
  867. hunks: hunks
  868. };
  869. }
  870. function formatPatch(diff) {
  871. var ret = [];
  872. if (diff.oldFileName == diff.newFileName) {
  873. ret.push('Index: ' + diff.oldFileName);
  874. }
  875. ret.push('===================================================================');
  876. ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
  877. ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
  878. for (var i = 0; i < diff.hunks.length; i++) {
  879. var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0,
  880. // the first number is one lower than one would expect.
  881. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
  882. if (hunk.oldLines === 0) {
  883. hunk.oldStart -= 1;
  884. }
  885. if (hunk.newLines === 0) {
  886. hunk.newStart -= 1;
  887. }
  888. ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
  889. ret.push.apply(ret, hunk.lines);
  890. }
  891. return ret.join('\n') + '\n';
  892. }
  893. function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  894. return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
  895. }
  896. function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
  897. return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
  898. }
  899. function arrayEqual(a, b) {
  900. if (a.length !== b.length) {
  901. return false;
  902. }
  903. return arrayStartsWith(a, b);
  904. }
  905. function arrayStartsWith(array, start) {
  906. if (start.length > array.length) {
  907. return false;
  908. }
  909. for (var i = 0; i < start.length; i++) {
  910. if (start[i] !== array[i]) {
  911. return false;
  912. }
  913. }
  914. return true;
  915. }
  916. function calcLineCount(hunk) {
  917. var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
  918. oldLines = _calcOldNewLineCount.oldLines,
  919. newLines = _calcOldNewLineCount.newLines;
  920. if (oldLines !== undefined) {
  921. hunk.oldLines = oldLines;
  922. } else {
  923. delete hunk.oldLines;
  924. }
  925. if (newLines !== undefined) {
  926. hunk.newLines = newLines;
  927. } else {
  928. delete hunk.newLines;
  929. }
  930. }
  931. function merge(mine, theirs, base) {
  932. mine = loadPatch(mine, base);
  933. theirs = loadPatch(theirs, base);
  934. var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
  935. // Leaving sanity checks on this to the API consumer that may know more about the
  936. // meaning in their own context.
  937. if (mine.index || theirs.index) {
  938. ret.index = mine.index || theirs.index;
  939. }
  940. if (mine.newFileName || theirs.newFileName) {
  941. if (!fileNameChanged(mine)) {
  942. // No header or no change in ours, use theirs (and ours if theirs does not exist)
  943. ret.oldFileName = theirs.oldFileName || mine.oldFileName;
  944. ret.newFileName = theirs.newFileName || mine.newFileName;
  945. ret.oldHeader = theirs.oldHeader || mine.oldHeader;
  946. ret.newHeader = theirs.newHeader || mine.newHeader;
  947. } else if (!fileNameChanged(theirs)) {
  948. // No header or no change in theirs, use ours
  949. ret.oldFileName = mine.oldFileName;
  950. ret.newFileName = mine.newFileName;
  951. ret.oldHeader = mine.oldHeader;
  952. ret.newHeader = mine.newHeader;
  953. } else {
  954. // Both changed... figure it out
  955. ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
  956. ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
  957. ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
  958. ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
  959. }
  960. }
  961. ret.hunks = [];
  962. var mineIndex = 0,
  963. theirsIndex = 0,
  964. mineOffset = 0,
  965. theirsOffset = 0;
  966. while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
  967. var mineCurrent = mine.hunks[mineIndex] || {
  968. oldStart: Infinity
  969. },
  970. theirsCurrent = theirs.hunks[theirsIndex] || {
  971. oldStart: Infinity
  972. };
  973. if (hunkBefore(mineCurrent, theirsCurrent)) {
  974. // This patch does not overlap with any of the others, yay.
  975. ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
  976. mineIndex++;
  977. theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
  978. } else if (hunkBefore(theirsCurrent, mineCurrent)) {
  979. // This patch does not overlap with any of the others, yay.
  980. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
  981. theirsIndex++;
  982. mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
  983. } else {
  984. // Overlap, merge as best we can
  985. var mergedHunk = {
  986. oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
  987. oldLines: 0,
  988. newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
  989. newLines: 0,
  990. lines: []
  991. };
  992. mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
  993. theirsIndex++;
  994. mineIndex++;
  995. ret.hunks.push(mergedHunk);
  996. }
  997. }
  998. return ret;
  999. }
  1000. function loadPatch(param, base) {
  1001. if (typeof param === 'string') {
  1002. if (/^@@/m.test(param) || /^Index:/m.test(param)) {
  1003. return parsePatch(param)[0];
  1004. }
  1005. if (!base) {
  1006. throw new Error('Must provide a base reference or pass in a patch');
  1007. }
  1008. return structuredPatch(undefined, undefined, base, param);
  1009. }
  1010. return param;
  1011. }
  1012. function fileNameChanged(patch) {
  1013. return patch.newFileName && patch.newFileName !== patch.oldFileName;
  1014. }
  1015. function selectField(index, mine, theirs) {
  1016. if (mine === theirs) {
  1017. return mine;
  1018. } else {
  1019. index.conflict = true;
  1020. return {
  1021. mine: mine,
  1022. theirs: theirs
  1023. };
  1024. }
  1025. }
  1026. function hunkBefore(test, check) {
  1027. return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
  1028. }
  1029. function cloneHunk(hunk, offset) {
  1030. return {
  1031. oldStart: hunk.oldStart,
  1032. oldLines: hunk.oldLines,
  1033. newStart: hunk.newStart + offset,
  1034. newLines: hunk.newLines,
  1035. lines: hunk.lines
  1036. };
  1037. }
  1038. function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
  1039. // This will generally result in a conflicted hunk, but there are cases where the context
  1040. // is the only overlap where we can successfully merge the content here.
  1041. var mine = {
  1042. offset: mineOffset,
  1043. lines: mineLines,
  1044. index: 0
  1045. },
  1046. their = {
  1047. offset: theirOffset,
  1048. lines: theirLines,
  1049. index: 0
  1050. }; // Handle any leading content
  1051. insertLeading(hunk, mine, their);
  1052. insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
  1053. while (mine.index < mine.lines.length && their.index < their.lines.length) {
  1054. var mineCurrent = mine.lines[mine.index],
  1055. theirCurrent = their.lines[their.index];
  1056. if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
  1057. // Both modified ...
  1058. mutualChange(hunk, mine, their);
  1059. } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
  1060. var _hunk$lines;
  1061. // Mine inserted
  1062. (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
  1063. } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
  1064. var _hunk$lines2;
  1065. // Theirs inserted
  1066. (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
  1067. } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
  1068. // Mine removed or edited
  1069. removal(hunk, mine, their);
  1070. } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
  1071. // Their removed or edited
  1072. removal(hunk, their, mine, true);
  1073. } else if (mineCurrent === theirCurrent) {
  1074. // Context identity
  1075. hunk.lines.push(mineCurrent);
  1076. mine.index++;
  1077. their.index++;
  1078. } else {
  1079. // Context mismatch
  1080. conflict(hunk, collectChange(mine), collectChange(their));
  1081. }
  1082. } // Now push anything that may be remaining
  1083. insertTrailing(hunk, mine);
  1084. insertTrailing(hunk, their);
  1085. calcLineCount(hunk);
  1086. }
  1087. function mutualChange(hunk, mine, their) {
  1088. var myChanges = collectChange(mine),
  1089. theirChanges = collectChange(their);
  1090. if (allRemoves(myChanges) && allRemoves(theirChanges)) {
  1091. // Special case for remove changes that are supersets of one another
  1092. if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
  1093. var _hunk$lines3;
  1094. (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
  1095. return;
  1096. } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
  1097. var _hunk$lines4;
  1098. (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
  1099. return;
  1100. }
  1101. } else if (arrayEqual(myChanges, theirChanges)) {
  1102. var _hunk$lines5;
  1103. (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
  1104. return;
  1105. }
  1106. conflict(hunk, myChanges, theirChanges);
  1107. }
  1108. function removal(hunk, mine, their, swap) {
  1109. var myChanges = collectChange(mine),
  1110. theirChanges = collectContext(their, myChanges);
  1111. if (theirChanges.merged) {
  1112. var _hunk$lines6;
  1113. (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
  1114. } else {
  1115. conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
  1116. }
  1117. }
  1118. function conflict(hunk, mine, their) {
  1119. hunk.conflict = true;
  1120. hunk.lines.push({
  1121. conflict: true,
  1122. mine: mine,
  1123. theirs: their
  1124. });
  1125. }
  1126. function insertLeading(hunk, insert, their) {
  1127. while (insert.offset < their.offset && insert.index < insert.lines.length) {
  1128. var line = insert.lines[insert.index++];
  1129. hunk.lines.push(line);
  1130. insert.offset++;
  1131. }
  1132. }
  1133. function insertTrailing(hunk, insert) {
  1134. while (insert.index < insert.lines.length) {
  1135. var line = insert.lines[insert.index++];
  1136. hunk.lines.push(line);
  1137. }
  1138. }
  1139. function collectChange(state) {
  1140. var ret = [],
  1141. operation = state.lines[state.index][0];
  1142. while (state.index < state.lines.length) {
  1143. var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
  1144. if (operation === '-' && line[0] === '+') {
  1145. operation = '+';
  1146. }
  1147. if (operation === line[0]) {
  1148. ret.push(line);
  1149. state.index++;
  1150. } else {
  1151. break;
  1152. }
  1153. }
  1154. return ret;
  1155. }
  1156. function collectContext(state, matchChanges) {
  1157. var changes = [],
  1158. merged = [],
  1159. matchIndex = 0,
  1160. contextChanges = false,
  1161. conflicted = false;
  1162. while (matchIndex < matchChanges.length && state.index < state.lines.length) {
  1163. var change = state.lines[state.index],
  1164. match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
  1165. if (match[0] === '+') {
  1166. break;
  1167. }
  1168. contextChanges = contextChanges || change[0] !== ' ';
  1169. merged.push(match);
  1170. matchIndex++; // Consume any additions in the other block as a conflict to attempt
  1171. // to pull in the remaining context after this
  1172. if (change[0] === '+') {
  1173. conflicted = true;
  1174. while (change[0] === '+') {
  1175. changes.push(change);
  1176. change = state.lines[++state.index];
  1177. }
  1178. }
  1179. if (match.substr(1) === change.substr(1)) {
  1180. changes.push(change);
  1181. state.index++;
  1182. } else {
  1183. conflicted = true;
  1184. }
  1185. }
  1186. if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
  1187. conflicted = true;
  1188. }
  1189. if (conflicted) {
  1190. return changes;
  1191. }
  1192. while (matchIndex < matchChanges.length) {
  1193. merged.push(matchChanges[matchIndex++]);
  1194. }
  1195. return {
  1196. merged: merged,
  1197. changes: changes
  1198. };
  1199. }
  1200. function allRemoves(changes) {
  1201. return changes.reduce(function (prev, change) {
  1202. return prev && change[0] === '-';
  1203. }, true);
  1204. }
  1205. function skipRemoveSuperset(state, removeChanges, delta) {
  1206. for (var i = 0; i < delta; i++) {
  1207. var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
  1208. if (state.lines[state.index + i] !== ' ' + changeContent) {
  1209. return false;
  1210. }
  1211. }
  1212. state.index += delta;
  1213. return true;
  1214. }
  1215. function calcOldNewLineCount(lines) {
  1216. var oldLines = 0;
  1217. var newLines = 0;
  1218. lines.forEach(function (line) {
  1219. if (typeof line !== 'string') {
  1220. var myCount = calcOldNewLineCount(line.mine);
  1221. var theirCount = calcOldNewLineCount(line.theirs);
  1222. if (oldLines !== undefined) {
  1223. if (myCount.oldLines === theirCount.oldLines) {
  1224. oldLines += myCount.oldLines;
  1225. } else {
  1226. oldLines = undefined;
  1227. }
  1228. }
  1229. if (newLines !== undefined) {
  1230. if (myCount.newLines === theirCount.newLines) {
  1231. newLines += myCount.newLines;
  1232. } else {
  1233. newLines = undefined;
  1234. }
  1235. }
  1236. } else {
  1237. if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
  1238. newLines++;
  1239. }
  1240. if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
  1241. oldLines++;
  1242. }
  1243. }
  1244. });
  1245. return {
  1246. oldLines: oldLines,
  1247. newLines: newLines
  1248. };
  1249. }
  1250. // See: http://code.google.com/p/google-diff-match-patch/wiki/API
  1251. function convertChangesToDMP(changes) {
  1252. var ret = [],
  1253. change,
  1254. operation;
  1255. for (var i = 0; i < changes.length; i++) {
  1256. change = changes[i];
  1257. if (change.added) {
  1258. operation = 1;
  1259. } else if (change.removed) {
  1260. operation = -1;
  1261. } else {
  1262. operation = 0;
  1263. }
  1264. ret.push([operation, change.value]);
  1265. }
  1266. return ret;
  1267. }
  1268. function convertChangesToXML(changes) {
  1269. var ret = [];
  1270. for (var i = 0; i < changes.length; i++) {
  1271. var change = changes[i];
  1272. if (change.added) {
  1273. ret.push('<ins>');
  1274. } else if (change.removed) {
  1275. ret.push('<del>');
  1276. }
  1277. ret.push(escapeHTML(change.value));
  1278. if (change.added) {
  1279. ret.push('</ins>');
  1280. } else if (change.removed) {
  1281. ret.push('</del>');
  1282. }
  1283. }
  1284. return ret.join('');
  1285. }
  1286. function escapeHTML(s) {
  1287. var n = s;
  1288. n = n.replace(/&/g, '&amp;');
  1289. n = n.replace(/</g, '&lt;');
  1290. n = n.replace(/>/g, '&gt;');
  1291. n = n.replace(/"/g, '&quot;');
  1292. return n;
  1293. }
  1294. exports.Diff = Diff;
  1295. exports.applyPatch = applyPatch;
  1296. exports.applyPatches = applyPatches;
  1297. exports.canonicalize = canonicalize;
  1298. exports.convertChangesToDMP = convertChangesToDMP;
  1299. exports.convertChangesToXML = convertChangesToXML;
  1300. exports.createPatch = createPatch;
  1301. exports.createTwoFilesPatch = createTwoFilesPatch;
  1302. exports.diffArrays = diffArrays;
  1303. exports.diffChars = diffChars;
  1304. exports.diffCss = diffCss;
  1305. exports.diffJson = diffJson;
  1306. exports.diffLines = diffLines;
  1307. exports.diffSentences = diffSentences;
  1308. exports.diffTrimmedLines = diffTrimmedLines;
  1309. exports.diffWords = diffWords;
  1310. exports.diffWordsWithSpace = diffWordsWithSpace;
  1311. exports.merge = merge;
  1312. exports.parsePatch = parsePatch;
  1313. exports.structuredPatch = structuredPatch;
  1314. Object.defineProperty(exports, '__esModule', { value: true });
  1315. })));