384.index.js 158 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059
  1. exports.id = 384;
  2. exports.ids = [384];
  3. exports.modules = {
  4. /***/ 52027:
  5. /***/ ((module) => {
  6. /**
  7. * Diff Match and Patch
  8. * Copyright 2018 The diff-match-patch Authors.
  9. * https://github.com/google/diff-match-patch
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /**
  24. * @fileoverview Computes the difference between two texts to create a patch.
  25. * Applies the patch onto another text, allowing for errors.
  26. * @author fraser@google.com (Neil Fraser)
  27. */
  28. /**
  29. * Class containing the diff, match and patch methods.
  30. * @constructor
  31. */
  32. var diff_match_patch = function() {
  33. // Defaults.
  34. // Redefine these in your program to override the defaults.
  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. // The number of bits in an int.
  53. this.Match_MaxBits = 32;
  54. };
  55. // DIFF FUNCTIONS
  56. /**
  57. * The data structure representing a diff is an array of tuples:
  58. * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
  59. * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
  60. */
  61. var DIFF_DELETE = -1;
  62. var DIFF_INSERT = 1;
  63. var DIFF_EQUAL = 0;
  64. /**
  65. * Class representing one diff tuple.
  66. * ~Attempts to look like a two-element array (which is what this used to be).~
  67. * Constructor returns an actual two-element array, to allow destructing @JackuB
  68. * See https://github.com/JackuB/diff-match-patch/issues/14 for details
  69. * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.
  70. * @param {string} text Text to be deleted, inserted, or retained.
  71. * @constructor
  72. */
  73. diff_match_patch.Diff = function(op, text) {
  74. return [op, text];
  75. };
  76. /**
  77. * Find the differences between two texts. Simplifies the problem by stripping
  78. * any common prefix or suffix off the texts before diffing.
  79. * @param {string} text1 Old string to be diffed.
  80. * @param {string} text2 New string to be diffed.
  81. * @param {boolean=} opt_checklines Optional speedup flag. If present and false,
  82. * then don't run a line-level diff first to identify the changed areas.
  83. * Defaults to true, which does a faster, slightly less optimal diff.
  84. * @param {number=} opt_deadline Optional time when the diff should be complete
  85. * by. Used internally for recursive calls. Users should set DiffTimeout
  86. * instead.
  87. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  88. */
  89. diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,
  90. opt_deadline) {
  91. // Set a deadline by which time the diff must be complete.
  92. if (typeof opt_deadline == 'undefined') {
  93. if (this.Diff_Timeout <= 0) {
  94. opt_deadline = Number.MAX_VALUE;
  95. } else {
  96. opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;
  97. }
  98. }
  99. var deadline = opt_deadline;
  100. // Check for null inputs.
  101. if (text1 == null || text2 == null) {
  102. throw new Error('Null input. (diff_main)');
  103. }
  104. // Check for equality (speedup).
  105. if (text1 == text2) {
  106. if (text1) {
  107. return [new diff_match_patch.Diff(DIFF_EQUAL, text1)];
  108. }
  109. return [];
  110. }
  111. if (typeof opt_checklines == 'undefined') {
  112. opt_checklines = true;
  113. }
  114. var checklines = opt_checklines;
  115. // Trim off common prefix (speedup).
  116. var commonlength = this.diff_commonPrefix(text1, text2);
  117. var commonprefix = text1.substring(0, commonlength);
  118. text1 = text1.substring(commonlength);
  119. text2 = text2.substring(commonlength);
  120. // Trim off common suffix (speedup).
  121. commonlength = this.diff_commonSuffix(text1, text2);
  122. var commonsuffix = text1.substring(text1.length - commonlength);
  123. text1 = text1.substring(0, text1.length - commonlength);
  124. text2 = text2.substring(0, text2.length - commonlength);
  125. // Compute the diff on the middle block.
  126. var diffs = this.diff_compute_(text1, text2, checklines, deadline);
  127. // Restore the prefix and suffix.
  128. if (commonprefix) {
  129. diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, commonprefix));
  130. }
  131. if (commonsuffix) {
  132. diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, commonsuffix));
  133. }
  134. this.diff_cleanupMerge(diffs);
  135. return diffs;
  136. };
  137. /**
  138. * Find the differences between two texts. Assumes that the texts do not
  139. * have any common prefix or suffix.
  140. * @param {string} text1 Old string to be diffed.
  141. * @param {string} text2 New string to be diffed.
  142. * @param {boolean} checklines Speedup flag. If false, then don't run a
  143. * line-level diff first to identify the changed areas.
  144. * If true, then run a faster, slightly less optimal diff.
  145. * @param {number} deadline Time when the diff should be complete by.
  146. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  147. * @private
  148. */
  149. diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,
  150. deadline) {
  151. var diffs;
  152. if (!text1) {
  153. // Just add some text (speedup).
  154. return [new diff_match_patch.Diff(DIFF_INSERT, text2)];
  155. }
  156. if (!text2) {
  157. // Just delete some text (speedup).
  158. return [new diff_match_patch.Diff(DIFF_DELETE, text1)];
  159. }
  160. var longtext = text1.length > text2.length ? text1 : text2;
  161. var shorttext = text1.length > text2.length ? text2 : text1;
  162. var i = longtext.indexOf(shorttext);
  163. if (i != -1) {
  164. // Shorter text is inside the longer text (speedup).
  165. diffs = [new diff_match_patch.Diff(DIFF_INSERT, longtext.substring(0, i)),
  166. new diff_match_patch.Diff(DIFF_EQUAL, shorttext),
  167. new diff_match_patch.Diff(DIFF_INSERT,
  168. longtext.substring(i + shorttext.length))];
  169. // Swap insertions for deletions if diff is reversed.
  170. if (text1.length > text2.length) {
  171. diffs[0][0] = diffs[2][0] = DIFF_DELETE;
  172. }
  173. return diffs;
  174. }
  175. if (shorttext.length == 1) {
  176. // Single character string.
  177. // After the previous speedup, the character can't be an equality.
  178. return [new diff_match_patch.Diff(DIFF_DELETE, text1),
  179. new diff_match_patch.Diff(DIFF_INSERT, text2)];
  180. }
  181. // Check to see if the problem can be split in two.
  182. var hm = this.diff_halfMatch_(text1, text2);
  183. if (hm) {
  184. // A half-match was found, sort out the return data.
  185. var text1_a = hm[0];
  186. var text1_b = hm[1];
  187. var text2_a = hm[2];
  188. var text2_b = hm[3];
  189. var mid_common = hm[4];
  190. // Send both pairs off for separate processing.
  191. var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);
  192. var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);
  193. // Merge the results.
  194. return diffs_a.concat([new diff_match_patch.Diff(DIFF_EQUAL, mid_common)],
  195. diffs_b);
  196. }
  197. if (checklines && text1.length > 100 && text2.length > 100) {
  198. return this.diff_lineMode_(text1, text2, deadline);
  199. }
  200. return this.diff_bisect_(text1, text2, deadline);
  201. };
  202. /**
  203. * Do a quick line-level diff on both strings, then rediff the parts for
  204. * greater accuracy.
  205. * This speedup can produce non-minimal diffs.
  206. * @param {string} text1 Old string to be diffed.
  207. * @param {string} text2 New string to be diffed.
  208. * @param {number} deadline Time when the diff should be complete by.
  209. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  210. * @private
  211. */
  212. diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {
  213. // Scan the text on a line-by-line basis first.
  214. var a = this.diff_linesToChars_(text1, text2);
  215. text1 = a.chars1;
  216. text2 = a.chars2;
  217. var linearray = a.lineArray;
  218. var diffs = this.diff_main(text1, text2, false, deadline);
  219. // Convert the diff back to original text.
  220. this.diff_charsToLines_(diffs, linearray);
  221. // Eliminate freak matches (e.g. blank lines)
  222. this.diff_cleanupSemantic(diffs);
  223. // Rediff any replacement blocks, this time character-by-character.
  224. // Add a dummy entry at the end.
  225. diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));
  226. var pointer = 0;
  227. var count_delete = 0;
  228. var count_insert = 0;
  229. var text_delete = '';
  230. var text_insert = '';
  231. while (pointer < diffs.length) {
  232. switch (diffs[pointer][0]) {
  233. case DIFF_INSERT:
  234. count_insert++;
  235. text_insert += diffs[pointer][1];
  236. break;
  237. case DIFF_DELETE:
  238. count_delete++;
  239. text_delete += diffs[pointer][1];
  240. break;
  241. case DIFF_EQUAL:
  242. // Upon reaching an equality, check for prior redundancies.
  243. if (count_delete >= 1 && count_insert >= 1) {
  244. // Delete the offending records and add the merged ones.
  245. diffs.splice(pointer - count_delete - count_insert,
  246. count_delete + count_insert);
  247. pointer = pointer - count_delete - count_insert;
  248. var subDiff =
  249. this.diff_main(text_delete, text_insert, false, deadline);
  250. for (var j = subDiff.length - 1; j >= 0; j--) {
  251. diffs.splice(pointer, 0, subDiff[j]);
  252. }
  253. pointer = pointer + subDiff.length;
  254. }
  255. count_insert = 0;
  256. count_delete = 0;
  257. text_delete = '';
  258. text_insert = '';
  259. break;
  260. }
  261. pointer++;
  262. }
  263. diffs.pop(); // Remove the dummy entry at the end.
  264. return diffs;
  265. };
  266. /**
  267. * Find the 'middle snake' of a diff, split the problem in two
  268. * and return the recursively constructed diff.
  269. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  270. * @param {string} text1 Old string to be diffed.
  271. * @param {string} text2 New string to be diffed.
  272. * @param {number} deadline Time at which to bail if not yet complete.
  273. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  274. * @private
  275. */
  276. diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {
  277. // Cache the text lengths to prevent multiple calls.
  278. var text1_length = text1.length;
  279. var text2_length = text2.length;
  280. var max_d = Math.ceil((text1_length + text2_length) / 2);
  281. var v_offset = max_d;
  282. var v_length = 2 * max_d;
  283. var v1 = new Array(v_length);
  284. var v2 = new Array(v_length);
  285. // Setting all elements to -1 is faster in Chrome & Firefox than mixing
  286. // integers and undefined.
  287. for (var x = 0; x < v_length; x++) {
  288. v1[x] = -1;
  289. v2[x] = -1;
  290. }
  291. v1[v_offset + 1] = 0;
  292. v2[v_offset + 1] = 0;
  293. var delta = text1_length - text2_length;
  294. // If the total number of characters is odd, then the front path will collide
  295. // with the reverse path.
  296. var front = (delta % 2 != 0);
  297. // Offsets for start and end of k loop.
  298. // Prevents mapping of space beyond the grid.
  299. var k1start = 0;
  300. var k1end = 0;
  301. var k2start = 0;
  302. var k2end = 0;
  303. for (var d = 0; d < max_d; d++) {
  304. // Bail out if deadline is reached.
  305. if ((new Date()).getTime() > deadline) {
  306. break;
  307. }
  308. // Walk the front path one step.
  309. for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
  310. var k1_offset = v_offset + k1;
  311. var x1;
  312. if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
  313. x1 = v1[k1_offset + 1];
  314. } else {
  315. x1 = v1[k1_offset - 1] + 1;
  316. }
  317. var y1 = x1 - k1;
  318. while (x1 < text1_length && y1 < text2_length &&
  319. text1.charAt(x1) == text2.charAt(y1)) {
  320. x1++;
  321. y1++;
  322. }
  323. v1[k1_offset] = x1;
  324. if (x1 > text1_length) {
  325. // Ran off the right of the graph.
  326. k1end += 2;
  327. } else if (y1 > text2_length) {
  328. // Ran off the bottom of the graph.
  329. k1start += 2;
  330. } else if (front) {
  331. var k2_offset = v_offset + delta - k1;
  332. if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
  333. // Mirror x2 onto top-left coordinate system.
  334. var x2 = text1_length - v2[k2_offset];
  335. if (x1 >= x2) {
  336. // Overlap detected.
  337. return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
  338. }
  339. }
  340. }
  341. }
  342. // Walk the reverse path one step.
  343. for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
  344. var k2_offset = v_offset + k2;
  345. var x2;
  346. if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
  347. x2 = v2[k2_offset + 1];
  348. } else {
  349. x2 = v2[k2_offset - 1] + 1;
  350. }
  351. var y2 = x2 - k2;
  352. while (x2 < text1_length && y2 < text2_length &&
  353. text1.charAt(text1_length - x2 - 1) ==
  354. text2.charAt(text2_length - y2 - 1)) {
  355. x2++;
  356. y2++;
  357. }
  358. v2[k2_offset] = x2;
  359. if (x2 > text1_length) {
  360. // Ran off the left of the graph.
  361. k2end += 2;
  362. } else if (y2 > text2_length) {
  363. // Ran off the top of the graph.
  364. k2start += 2;
  365. } else if (!front) {
  366. var k1_offset = v_offset + delta - k2;
  367. if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
  368. var x1 = v1[k1_offset];
  369. var y1 = v_offset + x1 - k1_offset;
  370. // Mirror x2 onto top-left coordinate system.
  371. x2 = text1_length - x2;
  372. if (x1 >= x2) {
  373. // Overlap detected.
  374. return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
  375. }
  376. }
  377. }
  378. }
  379. }
  380. // Diff took too long and hit the deadline or
  381. // number of diffs equals number of characters, no commonality at all.
  382. return [new diff_match_patch.Diff(DIFF_DELETE, text1),
  383. new diff_match_patch.Diff(DIFF_INSERT, text2)];
  384. };
  385. /**
  386. * Given the location of the 'middle snake', split the diff in two parts
  387. * and recurse.
  388. * @param {string} text1 Old string to be diffed.
  389. * @param {string} text2 New string to be diffed.
  390. * @param {number} x Index of split point in text1.
  391. * @param {number} y Index of split point in text2.
  392. * @param {number} deadline Time at which to bail if not yet complete.
  393. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  394. * @private
  395. */
  396. diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,
  397. deadline) {
  398. var text1a = text1.substring(0, x);
  399. var text2a = text2.substring(0, y);
  400. var text1b = text1.substring(x);
  401. var text2b = text2.substring(y);
  402. // Compute both diffs serially.
  403. var diffs = this.diff_main(text1a, text2a, false, deadline);
  404. var diffsb = this.diff_main(text1b, text2b, false, deadline);
  405. return diffs.concat(diffsb);
  406. };
  407. /**
  408. * Split two texts into an array of strings. Reduce the texts to a string of
  409. * hashes where each Unicode character represents one line.
  410. * @param {string} text1 First string.
  411. * @param {string} text2 Second string.
  412. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
  413. * An object containing the encoded text1, the encoded text2 and
  414. * the array of unique strings.
  415. * The zeroth element of the array of unique strings is intentionally blank.
  416. * @private
  417. */
  418. diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {
  419. var lineArray = []; // e.g. lineArray[4] == 'Hello\n'
  420. var lineHash = {}; // e.g. lineHash['Hello\n'] == 4
  421. // '\x00' is a valid character, but various debuggers don't like it.
  422. // So we'll insert a junk entry to avoid generating a null character.
  423. lineArray[0] = '';
  424. /**
  425. * Split a text into an array of strings. Reduce the texts to a string of
  426. * hashes where each Unicode character represents one line.
  427. * Modifies linearray and linehash through being a closure.
  428. * @param {string} text String to encode.
  429. * @return {string} Encoded string.
  430. * @private
  431. */
  432. function diff_linesToCharsMunge_(text) {
  433. var chars = '';
  434. // Walk the text, pulling out a substring for each line.
  435. // text.split('\n') would would temporarily double our memory footprint.
  436. // Modifying text would create many large strings to garbage collect.
  437. var lineStart = 0;
  438. var lineEnd = -1;
  439. // Keeping our own length variable is faster than looking it up.
  440. var lineArrayLength = lineArray.length;
  441. while (lineEnd < text.length - 1) {
  442. lineEnd = text.indexOf('\n', lineStart);
  443. if (lineEnd == -1) {
  444. lineEnd = text.length - 1;
  445. }
  446. var line = text.substring(lineStart, lineEnd + 1);
  447. if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
  448. (lineHash[line] !== undefined)) {
  449. chars += String.fromCharCode(lineHash[line]);
  450. } else {
  451. if (lineArrayLength == maxLines) {
  452. // Bail out at 65535 because
  453. // String.fromCharCode(65536) == String.fromCharCode(0)
  454. line = text.substring(lineStart);
  455. lineEnd = text.length;
  456. }
  457. chars += String.fromCharCode(lineArrayLength);
  458. lineHash[line] = lineArrayLength;
  459. lineArray[lineArrayLength++] = line;
  460. }
  461. lineStart = lineEnd + 1;
  462. }
  463. return chars;
  464. }
  465. // Allocate 2/3rds of the space for text1, the rest for text2.
  466. var maxLines = 40000;
  467. var chars1 = diff_linesToCharsMunge_(text1);
  468. maxLines = 65535;
  469. var chars2 = diff_linesToCharsMunge_(text2);
  470. return {chars1: chars1, chars2: chars2, lineArray: lineArray};
  471. };
  472. /**
  473. * Rehydrate the text in a diff from a string of line hashes to real lines of
  474. * text.
  475. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  476. * @param {!Array.<string>} lineArray Array of unique strings.
  477. * @private
  478. */
  479. diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {
  480. for (var i = 0; i < diffs.length; i++) {
  481. var chars = diffs[i][1];
  482. var text = [];
  483. for (var j = 0; j < chars.length; j++) {
  484. text[j] = lineArray[chars.charCodeAt(j)];
  485. }
  486. diffs[i][1] = text.join('');
  487. }
  488. };
  489. /**
  490. * Determine the common prefix of two strings.
  491. * @param {string} text1 First string.
  492. * @param {string} text2 Second string.
  493. * @return {number} The number of characters common to the start of each
  494. * string.
  495. */
  496. diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {
  497. // Quick check for common null cases.
  498. if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
  499. return 0;
  500. }
  501. // Binary search.
  502. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  503. var pointermin = 0;
  504. var pointermax = Math.min(text1.length, text2.length);
  505. var pointermid = pointermax;
  506. var pointerstart = 0;
  507. while (pointermin < pointermid) {
  508. if (text1.substring(pointerstart, pointermid) ==
  509. text2.substring(pointerstart, pointermid)) {
  510. pointermin = pointermid;
  511. pointerstart = pointermin;
  512. } else {
  513. pointermax = pointermid;
  514. }
  515. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  516. }
  517. return pointermid;
  518. };
  519. /**
  520. * Determine the common suffix of two strings.
  521. * @param {string} text1 First string.
  522. * @param {string} text2 Second string.
  523. * @return {number} The number of characters common to the end of each string.
  524. */
  525. diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {
  526. // Quick check for common null cases.
  527. if (!text1 || !text2 ||
  528. text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {
  529. return 0;
  530. }
  531. // Binary search.
  532. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  533. var pointermin = 0;
  534. var pointermax = Math.min(text1.length, text2.length);
  535. var pointermid = pointermax;
  536. var pointerend = 0;
  537. while (pointermin < pointermid) {
  538. if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==
  539. text2.substring(text2.length - pointermid, text2.length - pointerend)) {
  540. pointermin = pointermid;
  541. pointerend = pointermin;
  542. } else {
  543. pointermax = pointermid;
  544. }
  545. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  546. }
  547. return pointermid;
  548. };
  549. /**
  550. * Determine if the suffix of one string is the prefix of another.
  551. * @param {string} text1 First string.
  552. * @param {string} text2 Second string.
  553. * @return {number} The number of characters common to the end of the first
  554. * string and the start of the second string.
  555. * @private
  556. */
  557. diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {
  558. // Cache the text lengths to prevent multiple calls.
  559. var text1_length = text1.length;
  560. var text2_length = text2.length;
  561. // Eliminate the null case.
  562. if (text1_length == 0 || text2_length == 0) {
  563. return 0;
  564. }
  565. // Truncate the longer string.
  566. if (text1_length > text2_length) {
  567. text1 = text1.substring(text1_length - text2_length);
  568. } else if (text1_length < text2_length) {
  569. text2 = text2.substring(0, text1_length);
  570. }
  571. var text_length = Math.min(text1_length, text2_length);
  572. // Quick check for the worst case.
  573. if (text1 == text2) {
  574. return text_length;
  575. }
  576. // Start by looking for a single character match
  577. // and increase length until no match is found.
  578. // Performance analysis: https://neil.fraser.name/news/2010/11/04/
  579. var best = 0;
  580. var length = 1;
  581. while (true) {
  582. var pattern = text1.substring(text_length - length);
  583. var found = text2.indexOf(pattern);
  584. if (found == -1) {
  585. return best;
  586. }
  587. length += found;
  588. if (found == 0 || text1.substring(text_length - length) ==
  589. text2.substring(0, length)) {
  590. best = length;
  591. length++;
  592. }
  593. }
  594. };
  595. /**
  596. * Do the two texts share a substring which is at least half the length of the
  597. * longer text?
  598. * This speedup can produce non-minimal diffs.
  599. * @param {string} text1 First string.
  600. * @param {string} text2 Second string.
  601. * @return {Array.<string>} Five element Array, containing the prefix of
  602. * text1, the suffix of text1, the prefix of text2, the suffix of
  603. * text2 and the common middle. Or null if there was no match.
  604. * @private
  605. */
  606. diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) {
  607. if (this.Diff_Timeout <= 0) {
  608. // Don't risk returning a non-optimal diff if we have unlimited time.
  609. return null;
  610. }
  611. var longtext = text1.length > text2.length ? text1 : text2;
  612. var shorttext = text1.length > text2.length ? text2 : text1;
  613. if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
  614. return null; // Pointless.
  615. }
  616. var dmp = this; // 'this' becomes 'window' in a closure.
  617. /**
  618. * Does a substring of shorttext exist within longtext such that the substring
  619. * is at least half the length of longtext?
  620. * Closure, but does not reference any external variables.
  621. * @param {string} longtext Longer string.
  622. * @param {string} shorttext Shorter string.
  623. * @param {number} i Start index of quarter length substring within longtext.
  624. * @return {Array.<string>} Five element Array, containing the prefix of
  625. * longtext, the suffix of longtext, the prefix of shorttext, the suffix
  626. * of shorttext and the common middle. Or null if there was no match.
  627. * @private
  628. */
  629. function diff_halfMatchI_(longtext, shorttext, i) {
  630. // Start with a 1/4 length substring at position i as a seed.
  631. var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
  632. var j = -1;
  633. var best_common = '';
  634. var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
  635. while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
  636. var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),
  637. shorttext.substring(j));
  638. var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),
  639. shorttext.substring(0, j));
  640. if (best_common.length < suffixLength + prefixLength) {
  641. best_common = shorttext.substring(j - suffixLength, j) +
  642. shorttext.substring(j, j + prefixLength);
  643. best_longtext_a = longtext.substring(0, i - suffixLength);
  644. best_longtext_b = longtext.substring(i + prefixLength);
  645. best_shorttext_a = shorttext.substring(0, j - suffixLength);
  646. best_shorttext_b = shorttext.substring(j + prefixLength);
  647. }
  648. }
  649. if (best_common.length * 2 >= longtext.length) {
  650. return [best_longtext_a, best_longtext_b,
  651. best_shorttext_a, best_shorttext_b, best_common];
  652. } else {
  653. return null;
  654. }
  655. }
  656. // First check if the second quarter is the seed for a half-match.
  657. var hm1 = diff_halfMatchI_(longtext, shorttext,
  658. Math.ceil(longtext.length / 4));
  659. // Check again based on the third quarter.
  660. var hm2 = diff_halfMatchI_(longtext, shorttext,
  661. Math.ceil(longtext.length / 2));
  662. var hm;
  663. if (!hm1 && !hm2) {
  664. return null;
  665. } else if (!hm2) {
  666. hm = hm1;
  667. } else if (!hm1) {
  668. hm = hm2;
  669. } else {
  670. // Both matched. Select the longest.
  671. hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
  672. }
  673. // A half-match was found, sort out the return data.
  674. var text1_a, text1_b, text2_a, text2_b;
  675. if (text1.length > text2.length) {
  676. text1_a = hm[0];
  677. text1_b = hm[1];
  678. text2_a = hm[2];
  679. text2_b = hm[3];
  680. } else {
  681. text2_a = hm[0];
  682. text2_b = hm[1];
  683. text1_a = hm[2];
  684. text1_b = hm[3];
  685. }
  686. var mid_common = hm[4];
  687. return [text1_a, text1_b, text2_a, text2_b, mid_common];
  688. };
  689. /**
  690. * Reduce the number of edits by eliminating semantically trivial equalities.
  691. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  692. */
  693. diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {
  694. var changes = false;
  695. var equalities = []; // Stack of indices where equalities are found.
  696. var equalitiesLength = 0; // Keeping our own length var is faster in JS.
  697. /** @type {?string} */
  698. var lastEquality = null;
  699. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  700. var pointer = 0; // Index of current position.
  701. // Number of characters that changed prior to the equality.
  702. var length_insertions1 = 0;
  703. var length_deletions1 = 0;
  704. // Number of characters that changed after the equality.
  705. var length_insertions2 = 0;
  706. var length_deletions2 = 0;
  707. while (pointer < diffs.length) {
  708. if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
  709. equalities[equalitiesLength++] = pointer;
  710. length_insertions1 = length_insertions2;
  711. length_deletions1 = length_deletions2;
  712. length_insertions2 = 0;
  713. length_deletions2 = 0;
  714. lastEquality = diffs[pointer][1];
  715. } else { // An insertion or deletion.
  716. if (diffs[pointer][0] == DIFF_INSERT) {
  717. length_insertions2 += diffs[pointer][1].length;
  718. } else {
  719. length_deletions2 += diffs[pointer][1].length;
  720. }
  721. // Eliminate an equality that is smaller or equal to the edits on both
  722. // sides of it.
  723. if (lastEquality && (lastEquality.length <=
  724. Math.max(length_insertions1, length_deletions1)) &&
  725. (lastEquality.length <= Math.max(length_insertions2,
  726. length_deletions2))) {
  727. // Duplicate record.
  728. diffs.splice(equalities[equalitiesLength - 1], 0,
  729. new diff_match_patch.Diff(DIFF_DELETE, lastEquality));
  730. // Change second copy to insert.
  731. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  732. // Throw away the equality we just deleted.
  733. equalitiesLength--;
  734. // Throw away the previous equality (it needs to be reevaluated).
  735. equalitiesLength--;
  736. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  737. length_insertions1 = 0; // Reset the counters.
  738. length_deletions1 = 0;
  739. length_insertions2 = 0;
  740. length_deletions2 = 0;
  741. lastEquality = null;
  742. changes = true;
  743. }
  744. }
  745. pointer++;
  746. }
  747. // Normalize the diff.
  748. if (changes) {
  749. this.diff_cleanupMerge(diffs);
  750. }
  751. this.diff_cleanupSemanticLossless(diffs);
  752. // Find any overlaps between deletions and insertions.
  753. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  754. // -> <del>abc</del>xxx<ins>def</ins>
  755. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  756. // -> <ins>def</ins>xxx<del>abc</del>
  757. // Only extract an overlap if it is as big as the edit ahead or behind it.
  758. pointer = 1;
  759. while (pointer < diffs.length) {
  760. if (diffs[pointer - 1][0] == DIFF_DELETE &&
  761. diffs[pointer][0] == DIFF_INSERT) {
  762. var deletion = diffs[pointer - 1][1];
  763. var insertion = diffs[pointer][1];
  764. var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);
  765. var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);
  766. if (overlap_length1 >= overlap_length2) {
  767. if (overlap_length1 >= deletion.length / 2 ||
  768. overlap_length1 >= insertion.length / 2) {
  769. // Overlap found. Insert an equality and trim the surrounding edits.
  770. diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,
  771. insertion.substring(0, overlap_length1)));
  772. diffs[pointer - 1][1] =
  773. deletion.substring(0, deletion.length - overlap_length1);
  774. diffs[pointer + 1][1] = insertion.substring(overlap_length1);
  775. pointer++;
  776. }
  777. } else {
  778. if (overlap_length2 >= deletion.length / 2 ||
  779. overlap_length2 >= insertion.length / 2) {
  780. // Reverse overlap found.
  781. // Insert an equality and swap and trim the surrounding edits.
  782. diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,
  783. deletion.substring(0, overlap_length2)));
  784. diffs[pointer - 1][0] = DIFF_INSERT;
  785. diffs[pointer - 1][1] =
  786. insertion.substring(0, insertion.length - overlap_length2);
  787. diffs[pointer + 1][0] = DIFF_DELETE;
  788. diffs[pointer + 1][1] =
  789. deletion.substring(overlap_length2);
  790. pointer++;
  791. }
  792. }
  793. pointer++;
  794. }
  795. pointer++;
  796. }
  797. };
  798. /**
  799. * Look for single edits surrounded on both sides by equalities
  800. * which can be shifted sideways to align the edit to a word boundary.
  801. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
  802. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  803. */
  804. diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {
  805. /**
  806. * Given two strings, compute a score representing whether the internal
  807. * boundary falls on logical boundaries.
  808. * Scores range from 6 (best) to 0 (worst).
  809. * Closure, but does not reference any external variables.
  810. * @param {string} one First string.
  811. * @param {string} two Second string.
  812. * @return {number} The score.
  813. * @private
  814. */
  815. function diff_cleanupSemanticScore_(one, two) {
  816. if (!one || !two) {
  817. // Edges are the best.
  818. return 6;
  819. }
  820. // Each port of this function behaves slightly differently due to
  821. // subtle differences in each language's definition of things like
  822. // 'whitespace'. Since this function's purpose is largely cosmetic,
  823. // the choice has been made to use each language's native features
  824. // rather than force total conformity.
  825. var char1 = one.charAt(one.length - 1);
  826. var char2 = two.charAt(0);
  827. var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);
  828. var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);
  829. var whitespace1 = nonAlphaNumeric1 &&
  830. char1.match(diff_match_patch.whitespaceRegex_);
  831. var whitespace2 = nonAlphaNumeric2 &&
  832. char2.match(diff_match_patch.whitespaceRegex_);
  833. var lineBreak1 = whitespace1 &&
  834. char1.match(diff_match_patch.linebreakRegex_);
  835. var lineBreak2 = whitespace2 &&
  836. char2.match(diff_match_patch.linebreakRegex_);
  837. var blankLine1 = lineBreak1 &&
  838. one.match(diff_match_patch.blanklineEndRegex_);
  839. var blankLine2 = lineBreak2 &&
  840. two.match(diff_match_patch.blanklineStartRegex_);
  841. if (blankLine1 || blankLine2) {
  842. // Five points for blank lines.
  843. return 5;
  844. } else if (lineBreak1 || lineBreak2) {
  845. // Four points for line breaks.
  846. return 4;
  847. } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
  848. // Three points for end of sentences.
  849. return 3;
  850. } else if (whitespace1 || whitespace2) {
  851. // Two points for whitespace.
  852. return 2;
  853. } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
  854. // One point for non-alphanumeric.
  855. return 1;
  856. }
  857. return 0;
  858. }
  859. var pointer = 1;
  860. // Intentionally ignore the first and last element (don't need checking).
  861. while (pointer < diffs.length - 1) {
  862. if (diffs[pointer - 1][0] == DIFF_EQUAL &&
  863. diffs[pointer + 1][0] == DIFF_EQUAL) {
  864. // This is a single edit surrounded by equalities.
  865. var equality1 = diffs[pointer - 1][1];
  866. var edit = diffs[pointer][1];
  867. var equality2 = diffs[pointer + 1][1];
  868. // First, shift the edit as far left as possible.
  869. var commonOffset = this.diff_commonSuffix(equality1, edit);
  870. if (commonOffset) {
  871. var commonString = edit.substring(edit.length - commonOffset);
  872. equality1 = equality1.substring(0, equality1.length - commonOffset);
  873. edit = commonString + edit.substring(0, edit.length - commonOffset);
  874. equality2 = commonString + equality2;
  875. }
  876. // Second, step character by character right, looking for the best fit.
  877. var bestEquality1 = equality1;
  878. var bestEdit = edit;
  879. var bestEquality2 = equality2;
  880. var bestScore = diff_cleanupSemanticScore_(equality1, edit) +
  881. diff_cleanupSemanticScore_(edit, equality2);
  882. while (edit.charAt(0) === equality2.charAt(0)) {
  883. equality1 += edit.charAt(0);
  884. edit = edit.substring(1) + equality2.charAt(0);
  885. equality2 = equality2.substring(1);
  886. var score = diff_cleanupSemanticScore_(equality1, edit) +
  887. diff_cleanupSemanticScore_(edit, equality2);
  888. // The >= encourages trailing rather than leading whitespace on edits.
  889. if (score >= bestScore) {
  890. bestScore = score;
  891. bestEquality1 = equality1;
  892. bestEdit = edit;
  893. bestEquality2 = equality2;
  894. }
  895. }
  896. if (diffs[pointer - 1][1] != bestEquality1) {
  897. // We have an improvement, save it back to the diff.
  898. if (bestEquality1) {
  899. diffs[pointer - 1][1] = bestEquality1;
  900. } else {
  901. diffs.splice(pointer - 1, 1);
  902. pointer--;
  903. }
  904. diffs[pointer][1] = bestEdit;
  905. if (bestEquality2) {
  906. diffs[pointer + 1][1] = bestEquality2;
  907. } else {
  908. diffs.splice(pointer + 1, 1);
  909. pointer--;
  910. }
  911. }
  912. }
  913. pointer++;
  914. }
  915. };
  916. // Define some regex patterns for matching boundaries.
  917. diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;
  918. diff_match_patch.whitespaceRegex_ = /\s/;
  919. diff_match_patch.linebreakRegex_ = /[\r\n]/;
  920. diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/;
  921. diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/;
  922. /**
  923. * Reduce the number of edits by eliminating operationally trivial equalities.
  924. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  925. */
  926. diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {
  927. var changes = false;
  928. var equalities = []; // Stack of indices where equalities are found.
  929. var equalitiesLength = 0; // Keeping our own length var is faster in JS.
  930. /** @type {?string} */
  931. var lastEquality = null;
  932. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  933. var pointer = 0; // Index of current position.
  934. // Is there an insertion operation before the last equality.
  935. var pre_ins = false;
  936. // Is there a deletion operation before the last equality.
  937. var pre_del = false;
  938. // Is there an insertion operation after the last equality.
  939. var post_ins = false;
  940. // Is there a deletion operation after the last equality.
  941. var post_del = false;
  942. while (pointer < diffs.length) {
  943. if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
  944. if (diffs[pointer][1].length < this.Diff_EditCost &&
  945. (post_ins || post_del)) {
  946. // Candidate found.
  947. equalities[equalitiesLength++] = pointer;
  948. pre_ins = post_ins;
  949. pre_del = post_del;
  950. lastEquality = diffs[pointer][1];
  951. } else {
  952. // Not a candidate, and can never become one.
  953. equalitiesLength = 0;
  954. lastEquality = null;
  955. }
  956. post_ins = post_del = false;
  957. } else { // An insertion or deletion.
  958. if (diffs[pointer][0] == DIFF_DELETE) {
  959. post_del = true;
  960. } else {
  961. post_ins = true;
  962. }
  963. /*
  964. * Five types to be split:
  965. * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  966. * <ins>A</ins>X<ins>C</ins><del>D</del>
  967. * <ins>A</ins><del>B</del>X<ins>C</ins>
  968. * <ins>A</del>X<ins>C</ins><del>D</del>
  969. * <ins>A</ins><del>B</del>X<del>C</del>
  970. */
  971. if (lastEquality && ((pre_ins && pre_del && post_ins && post_del) ||
  972. ((lastEquality.length < this.Diff_EditCost / 2) &&
  973. (pre_ins + pre_del + post_ins + post_del) == 3))) {
  974. // Duplicate record.
  975. diffs.splice(equalities[equalitiesLength - 1], 0,
  976. new diff_match_patch.Diff(DIFF_DELETE, lastEquality));
  977. // Change second copy to insert.
  978. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  979. equalitiesLength--; // Throw away the equality we just deleted;
  980. lastEquality = null;
  981. if (pre_ins && pre_del) {
  982. // No changes made which could affect previous entry, keep going.
  983. post_ins = post_del = true;
  984. equalitiesLength = 0;
  985. } else {
  986. equalitiesLength--; // Throw away the previous equality.
  987. pointer = equalitiesLength > 0 ?
  988. equalities[equalitiesLength - 1] : -1;
  989. post_ins = post_del = false;
  990. }
  991. changes = true;
  992. }
  993. }
  994. pointer++;
  995. }
  996. if (changes) {
  997. this.diff_cleanupMerge(diffs);
  998. }
  999. };
  1000. /**
  1001. * Reorder and merge like edit sections. Merge equalities.
  1002. * Any edit section can move as long as it doesn't cross an equality.
  1003. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1004. */
  1005. diff_match_patch.prototype.diff_cleanupMerge = function(diffs) {
  1006. // Add a dummy entry at the end.
  1007. diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));
  1008. var pointer = 0;
  1009. var count_delete = 0;
  1010. var count_insert = 0;
  1011. var text_delete = '';
  1012. var text_insert = '';
  1013. var commonlength;
  1014. while (pointer < diffs.length) {
  1015. switch (diffs[pointer][0]) {
  1016. case DIFF_INSERT:
  1017. count_insert++;
  1018. text_insert += diffs[pointer][1];
  1019. pointer++;
  1020. break;
  1021. case DIFF_DELETE:
  1022. count_delete++;
  1023. text_delete += diffs[pointer][1];
  1024. pointer++;
  1025. break;
  1026. case DIFF_EQUAL:
  1027. // Upon reaching an equality, check for prior redundancies.
  1028. if (count_delete + count_insert > 1) {
  1029. if (count_delete !== 0 && count_insert !== 0) {
  1030. // Factor out any common prefixies.
  1031. commonlength = this.diff_commonPrefix(text_insert, text_delete);
  1032. if (commonlength !== 0) {
  1033. if ((pointer - count_delete - count_insert) > 0 &&
  1034. diffs[pointer - count_delete - count_insert - 1][0] ==
  1035. DIFF_EQUAL) {
  1036. diffs[pointer - count_delete - count_insert - 1][1] +=
  1037. text_insert.substring(0, commonlength);
  1038. } else {
  1039. diffs.splice(0, 0, new diff_match_patch.Diff(DIFF_EQUAL,
  1040. text_insert.substring(0, commonlength)));
  1041. pointer++;
  1042. }
  1043. text_insert = text_insert.substring(commonlength);
  1044. text_delete = text_delete.substring(commonlength);
  1045. }
  1046. // Factor out any common suffixies.
  1047. commonlength = this.diff_commonSuffix(text_insert, text_delete);
  1048. if (commonlength !== 0) {
  1049. diffs[pointer][1] = text_insert.substring(text_insert.length -
  1050. commonlength) + diffs[pointer][1];
  1051. text_insert = text_insert.substring(0, text_insert.length -
  1052. commonlength);
  1053. text_delete = text_delete.substring(0, text_delete.length -
  1054. commonlength);
  1055. }
  1056. }
  1057. // Delete the offending records and add the merged ones.
  1058. pointer -= count_delete + count_insert;
  1059. diffs.splice(pointer, count_delete + count_insert);
  1060. if (text_delete.length) {
  1061. diffs.splice(pointer, 0,
  1062. new diff_match_patch.Diff(DIFF_DELETE, text_delete));
  1063. pointer++;
  1064. }
  1065. if (text_insert.length) {
  1066. diffs.splice(pointer, 0,
  1067. new diff_match_patch.Diff(DIFF_INSERT, text_insert));
  1068. pointer++;
  1069. }
  1070. pointer++;
  1071. } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {
  1072. // Merge this equality with the previous one.
  1073. diffs[pointer - 1][1] += diffs[pointer][1];
  1074. diffs.splice(pointer, 1);
  1075. } else {
  1076. pointer++;
  1077. }
  1078. count_insert = 0;
  1079. count_delete = 0;
  1080. text_delete = '';
  1081. text_insert = '';
  1082. break;
  1083. }
  1084. }
  1085. if (diffs[diffs.length - 1][1] === '') {
  1086. diffs.pop(); // Remove the dummy entry at the end.
  1087. }
  1088. // Second pass: look for single edits surrounded on both sides by equalities
  1089. // which can be shifted sideways to eliminate an equality.
  1090. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  1091. var changes = false;
  1092. pointer = 1;
  1093. // Intentionally ignore the first and last element (don't need checking).
  1094. while (pointer < diffs.length - 1) {
  1095. if (diffs[pointer - 1][0] == DIFF_EQUAL &&
  1096. diffs[pointer + 1][0] == DIFF_EQUAL) {
  1097. // This is a single edit surrounded by equalities.
  1098. if (diffs[pointer][1].substring(diffs[pointer][1].length -
  1099. diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {
  1100. // Shift the edit over the previous equality.
  1101. diffs[pointer][1] = diffs[pointer - 1][1] +
  1102. diffs[pointer][1].substring(0, diffs[pointer][1].length -
  1103. diffs[pointer - 1][1].length);
  1104. diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
  1105. diffs.splice(pointer - 1, 1);
  1106. changes = true;
  1107. } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
  1108. diffs[pointer + 1][1]) {
  1109. // Shift the edit over the next equality.
  1110. diffs[pointer - 1][1] += diffs[pointer + 1][1];
  1111. diffs[pointer][1] =
  1112. diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
  1113. diffs[pointer + 1][1];
  1114. diffs.splice(pointer + 1, 1);
  1115. changes = true;
  1116. }
  1117. }
  1118. pointer++;
  1119. }
  1120. // If shifts were made, the diff needs reordering and another shift sweep.
  1121. if (changes) {
  1122. this.diff_cleanupMerge(diffs);
  1123. }
  1124. };
  1125. /**
  1126. * loc is a location in text1, compute and return the equivalent location in
  1127. * text2.
  1128. * e.g. 'The cat' vs 'The big cat', 1->1, 5->8
  1129. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1130. * @param {number} loc Location within text1.
  1131. * @return {number} Location within text2.
  1132. */
  1133. diff_match_patch.prototype.diff_xIndex = function(diffs, loc) {
  1134. var chars1 = 0;
  1135. var chars2 = 0;
  1136. var last_chars1 = 0;
  1137. var last_chars2 = 0;
  1138. var x;
  1139. for (x = 0; x < diffs.length; x++) {
  1140. if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion.
  1141. chars1 += diffs[x][1].length;
  1142. }
  1143. if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion.
  1144. chars2 += diffs[x][1].length;
  1145. }
  1146. if (chars1 > loc) { // Overshot the location.
  1147. break;
  1148. }
  1149. last_chars1 = chars1;
  1150. last_chars2 = chars2;
  1151. }
  1152. // Was the location was deleted?
  1153. if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {
  1154. return last_chars2;
  1155. }
  1156. // Add the remaining character length.
  1157. return last_chars2 + (loc - last_chars1);
  1158. };
  1159. /**
  1160. * Convert a diff array into a pretty HTML report.
  1161. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1162. * @return {string} HTML representation.
  1163. */
  1164. diff_match_patch.prototype.diff_prettyHtml = function(diffs) {
  1165. var html = [];
  1166. var pattern_amp = /&/g;
  1167. var pattern_lt = /</g;
  1168. var pattern_gt = />/g;
  1169. var pattern_para = /\n/g;
  1170. for (var x = 0; x < diffs.length; x++) {
  1171. var op = diffs[x][0]; // Operation (insert, delete, equal)
  1172. var data = diffs[x][1]; // Text of change.
  1173. var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')
  1174. .replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');
  1175. switch (op) {
  1176. case DIFF_INSERT:
  1177. html[x] = '<ins style="background:#e6ffe6;">' + text + '</ins>';
  1178. break;
  1179. case DIFF_DELETE:
  1180. html[x] = '<del style="background:#ffe6e6;">' + text + '</del>';
  1181. break;
  1182. case DIFF_EQUAL:
  1183. html[x] = '<span>' + text + '</span>';
  1184. break;
  1185. }
  1186. }
  1187. return html.join('');
  1188. };
  1189. /**
  1190. * Compute and return the source text (all equalities and deletions).
  1191. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1192. * @return {string} Source text.
  1193. */
  1194. diff_match_patch.prototype.diff_text1 = function(diffs) {
  1195. var text = [];
  1196. for (var x = 0; x < diffs.length; x++) {
  1197. if (diffs[x][0] !== DIFF_INSERT) {
  1198. text[x] = diffs[x][1];
  1199. }
  1200. }
  1201. return text.join('');
  1202. };
  1203. /**
  1204. * Compute and return the destination text (all equalities and insertions).
  1205. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1206. * @return {string} Destination text.
  1207. */
  1208. diff_match_patch.prototype.diff_text2 = function(diffs) {
  1209. var text = [];
  1210. for (var x = 0; x < diffs.length; x++) {
  1211. if (diffs[x][0] !== DIFF_DELETE) {
  1212. text[x] = diffs[x][1];
  1213. }
  1214. }
  1215. return text.join('');
  1216. };
  1217. /**
  1218. * Compute the Levenshtein distance; the number of inserted, deleted or
  1219. * substituted characters.
  1220. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1221. * @return {number} Number of changes.
  1222. */
  1223. diff_match_patch.prototype.diff_levenshtein = function(diffs) {
  1224. var levenshtein = 0;
  1225. var insertions = 0;
  1226. var deletions = 0;
  1227. for (var x = 0; x < diffs.length; x++) {
  1228. var op = diffs[x][0];
  1229. var data = diffs[x][1];
  1230. switch (op) {
  1231. case DIFF_INSERT:
  1232. insertions += data.length;
  1233. break;
  1234. case DIFF_DELETE:
  1235. deletions += data.length;
  1236. break;
  1237. case DIFF_EQUAL:
  1238. // A deletion and an insertion is one substitution.
  1239. levenshtein += Math.max(insertions, deletions);
  1240. insertions = 0;
  1241. deletions = 0;
  1242. break;
  1243. }
  1244. }
  1245. levenshtein += Math.max(insertions, deletions);
  1246. return levenshtein;
  1247. };
  1248. /**
  1249. * Crush the diff into an encoded string which describes the operations
  1250. * required to transform text1 into text2.
  1251. * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
  1252. * Operations are tab-separated. Inserted text is escaped using %xx notation.
  1253. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1254. * @return {string} Delta text.
  1255. */
  1256. diff_match_patch.prototype.diff_toDelta = function(diffs) {
  1257. var text = [];
  1258. for (var x = 0; x < diffs.length; x++) {
  1259. switch (diffs[x][0]) {
  1260. case DIFF_INSERT:
  1261. text[x] = '+' + encodeURI(diffs[x][1]);
  1262. break;
  1263. case DIFF_DELETE:
  1264. text[x] = '-' + diffs[x][1].length;
  1265. break;
  1266. case DIFF_EQUAL:
  1267. text[x] = '=' + diffs[x][1].length;
  1268. break;
  1269. }
  1270. }
  1271. return text.join('\t').replace(/%20/g, ' ');
  1272. };
  1273. /**
  1274. * Given the original text1, and an encoded string which describes the
  1275. * operations required to transform text1 into text2, compute the full diff.
  1276. * @param {string} text1 Source string for the diff.
  1277. * @param {string} delta Delta text.
  1278. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  1279. * @throws {!Error} If invalid input.
  1280. */
  1281. diff_match_patch.prototype.diff_fromDelta = function(text1, delta) {
  1282. var diffs = [];
  1283. var diffsLength = 0; // Keeping our own length var is faster in JS.
  1284. var pointer = 0; // Cursor in text1
  1285. var tokens = delta.split(/\t/g);
  1286. for (var x = 0; x < tokens.length; x++) {
  1287. // Each token begins with a one character parameter which specifies the
  1288. // operation of this token (delete, insert, equality).
  1289. var param = tokens[x].substring(1);
  1290. switch (tokens[x].charAt(0)) {
  1291. case '+':
  1292. try {
  1293. diffs[diffsLength++] =
  1294. new diff_match_patch.Diff(DIFF_INSERT, decodeURI(param));
  1295. } catch (ex) {
  1296. // Malformed URI sequence.
  1297. throw new Error('Illegal escape in diff_fromDelta: ' + param);
  1298. }
  1299. break;
  1300. case '-':
  1301. // Fall through.
  1302. case '=':
  1303. var n = parseInt(param, 10);
  1304. if (isNaN(n) || n < 0) {
  1305. throw new Error('Invalid number in diff_fromDelta: ' + param);
  1306. }
  1307. var text = text1.substring(pointer, pointer += n);
  1308. if (tokens[x].charAt(0) == '=') {
  1309. diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_EQUAL, text);
  1310. } else {
  1311. diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_DELETE, text);
  1312. }
  1313. break;
  1314. default:
  1315. // Blank tokens are ok (from a trailing \t).
  1316. // Anything else is an error.
  1317. if (tokens[x]) {
  1318. throw new Error('Invalid diff operation in diff_fromDelta: ' +
  1319. tokens[x]);
  1320. }
  1321. }
  1322. }
  1323. if (pointer != text1.length) {
  1324. throw new Error('Delta length (' + pointer +
  1325. ') does not equal source text length (' + text1.length + ').');
  1326. }
  1327. return diffs;
  1328. };
  1329. // MATCH FUNCTIONS
  1330. /**
  1331. * Locate the best instance of 'pattern' in 'text' near 'loc'.
  1332. * @param {string} text The text to search.
  1333. * @param {string} pattern The pattern to search for.
  1334. * @param {number} loc The location to search around.
  1335. * @return {number} Best match index or -1.
  1336. */
  1337. diff_match_patch.prototype.match_main = function(text, pattern, loc) {
  1338. // Check for null inputs.
  1339. if (text == null || pattern == null || loc == null) {
  1340. throw new Error('Null input. (match_main)');
  1341. }
  1342. loc = Math.max(0, Math.min(loc, text.length));
  1343. if (text == pattern) {
  1344. // Shortcut (potentially not guaranteed by the algorithm)
  1345. return 0;
  1346. } else if (!text.length) {
  1347. // Nothing to match.
  1348. return -1;
  1349. } else if (text.substring(loc, loc + pattern.length) == pattern) {
  1350. // Perfect match at the perfect spot! (Includes case of null pattern)
  1351. return loc;
  1352. } else {
  1353. // Do a fuzzy compare.
  1354. return this.match_bitap_(text, pattern, loc);
  1355. }
  1356. };
  1357. /**
  1358. * Locate the best instance of 'pattern' in 'text' near 'loc' using the
  1359. * Bitap algorithm.
  1360. * @param {string} text The text to search.
  1361. * @param {string} pattern The pattern to search for.
  1362. * @param {number} loc The location to search around.
  1363. * @return {number} Best match index or -1.
  1364. * @private
  1365. */
  1366. diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {
  1367. if (pattern.length > this.Match_MaxBits) {
  1368. throw new Error('Pattern too long for this browser.');
  1369. }
  1370. // Initialise the alphabet.
  1371. var s = this.match_alphabet_(pattern);
  1372. var dmp = this; // 'this' becomes 'window' in a closure.
  1373. /**
  1374. * Compute and return the score for a match with e errors and x location.
  1375. * Accesses loc and pattern through being a closure.
  1376. * @param {number} e Number of errors in match.
  1377. * @param {number} x Location of match.
  1378. * @return {number} Overall score for match (0.0 = good, 1.0 = bad).
  1379. * @private
  1380. */
  1381. function match_bitapScore_(e, x) {
  1382. var accuracy = e / pattern.length;
  1383. var proximity = Math.abs(loc - x);
  1384. if (!dmp.Match_Distance) {
  1385. // Dodge divide by zero error.
  1386. return proximity ? 1.0 : accuracy;
  1387. }
  1388. return accuracy + (proximity / dmp.Match_Distance);
  1389. }
  1390. // Highest score beyond which we give up.
  1391. var score_threshold = this.Match_Threshold;
  1392. // Is there a nearby exact match? (speedup)
  1393. var best_loc = text.indexOf(pattern, loc);
  1394. if (best_loc != -1) {
  1395. score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);
  1396. // What about in the other direction? (speedup)
  1397. best_loc = text.lastIndexOf(pattern, loc + pattern.length);
  1398. if (best_loc != -1) {
  1399. score_threshold =
  1400. Math.min(match_bitapScore_(0, best_loc), score_threshold);
  1401. }
  1402. }
  1403. // Initialise the bit arrays.
  1404. var matchmask = 1 << (pattern.length - 1);
  1405. best_loc = -1;
  1406. var bin_min, bin_mid;
  1407. var bin_max = pattern.length + text.length;
  1408. var last_rd;
  1409. for (var d = 0; d < pattern.length; d++) {
  1410. // Scan for the best match; each iteration allows for one more error.
  1411. // Run a binary search to determine how far from 'loc' we can stray at this
  1412. // error level.
  1413. bin_min = 0;
  1414. bin_mid = bin_max;
  1415. while (bin_min < bin_mid) {
  1416. if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {
  1417. bin_min = bin_mid;
  1418. } else {
  1419. bin_max = bin_mid;
  1420. }
  1421. bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);
  1422. }
  1423. // Use the result from this iteration as the maximum for the next.
  1424. bin_max = bin_mid;
  1425. var start = Math.max(1, loc - bin_mid + 1);
  1426. var finish = Math.min(loc + bin_mid, text.length) + pattern.length;
  1427. var rd = Array(finish + 2);
  1428. rd[finish + 1] = (1 << d) - 1;
  1429. for (var j = finish; j >= start; j--) {
  1430. // The alphabet (s) is a sparse hash, so the following line generates
  1431. // warnings.
  1432. var charMatch = s[text.charAt(j - 1)];
  1433. if (d === 0) { // First pass: exact match.
  1434. rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;
  1435. } else { // Subsequent passes: fuzzy match.
  1436. rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |
  1437. (((last_rd[j + 1] | last_rd[j]) << 1) | 1) |
  1438. last_rd[j + 1];
  1439. }
  1440. if (rd[j] & matchmask) {
  1441. var score = match_bitapScore_(d, j - 1);
  1442. // This match will almost certainly be better than any existing match.
  1443. // But check anyway.
  1444. if (score <= score_threshold) {
  1445. // Told you so.
  1446. score_threshold = score;
  1447. best_loc = j - 1;
  1448. if (best_loc > loc) {
  1449. // When passing loc, don't exceed our current distance from loc.
  1450. start = Math.max(1, 2 * loc - best_loc);
  1451. } else {
  1452. // Already passed loc, downhill from here on in.
  1453. break;
  1454. }
  1455. }
  1456. }
  1457. }
  1458. // No hope for a (better) match at greater error levels.
  1459. if (match_bitapScore_(d + 1, loc) > score_threshold) {
  1460. break;
  1461. }
  1462. last_rd = rd;
  1463. }
  1464. return best_loc;
  1465. };
  1466. /**
  1467. * Initialise the alphabet for the Bitap algorithm.
  1468. * @param {string} pattern The text to encode.
  1469. * @return {!Object} Hash of character locations.
  1470. * @private
  1471. */
  1472. diff_match_patch.prototype.match_alphabet_ = function(pattern) {
  1473. var s = {};
  1474. for (var i = 0; i < pattern.length; i++) {
  1475. s[pattern.charAt(i)] = 0;
  1476. }
  1477. for (var i = 0; i < pattern.length; i++) {
  1478. s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);
  1479. }
  1480. return s;
  1481. };
  1482. // PATCH FUNCTIONS
  1483. /**
  1484. * Increase the context until it is unique,
  1485. * but don't let the pattern expand beyond Match_MaxBits.
  1486. * @param {!diff_match_patch.patch_obj} patch The patch to grow.
  1487. * @param {string} text Source text.
  1488. * @private
  1489. */
  1490. diff_match_patch.prototype.patch_addContext_ = function(patch, text) {
  1491. if (text.length == 0) {
  1492. return;
  1493. }
  1494. if (patch.start2 === null) {
  1495. throw Error('patch not initialized');
  1496. }
  1497. var pattern = text.substring(patch.start2, patch.start2 + patch.length1);
  1498. var padding = 0;
  1499. // Look for the first and last matches of pattern in text. If two different
  1500. // matches are found, increase the pattern length.
  1501. while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&
  1502. pattern.length < this.Match_MaxBits - this.Patch_Margin -
  1503. this.Patch_Margin) {
  1504. padding += this.Patch_Margin;
  1505. pattern = text.substring(patch.start2 - padding,
  1506. patch.start2 + patch.length1 + padding);
  1507. }
  1508. // Add one chunk for good luck.
  1509. padding += this.Patch_Margin;
  1510. // Add the prefix.
  1511. var prefix = text.substring(patch.start2 - padding, patch.start2);
  1512. if (prefix) {
  1513. patch.diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, prefix));
  1514. }
  1515. // Add the suffix.
  1516. var suffix = text.substring(patch.start2 + patch.length1,
  1517. patch.start2 + patch.length1 + padding);
  1518. if (suffix) {
  1519. patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, suffix));
  1520. }
  1521. // Roll back the start points.
  1522. patch.start1 -= prefix.length;
  1523. patch.start2 -= prefix.length;
  1524. // Extend the lengths.
  1525. patch.length1 += prefix.length + suffix.length;
  1526. patch.length2 += prefix.length + suffix.length;
  1527. };
  1528. /**
  1529. * Compute a list of patches to turn text1 into text2.
  1530. * Use diffs if provided, otherwise compute it ourselves.
  1531. * There are four ways to call this function, depending on what data is
  1532. * available to the caller:
  1533. * Method 1:
  1534. * a = text1, b = text2
  1535. * Method 2:
  1536. * a = diffs
  1537. * Method 3 (optimal):
  1538. * a = text1, b = diffs
  1539. * Method 4 (deprecated, use method 3):
  1540. * a = text1, b = text2, c = diffs
  1541. *
  1542. * @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or
  1543. * Array of diff tuples for text1 to text2 (method 2).
  1544. * @param {string|!Array.<!diff_match_patch.Diff>=} opt_b text2 (methods 1,4) or
  1545. * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
  1546. * @param {string|!Array.<!diff_match_patch.Diff>=} opt_c Array of diff tuples
  1547. * for text1 to text2 (method 4) or undefined (methods 1,2,3).
  1548. * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
  1549. */
  1550. diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {
  1551. var text1, diffs;
  1552. if (typeof a == 'string' && typeof opt_b == 'string' &&
  1553. typeof opt_c == 'undefined') {
  1554. // Method 1: text1, text2
  1555. // Compute diffs from text1 and text2.
  1556. text1 = /** @type {string} */(a);
  1557. diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);
  1558. if (diffs.length > 2) {
  1559. this.diff_cleanupSemantic(diffs);
  1560. this.diff_cleanupEfficiency(diffs);
  1561. }
  1562. } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&
  1563. typeof opt_c == 'undefined') {
  1564. // Method 2: diffs
  1565. // Compute text1 from diffs.
  1566. diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a);
  1567. text1 = this.diff_text1(diffs);
  1568. } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&
  1569. typeof opt_c == 'undefined') {
  1570. // Method 3: text1, diffs
  1571. text1 = /** @type {string} */(a);
  1572. diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b);
  1573. } else if (typeof a == 'string' && typeof opt_b == 'string' &&
  1574. opt_c && typeof opt_c == 'object') {
  1575. // Method 4: text1, text2, diffs
  1576. // text2 is not used.
  1577. text1 = /** @type {string} */(a);
  1578. diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c);
  1579. } else {
  1580. throw new Error('Unknown call format to patch_make.');
  1581. }
  1582. if (diffs.length === 0) {
  1583. return []; // Get rid of the null case.
  1584. }
  1585. var patches = [];
  1586. var patch = new diff_match_patch.patch_obj();
  1587. var patchDiffLength = 0; // Keeping our own length var is faster in JS.
  1588. var char_count1 = 0; // Number of characters into the text1 string.
  1589. var char_count2 = 0; // Number of characters into the text2 string.
  1590. // Start with text1 (prepatch_text) and apply the diffs until we arrive at
  1591. // text2 (postpatch_text). We recreate the patches one by one to determine
  1592. // context info.
  1593. var prepatch_text = text1;
  1594. var postpatch_text = text1;
  1595. for (var x = 0; x < diffs.length; x++) {
  1596. var diff_type = diffs[x][0];
  1597. var diff_text = diffs[x][1];
  1598. if (!patchDiffLength && diff_type !== DIFF_EQUAL) {
  1599. // A new patch starts here.
  1600. patch.start1 = char_count1;
  1601. patch.start2 = char_count2;
  1602. }
  1603. switch (diff_type) {
  1604. case DIFF_INSERT:
  1605. patch.diffs[patchDiffLength++] = diffs[x];
  1606. patch.length2 += diff_text.length;
  1607. postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +
  1608. postpatch_text.substring(char_count2);
  1609. break;
  1610. case DIFF_DELETE:
  1611. patch.length1 += diff_text.length;
  1612. patch.diffs[patchDiffLength++] = diffs[x];
  1613. postpatch_text = postpatch_text.substring(0, char_count2) +
  1614. postpatch_text.substring(char_count2 +
  1615. diff_text.length);
  1616. break;
  1617. case DIFF_EQUAL:
  1618. if (diff_text.length <= 2 * this.Patch_Margin &&
  1619. patchDiffLength && diffs.length != x + 1) {
  1620. // Small equality inside a patch.
  1621. patch.diffs[patchDiffLength++] = diffs[x];
  1622. patch.length1 += diff_text.length;
  1623. patch.length2 += diff_text.length;
  1624. } else if (diff_text.length >= 2 * this.Patch_Margin) {
  1625. // Time for a new patch.
  1626. if (patchDiffLength) {
  1627. this.patch_addContext_(patch, prepatch_text);
  1628. patches.push(patch);
  1629. patch = new diff_match_patch.patch_obj();
  1630. patchDiffLength = 0;
  1631. // Unlike Unidiff, our patch lists have a rolling context.
  1632. // https://github.com/google/diff-match-patch/wiki/Unidiff
  1633. // Update prepatch text & pos to reflect the application of the
  1634. // just completed patch.
  1635. prepatch_text = postpatch_text;
  1636. char_count1 = char_count2;
  1637. }
  1638. }
  1639. break;
  1640. }
  1641. // Update the current character count.
  1642. if (diff_type !== DIFF_INSERT) {
  1643. char_count1 += diff_text.length;
  1644. }
  1645. if (diff_type !== DIFF_DELETE) {
  1646. char_count2 += diff_text.length;
  1647. }
  1648. }
  1649. // Pick up the leftover patch if not empty.
  1650. if (patchDiffLength) {
  1651. this.patch_addContext_(patch, prepatch_text);
  1652. patches.push(patch);
  1653. }
  1654. return patches;
  1655. };
  1656. /**
  1657. * Given an array of patches, return another array that is identical.
  1658. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1659. * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
  1660. */
  1661. diff_match_patch.prototype.patch_deepCopy = function(patches) {
  1662. // Making deep copies is hard in JavaScript.
  1663. var patchesCopy = [];
  1664. for (var x = 0; x < patches.length; x++) {
  1665. var patch = patches[x];
  1666. var patchCopy = new diff_match_patch.patch_obj();
  1667. patchCopy.diffs = [];
  1668. for (var y = 0; y < patch.diffs.length; y++) {
  1669. patchCopy.diffs[y] =
  1670. new diff_match_patch.Diff(patch.diffs[y][0], patch.diffs[y][1]);
  1671. }
  1672. patchCopy.start1 = patch.start1;
  1673. patchCopy.start2 = patch.start2;
  1674. patchCopy.length1 = patch.length1;
  1675. patchCopy.length2 = patch.length2;
  1676. patchesCopy[x] = patchCopy;
  1677. }
  1678. return patchesCopy;
  1679. };
  1680. /**
  1681. * Merge a set of patches onto the text. Return a patched text, as well
  1682. * as a list of true/false values indicating which patches were applied.
  1683. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1684. * @param {string} text Old text.
  1685. * @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the
  1686. * new text and an array of boolean values.
  1687. */
  1688. diff_match_patch.prototype.patch_apply = function(patches, text) {
  1689. if (patches.length == 0) {
  1690. return [text, []];
  1691. }
  1692. // Deep copy the patches so that no changes are made to originals.
  1693. patches = this.patch_deepCopy(patches);
  1694. var nullPadding = this.patch_addPadding(patches);
  1695. text = nullPadding + text + nullPadding;
  1696. this.patch_splitMax(patches);
  1697. // delta keeps track of the offset between the expected and actual location
  1698. // of the previous patch. If there are patches expected at positions 10 and
  1699. // 20, but the first patch was found at 12, delta is 2 and the second patch
  1700. // has an effective expected position of 22.
  1701. var delta = 0;
  1702. var results = [];
  1703. for (var x = 0; x < patches.length; x++) {
  1704. var expected_loc = patches[x].start2 + delta;
  1705. var text1 = this.diff_text1(patches[x].diffs);
  1706. var start_loc;
  1707. var end_loc = -1;
  1708. if (text1.length > this.Match_MaxBits) {
  1709. // patch_splitMax will only provide an oversized pattern in the case of
  1710. // a monster delete.
  1711. start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),
  1712. expected_loc);
  1713. if (start_loc != -1) {
  1714. end_loc = this.match_main(text,
  1715. text1.substring(text1.length - this.Match_MaxBits),
  1716. expected_loc + text1.length - this.Match_MaxBits);
  1717. if (end_loc == -1 || start_loc >= end_loc) {
  1718. // Can't find valid trailing context. Drop this patch.
  1719. start_loc = -1;
  1720. }
  1721. }
  1722. } else {
  1723. start_loc = this.match_main(text, text1, expected_loc);
  1724. }
  1725. if (start_loc == -1) {
  1726. // No match found. :(
  1727. results[x] = false;
  1728. // Subtract the delta for this failed patch from subsequent patches.
  1729. delta -= patches[x].length2 - patches[x].length1;
  1730. } else {
  1731. // Found a match. :)
  1732. results[x] = true;
  1733. delta = start_loc - expected_loc;
  1734. var text2;
  1735. if (end_loc == -1) {
  1736. text2 = text.substring(start_loc, start_loc + text1.length);
  1737. } else {
  1738. text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);
  1739. }
  1740. if (text1 == text2) {
  1741. // Perfect match, just shove the replacement text in.
  1742. text = text.substring(0, start_loc) +
  1743. this.diff_text2(patches[x].diffs) +
  1744. text.substring(start_loc + text1.length);
  1745. } else {
  1746. // Imperfect match. Run a diff to get a framework of equivalent
  1747. // indices.
  1748. var diffs = this.diff_main(text1, text2, false);
  1749. if (text1.length > this.Match_MaxBits &&
  1750. this.diff_levenshtein(diffs) / text1.length >
  1751. this.Patch_DeleteThreshold) {
  1752. // The end points match, but the content is unacceptably bad.
  1753. results[x] = false;
  1754. } else {
  1755. this.diff_cleanupSemanticLossless(diffs);
  1756. var index1 = 0;
  1757. var index2;
  1758. for (var y = 0; y < patches[x].diffs.length; y++) {
  1759. var mod = patches[x].diffs[y];
  1760. if (mod[0] !== DIFF_EQUAL) {
  1761. index2 = this.diff_xIndex(diffs, index1);
  1762. }
  1763. if (mod[0] === DIFF_INSERT) { // Insertion
  1764. text = text.substring(0, start_loc + index2) + mod[1] +
  1765. text.substring(start_loc + index2);
  1766. } else if (mod[0] === DIFF_DELETE) { // Deletion
  1767. text = text.substring(0, start_loc + index2) +
  1768. text.substring(start_loc + this.diff_xIndex(diffs,
  1769. index1 + mod[1].length));
  1770. }
  1771. if (mod[0] !== DIFF_DELETE) {
  1772. index1 += mod[1].length;
  1773. }
  1774. }
  1775. }
  1776. }
  1777. }
  1778. }
  1779. // Strip the padding off.
  1780. text = text.substring(nullPadding.length, text.length - nullPadding.length);
  1781. return [text, results];
  1782. };
  1783. /**
  1784. * Add some padding on text start and end so that edges can match something.
  1785. * Intended to be called only from within patch_apply.
  1786. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1787. * @return {string} The padding string added to each side.
  1788. */
  1789. diff_match_patch.prototype.patch_addPadding = function(patches) {
  1790. var paddingLength = this.Patch_Margin;
  1791. var nullPadding = '';
  1792. for (var x = 1; x <= paddingLength; x++) {
  1793. nullPadding += String.fromCharCode(x);
  1794. }
  1795. // Bump all the patches forward.
  1796. for (var x = 0; x < patches.length; x++) {
  1797. patches[x].start1 += paddingLength;
  1798. patches[x].start2 += paddingLength;
  1799. }
  1800. // Add some padding on start of first diff.
  1801. var patch = patches[0];
  1802. var diffs = patch.diffs;
  1803. if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {
  1804. // Add nullPadding equality.
  1805. diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));
  1806. patch.start1 -= paddingLength; // Should be 0.
  1807. patch.start2 -= paddingLength; // Should be 0.
  1808. patch.length1 += paddingLength;
  1809. patch.length2 += paddingLength;
  1810. } else if (paddingLength > diffs[0][1].length) {
  1811. // Grow first equality.
  1812. var extraLength = paddingLength - diffs[0][1].length;
  1813. diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];
  1814. patch.start1 -= extraLength;
  1815. patch.start2 -= extraLength;
  1816. patch.length1 += extraLength;
  1817. patch.length2 += extraLength;
  1818. }
  1819. // Add some padding on end of last diff.
  1820. patch = patches[patches.length - 1];
  1821. diffs = patch.diffs;
  1822. if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {
  1823. // Add nullPadding equality.
  1824. diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));
  1825. patch.length1 += paddingLength;
  1826. patch.length2 += paddingLength;
  1827. } else if (paddingLength > diffs[diffs.length - 1][1].length) {
  1828. // Grow last equality.
  1829. var extraLength = paddingLength - diffs[diffs.length - 1][1].length;
  1830. diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);
  1831. patch.length1 += extraLength;
  1832. patch.length2 += extraLength;
  1833. }
  1834. return nullPadding;
  1835. };
  1836. /**
  1837. * Look through the patches and break up any which are longer than the maximum
  1838. * limit of the match algorithm.
  1839. * Intended to be called only from within patch_apply.
  1840. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1841. */
  1842. diff_match_patch.prototype.patch_splitMax = function(patches) {
  1843. var patch_size = this.Match_MaxBits;
  1844. for (var x = 0; x < patches.length; x++) {
  1845. if (patches[x].length1 <= patch_size) {
  1846. continue;
  1847. }
  1848. var bigpatch = patches[x];
  1849. // Remove the big old patch.
  1850. patches.splice(x--, 1);
  1851. var start1 = bigpatch.start1;
  1852. var start2 = bigpatch.start2;
  1853. var precontext = '';
  1854. while (bigpatch.diffs.length !== 0) {
  1855. // Create one of several smaller patches.
  1856. var patch = new diff_match_patch.patch_obj();
  1857. var empty = true;
  1858. patch.start1 = start1 - precontext.length;
  1859. patch.start2 = start2 - precontext.length;
  1860. if (precontext !== '') {
  1861. patch.length1 = patch.length2 = precontext.length;
  1862. patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, precontext));
  1863. }
  1864. while (bigpatch.diffs.length !== 0 &&
  1865. patch.length1 < patch_size - this.Patch_Margin) {
  1866. var diff_type = bigpatch.diffs[0][0];
  1867. var diff_text = bigpatch.diffs[0][1];
  1868. if (diff_type === DIFF_INSERT) {
  1869. // Insertions are harmless.
  1870. patch.length2 += diff_text.length;
  1871. start2 += diff_text.length;
  1872. patch.diffs.push(bigpatch.diffs.shift());
  1873. empty = false;
  1874. } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&
  1875. patch.diffs[0][0] == DIFF_EQUAL &&
  1876. diff_text.length > 2 * patch_size) {
  1877. // This is a large deletion. Let it pass in one chunk.
  1878. patch.length1 += diff_text.length;
  1879. start1 += diff_text.length;
  1880. empty = false;
  1881. patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));
  1882. bigpatch.diffs.shift();
  1883. } else {
  1884. // Deletion or equality. Only take as much as we can stomach.
  1885. diff_text = diff_text.substring(0,
  1886. patch_size - patch.length1 - this.Patch_Margin);
  1887. patch.length1 += diff_text.length;
  1888. start1 += diff_text.length;
  1889. if (diff_type === DIFF_EQUAL) {
  1890. patch.length2 += diff_text.length;
  1891. start2 += diff_text.length;
  1892. } else {
  1893. empty = false;
  1894. }
  1895. patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));
  1896. if (diff_text == bigpatch.diffs[0][1]) {
  1897. bigpatch.diffs.shift();
  1898. } else {
  1899. bigpatch.diffs[0][1] =
  1900. bigpatch.diffs[0][1].substring(diff_text.length);
  1901. }
  1902. }
  1903. }
  1904. // Compute the head context for the next patch.
  1905. precontext = this.diff_text2(patch.diffs);
  1906. precontext =
  1907. precontext.substring(precontext.length - this.Patch_Margin);
  1908. // Append the end context for this patch.
  1909. var postcontext = this.diff_text1(bigpatch.diffs)
  1910. .substring(0, this.Patch_Margin);
  1911. if (postcontext !== '') {
  1912. patch.length1 += postcontext.length;
  1913. patch.length2 += postcontext.length;
  1914. if (patch.diffs.length !== 0 &&
  1915. patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {
  1916. patch.diffs[patch.diffs.length - 1][1] += postcontext;
  1917. } else {
  1918. patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, postcontext));
  1919. }
  1920. }
  1921. if (!empty) {
  1922. patches.splice(++x, 0, patch);
  1923. }
  1924. }
  1925. }
  1926. };
  1927. /**
  1928. * Take a list of patches and return a textual representation.
  1929. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1930. * @return {string} Text representation of patches.
  1931. */
  1932. diff_match_patch.prototype.patch_toText = function(patches) {
  1933. var text = [];
  1934. for (var x = 0; x < patches.length; x++) {
  1935. text[x] = patches[x];
  1936. }
  1937. return text.join('');
  1938. };
  1939. /**
  1940. * Parse a textual representation of patches and return a list of Patch objects.
  1941. * @param {string} textline Text representation of patches.
  1942. * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
  1943. * @throws {!Error} If invalid input.
  1944. */
  1945. diff_match_patch.prototype.patch_fromText = function(textline) {
  1946. var patches = [];
  1947. if (!textline) {
  1948. return patches;
  1949. }
  1950. var text = textline.split('\n');
  1951. var textPointer = 0;
  1952. var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
  1953. while (textPointer < text.length) {
  1954. var m = text[textPointer].match(patchHeader);
  1955. if (!m) {
  1956. throw new Error('Invalid patch string: ' + text[textPointer]);
  1957. }
  1958. var patch = new diff_match_patch.patch_obj();
  1959. patches.push(patch);
  1960. patch.start1 = parseInt(m[1], 10);
  1961. if (m[2] === '') {
  1962. patch.start1--;
  1963. patch.length1 = 1;
  1964. } else if (m[2] == '0') {
  1965. patch.length1 = 0;
  1966. } else {
  1967. patch.start1--;
  1968. patch.length1 = parseInt(m[2], 10);
  1969. }
  1970. patch.start2 = parseInt(m[3], 10);
  1971. if (m[4] === '') {
  1972. patch.start2--;
  1973. patch.length2 = 1;
  1974. } else if (m[4] == '0') {
  1975. patch.length2 = 0;
  1976. } else {
  1977. patch.start2--;
  1978. patch.length2 = parseInt(m[4], 10);
  1979. }
  1980. textPointer++;
  1981. while (textPointer < text.length) {
  1982. var sign = text[textPointer].charAt(0);
  1983. try {
  1984. var line = decodeURI(text[textPointer].substring(1));
  1985. } catch (ex) {
  1986. // Malformed URI sequence.
  1987. throw new Error('Illegal escape in patch_fromText: ' + line);
  1988. }
  1989. if (sign == '-') {
  1990. // Deletion.
  1991. patch.diffs.push(new diff_match_patch.Diff(DIFF_DELETE, line));
  1992. } else if (sign == '+') {
  1993. // Insertion.
  1994. patch.diffs.push(new diff_match_patch.Diff(DIFF_INSERT, line));
  1995. } else if (sign == ' ') {
  1996. // Minor equality.
  1997. patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, line));
  1998. } else if (sign == '@') {
  1999. // Start of next patch.
  2000. break;
  2001. } else if (sign === '') {
  2002. // Blank line? Whatever.
  2003. } else {
  2004. // WTF?
  2005. throw new Error('Invalid patch mode "' + sign + '" in: ' + line);
  2006. }
  2007. textPointer++;
  2008. }
  2009. }
  2010. return patches;
  2011. };
  2012. /**
  2013. * Class representing one patch operation.
  2014. * @constructor
  2015. */
  2016. diff_match_patch.patch_obj = function() {
  2017. /** @type {!Array.<!diff_match_patch.Diff>} */
  2018. this.diffs = [];
  2019. /** @type {?number} */
  2020. this.start1 = null;
  2021. /** @type {?number} */
  2022. this.start2 = null;
  2023. /** @type {number} */
  2024. this.length1 = 0;
  2025. /** @type {number} */
  2026. this.length2 = 0;
  2027. };
  2028. /**
  2029. * Emulate GNU diff's format.
  2030. * Header: @@ -382,8 +481,9 @@
  2031. * Indices are printed as 1-based, not 0-based.
  2032. * @return {string} The GNU diff string.
  2033. */
  2034. diff_match_patch.patch_obj.prototype.toString = function() {
  2035. var coords1, coords2;
  2036. if (this.length1 === 0) {
  2037. coords1 = this.start1 + ',0';
  2038. } else if (this.length1 == 1) {
  2039. coords1 = this.start1 + 1;
  2040. } else {
  2041. coords1 = (this.start1 + 1) + ',' + this.length1;
  2042. }
  2043. if (this.length2 === 0) {
  2044. coords2 = this.start2 + ',0';
  2045. } else if (this.length2 == 1) {
  2046. coords2 = this.start2 + 1;
  2047. } else {
  2048. coords2 = (this.start2 + 1) + ',' + this.length2;
  2049. }
  2050. var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n'];
  2051. var op;
  2052. // Escape the body of the patch with %xx notation.
  2053. for (var x = 0; x < this.diffs.length; x++) {
  2054. switch (this.diffs[x][0]) {
  2055. case DIFF_INSERT:
  2056. op = '+';
  2057. break;
  2058. case DIFF_DELETE:
  2059. op = '-';
  2060. break;
  2061. case DIFF_EQUAL:
  2062. op = ' ';
  2063. break;
  2064. }
  2065. text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n';
  2066. }
  2067. return text.join('').replace(/%20/g, ' ');
  2068. };
  2069. // The following export code was added by @ForbesLindesay
  2070. module.exports = diff_match_patch;
  2071. module.exports.diff_match_patch = diff_match_patch;
  2072. module.exports.DIFF_DELETE = DIFF_DELETE;
  2073. module.exports.DIFF_INSERT = DIFF_INSERT;
  2074. module.exports.DIFF_EQUAL = DIFF_EQUAL;
  2075. /***/ }),
  2076. /***/ 21766:
  2077. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2078. "use strict";
  2079. const path = __webpack_require__(85622);
  2080. const os = __webpack_require__(12087);
  2081. const homedir = os.homedir();
  2082. const tmpdir = os.tmpdir();
  2083. const {env} = process;
  2084. const macos = name => {
  2085. const library = path.join(homedir, 'Library');
  2086. return {
  2087. data: path.join(library, 'Application Support', name),
  2088. config: path.join(library, 'Preferences', name),
  2089. cache: path.join(library, 'Caches', name),
  2090. log: path.join(library, 'Logs', name),
  2091. temp: path.join(tmpdir, name)
  2092. };
  2093. };
  2094. const windows = name => {
  2095. const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming');
  2096. const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local');
  2097. return {
  2098. // Data/config/cache/log are invented by me as Windows isn't opinionated about this
  2099. data: path.join(localAppData, name, 'Data'),
  2100. config: path.join(appData, name, 'Config'),
  2101. cache: path.join(localAppData, name, 'Cache'),
  2102. log: path.join(localAppData, name, 'Log'),
  2103. temp: path.join(tmpdir, name)
  2104. };
  2105. };
  2106. // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
  2107. const linux = name => {
  2108. const username = path.basename(homedir);
  2109. return {
  2110. data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name),
  2111. config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name),
  2112. cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name),
  2113. // https://wiki.debian.org/XDGBaseDirectorySpecification#state
  2114. log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name),
  2115. temp: path.join(tmpdir, username, name)
  2116. };
  2117. };
  2118. const envPaths = (name, options) => {
  2119. if (typeof name !== 'string') {
  2120. throw new TypeError(`Expected string, got ${typeof name}`);
  2121. }
  2122. options = Object.assign({suffix: 'nodejs'}, options);
  2123. if (options.suffix) {
  2124. // Add suffix to prevent possible conflict with native apps
  2125. name += `-${options.suffix}`;
  2126. }
  2127. if (process.platform === 'darwin') {
  2128. return macos(name);
  2129. }
  2130. if (process.platform === 'win32') {
  2131. return windows(name);
  2132. }
  2133. return linux(name);
  2134. };
  2135. module.exports = envPaths;
  2136. // TODO: Remove this for the next major release
  2137. module.exports.default = envPaths;
  2138. /***/ }),
  2139. /***/ 79732:
  2140. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  2141. "use strict";
  2142. __webpack_require__.r(__webpack_exports__);
  2143. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2144. /* harmony export */ "DiffPatcher": () => (/* binding */ DiffPatcher),
  2145. /* harmony export */ "formatters": () => (/* binding */ index),
  2146. /* harmony export */ "console": () => (/* binding */ console$1),
  2147. /* harmony export */ "create": () => (/* binding */ create),
  2148. /* harmony export */ "dateReviver": () => (/* binding */ dateReviver),
  2149. /* harmony export */ "diff": () => (/* binding */ diff),
  2150. /* harmony export */ "patch": () => (/* binding */ patch),
  2151. /* harmony export */ "unpatch": () => (/* binding */ unpatch),
  2152. /* harmony export */ "reverse": () => (/* binding */ reverse),
  2153. /* harmony export */ "clone": () => (/* binding */ clone$1)
  2154. /* harmony export */ });
  2155. /* harmony import */ var diff_match_patch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52027);
  2156. /* harmony import */ var diff_match_patch__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(diff_match_patch__WEBPACK_IMPORTED_MODULE_0__);
  2157. /* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32589);
  2158. /* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_1__);
  2159. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  2160. return typeof obj;
  2161. } : function (obj) {
  2162. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  2163. };
  2164. var classCallCheck = function (instance, Constructor) {
  2165. if (!(instance instanceof Constructor)) {
  2166. throw new TypeError("Cannot call a class as a function");
  2167. }
  2168. };
  2169. var createClass = function () {
  2170. function defineProperties(target, props) {
  2171. for (var i = 0; i < props.length; i++) {
  2172. var descriptor = props[i];
  2173. descriptor.enumerable = descriptor.enumerable || false;
  2174. descriptor.configurable = true;
  2175. if ("value" in descriptor) descriptor.writable = true;
  2176. Object.defineProperty(target, descriptor.key, descriptor);
  2177. }
  2178. }
  2179. return function (Constructor, protoProps, staticProps) {
  2180. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  2181. if (staticProps) defineProperties(Constructor, staticProps);
  2182. return Constructor;
  2183. };
  2184. }();
  2185. var get = function get(object, property, receiver) {
  2186. if (object === null) object = Function.prototype;
  2187. var desc = Object.getOwnPropertyDescriptor(object, property);
  2188. if (desc === undefined) {
  2189. var parent = Object.getPrototypeOf(object);
  2190. if (parent === null) {
  2191. return undefined;
  2192. } else {
  2193. return get(parent, property, receiver);
  2194. }
  2195. } else if ("value" in desc) {
  2196. return desc.value;
  2197. } else {
  2198. var getter = desc.get;
  2199. if (getter === undefined) {
  2200. return undefined;
  2201. }
  2202. return getter.call(receiver);
  2203. }
  2204. };
  2205. var inherits = function (subClass, superClass) {
  2206. if (typeof superClass !== "function" && superClass !== null) {
  2207. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  2208. }
  2209. subClass.prototype = Object.create(superClass && superClass.prototype, {
  2210. constructor: {
  2211. value: subClass,
  2212. enumerable: false,
  2213. writable: true,
  2214. configurable: true
  2215. }
  2216. });
  2217. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  2218. };
  2219. var possibleConstructorReturn = function (self, call) {
  2220. if (!self) {
  2221. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  2222. }
  2223. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  2224. };
  2225. var slicedToArray = function () {
  2226. function sliceIterator(arr, i) {
  2227. var _arr = [];
  2228. var _n = true;
  2229. var _d = false;
  2230. var _e = undefined;
  2231. try {
  2232. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  2233. _arr.push(_s.value);
  2234. if (i && _arr.length === i) break;
  2235. }
  2236. } catch (err) {
  2237. _d = true;
  2238. _e = err;
  2239. } finally {
  2240. try {
  2241. if (!_n && _i["return"]) _i["return"]();
  2242. } finally {
  2243. if (_d) throw _e;
  2244. }
  2245. }
  2246. return _arr;
  2247. }
  2248. return function (arr, i) {
  2249. if (Array.isArray(arr)) {
  2250. return arr;
  2251. } else if (Symbol.iterator in Object(arr)) {
  2252. return sliceIterator(arr, i);
  2253. } else {
  2254. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  2255. }
  2256. };
  2257. }();
  2258. var toConsumableArray = function (arr) {
  2259. if (Array.isArray(arr)) {
  2260. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  2261. return arr2;
  2262. } else {
  2263. return Array.from(arr);
  2264. }
  2265. };
  2266. var Processor = function () {
  2267. function Processor(options) {
  2268. classCallCheck(this, Processor);
  2269. this.selfOptions = options || {};
  2270. this.pipes = {};
  2271. }
  2272. createClass(Processor, [{
  2273. key: 'options',
  2274. value: function options(_options) {
  2275. if (_options) {
  2276. this.selfOptions = _options;
  2277. }
  2278. return this.selfOptions;
  2279. }
  2280. }, {
  2281. key: 'pipe',
  2282. value: function pipe(name, pipeArg) {
  2283. var pipe = pipeArg;
  2284. if (typeof name === 'string') {
  2285. if (typeof pipe === 'undefined') {
  2286. return this.pipes[name];
  2287. } else {
  2288. this.pipes[name] = pipe;
  2289. }
  2290. }
  2291. if (name && name.name) {
  2292. pipe = name;
  2293. if (pipe.processor === this) {
  2294. return pipe;
  2295. }
  2296. this.pipes[pipe.name] = pipe;
  2297. }
  2298. pipe.processor = this;
  2299. return pipe;
  2300. }
  2301. }, {
  2302. key: 'process',
  2303. value: function process(input, pipe) {
  2304. var context = input;
  2305. context.options = this.options();
  2306. var nextPipe = pipe || input.pipe || 'default';
  2307. var lastPipe = void 0;
  2308. var lastContext = void 0;
  2309. while (nextPipe) {
  2310. if (typeof context.nextAfterChildren !== 'undefined') {
  2311. // children processed and coming back to parent
  2312. context.next = context.nextAfterChildren;
  2313. context.nextAfterChildren = null;
  2314. }
  2315. if (typeof nextPipe === 'string') {
  2316. nextPipe = this.pipe(nextPipe);
  2317. }
  2318. nextPipe.process(context);
  2319. lastContext = context;
  2320. lastPipe = nextPipe;
  2321. nextPipe = null;
  2322. if (context) {
  2323. if (context.next) {
  2324. context = context.next;
  2325. nextPipe = lastContext.nextPipe || context.pipe || lastPipe;
  2326. }
  2327. }
  2328. }
  2329. return context.hasResult ? context.result : undefined;
  2330. }
  2331. }]);
  2332. return Processor;
  2333. }();
  2334. var Pipe = function () {
  2335. function Pipe(name) {
  2336. classCallCheck(this, Pipe);
  2337. this.name = name;
  2338. this.filters = [];
  2339. }
  2340. createClass(Pipe, [{
  2341. key: 'process',
  2342. value: function process(input) {
  2343. if (!this.processor) {
  2344. throw new Error('add this pipe to a processor before using it');
  2345. }
  2346. var debug = this.debug;
  2347. var length = this.filters.length;
  2348. var context = input;
  2349. for (var index = 0; index < length; index++) {
  2350. var filter = this.filters[index];
  2351. if (debug) {
  2352. this.log('filter: ' + filter.filterName);
  2353. }
  2354. filter(context);
  2355. if ((typeof context === 'undefined' ? 'undefined' : _typeof(context)) === 'object' && context.exiting) {
  2356. context.exiting = false;
  2357. break;
  2358. }
  2359. }
  2360. if (!context.next && this.resultCheck) {
  2361. this.resultCheck(context);
  2362. }
  2363. }
  2364. }, {
  2365. key: 'log',
  2366. value: function log(msg) {
  2367. console.log('[jsondiffpatch] ' + this.name + ' pipe, ' + msg);
  2368. }
  2369. }, {
  2370. key: 'append',
  2371. value: function append() {
  2372. var _filters;
  2373. (_filters = this.filters).push.apply(_filters, arguments);
  2374. return this;
  2375. }
  2376. }, {
  2377. key: 'prepend',
  2378. value: function prepend() {
  2379. var _filters2;
  2380. (_filters2 = this.filters).unshift.apply(_filters2, arguments);
  2381. return this;
  2382. }
  2383. }, {
  2384. key: 'indexOf',
  2385. value: function indexOf(filterName) {
  2386. if (!filterName) {
  2387. throw new Error('a filter name is required');
  2388. }
  2389. for (var index = 0; index < this.filters.length; index++) {
  2390. var filter = this.filters[index];
  2391. if (filter.filterName === filterName) {
  2392. return index;
  2393. }
  2394. }
  2395. throw new Error('filter not found: ' + filterName);
  2396. }
  2397. }, {
  2398. key: 'list',
  2399. value: function list() {
  2400. return this.filters.map(function (f) {
  2401. return f.filterName;
  2402. });
  2403. }
  2404. }, {
  2405. key: 'after',
  2406. value: function after(filterName) {
  2407. var index = this.indexOf(filterName);
  2408. var params = Array.prototype.slice.call(arguments, 1);
  2409. if (!params.length) {
  2410. throw new Error('a filter is required');
  2411. }
  2412. params.unshift(index + 1, 0);
  2413. Array.prototype.splice.apply(this.filters, params);
  2414. return this;
  2415. }
  2416. }, {
  2417. key: 'before',
  2418. value: function before(filterName) {
  2419. var index = this.indexOf(filterName);
  2420. var params = Array.prototype.slice.call(arguments, 1);
  2421. if (!params.length) {
  2422. throw new Error('a filter is required');
  2423. }
  2424. params.unshift(index, 0);
  2425. Array.prototype.splice.apply(this.filters, params);
  2426. return this;
  2427. }
  2428. }, {
  2429. key: 'replace',
  2430. value: function replace(filterName) {
  2431. var index = this.indexOf(filterName);
  2432. var params = Array.prototype.slice.call(arguments, 1);
  2433. if (!params.length) {
  2434. throw new Error('a filter is required');
  2435. }
  2436. params.unshift(index, 1);
  2437. Array.prototype.splice.apply(this.filters, params);
  2438. return this;
  2439. }
  2440. }, {
  2441. key: 'remove',
  2442. value: function remove(filterName) {
  2443. var index = this.indexOf(filterName);
  2444. this.filters.splice(index, 1);
  2445. return this;
  2446. }
  2447. }, {
  2448. key: 'clear',
  2449. value: function clear() {
  2450. this.filters.length = 0;
  2451. return this;
  2452. }
  2453. }, {
  2454. key: 'shouldHaveResult',
  2455. value: function shouldHaveResult(should) {
  2456. if (should === false) {
  2457. this.resultCheck = null;
  2458. return;
  2459. }
  2460. if (this.resultCheck) {
  2461. return;
  2462. }
  2463. var pipe = this;
  2464. this.resultCheck = function (context) {
  2465. if (!context.hasResult) {
  2466. console.log(context);
  2467. var error = new Error(pipe.name + ' failed');
  2468. error.noResult = true;
  2469. throw error;
  2470. }
  2471. };
  2472. return this;
  2473. }
  2474. }]);
  2475. return Pipe;
  2476. }();
  2477. var Context = function () {
  2478. function Context() {
  2479. classCallCheck(this, Context);
  2480. }
  2481. createClass(Context, [{
  2482. key: 'setResult',
  2483. value: function setResult(result) {
  2484. this.result = result;
  2485. this.hasResult = true;
  2486. return this;
  2487. }
  2488. }, {
  2489. key: 'exit',
  2490. value: function exit() {
  2491. this.exiting = true;
  2492. return this;
  2493. }
  2494. }, {
  2495. key: 'switchTo',
  2496. value: function switchTo(next, pipe) {
  2497. if (typeof next === 'string' || next instanceof Pipe) {
  2498. this.nextPipe = next;
  2499. } else {
  2500. this.next = next;
  2501. if (pipe) {
  2502. this.nextPipe = pipe;
  2503. }
  2504. }
  2505. return this;
  2506. }
  2507. }, {
  2508. key: 'push',
  2509. value: function push(child, name) {
  2510. child.parent = this;
  2511. if (typeof name !== 'undefined') {
  2512. child.childName = name;
  2513. }
  2514. child.root = this.root || this;
  2515. child.options = child.options || this.options;
  2516. if (!this.children) {
  2517. this.children = [child];
  2518. this.nextAfterChildren = this.next || null;
  2519. this.next = child;
  2520. } else {
  2521. this.children[this.children.length - 1].next = child;
  2522. this.children.push(child);
  2523. }
  2524. child.next = this;
  2525. return this;
  2526. }
  2527. }]);
  2528. return Context;
  2529. }();
  2530. var isArray = typeof Array.isArray === 'function' ? Array.isArray : function (a) {
  2531. return a instanceof Array;
  2532. };
  2533. function cloneRegExp(re) {
  2534. var regexMatch = /^\/(.*)\/([gimyu]*)$/.exec(re.toString());
  2535. return new RegExp(regexMatch[1], regexMatch[2]);
  2536. }
  2537. function clone(arg) {
  2538. if ((typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) !== 'object') {
  2539. return arg;
  2540. }
  2541. if (arg === null) {
  2542. return null;
  2543. }
  2544. if (isArray(arg)) {
  2545. return arg.map(clone);
  2546. }
  2547. if (arg instanceof Date) {
  2548. return new Date(arg.getTime());
  2549. }
  2550. if (arg instanceof RegExp) {
  2551. return cloneRegExp(arg);
  2552. }
  2553. var cloned = {};
  2554. for (var name in arg) {
  2555. if (Object.prototype.hasOwnProperty.call(arg, name)) {
  2556. cloned[name] = clone(arg[name]);
  2557. }
  2558. }
  2559. return cloned;
  2560. }
  2561. var DiffContext = function (_Context) {
  2562. inherits(DiffContext, _Context);
  2563. function DiffContext(left, right) {
  2564. classCallCheck(this, DiffContext);
  2565. var _this = possibleConstructorReturn(this, (DiffContext.__proto__ || Object.getPrototypeOf(DiffContext)).call(this));
  2566. _this.left = left;
  2567. _this.right = right;
  2568. _this.pipe = 'diff';
  2569. return _this;
  2570. }
  2571. createClass(DiffContext, [{
  2572. key: 'setResult',
  2573. value: function setResult(result) {
  2574. if (this.options.cloneDiffValues && (typeof result === 'undefined' ? 'undefined' : _typeof(result)) === 'object') {
  2575. var clone$$1 = typeof this.options.cloneDiffValues === 'function' ? this.options.cloneDiffValues : clone;
  2576. if (_typeof(result[0]) === 'object') {
  2577. result[0] = clone$$1(result[0]);
  2578. }
  2579. if (_typeof(result[1]) === 'object') {
  2580. result[1] = clone$$1(result[1]);
  2581. }
  2582. }
  2583. return Context.prototype.setResult.apply(this, arguments);
  2584. }
  2585. }]);
  2586. return DiffContext;
  2587. }(Context);
  2588. var PatchContext = function (_Context) {
  2589. inherits(PatchContext, _Context);
  2590. function PatchContext(left, delta) {
  2591. classCallCheck(this, PatchContext);
  2592. var _this = possibleConstructorReturn(this, (PatchContext.__proto__ || Object.getPrototypeOf(PatchContext)).call(this));
  2593. _this.left = left;
  2594. _this.delta = delta;
  2595. _this.pipe = 'patch';
  2596. return _this;
  2597. }
  2598. return PatchContext;
  2599. }(Context);
  2600. var ReverseContext = function (_Context) {
  2601. inherits(ReverseContext, _Context);
  2602. function ReverseContext(delta) {
  2603. classCallCheck(this, ReverseContext);
  2604. var _this = possibleConstructorReturn(this, (ReverseContext.__proto__ || Object.getPrototypeOf(ReverseContext)).call(this));
  2605. _this.delta = delta;
  2606. _this.pipe = 'reverse';
  2607. return _this;
  2608. }
  2609. return ReverseContext;
  2610. }(Context);
  2611. var isArray$1 = typeof Array.isArray === 'function' ? Array.isArray : function (a) {
  2612. return a instanceof Array;
  2613. };
  2614. var diffFilter = function trivialMatchesDiffFilter(context) {
  2615. if (context.left === context.right) {
  2616. context.setResult(undefined).exit();
  2617. return;
  2618. }
  2619. if (typeof context.left === 'undefined') {
  2620. if (typeof context.right === 'function') {
  2621. throw new Error('functions are not supported');
  2622. }
  2623. context.setResult([context.right]).exit();
  2624. return;
  2625. }
  2626. if (typeof context.right === 'undefined') {
  2627. context.setResult([context.left, 0, 0]).exit();
  2628. return;
  2629. }
  2630. if (typeof context.left === 'function' || typeof context.right === 'function') {
  2631. throw new Error('functions are not supported');
  2632. }
  2633. context.leftType = context.left === null ? 'null' : _typeof(context.left);
  2634. context.rightType = context.right === null ? 'null' : _typeof(context.right);
  2635. if (context.leftType !== context.rightType) {
  2636. context.setResult([context.left, context.right]).exit();
  2637. return;
  2638. }
  2639. if (context.leftType === 'boolean' || context.leftType === 'number') {
  2640. context.setResult([context.left, context.right]).exit();
  2641. return;
  2642. }
  2643. if (context.leftType === 'object') {
  2644. context.leftIsArray = isArray$1(context.left);
  2645. }
  2646. if (context.rightType === 'object') {
  2647. context.rightIsArray = isArray$1(context.right);
  2648. }
  2649. if (context.leftIsArray !== context.rightIsArray) {
  2650. context.setResult([context.left, context.right]).exit();
  2651. return;
  2652. }
  2653. if (context.left instanceof RegExp) {
  2654. if (context.right instanceof RegExp) {
  2655. context.setResult([context.left.toString(), context.right.toString()]).exit();
  2656. } else {
  2657. context.setResult([context.left, context.right]).exit();
  2658. }
  2659. }
  2660. };
  2661. diffFilter.filterName = 'trivial';
  2662. var patchFilter = function trivialMatchesPatchFilter(context) {
  2663. if (typeof context.delta === 'undefined') {
  2664. context.setResult(context.left).exit();
  2665. return;
  2666. }
  2667. context.nested = !isArray$1(context.delta);
  2668. if (context.nested) {
  2669. return;
  2670. }
  2671. if (context.delta.length === 1) {
  2672. context.setResult(context.delta[0]).exit();
  2673. return;
  2674. }
  2675. if (context.delta.length === 2) {
  2676. if (context.left instanceof RegExp) {
  2677. var regexArgs = /^\/(.*)\/([gimyu]+)$/.exec(context.delta[1]);
  2678. if (regexArgs) {
  2679. context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();
  2680. return;
  2681. }
  2682. }
  2683. context.setResult(context.delta[1]).exit();
  2684. return;
  2685. }
  2686. if (context.delta.length === 3 && context.delta[2] === 0) {
  2687. context.setResult(undefined).exit();
  2688. }
  2689. };
  2690. patchFilter.filterName = 'trivial';
  2691. var reverseFilter = function trivialReferseFilter(context) {
  2692. if (typeof context.delta === 'undefined') {
  2693. context.setResult(context.delta).exit();
  2694. return;
  2695. }
  2696. context.nested = !isArray$1(context.delta);
  2697. if (context.nested) {
  2698. return;
  2699. }
  2700. if (context.delta.length === 1) {
  2701. context.setResult([context.delta[0], 0, 0]).exit();
  2702. return;
  2703. }
  2704. if (context.delta.length === 2) {
  2705. context.setResult([context.delta[1], context.delta[0]]).exit();
  2706. return;
  2707. }
  2708. if (context.delta.length === 3 && context.delta[2] === 0) {
  2709. context.setResult([context.delta[0]]).exit();
  2710. }
  2711. };
  2712. reverseFilter.filterName = 'trivial';
  2713. function collectChildrenDiffFilter(context) {
  2714. if (!context || !context.children) {
  2715. return;
  2716. }
  2717. var length = context.children.length;
  2718. var child = void 0;
  2719. var result = context.result;
  2720. for (var index = 0; index < length; index++) {
  2721. child = context.children[index];
  2722. if (typeof child.result === 'undefined') {
  2723. continue;
  2724. }
  2725. result = result || {};
  2726. result[child.childName] = child.result;
  2727. }
  2728. if (result && context.leftIsArray) {
  2729. result._t = 'a';
  2730. }
  2731. context.setResult(result).exit();
  2732. }
  2733. collectChildrenDiffFilter.filterName = 'collectChildren';
  2734. function objectsDiffFilter(context) {
  2735. if (context.leftIsArray || context.leftType !== 'object') {
  2736. return;
  2737. }
  2738. var name = void 0;
  2739. var child = void 0;
  2740. var propertyFilter = context.options.propertyFilter;
  2741. for (name in context.left) {
  2742. if (!Object.prototype.hasOwnProperty.call(context.left, name)) {
  2743. continue;
  2744. }
  2745. if (propertyFilter && !propertyFilter(name, context)) {
  2746. continue;
  2747. }
  2748. child = new DiffContext(context.left[name], context.right[name]);
  2749. context.push(child, name);
  2750. }
  2751. for (name in context.right) {
  2752. if (!Object.prototype.hasOwnProperty.call(context.right, name)) {
  2753. continue;
  2754. }
  2755. if (propertyFilter && !propertyFilter(name, context)) {
  2756. continue;
  2757. }
  2758. if (typeof context.left[name] === 'undefined') {
  2759. child = new DiffContext(undefined, context.right[name]);
  2760. context.push(child, name);
  2761. }
  2762. }
  2763. if (!context.children || context.children.length === 0) {
  2764. context.setResult(undefined).exit();
  2765. return;
  2766. }
  2767. context.exit();
  2768. }
  2769. objectsDiffFilter.filterName = 'objects';
  2770. var patchFilter$1 = function nestedPatchFilter(context) {
  2771. if (!context.nested) {
  2772. return;
  2773. }
  2774. if (context.delta._t) {
  2775. return;
  2776. }
  2777. var name = void 0;
  2778. var child = void 0;
  2779. for (name in context.delta) {
  2780. child = new PatchContext(context.left[name], context.delta[name]);
  2781. context.push(child, name);
  2782. }
  2783. context.exit();
  2784. };
  2785. patchFilter$1.filterName = 'objects';
  2786. var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
  2787. if (!context || !context.children) {
  2788. return;
  2789. }
  2790. if (context.delta._t) {
  2791. return;
  2792. }
  2793. var length = context.children.length;
  2794. var child = void 0;
  2795. for (var index = 0; index < length; index++) {
  2796. child = context.children[index];
  2797. if (Object.prototype.hasOwnProperty.call(context.left, child.childName) && child.result === undefined) {
  2798. delete context.left[child.childName];
  2799. } else if (context.left[child.childName] !== child.result) {
  2800. context.left[child.childName] = child.result;
  2801. }
  2802. }
  2803. context.setResult(context.left).exit();
  2804. };
  2805. collectChildrenPatchFilter.filterName = 'collectChildren';
  2806. var reverseFilter$1 = function nestedReverseFilter(context) {
  2807. if (!context.nested) {
  2808. return;
  2809. }
  2810. if (context.delta._t) {
  2811. return;
  2812. }
  2813. var name = void 0;
  2814. var child = void 0;
  2815. for (name in context.delta) {
  2816. child = new ReverseContext(context.delta[name]);
  2817. context.push(child, name);
  2818. }
  2819. context.exit();
  2820. };
  2821. reverseFilter$1.filterName = 'objects';
  2822. function collectChildrenReverseFilter(context) {
  2823. if (!context || !context.children) {
  2824. return;
  2825. }
  2826. if (context.delta._t) {
  2827. return;
  2828. }
  2829. var length = context.children.length;
  2830. var child = void 0;
  2831. var delta = {};
  2832. for (var index = 0; index < length; index++) {
  2833. child = context.children[index];
  2834. if (delta[child.childName] !== child.result) {
  2835. delta[child.childName] = child.result;
  2836. }
  2837. }
  2838. context.setResult(delta).exit();
  2839. }
  2840. collectChildrenReverseFilter.filterName = 'collectChildren';
  2841. /*
  2842. LCS implementation that supports arrays or strings
  2843. reference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
  2844. */
  2845. var defaultMatch = function defaultMatch(array1, array2, index1, index2) {
  2846. return array1[index1] === array2[index2];
  2847. };
  2848. var lengthMatrix = function lengthMatrix(array1, array2, match, context) {
  2849. var len1 = array1.length;
  2850. var len2 = array2.length;
  2851. var x = void 0,
  2852. y = void 0;
  2853. // initialize empty matrix of len1+1 x len2+1
  2854. var matrix = [len1 + 1];
  2855. for (x = 0; x < len1 + 1; x++) {
  2856. matrix[x] = [len2 + 1];
  2857. for (y = 0; y < len2 + 1; y++) {
  2858. matrix[x][y] = 0;
  2859. }
  2860. }
  2861. matrix.match = match;
  2862. // save sequence lengths for each coordinate
  2863. for (x = 1; x < len1 + 1; x++) {
  2864. for (y = 1; y < len2 + 1; y++) {
  2865. if (match(array1, array2, x - 1, y - 1, context)) {
  2866. matrix[x][y] = matrix[x - 1][y - 1] + 1;
  2867. } else {
  2868. matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]);
  2869. }
  2870. }
  2871. }
  2872. return matrix;
  2873. };
  2874. var backtrack = function backtrack(matrix, array1, array2, context) {
  2875. var index1 = array1.length;
  2876. var index2 = array2.length;
  2877. var subsequence = {
  2878. sequence: [],
  2879. indices1: [],
  2880. indices2: []
  2881. };
  2882. while (index1 !== 0 && index2 !== 0) {
  2883. var sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);
  2884. if (sameLetter) {
  2885. subsequence.sequence.unshift(array1[index1 - 1]);
  2886. subsequence.indices1.unshift(index1 - 1);
  2887. subsequence.indices2.unshift(index2 - 1);
  2888. --index1;
  2889. --index2;
  2890. } else {
  2891. var valueAtMatrixAbove = matrix[index1][index2 - 1];
  2892. var valueAtMatrixLeft = matrix[index1 - 1][index2];
  2893. if (valueAtMatrixAbove > valueAtMatrixLeft) {
  2894. --index2;
  2895. } else {
  2896. --index1;
  2897. }
  2898. }
  2899. }
  2900. return subsequence;
  2901. };
  2902. var get$1 = function get(array1, array2, match, context) {
  2903. var innerContext = context || {};
  2904. var matrix = lengthMatrix(array1, array2, match || defaultMatch, innerContext);
  2905. var result = backtrack(matrix, array1, array2, innerContext);
  2906. if (typeof array1 === 'string' && typeof array2 === 'string') {
  2907. result.sequence = result.sequence.join('');
  2908. }
  2909. return result;
  2910. };
  2911. var lcs = {
  2912. get: get$1
  2913. };
  2914. var ARRAY_MOVE = 3;
  2915. var isArray$2 = typeof Array.isArray === 'function' ? Array.isArray : function (a) {
  2916. return a instanceof Array;
  2917. };
  2918. var arrayIndexOf = typeof Array.prototype.indexOf === 'function' ? function (array, item) {
  2919. return array.indexOf(item);
  2920. } : function (array, item) {
  2921. var length = array.length;
  2922. for (var i = 0; i < length; i++) {
  2923. if (array[i] === item) {
  2924. return i;
  2925. }
  2926. }
  2927. return -1;
  2928. };
  2929. function arraysHaveMatchByRef(array1, array2, len1, len2) {
  2930. for (var index1 = 0; index1 < len1; index1++) {
  2931. var val1 = array1[index1];
  2932. for (var index2 = 0; index2 < len2; index2++) {
  2933. var val2 = array2[index2];
  2934. if (index1 !== index2 && val1 === val2) {
  2935. return true;
  2936. }
  2937. }
  2938. }
  2939. }
  2940. function matchItems(array1, array2, index1, index2, context) {
  2941. var value1 = array1[index1];
  2942. var value2 = array2[index2];
  2943. if (value1 === value2) {
  2944. return true;
  2945. }
  2946. if ((typeof value1 === 'undefined' ? 'undefined' : _typeof(value1)) !== 'object' || (typeof value2 === 'undefined' ? 'undefined' : _typeof(value2)) !== 'object') {
  2947. return false;
  2948. }
  2949. var objectHash = context.objectHash;
  2950. if (!objectHash) {
  2951. // no way to match objects was provided, try match by position
  2952. return context.matchByPosition && index1 === index2;
  2953. }
  2954. var hash1 = void 0;
  2955. var hash2 = void 0;
  2956. if (typeof index1 === 'number') {
  2957. context.hashCache1 = context.hashCache1 || [];
  2958. hash1 = context.hashCache1[index1];
  2959. if (typeof hash1 === 'undefined') {
  2960. context.hashCache1[index1] = hash1 = objectHash(value1, index1);
  2961. }
  2962. } else {
  2963. hash1 = objectHash(value1);
  2964. }
  2965. if (typeof hash1 === 'undefined') {
  2966. return false;
  2967. }
  2968. if (typeof index2 === 'number') {
  2969. context.hashCache2 = context.hashCache2 || [];
  2970. hash2 = context.hashCache2[index2];
  2971. if (typeof hash2 === 'undefined') {
  2972. context.hashCache2[index2] = hash2 = objectHash(value2, index2);
  2973. }
  2974. } else {
  2975. hash2 = objectHash(value2);
  2976. }
  2977. if (typeof hash2 === 'undefined') {
  2978. return false;
  2979. }
  2980. return hash1 === hash2;
  2981. }
  2982. var diffFilter$1 = function arraysDiffFilter(context) {
  2983. if (!context.leftIsArray) {
  2984. return;
  2985. }
  2986. var matchContext = {
  2987. objectHash: context.options && context.options.objectHash,
  2988. matchByPosition: context.options && context.options.matchByPosition
  2989. };
  2990. var commonHead = 0;
  2991. var commonTail = 0;
  2992. var index = void 0;
  2993. var index1 = void 0;
  2994. var index2 = void 0;
  2995. var array1 = context.left;
  2996. var array2 = context.right;
  2997. var len1 = array1.length;
  2998. var len2 = array2.length;
  2999. var child = void 0;
  3000. if (len1 > 0 && len2 > 0 && !matchContext.objectHash && typeof matchContext.matchByPosition !== 'boolean') {
  3001. matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
  3002. }
  3003. // separate common head
  3004. while (commonHead < len1 && commonHead < len2 && matchItems(array1, array2, commonHead, commonHead, matchContext)) {
  3005. index = commonHead;
  3006. child = new DiffContext(context.left[index], context.right[index]);
  3007. context.push(child, index);
  3008. commonHead++;
  3009. }
  3010. // separate common tail
  3011. while (commonTail + commonHead < len1 && commonTail + commonHead < len2 && matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
  3012. index1 = len1 - 1 - commonTail;
  3013. index2 = len2 - 1 - commonTail;
  3014. child = new DiffContext(context.left[index1], context.right[index2]);
  3015. context.push(child, index2);
  3016. commonTail++;
  3017. }
  3018. var result = void 0;
  3019. if (commonHead + commonTail === len1) {
  3020. if (len1 === len2) {
  3021. // arrays are identical
  3022. context.setResult(undefined).exit();
  3023. return;
  3024. }
  3025. // trivial case, a block (1 or more consecutive items) was added
  3026. result = result || {
  3027. _t: 'a'
  3028. };
  3029. for (index = commonHead; index < len2 - commonTail; index++) {
  3030. result[index] = [array2[index]];
  3031. }
  3032. context.setResult(result).exit();
  3033. return;
  3034. }
  3035. if (commonHead + commonTail === len2) {
  3036. // trivial case, a block (1 or more consecutive items) was removed
  3037. result = result || {
  3038. _t: 'a'
  3039. };
  3040. for (index = commonHead; index < len1 - commonTail; index++) {
  3041. result['_' + index] = [array1[index], 0, 0];
  3042. }
  3043. context.setResult(result).exit();
  3044. return;
  3045. }
  3046. // reset hash cache
  3047. delete matchContext.hashCache1;
  3048. delete matchContext.hashCache2;
  3049. // diff is not trivial, find the LCS (Longest Common Subsequence)
  3050. var trimmed1 = array1.slice(commonHead, len1 - commonTail);
  3051. var trimmed2 = array2.slice(commonHead, len2 - commonTail);
  3052. var seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);
  3053. var removedItems = [];
  3054. result = result || {
  3055. _t: 'a'
  3056. };
  3057. for (index = commonHead; index < len1 - commonTail; index++) {
  3058. if (arrayIndexOf(seq.indices1, index - commonHead) < 0) {
  3059. // removed
  3060. result['_' + index] = [array1[index], 0, 0];
  3061. removedItems.push(index);
  3062. }
  3063. }
  3064. var detectMove = true;
  3065. if (context.options && context.options.arrays && context.options.arrays.detectMove === false) {
  3066. detectMove = false;
  3067. }
  3068. var includeValueOnMove = false;
  3069. if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) {
  3070. includeValueOnMove = true;
  3071. }
  3072. var removedItemsLength = removedItems.length;
  3073. for (index = commonHead; index < len2 - commonTail; index++) {
  3074. var indexOnArray2 = arrayIndexOf(seq.indices2, index - commonHead);
  3075. if (indexOnArray2 < 0) {
  3076. // added, try to match with a removed item and register as position move
  3077. var isMove = false;
  3078. if (detectMove && removedItemsLength > 0) {
  3079. for (var removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
  3080. index1 = removedItems[removeItemIndex1];
  3081. if (matchItems(trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext)) {
  3082. // store position move as: [originalValue, newPosition, ARRAY_MOVE]
  3083. result['_' + index1].splice(1, 2, index, ARRAY_MOVE);
  3084. if (!includeValueOnMove) {
  3085. // don't include moved value on diff, to save bytes
  3086. result['_' + index1][0] = '';
  3087. }
  3088. index2 = index;
  3089. child = new DiffContext(context.left[index1], context.right[index2]);
  3090. context.push(child, index2);
  3091. removedItems.splice(removeItemIndex1, 1);
  3092. isMove = true;
  3093. break;
  3094. }
  3095. }
  3096. }
  3097. if (!isMove) {
  3098. // added
  3099. result[index] = [array2[index]];
  3100. }
  3101. } else {
  3102. // match, do inner diff
  3103. index1 = seq.indices1[indexOnArray2] + commonHead;
  3104. index2 = seq.indices2[indexOnArray2] + commonHead;
  3105. child = new DiffContext(context.left[index1], context.right[index2]);
  3106. context.push(child, index2);
  3107. }
  3108. }
  3109. context.setResult(result).exit();
  3110. };
  3111. diffFilter$1.filterName = 'arrays';
  3112. var compare = {
  3113. numerically: function numerically(a, b) {
  3114. return a - b;
  3115. },
  3116. numericallyBy: function numericallyBy(name) {
  3117. return function (a, b) {
  3118. return a[name] - b[name];
  3119. };
  3120. }
  3121. };
  3122. var patchFilter$2 = function nestedPatchFilter(context) {
  3123. if (!context.nested) {
  3124. return;
  3125. }
  3126. if (context.delta._t !== 'a') {
  3127. return;
  3128. }
  3129. var index = void 0;
  3130. var index1 = void 0;
  3131. var delta = context.delta;
  3132. var array = context.left;
  3133. // first, separate removals, insertions and modifications
  3134. var toRemove = [];
  3135. var toInsert = [];
  3136. var toModify = [];
  3137. for (index in delta) {
  3138. if (index !== '_t') {
  3139. if (index[0] === '_') {
  3140. // removed item from original array
  3141. if (delta[index][2] === 0 || delta[index][2] === ARRAY_MOVE) {
  3142. toRemove.push(parseInt(index.slice(1), 10));
  3143. } else {
  3144. throw new Error('only removal or move can be applied at original array indices,' + (' invalid diff type: ' + delta[index][2]));
  3145. }
  3146. } else {
  3147. if (delta[index].length === 1) {
  3148. // added item at new array
  3149. toInsert.push({
  3150. index: parseInt(index, 10),
  3151. value: delta[index][0]
  3152. });
  3153. } else {
  3154. // modified item at new array
  3155. toModify.push({
  3156. index: parseInt(index, 10),
  3157. delta: delta[index]
  3158. });
  3159. }
  3160. }
  3161. }
  3162. }
  3163. // remove items, in reverse order to avoid sawing our own floor
  3164. toRemove = toRemove.sort(compare.numerically);
  3165. for (index = toRemove.length - 1; index >= 0; index--) {
  3166. index1 = toRemove[index];
  3167. var indexDiff = delta['_' + index1];
  3168. var removedValue = array.splice(index1, 1)[0];
  3169. if (indexDiff[2] === ARRAY_MOVE) {
  3170. // reinsert later
  3171. toInsert.push({
  3172. index: indexDiff[1],
  3173. value: removedValue
  3174. });
  3175. }
  3176. }
  3177. // insert items, in reverse order to avoid moving our own floor
  3178. toInsert = toInsert.sort(compare.numericallyBy('index'));
  3179. var toInsertLength = toInsert.length;
  3180. for (index = 0; index < toInsertLength; index++) {
  3181. var insertion = toInsert[index];
  3182. array.splice(insertion.index, 0, insertion.value);
  3183. }
  3184. // apply modifications
  3185. var toModifyLength = toModify.length;
  3186. var child = void 0;
  3187. if (toModifyLength > 0) {
  3188. for (index = 0; index < toModifyLength; index++) {
  3189. var modification = toModify[index];
  3190. child = new PatchContext(context.left[modification.index], modification.delta);
  3191. context.push(child, modification.index);
  3192. }
  3193. }
  3194. if (!context.children) {
  3195. context.setResult(context.left).exit();
  3196. return;
  3197. }
  3198. context.exit();
  3199. };
  3200. patchFilter$2.filterName = 'arrays';
  3201. var collectChildrenPatchFilter$1 = function collectChildrenPatchFilter(context) {
  3202. if (!context || !context.children) {
  3203. return;
  3204. }
  3205. if (context.delta._t !== 'a') {
  3206. return;
  3207. }
  3208. var length = context.children.length;
  3209. var child = void 0;
  3210. for (var index = 0; index < length; index++) {
  3211. child = context.children[index];
  3212. context.left[child.childName] = child.result;
  3213. }
  3214. context.setResult(context.left).exit();
  3215. };
  3216. collectChildrenPatchFilter$1.filterName = 'arraysCollectChildren';
  3217. var reverseFilter$2 = function arraysReverseFilter(context) {
  3218. if (!context.nested) {
  3219. if (context.delta[2] === ARRAY_MOVE) {
  3220. context.newName = '_' + context.delta[1];
  3221. context.setResult([context.delta[0], parseInt(context.childName.substr(1), 10), ARRAY_MOVE]).exit();
  3222. }
  3223. return;
  3224. }
  3225. if (context.delta._t !== 'a') {
  3226. return;
  3227. }
  3228. var name = void 0;
  3229. var child = void 0;
  3230. for (name in context.delta) {
  3231. if (name === '_t') {
  3232. continue;
  3233. }
  3234. child = new ReverseContext(context.delta[name]);
  3235. context.push(child, name);
  3236. }
  3237. context.exit();
  3238. };
  3239. reverseFilter$2.filterName = 'arrays';
  3240. var reverseArrayDeltaIndex = function reverseArrayDeltaIndex(delta, index, itemDelta) {
  3241. if (typeof index === 'string' && index[0] === '_') {
  3242. return parseInt(index.substr(1), 10);
  3243. } else if (isArray$2(itemDelta) && itemDelta[2] === 0) {
  3244. return '_' + index;
  3245. }
  3246. var reverseIndex = +index;
  3247. for (var deltaIndex in delta) {
  3248. var deltaItem = delta[deltaIndex];
  3249. if (isArray$2(deltaItem)) {
  3250. if (deltaItem[2] === ARRAY_MOVE) {
  3251. var moveFromIndex = parseInt(deltaIndex.substr(1), 10);
  3252. var moveToIndex = deltaItem[1];
  3253. if (moveToIndex === +index) {
  3254. return moveFromIndex;
  3255. }
  3256. if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
  3257. reverseIndex++;
  3258. } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) {
  3259. reverseIndex--;
  3260. }
  3261. } else if (deltaItem[2] === 0) {
  3262. var deleteIndex = parseInt(deltaIndex.substr(1), 10);
  3263. if (deleteIndex <= reverseIndex) {
  3264. reverseIndex++;
  3265. }
  3266. } else if (deltaItem.length === 1 && deltaIndex <= reverseIndex) {
  3267. reverseIndex--;
  3268. }
  3269. }
  3270. }
  3271. return reverseIndex;
  3272. };
  3273. function collectChildrenReverseFilter$1(context) {
  3274. if (!context || !context.children) {
  3275. return;
  3276. }
  3277. if (context.delta._t !== 'a') {
  3278. return;
  3279. }
  3280. var length = context.children.length;
  3281. var child = void 0;
  3282. var delta = {
  3283. _t: 'a'
  3284. };
  3285. for (var index = 0; index < length; index++) {
  3286. child = context.children[index];
  3287. var name = child.newName;
  3288. if (typeof name === 'undefined') {
  3289. name = reverseArrayDeltaIndex(context.delta, child.childName, child.result);
  3290. }
  3291. if (delta[name] !== child.result) {
  3292. delta[name] = child.result;
  3293. }
  3294. }
  3295. context.setResult(delta).exit();
  3296. }
  3297. collectChildrenReverseFilter$1.filterName = 'arraysCollectChildren';
  3298. var diffFilter$2 = function datesDiffFilter(context) {
  3299. if (context.left instanceof Date) {
  3300. if (context.right instanceof Date) {
  3301. if (context.left.getTime() !== context.right.getTime()) {
  3302. context.setResult([context.left, context.right]);
  3303. } else {
  3304. context.setResult(undefined);
  3305. }
  3306. } else {
  3307. context.setResult([context.left, context.right]);
  3308. }
  3309. context.exit();
  3310. } else if (context.right instanceof Date) {
  3311. context.setResult([context.left, context.right]).exit();
  3312. }
  3313. };
  3314. diffFilter$2.filterName = 'dates';
  3315. /* global diff_match_patch */
  3316. var TEXT_DIFF = 2;
  3317. var DEFAULT_MIN_LENGTH = 60;
  3318. var cachedDiffPatch = null;
  3319. var getDiffMatchPatch = function getDiffMatchPatch(required) {
  3320. /* jshint camelcase: false */
  3321. if (!cachedDiffPatch) {
  3322. var instance = void 0;
  3323. /* eslint-disable camelcase, new-cap */
  3324. if (typeof diff_match_patch !== 'undefined') {
  3325. // already loaded, probably a browser
  3326. instance = typeof diff_match_patch === 'function' ? new diff_match_patch() : new diff_match_patch.diff_match_patch();
  3327. } else if ((diff_match_patch__WEBPACK_IMPORTED_MODULE_0___default())) {
  3328. try {
  3329. instance = (diff_match_patch__WEBPACK_IMPORTED_MODULE_0___default()) && new (diff_match_patch__WEBPACK_IMPORTED_MODULE_0___default())();
  3330. } catch (err) {
  3331. instance = null;
  3332. }
  3333. }
  3334. /* eslint-enable camelcase, new-cap */
  3335. if (!instance) {
  3336. if (!required) {
  3337. return null;
  3338. }
  3339. var error = new Error('text diff_match_patch library not found');
  3340. // eslint-disable-next-line camelcase
  3341. error.diff_match_patch_not_found = true;
  3342. throw error;
  3343. }
  3344. cachedDiffPatch = {
  3345. diff: function diff(txt1, txt2) {
  3346. return instance.patch_toText(instance.patch_make(txt1, txt2));
  3347. },
  3348. patch: function patch(txt1, _patch) {
  3349. var results = instance.patch_apply(instance.patch_fromText(_patch), txt1);
  3350. for (var i = 0; i < results[1].length; i++) {
  3351. if (!results[1][i]) {
  3352. var _error = new Error('text patch failed');
  3353. _error.textPatchFailed = true;
  3354. }
  3355. }
  3356. return results[0];
  3357. }
  3358. };
  3359. }
  3360. return cachedDiffPatch;
  3361. };
  3362. var diffFilter$3 = function textsDiffFilter(context) {
  3363. if (context.leftType !== 'string') {
  3364. return;
  3365. }
  3366. var minLength = context.options && context.options.textDiff && context.options.textDiff.minLength || DEFAULT_MIN_LENGTH;
  3367. if (context.left.length < minLength || context.right.length < minLength) {
  3368. context.setResult([context.left, context.right]).exit();
  3369. return;
  3370. }
  3371. // large text, try to use a text-diff algorithm
  3372. var diffMatchPatch = getDiffMatchPatch();
  3373. if (!diffMatchPatch) {
  3374. // diff-match-patch library not available,
  3375. // fallback to regular string replace
  3376. context.setResult([context.left, context.right]).exit();
  3377. return;
  3378. }
  3379. var diff = diffMatchPatch.diff;
  3380. context.setResult([diff(context.left, context.right), 0, TEXT_DIFF]).exit();
  3381. };
  3382. diffFilter$3.filterName = 'texts';
  3383. var patchFilter$3 = function textsPatchFilter(context) {
  3384. if (context.nested) {
  3385. return;
  3386. }
  3387. if (context.delta[2] !== TEXT_DIFF) {
  3388. return;
  3389. }
  3390. // text-diff, use a text-patch algorithm
  3391. var patch = getDiffMatchPatch(true).patch;
  3392. context.setResult(patch(context.left, context.delta[0])).exit();
  3393. };
  3394. patchFilter$3.filterName = 'texts';
  3395. var textDeltaReverse = function textDeltaReverse(delta) {
  3396. var i = void 0;
  3397. var l = void 0;
  3398. var lines = void 0;
  3399. var line = void 0;
  3400. var lineTmp = void 0;
  3401. var header = null;
  3402. var headerRegex = /^@@ +-(\d+),(\d+) +\+(\d+),(\d+) +@@$/;
  3403. var lineHeader = void 0;
  3404. lines = delta.split('\n');
  3405. for (i = 0, l = lines.length; i < l; i++) {
  3406. line = lines[i];
  3407. var lineStart = line.slice(0, 1);
  3408. if (lineStart === '@') {
  3409. header = headerRegex.exec(line);
  3410. lineHeader = i;
  3411. // fix header
  3412. lines[lineHeader] = '@@ -' + header[3] + ',' + header[4] + ' +' + header[1] + ',' + header[2] + ' @@';
  3413. } else if (lineStart === '+') {
  3414. lines[i] = '-' + lines[i].slice(1);
  3415. if (lines[i - 1].slice(0, 1) === '+') {
  3416. // swap lines to keep default order (-+)
  3417. lineTmp = lines[i];
  3418. lines[i] = lines[i - 1];
  3419. lines[i - 1] = lineTmp;
  3420. }
  3421. } else if (lineStart === '-') {
  3422. lines[i] = '+' + lines[i].slice(1);
  3423. }
  3424. }
  3425. return lines.join('\n');
  3426. };
  3427. var reverseFilter$3 = function textsReverseFilter(context) {
  3428. if (context.nested) {
  3429. return;
  3430. }
  3431. if (context.delta[2] !== TEXT_DIFF) {
  3432. return;
  3433. }
  3434. // text-diff, use a text-diff algorithm
  3435. context.setResult([textDeltaReverse(context.delta[0]), 0, TEXT_DIFF]).exit();
  3436. };
  3437. reverseFilter$3.filterName = 'texts';
  3438. var DiffPatcher = function () {
  3439. function DiffPatcher(options) {
  3440. classCallCheck(this, DiffPatcher);
  3441. this.processor = new Processor(options);
  3442. this.processor.pipe(new Pipe('diff').append(collectChildrenDiffFilter, diffFilter, diffFilter$2, diffFilter$3, objectsDiffFilter, diffFilter$1).shouldHaveResult());
  3443. this.processor.pipe(new Pipe('patch').append(collectChildrenPatchFilter, collectChildrenPatchFilter$1, patchFilter, patchFilter$3, patchFilter$1, patchFilter$2).shouldHaveResult());
  3444. this.processor.pipe(new Pipe('reverse').append(collectChildrenReverseFilter, collectChildrenReverseFilter$1, reverseFilter, reverseFilter$3, reverseFilter$1, reverseFilter$2).shouldHaveResult());
  3445. }
  3446. createClass(DiffPatcher, [{
  3447. key: 'options',
  3448. value: function options() {
  3449. var _processor;
  3450. return (_processor = this.processor).options.apply(_processor, arguments);
  3451. }
  3452. }, {
  3453. key: 'diff',
  3454. value: function diff(left, right) {
  3455. return this.processor.process(new DiffContext(left, right));
  3456. }
  3457. }, {
  3458. key: 'patch',
  3459. value: function patch(left, delta) {
  3460. return this.processor.process(new PatchContext(left, delta));
  3461. }
  3462. }, {
  3463. key: 'reverse',
  3464. value: function reverse(delta) {
  3465. return this.processor.process(new ReverseContext(delta));
  3466. }
  3467. }, {
  3468. key: 'unpatch',
  3469. value: function unpatch(right, delta) {
  3470. return this.patch(right, this.reverse(delta));
  3471. }
  3472. }, {
  3473. key: 'clone',
  3474. value: function clone$$1(value) {
  3475. return clone(value);
  3476. }
  3477. }]);
  3478. return DiffPatcher;
  3479. }();
  3480. var isArray$3 = typeof Array.isArray === 'function' ? Array.isArray : function (a) {
  3481. return a instanceof Array;
  3482. };
  3483. var getObjectKeys = typeof Object.keys === 'function' ? function (obj) {
  3484. return Object.keys(obj);
  3485. } : function (obj) {
  3486. var names = [];
  3487. for (var property in obj) {
  3488. if (Object.prototype.hasOwnProperty.call(obj, property)) {
  3489. names.push(property);
  3490. }
  3491. }
  3492. return names;
  3493. };
  3494. var trimUnderscore = function trimUnderscore(str) {
  3495. if (str.substr(0, 1) === '_') {
  3496. return str.slice(1);
  3497. }
  3498. return str;
  3499. };
  3500. var arrayKeyToSortNumber = function arrayKeyToSortNumber(key) {
  3501. if (key === '_t') {
  3502. return -1;
  3503. } else {
  3504. if (key.substr(0, 1) === '_') {
  3505. return parseInt(key.slice(1), 10);
  3506. } else {
  3507. return parseInt(key, 10) + 0.1;
  3508. }
  3509. }
  3510. };
  3511. var arrayKeyComparer = function arrayKeyComparer(key1, key2) {
  3512. return arrayKeyToSortNumber(key1) - arrayKeyToSortNumber(key2);
  3513. };
  3514. var BaseFormatter = function () {
  3515. function BaseFormatter() {
  3516. classCallCheck(this, BaseFormatter);
  3517. }
  3518. createClass(BaseFormatter, [{
  3519. key: 'format',
  3520. value: function format(delta, left) {
  3521. var context = {};
  3522. this.prepareContext(context);
  3523. this.recurse(context, delta, left);
  3524. return this.finalize(context);
  3525. }
  3526. }, {
  3527. key: 'prepareContext',
  3528. value: function prepareContext(context) {
  3529. context.buffer = [];
  3530. context.out = function () {
  3531. var _buffer;
  3532. (_buffer = this.buffer).push.apply(_buffer, arguments);
  3533. };
  3534. }
  3535. }, {
  3536. key: 'typeFormattterNotFound',
  3537. value: function typeFormattterNotFound(context, deltaType) {
  3538. throw new Error('cannot format delta type: ' + deltaType);
  3539. }
  3540. }, {
  3541. key: 'typeFormattterErrorFormatter',
  3542. value: function typeFormattterErrorFormatter(context, err) {
  3543. return err.toString();
  3544. }
  3545. }, {
  3546. key: 'finalize',
  3547. value: function finalize(_ref) {
  3548. var buffer = _ref.buffer;
  3549. if (isArray$3(buffer)) {
  3550. return buffer.join('');
  3551. }
  3552. }
  3553. }, {
  3554. key: 'recurse',
  3555. value: function recurse(context, delta, left, key, leftKey, movedFrom, isLast) {
  3556. var useMoveOriginHere = delta && movedFrom;
  3557. var leftValue = useMoveOriginHere ? movedFrom.value : left;
  3558. if (typeof delta === 'undefined' && typeof key === 'undefined') {
  3559. return undefined;
  3560. }
  3561. var type = this.getDeltaType(delta, movedFrom);
  3562. var nodeType = type === 'node' ? delta._t === 'a' ? 'array' : 'object' : '';
  3563. if (typeof key !== 'undefined') {
  3564. this.nodeBegin(context, key, leftKey, type, nodeType, isLast);
  3565. } else {
  3566. this.rootBegin(context, type, nodeType);
  3567. }
  3568. var typeFormattter = void 0;
  3569. try {
  3570. typeFormattter = this['format_' + type] || this.typeFormattterNotFound(context, type);
  3571. typeFormattter.call(this, context, delta, leftValue, key, leftKey, movedFrom);
  3572. } catch (err) {
  3573. this.typeFormattterErrorFormatter(context, err, delta, leftValue, key, leftKey, movedFrom);
  3574. if (typeof console !== 'undefined' && console.error) {
  3575. console.error(err.stack);
  3576. }
  3577. }
  3578. if (typeof key !== 'undefined') {
  3579. this.nodeEnd(context, key, leftKey, type, nodeType, isLast);
  3580. } else {
  3581. this.rootEnd(context, type, nodeType);
  3582. }
  3583. }
  3584. }, {
  3585. key: 'formatDeltaChildren',
  3586. value: function formatDeltaChildren(context, delta, left) {
  3587. var self = this;
  3588. this.forEachDeltaKey(delta, left, function (key, leftKey, movedFrom, isLast) {
  3589. self.recurse(context, delta[key], left ? left[leftKey] : undefined, key, leftKey, movedFrom, isLast);
  3590. });
  3591. }
  3592. }, {
  3593. key: 'forEachDeltaKey',
  3594. value: function forEachDeltaKey(delta, left, fn) {
  3595. var keys = getObjectKeys(delta);
  3596. var arrayKeys = delta._t === 'a';
  3597. var moveDestinations = {};
  3598. var name = void 0;
  3599. if (typeof left !== 'undefined') {
  3600. for (name in left) {
  3601. if (Object.prototype.hasOwnProperty.call(left, name)) {
  3602. if (typeof delta[name] === 'undefined' && (!arrayKeys || typeof delta['_' + name] === 'undefined')) {
  3603. keys.push(name);
  3604. }
  3605. }
  3606. }
  3607. }
  3608. // look for move destinations
  3609. for (name in delta) {
  3610. if (Object.prototype.hasOwnProperty.call(delta, name)) {
  3611. var value = delta[name];
  3612. if (isArray$3(value) && value[2] === 3) {
  3613. moveDestinations[value[1].toString()] = {
  3614. key: name,
  3615. value: left && left[parseInt(name.substr(1))]
  3616. };
  3617. if (this.includeMoveDestinations !== false) {
  3618. if (typeof left === 'undefined' && typeof delta[value[1]] === 'undefined') {
  3619. keys.push(value[1].toString());
  3620. }
  3621. }
  3622. }
  3623. }
  3624. }
  3625. if (arrayKeys) {
  3626. keys.sort(arrayKeyComparer);
  3627. } else {
  3628. keys.sort();
  3629. }
  3630. for (var index = 0, length = keys.length; index < length; index++) {
  3631. var key = keys[index];
  3632. if (arrayKeys && key === '_t') {
  3633. continue;
  3634. }
  3635. var leftKey = arrayKeys ? typeof key === 'number' ? key : parseInt(trimUnderscore(key), 10) : key;
  3636. var isLast = index === length - 1;
  3637. fn(key, leftKey, moveDestinations[leftKey], isLast);
  3638. }
  3639. }
  3640. }, {
  3641. key: 'getDeltaType',
  3642. value: function getDeltaType(delta, movedFrom) {
  3643. if (typeof delta === 'undefined') {
  3644. if (typeof movedFrom !== 'undefined') {
  3645. return 'movedestination';
  3646. }
  3647. return 'unchanged';
  3648. }
  3649. if (isArray$3(delta)) {
  3650. if (delta.length === 1) {
  3651. return 'added';
  3652. }
  3653. if (delta.length === 2) {
  3654. return 'modified';
  3655. }
  3656. if (delta.length === 3 && delta[2] === 0) {
  3657. return 'deleted';
  3658. }
  3659. if (delta.length === 3 && delta[2] === 2) {
  3660. return 'textdiff';
  3661. }
  3662. if (delta.length === 3 && delta[2] === 3) {
  3663. return 'moved';
  3664. }
  3665. } else if ((typeof delta === 'undefined' ? 'undefined' : _typeof(delta)) === 'object') {
  3666. return 'node';
  3667. }
  3668. return 'unknown';
  3669. }
  3670. }, {
  3671. key: 'parseTextDiff',
  3672. value: function parseTextDiff(value) {
  3673. var output = [];
  3674. var lines = value.split('\n@@ ');
  3675. for (var i = 0, l = lines.length; i < l; i++) {
  3676. var line = lines[i];
  3677. var lineOutput = {
  3678. pieces: []
  3679. };
  3680. var location = /^(?:@@ )?[-+]?(\d+),(\d+)/.exec(line).slice(1);
  3681. lineOutput.location = {
  3682. line: location[0],
  3683. chr: location[1]
  3684. };
  3685. var pieces = line.split('\n').slice(1);
  3686. for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
  3687. var piece = pieces[pieceIndex];
  3688. if (!piece.length) {
  3689. continue;
  3690. }
  3691. var pieceOutput = {
  3692. type: 'context'
  3693. };
  3694. if (piece.substr(0, 1) === '+') {
  3695. pieceOutput.type = 'added';
  3696. } else if (piece.substr(0, 1) === '-') {
  3697. pieceOutput.type = 'deleted';
  3698. }
  3699. pieceOutput.text = piece.slice(1);
  3700. lineOutput.pieces.push(pieceOutput);
  3701. }
  3702. output.push(lineOutput);
  3703. }
  3704. return output;
  3705. }
  3706. }]);
  3707. return BaseFormatter;
  3708. }();
  3709. var base = Object.freeze({
  3710. default: BaseFormatter
  3711. });
  3712. var HtmlFormatter = function (_BaseFormatter) {
  3713. inherits(HtmlFormatter, _BaseFormatter);
  3714. function HtmlFormatter() {
  3715. classCallCheck(this, HtmlFormatter);
  3716. return possibleConstructorReturn(this, (HtmlFormatter.__proto__ || Object.getPrototypeOf(HtmlFormatter)).apply(this, arguments));
  3717. }
  3718. createClass(HtmlFormatter, [{
  3719. key: 'typeFormattterErrorFormatter',
  3720. value: function typeFormattterErrorFormatter(context, err) {
  3721. context.out('<pre class="jsondiffpatch-error">' + err + '</pre>');
  3722. }
  3723. }, {
  3724. key: 'formatValue',
  3725. value: function formatValue(context, value) {
  3726. context.out('<pre>' + htmlEscape(JSON.stringify(value, null, 2)) + '</pre>');
  3727. }
  3728. }, {
  3729. key: 'formatTextDiffString',
  3730. value: function formatTextDiffString(context, value) {
  3731. var lines = this.parseTextDiff(value);
  3732. context.out('<ul class="jsondiffpatch-textdiff">');
  3733. for (var i = 0, l = lines.length; i < l; i++) {
  3734. var line = lines[i];
  3735. context.out('<li><div class="jsondiffpatch-textdiff-location">' + ('<span class="jsondiffpatch-textdiff-line-number">' + line.location.line + '</span><span class="jsondiffpatch-textdiff-char">' + line.location.chr + '</span></div><div class="jsondiffpatch-textdiff-line">'));
  3736. var pieces = line.pieces;
  3737. for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
  3738. /* global decodeURI */
  3739. var piece = pieces[pieceIndex];
  3740. context.out('<span class="jsondiffpatch-textdiff-' + piece.type + '">' + htmlEscape(decodeURI(piece.text)) + '</span>');
  3741. }
  3742. context.out('</div></li>');
  3743. }
  3744. context.out('</ul>');
  3745. }
  3746. }, {
  3747. key: 'rootBegin',
  3748. value: function rootBegin(context, type, nodeType) {
  3749. var nodeClass = 'jsondiffpatch-' + type + (nodeType ? ' jsondiffpatch-child-node-type-' + nodeType : '');
  3750. context.out('<div class="jsondiffpatch-delta ' + nodeClass + '">');
  3751. }
  3752. }, {
  3753. key: 'rootEnd',
  3754. value: function rootEnd(context) {
  3755. context.out('</div>' + (context.hasArrows ? '<script type="text/javascript">setTimeout(' + (adjustArrows.toString() + ',10);</script>') : ''));
  3756. }
  3757. }, {
  3758. key: 'nodeBegin',
  3759. value: function nodeBegin(context, key, leftKey, type, nodeType) {
  3760. var nodeClass = 'jsondiffpatch-' + type + (nodeType ? ' jsondiffpatch-child-node-type-' + nodeType : '');
  3761. context.out('<li class="' + nodeClass + '" data-key="' + leftKey + '">' + ('<div class="jsondiffpatch-property-name">' + leftKey + '</div>'));
  3762. }
  3763. }, {
  3764. key: 'nodeEnd',
  3765. value: function nodeEnd(context) {
  3766. context.out('</li>');
  3767. }
  3768. /* jshint camelcase: false */
  3769. /* eslint-disable camelcase */
  3770. }, {
  3771. key: 'format_unchanged',
  3772. value: function format_unchanged(context, delta, left) {
  3773. if (typeof left === 'undefined') {
  3774. return;
  3775. }
  3776. context.out('<div class="jsondiffpatch-value">');
  3777. this.formatValue(context, left);
  3778. context.out('</div>');
  3779. }
  3780. }, {
  3781. key: 'format_movedestination',
  3782. value: function format_movedestination(context, delta, left) {
  3783. if (typeof left === 'undefined') {
  3784. return;
  3785. }
  3786. context.out('<div class="jsondiffpatch-value">');
  3787. this.formatValue(context, left);
  3788. context.out('</div>');
  3789. }
  3790. }, {
  3791. key: 'format_node',
  3792. value: function format_node(context, delta, left) {
  3793. // recurse
  3794. var nodeType = delta._t === 'a' ? 'array' : 'object';
  3795. context.out('<ul class="jsondiffpatch-node jsondiffpatch-node-type-' + nodeType + '">');
  3796. this.formatDeltaChildren(context, delta, left);
  3797. context.out('</ul>');
  3798. }
  3799. }, {
  3800. key: 'format_added',
  3801. value: function format_added(context, delta) {
  3802. context.out('<div class="jsondiffpatch-value">');
  3803. this.formatValue(context, delta[0]);
  3804. context.out('</div>');
  3805. }
  3806. }, {
  3807. key: 'format_modified',
  3808. value: function format_modified(context, delta) {
  3809. context.out('<div class="jsondiffpatch-value jsondiffpatch-left-value">');
  3810. this.formatValue(context, delta[0]);
  3811. context.out('</div>' + '<div class="jsondiffpatch-value jsondiffpatch-right-value">');
  3812. this.formatValue(context, delta[1]);
  3813. context.out('</div>');
  3814. }
  3815. }, {
  3816. key: 'format_deleted',
  3817. value: function format_deleted(context, delta) {
  3818. context.out('<div class="jsondiffpatch-value">');
  3819. this.formatValue(context, delta[0]);
  3820. context.out('</div>');
  3821. }
  3822. }, {
  3823. key: 'format_moved',
  3824. value: function format_moved(context, delta) {
  3825. context.out('<div class="jsondiffpatch-value">');
  3826. this.formatValue(context, delta[0]);
  3827. context.out('</div><div class="jsondiffpatch-moved-destination">' + delta[1] + '</div>');
  3828. // draw an SVG arrow from here to move destination
  3829. context.out(
  3830. /* jshint multistr: true */
  3831. '<div class="jsondiffpatch-arrow" ' + 'style="position: relative; left: -34px;">\n <svg width="30" height="60" ' + 'style="position: absolute; display: none;">\n <defs>\n <marker id="markerArrow" markerWidth="8" markerHeight="8"\n refx="2" refy="4"\n orient="auto" markerUnits="userSpaceOnUse">\n <path d="M1,1 L1,7 L7,4 L1,1" style="fill: #339;" />\n </marker>\n </defs>\n <path d="M30,0 Q-10,25 26,50"\n style="stroke: #88f; stroke-width: 2px; fill: none; ' + 'stroke-opacity: 0.5; marker-end: url(#markerArrow);"\n ></path>\n </svg>\n </div>');
  3832. context.hasArrows = true;
  3833. }
  3834. }, {
  3835. key: 'format_textdiff',
  3836. value: function format_textdiff(context, delta) {
  3837. context.out('<div class="jsondiffpatch-value">');
  3838. this.formatTextDiffString(context, delta[0]);
  3839. context.out('</div>');
  3840. }
  3841. }]);
  3842. return HtmlFormatter;
  3843. }(BaseFormatter);
  3844. function htmlEscape(text) {
  3845. var html = text;
  3846. var replacements = [[/&/g, '&amp;'], [/</g, '&lt;'], [/>/g, '&gt;'], [/'/g, '&apos;'], [/"/g, '&quot;']];
  3847. for (var i = 0; i < replacements.length; i++) {
  3848. html = html.replace(replacements[i][0], replacements[i][1]);
  3849. }
  3850. return html;
  3851. }
  3852. var adjustArrows = function jsondiffpatchHtmlFormatterAdjustArrows(nodeArg) {
  3853. var node = nodeArg || document;
  3854. var getElementText = function getElementText(_ref) {
  3855. var textContent = _ref.textContent,
  3856. innerText = _ref.innerText;
  3857. return textContent || innerText;
  3858. };
  3859. var eachByQuery = function eachByQuery(el, query, fn) {
  3860. var elems = el.querySelectorAll(query);
  3861. for (var i = 0, l = elems.length; i < l; i++) {
  3862. fn(elems[i]);
  3863. }
  3864. };
  3865. var eachChildren = function eachChildren(_ref2, fn) {
  3866. var children = _ref2.children;
  3867. for (var i = 0, l = children.length; i < l; i++) {
  3868. fn(children[i], i);
  3869. }
  3870. };
  3871. eachByQuery(node, '.jsondiffpatch-arrow', function (_ref3) {
  3872. var parentNode = _ref3.parentNode,
  3873. children = _ref3.children,
  3874. style = _ref3.style;
  3875. var arrowParent = parentNode;
  3876. var svg = children[0];
  3877. var path = svg.children[1];
  3878. svg.style.display = 'none';
  3879. var destination = getElementText(arrowParent.querySelector('.jsondiffpatch-moved-destination'));
  3880. var container = arrowParent.parentNode;
  3881. var destinationElem = void 0;
  3882. eachChildren(container, function (child) {
  3883. if (child.getAttribute('data-key') === destination) {
  3884. destinationElem = child;
  3885. }
  3886. });
  3887. if (!destinationElem) {
  3888. return;
  3889. }
  3890. try {
  3891. var distance = destinationElem.offsetTop - arrowParent.offsetTop;
  3892. svg.setAttribute('height', Math.abs(distance) + 6);
  3893. style.top = -8 + (distance > 0 ? 0 : distance) + 'px';
  3894. var curve = distance > 0 ? 'M30,0 Q-10,' + Math.round(distance / 2) + ' 26,' + (distance - 4) : 'M30,' + -distance + ' Q-10,' + Math.round(-distance / 2) + ' 26,4';
  3895. path.setAttribute('d', curve);
  3896. svg.style.display = '';
  3897. } catch (err) {}
  3898. });
  3899. };
  3900. /* jshint camelcase: true */
  3901. /* eslint-enable camelcase */
  3902. var showUnchanged = function showUnchanged(show, node, delay) {
  3903. var el = node || document.body;
  3904. var prefix = 'jsondiffpatch-unchanged-';
  3905. var classes = {
  3906. showing: prefix + 'showing',
  3907. hiding: prefix + 'hiding',
  3908. visible: prefix + 'visible',
  3909. hidden: prefix + 'hidden'
  3910. };
  3911. var list = el.classList;
  3912. if (!list) {
  3913. return;
  3914. }
  3915. if (!delay) {
  3916. list.remove(classes.showing);
  3917. list.remove(classes.hiding);
  3918. list.remove(classes.visible);
  3919. list.remove(classes.hidden);
  3920. if (show === false) {
  3921. list.add(classes.hidden);
  3922. }
  3923. return;
  3924. }
  3925. if (show === false) {
  3926. list.remove(classes.showing);
  3927. list.add(classes.visible);
  3928. setTimeout(function () {
  3929. list.add(classes.hiding);
  3930. }, 10);
  3931. } else {
  3932. list.remove(classes.hiding);
  3933. list.add(classes.showing);
  3934. list.remove(classes.hidden);
  3935. }
  3936. var intervalId = setInterval(function () {
  3937. adjustArrows(el);
  3938. }, 100);
  3939. setTimeout(function () {
  3940. list.remove(classes.showing);
  3941. list.remove(classes.hiding);
  3942. if (show === false) {
  3943. list.add(classes.hidden);
  3944. list.remove(classes.visible);
  3945. } else {
  3946. list.add(classes.visible);
  3947. list.remove(classes.hidden);
  3948. }
  3949. setTimeout(function () {
  3950. list.remove(classes.visible);
  3951. clearInterval(intervalId);
  3952. }, delay + 400);
  3953. }, delay);
  3954. };
  3955. var hideUnchanged = function hideUnchanged(node, delay) {
  3956. return showUnchanged(false, node, delay);
  3957. };
  3958. var defaultInstance = void 0;
  3959. function format(delta, left) {
  3960. if (!defaultInstance) {
  3961. defaultInstance = new HtmlFormatter();
  3962. }
  3963. return defaultInstance.format(delta, left);
  3964. }
  3965. var html = Object.freeze({
  3966. showUnchanged: showUnchanged,
  3967. hideUnchanged: hideUnchanged,
  3968. default: HtmlFormatter,
  3969. format: format
  3970. });
  3971. var AnnotatedFormatter = function (_BaseFormatter) {
  3972. inherits(AnnotatedFormatter, _BaseFormatter);
  3973. function AnnotatedFormatter() {
  3974. classCallCheck(this, AnnotatedFormatter);
  3975. var _this = possibleConstructorReturn(this, (AnnotatedFormatter.__proto__ || Object.getPrototypeOf(AnnotatedFormatter)).call(this));
  3976. _this.includeMoveDestinations = false;
  3977. return _this;
  3978. }
  3979. createClass(AnnotatedFormatter, [{
  3980. key: 'prepareContext',
  3981. value: function prepareContext(context) {
  3982. get(AnnotatedFormatter.prototype.__proto__ || Object.getPrototypeOf(AnnotatedFormatter.prototype), 'prepareContext', this).call(this, context);
  3983. context.indent = function (levels) {
  3984. this.indentLevel = (this.indentLevel || 0) + (typeof levels === 'undefined' ? 1 : levels);
  3985. this.indentPad = new Array(this.indentLevel + 1).join('&nbsp;&nbsp;');
  3986. };
  3987. context.row = function (json, htmlNote) {
  3988. context.out('<tr><td style="white-space: nowrap;">' + '<pre class="jsondiffpatch-annotated-indent"' + ' style="display: inline-block">');
  3989. context.out(context.indentPad);
  3990. context.out('</pre><pre style="display: inline-block">');
  3991. context.out(json);
  3992. context.out('</pre></td><td class="jsondiffpatch-delta-note"><div>');
  3993. context.out(htmlNote);
  3994. context.out('</div></td></tr>');
  3995. };
  3996. }
  3997. }, {
  3998. key: 'typeFormattterErrorFormatter',
  3999. value: function typeFormattterErrorFormatter(context, err) {
  4000. context.row('', '<pre class="jsondiffpatch-error">' + err + '</pre>');
  4001. }
  4002. }, {
  4003. key: 'formatTextDiffString',
  4004. value: function formatTextDiffString(context, value) {
  4005. var lines = this.parseTextDiff(value);
  4006. context.out('<ul class="jsondiffpatch-textdiff">');
  4007. for (var i = 0, l = lines.length; i < l; i++) {
  4008. var line = lines[i];
  4009. context.out('<li><div class="jsondiffpatch-textdiff-location">' + ('<span class="jsondiffpatch-textdiff-line-number">' + line.location.line + '</span><span class="jsondiffpatch-textdiff-char">' + line.location.chr + '</span></div><div class="jsondiffpatch-textdiff-line">'));
  4010. var pieces = line.pieces;
  4011. for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
  4012. var piece = pieces[pieceIndex];
  4013. context.out('<span class="jsondiffpatch-textdiff-' + piece.type + '">' + piece.text + '</span>');
  4014. }
  4015. context.out('</div></li>');
  4016. }
  4017. context.out('</ul>');
  4018. }
  4019. }, {
  4020. key: 'rootBegin',
  4021. value: function rootBegin(context, type, nodeType) {
  4022. context.out('<table class="jsondiffpatch-annotated-delta">');
  4023. if (type === 'node') {
  4024. context.row('{');
  4025. context.indent();
  4026. }
  4027. if (nodeType === 'array') {
  4028. context.row('"_t": "a",', 'Array delta (member names indicate array indices)');
  4029. }
  4030. }
  4031. }, {
  4032. key: 'rootEnd',
  4033. value: function rootEnd(context, type) {
  4034. if (type === 'node') {
  4035. context.indent(-1);
  4036. context.row('}');
  4037. }
  4038. context.out('</table>');
  4039. }
  4040. }, {
  4041. key: 'nodeBegin',
  4042. value: function nodeBegin(context, key, leftKey, type, nodeType) {
  4043. context.row('&quot;' + key + '&quot;: {');
  4044. if (type === 'node') {
  4045. context.indent();
  4046. }
  4047. if (nodeType === 'array') {
  4048. context.row('"_t": "a",', 'Array delta (member names indicate array indices)');
  4049. }
  4050. }
  4051. }, {
  4052. key: 'nodeEnd',
  4053. value: function nodeEnd(context, key, leftKey, type, nodeType, isLast) {
  4054. if (type === 'node') {
  4055. context.indent(-1);
  4056. }
  4057. context.row('}' + (isLast ? '' : ','));
  4058. }
  4059. /* jshint camelcase: false */
  4060. /* eslint-disable camelcase */
  4061. }, {
  4062. key: 'format_unchanged',
  4063. value: function format_unchanged() {}
  4064. }, {
  4065. key: 'format_movedestination',
  4066. value: function format_movedestination() {}
  4067. }, {
  4068. key: 'format_node',
  4069. value: function format_node(context, delta, left) {
  4070. // recurse
  4071. this.formatDeltaChildren(context, delta, left);
  4072. }
  4073. }]);
  4074. return AnnotatedFormatter;
  4075. }(BaseFormatter);
  4076. /* eslint-enable camelcase */
  4077. var wrapPropertyName = function wrapPropertyName(name) {
  4078. return '<pre style="display:inline-block">&quot;' + name + '&quot;</pre>';
  4079. };
  4080. var deltaAnnotations = {
  4081. added: function added(delta, left, key, leftKey) {
  4082. var formatLegend = ' <pre>([newValue])</pre>';
  4083. if (typeof leftKey === 'undefined') {
  4084. return 'new value' + formatLegend;
  4085. }
  4086. if (typeof leftKey === 'number') {
  4087. return 'insert at index ' + leftKey + formatLegend;
  4088. }
  4089. return 'add property ' + wrapPropertyName(leftKey) + formatLegend;
  4090. },
  4091. modified: function modified(delta, left, key, leftKey) {
  4092. var formatLegend = ' <pre>([previousValue, newValue])</pre>';
  4093. if (typeof leftKey === 'undefined') {
  4094. return 'modify value' + formatLegend;
  4095. }
  4096. if (typeof leftKey === 'number') {
  4097. return 'modify at index ' + leftKey + formatLegend;
  4098. }
  4099. return 'modify property ' + wrapPropertyName(leftKey) + formatLegend;
  4100. },
  4101. deleted: function deleted(delta, left, key, leftKey) {
  4102. var formatLegend = ' <pre>([previousValue, 0, 0])</pre>';
  4103. if (typeof leftKey === 'undefined') {
  4104. return 'delete value' + formatLegend;
  4105. }
  4106. if (typeof leftKey === 'number') {
  4107. return 'remove index ' + leftKey + formatLegend;
  4108. }
  4109. return 'delete property ' + wrapPropertyName(leftKey) + formatLegend;
  4110. },
  4111. moved: function moved(delta, left, key, leftKey) {
  4112. return 'move from <span title="(position to remove at original state)">' + ('index ' + leftKey + '</span> to <span title="(position to insert at final') + (' state)">index ' + delta[1] + '</span>');
  4113. },
  4114. textdiff: function textdiff(delta, left, key, leftKey) {
  4115. var location = typeof leftKey === 'undefined' ? '' : typeof leftKey === 'number' ? ' at index ' + leftKey : ' at property ' + wrapPropertyName(leftKey);
  4116. return 'text diff' + location + ', format is <a href="https://code.google.com/' + 'p/google-diff-match-patch/wiki/Unidiff">a variation of Unidiff</a>';
  4117. }
  4118. };
  4119. var formatAnyChange = function formatAnyChange(context, delta) {
  4120. var deltaType = this.getDeltaType(delta);
  4121. var annotator = deltaAnnotations[deltaType];
  4122. var htmlNote = annotator && annotator.apply(annotator, Array.prototype.slice.call(arguments, 1));
  4123. var json = JSON.stringify(delta, null, 2);
  4124. if (deltaType === 'textdiff') {
  4125. // split text diffs lines
  4126. json = json.split('\\n').join('\\n"+\n "');
  4127. }
  4128. context.indent();
  4129. context.row(json, htmlNote);
  4130. context.indent(-1);
  4131. };
  4132. /* eslint-disable camelcase */
  4133. AnnotatedFormatter.prototype.format_added = formatAnyChange;
  4134. AnnotatedFormatter.prototype.format_modified = formatAnyChange;
  4135. AnnotatedFormatter.prototype.format_deleted = formatAnyChange;
  4136. AnnotatedFormatter.prototype.format_moved = formatAnyChange;
  4137. AnnotatedFormatter.prototype.format_textdiff = formatAnyChange;
  4138. var defaultInstance$1 = void 0;
  4139. function format$1(delta, left) {
  4140. if (!defaultInstance$1) {
  4141. defaultInstance$1 = new AnnotatedFormatter();
  4142. }
  4143. return defaultInstance$1.format(delta, left);
  4144. }
  4145. var annotated = Object.freeze({
  4146. default: AnnotatedFormatter,
  4147. format: format$1
  4148. });
  4149. var OPERATIONS = {
  4150. add: 'add',
  4151. remove: 'remove',
  4152. replace: 'replace',
  4153. move: 'move'
  4154. };
  4155. var JSONFormatter = function (_BaseFormatter) {
  4156. inherits(JSONFormatter, _BaseFormatter);
  4157. function JSONFormatter() {
  4158. classCallCheck(this, JSONFormatter);
  4159. var _this = possibleConstructorReturn(this, (JSONFormatter.__proto__ || Object.getPrototypeOf(JSONFormatter)).call(this));
  4160. _this.includeMoveDestinations = true;
  4161. return _this;
  4162. }
  4163. createClass(JSONFormatter, [{
  4164. key: 'prepareContext',
  4165. value: function prepareContext(context) {
  4166. get(JSONFormatter.prototype.__proto__ || Object.getPrototypeOf(JSONFormatter.prototype), 'prepareContext', this).call(this, context);
  4167. context.result = [];
  4168. context.path = [];
  4169. context.pushCurrentOp = function (obj) {
  4170. var op = obj.op,
  4171. value = obj.value;
  4172. var val = {
  4173. op: op,
  4174. path: this.currentPath()
  4175. };
  4176. if (typeof value !== 'undefined') {
  4177. val.value = value;
  4178. }
  4179. this.result.push(val);
  4180. };
  4181. context.pushMoveOp = function (to) {
  4182. var from = this.currentPath();
  4183. this.result.push({
  4184. op: OPERATIONS.move,
  4185. from: from,
  4186. path: this.toPath(to)
  4187. });
  4188. };
  4189. context.currentPath = function () {
  4190. return '/' + this.path.join('/');
  4191. };
  4192. context.toPath = function (toPath) {
  4193. var to = this.path.slice();
  4194. to[to.length - 1] = toPath;
  4195. return '/' + to.join('/');
  4196. };
  4197. }
  4198. }, {
  4199. key: 'typeFormattterErrorFormatter',
  4200. value: function typeFormattterErrorFormatter(context, err) {
  4201. context.out('[ERROR] ' + err);
  4202. }
  4203. }, {
  4204. key: 'rootBegin',
  4205. value: function rootBegin() {}
  4206. }, {
  4207. key: 'rootEnd',
  4208. value: function rootEnd() {}
  4209. }, {
  4210. key: 'nodeBegin',
  4211. value: function nodeBegin(_ref, key, leftKey) {
  4212. var path = _ref.path;
  4213. path.push(leftKey);
  4214. }
  4215. }, {
  4216. key: 'nodeEnd',
  4217. value: function nodeEnd(_ref2) {
  4218. var path = _ref2.path;
  4219. path.pop();
  4220. }
  4221. /* jshint camelcase: false */
  4222. /* eslint-disable camelcase */
  4223. }, {
  4224. key: 'format_unchanged',
  4225. value: function format_unchanged() {}
  4226. }, {
  4227. key: 'format_movedestination',
  4228. value: function format_movedestination() {}
  4229. }, {
  4230. key: 'format_node',
  4231. value: function format_node(context, delta, left) {
  4232. this.formatDeltaChildren(context, delta, left);
  4233. }
  4234. }, {
  4235. key: 'format_added',
  4236. value: function format_added(context, delta) {
  4237. context.pushCurrentOp({ op: OPERATIONS.add, value: delta[0] });
  4238. }
  4239. }, {
  4240. key: 'format_modified',
  4241. value: function format_modified(context, delta) {
  4242. context.pushCurrentOp({ op: OPERATIONS.replace, value: delta[1] });
  4243. }
  4244. }, {
  4245. key: 'format_deleted',
  4246. value: function format_deleted(context) {
  4247. context.pushCurrentOp({ op: OPERATIONS.remove });
  4248. }
  4249. }, {
  4250. key: 'format_moved',
  4251. value: function format_moved(context, delta) {
  4252. var to = delta[1];
  4253. context.pushMoveOp(to);
  4254. }
  4255. }, {
  4256. key: 'format_textdiff',
  4257. value: function format_textdiff() {
  4258. throw new Error('Not implemented');
  4259. }
  4260. }, {
  4261. key: 'format',
  4262. value: function format(delta, left) {
  4263. var context = {};
  4264. this.prepareContext(context);
  4265. this.recurse(context, delta, left);
  4266. return context.result;
  4267. }
  4268. }]);
  4269. return JSONFormatter;
  4270. }(BaseFormatter);
  4271. var last = function last(arr) {
  4272. return arr[arr.length - 1];
  4273. };
  4274. var sortBy = function sortBy(arr, pred) {
  4275. arr.sort(pred);
  4276. return arr;
  4277. };
  4278. var compareByIndexDesc = function compareByIndexDesc(indexA, indexB) {
  4279. var lastA = parseInt(indexA, 10);
  4280. var lastB = parseInt(indexB, 10);
  4281. if (!(isNaN(lastA) || isNaN(lastB))) {
  4282. return lastB - lastA;
  4283. } else {
  4284. return 0;
  4285. }
  4286. };
  4287. var opsByDescendingOrder = function opsByDescendingOrder(removeOps) {
  4288. return sortBy(removeOps, function (a, b) {
  4289. var splitA = a.path.split('/');
  4290. var splitB = b.path.split('/');
  4291. if (splitA.length !== splitB.length) {
  4292. return splitA.length - splitB.length;
  4293. } else {
  4294. return compareByIndexDesc(last(splitA), last(splitB));
  4295. }
  4296. });
  4297. };
  4298. var partitionOps = function partitionOps(arr, fns) {
  4299. var initArr = Array(fns.length + 1).fill().map(function () {
  4300. return [];
  4301. });
  4302. return arr.map(function (item) {
  4303. var position = fns.map(function (fn) {
  4304. return fn(item);
  4305. }).indexOf(true);
  4306. if (position < 0) {
  4307. position = fns.length;
  4308. }
  4309. return { item: item, position: position };
  4310. }).reduce(function (acc, item) {
  4311. acc[item.position].push(item.item);
  4312. return acc;
  4313. }, initArr);
  4314. };
  4315. var isMoveOp = function isMoveOp(_ref3) {
  4316. var op = _ref3.op;
  4317. return op === 'move';
  4318. };
  4319. var isRemoveOp = function isRemoveOp(_ref4) {
  4320. var op = _ref4.op;
  4321. return op === 'remove';
  4322. };
  4323. var reorderOps = function reorderOps(diff) {
  4324. var _partitionOps = partitionOps(diff, [isMoveOp, isRemoveOp]),
  4325. _partitionOps2 = slicedToArray(_partitionOps, 3),
  4326. moveOps = _partitionOps2[0],
  4327. removedOps = _partitionOps2[1],
  4328. restOps = _partitionOps2[2];
  4329. var removeOpsReverse = opsByDescendingOrder(removedOps);
  4330. return [].concat(toConsumableArray(removeOpsReverse), toConsumableArray(moveOps), toConsumableArray(restOps));
  4331. };
  4332. var defaultInstance$2 = void 0;
  4333. var format$2 = function format(delta, left) {
  4334. if (!defaultInstance$2) {
  4335. defaultInstance$2 = new JSONFormatter();
  4336. }
  4337. return reorderOps(defaultInstance$2.format(delta, left));
  4338. };
  4339. var log = function log(delta, left) {
  4340. console.log(format$2(delta, left));
  4341. };
  4342. var jsonpatch = Object.freeze({
  4343. default: JSONFormatter,
  4344. partitionOps: partitionOps,
  4345. format: format$2,
  4346. log: log
  4347. });
  4348. function chalkColor(name) {
  4349. return (chalk__WEBPACK_IMPORTED_MODULE_1___default()) && (chalk__WEBPACK_IMPORTED_MODULE_1___default())[name] || function () {
  4350. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  4351. args[_key] = arguments[_key];
  4352. }
  4353. return args;
  4354. };
  4355. }
  4356. var colors = {
  4357. added: chalkColor('green'),
  4358. deleted: chalkColor('red'),
  4359. movedestination: chalkColor('gray'),
  4360. moved: chalkColor('yellow'),
  4361. unchanged: chalkColor('gray'),
  4362. error: chalkColor('white.bgRed'),
  4363. textDiffLine: chalkColor('gray')
  4364. };
  4365. var ConsoleFormatter = function (_BaseFormatter) {
  4366. inherits(ConsoleFormatter, _BaseFormatter);
  4367. function ConsoleFormatter() {
  4368. classCallCheck(this, ConsoleFormatter);
  4369. var _this = possibleConstructorReturn(this, (ConsoleFormatter.__proto__ || Object.getPrototypeOf(ConsoleFormatter)).call(this));
  4370. _this.includeMoveDestinations = false;
  4371. return _this;
  4372. }
  4373. createClass(ConsoleFormatter, [{
  4374. key: 'prepareContext',
  4375. value: function prepareContext(context) {
  4376. get(ConsoleFormatter.prototype.__proto__ || Object.getPrototypeOf(ConsoleFormatter.prototype), 'prepareContext', this).call(this, context);
  4377. context.indent = function (levels) {
  4378. this.indentLevel = (this.indentLevel || 0) + (typeof levels === 'undefined' ? 1 : levels);
  4379. this.indentPad = new Array(this.indentLevel + 1).join(' ');
  4380. this.outLine();
  4381. };
  4382. context.outLine = function () {
  4383. this.buffer.push('\n' + (this.indentPad || ''));
  4384. };
  4385. context.out = function () {
  4386. for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  4387. args[_key2] = arguments[_key2];
  4388. }
  4389. for (var i = 0, l = args.length; i < l; i++) {
  4390. var lines = args[i].split('\n');
  4391. var text = lines.join('\n' + (this.indentPad || ''));
  4392. if (this.color && this.color[0]) {
  4393. text = this.color[0](text);
  4394. }
  4395. this.buffer.push(text);
  4396. }
  4397. };
  4398. context.pushColor = function (color) {
  4399. this.color = this.color || [];
  4400. this.color.unshift(color);
  4401. };
  4402. context.popColor = function () {
  4403. this.color = this.color || [];
  4404. this.color.shift();
  4405. };
  4406. }
  4407. }, {
  4408. key: 'typeFormattterErrorFormatter',
  4409. value: function typeFormattterErrorFormatter(context, err) {
  4410. context.pushColor(colors.error);
  4411. context.out('[ERROR]' + err);
  4412. context.popColor();
  4413. }
  4414. }, {
  4415. key: 'formatValue',
  4416. value: function formatValue(context, value) {
  4417. context.out(JSON.stringify(value, null, 2));
  4418. }
  4419. }, {
  4420. key: 'formatTextDiffString',
  4421. value: function formatTextDiffString(context, value) {
  4422. var lines = this.parseTextDiff(value);
  4423. context.indent();
  4424. for (var i = 0, l = lines.length; i < l; i++) {
  4425. var line = lines[i];
  4426. context.pushColor(colors.textDiffLine);
  4427. context.out(line.location.line + ',' + line.location.chr + ' ');
  4428. context.popColor();
  4429. var pieces = line.pieces;
  4430. for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
  4431. var piece = pieces[pieceIndex];
  4432. context.pushColor(colors[piece.type]);
  4433. context.out(piece.text);
  4434. context.popColor();
  4435. }
  4436. if (i < l - 1) {
  4437. context.outLine();
  4438. }
  4439. }
  4440. context.indent(-1);
  4441. }
  4442. }, {
  4443. key: 'rootBegin',
  4444. value: function rootBegin(context, type, nodeType) {
  4445. context.pushColor(colors[type]);
  4446. if (type === 'node') {
  4447. context.out(nodeType === 'array' ? '[' : '{');
  4448. context.indent();
  4449. }
  4450. }
  4451. }, {
  4452. key: 'rootEnd',
  4453. value: function rootEnd(context, type, nodeType) {
  4454. if (type === 'node') {
  4455. context.indent(-1);
  4456. context.out(nodeType === 'array' ? ']' : '}');
  4457. }
  4458. context.popColor();
  4459. }
  4460. }, {
  4461. key: 'nodeBegin',
  4462. value: function nodeBegin(context, key, leftKey, type, nodeType) {
  4463. context.pushColor(colors[type]);
  4464. context.out(leftKey + ': ');
  4465. if (type === 'node') {
  4466. context.out(nodeType === 'array' ? '[' : '{');
  4467. context.indent();
  4468. }
  4469. }
  4470. }, {
  4471. key: 'nodeEnd',
  4472. value: function nodeEnd(context, key, leftKey, type, nodeType, isLast) {
  4473. if (type === 'node') {
  4474. context.indent(-1);
  4475. context.out(nodeType === 'array' ? ']' : '}' + (isLast ? '' : ','));
  4476. }
  4477. if (!isLast) {
  4478. context.outLine();
  4479. }
  4480. context.popColor();
  4481. }
  4482. /* jshint camelcase: false */
  4483. /* eslint-disable camelcase */
  4484. }, {
  4485. key: 'format_unchanged',
  4486. value: function format_unchanged(context, delta, left) {
  4487. if (typeof left === 'undefined') {
  4488. return;
  4489. }
  4490. this.formatValue(context, left);
  4491. }
  4492. }, {
  4493. key: 'format_movedestination',
  4494. value: function format_movedestination(context, delta, left) {
  4495. if (typeof left === 'undefined') {
  4496. return;
  4497. }
  4498. this.formatValue(context, left);
  4499. }
  4500. }, {
  4501. key: 'format_node',
  4502. value: function format_node(context, delta, left) {
  4503. // recurse
  4504. this.formatDeltaChildren(context, delta, left);
  4505. }
  4506. }, {
  4507. key: 'format_added',
  4508. value: function format_added(context, delta) {
  4509. this.formatValue(context, delta[0]);
  4510. }
  4511. }, {
  4512. key: 'format_modified',
  4513. value: function format_modified(context, delta) {
  4514. context.pushColor(colors.deleted);
  4515. this.formatValue(context, delta[0]);
  4516. context.popColor();
  4517. context.out(' => ');
  4518. context.pushColor(colors.added);
  4519. this.formatValue(context, delta[1]);
  4520. context.popColor();
  4521. }
  4522. }, {
  4523. key: 'format_deleted',
  4524. value: function format_deleted(context, delta) {
  4525. this.formatValue(context, delta[0]);
  4526. }
  4527. }, {
  4528. key: 'format_moved',
  4529. value: function format_moved(context, delta) {
  4530. context.out('==> ' + delta[1]);
  4531. }
  4532. }, {
  4533. key: 'format_textdiff',
  4534. value: function format_textdiff(context, delta) {
  4535. this.formatTextDiffString(context, delta[0]);
  4536. }
  4537. }]);
  4538. return ConsoleFormatter;
  4539. }(BaseFormatter);
  4540. var defaultInstance$3 = void 0;
  4541. var format$3 = function format(delta, left) {
  4542. if (!defaultInstance$3) {
  4543. defaultInstance$3 = new ConsoleFormatter();
  4544. }
  4545. return defaultInstance$3.format(delta, left);
  4546. };
  4547. function log$1(delta, left) {
  4548. console.log(format$3(delta, left));
  4549. }
  4550. var console$1 = Object.freeze({
  4551. default: ConsoleFormatter,
  4552. format: format$3,
  4553. log: log$1
  4554. });
  4555. var index = Object.freeze({
  4556. base: base,
  4557. html: html,
  4558. annotated: annotated,
  4559. jsonpatch: jsonpatch,
  4560. console: console$1
  4561. });
  4562. // use as 2nd parameter for JSON.parse to revive Date instances
  4563. function dateReviver(key, value) {
  4564. var parts = void 0;
  4565. if (typeof value === 'string') {
  4566. // eslint-disable-next-line max-len
  4567. parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d*))?(Z|([+-])(\d{2}):(\d{2}))$/.exec(value);
  4568. if (parts) {
  4569. return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6], +(parts[7] || 0)));
  4570. }
  4571. }
  4572. return value;
  4573. }
  4574. function create(options) {
  4575. return new DiffPatcher(options);
  4576. }
  4577. var defaultInstance$4 = void 0;
  4578. function diff() {
  4579. if (!defaultInstance$4) {
  4580. defaultInstance$4 = new DiffPatcher();
  4581. }
  4582. return defaultInstance$4.diff.apply(defaultInstance$4, arguments);
  4583. }
  4584. function patch() {
  4585. if (!defaultInstance$4) {
  4586. defaultInstance$4 = new DiffPatcher();
  4587. }
  4588. return defaultInstance$4.patch.apply(defaultInstance$4, arguments);
  4589. }
  4590. function unpatch() {
  4591. if (!defaultInstance$4) {
  4592. defaultInstance$4 = new DiffPatcher();
  4593. }
  4594. return defaultInstance$4.unpatch.apply(defaultInstance$4, arguments);
  4595. }
  4596. function reverse() {
  4597. if (!defaultInstance$4) {
  4598. defaultInstance$4 = new DiffPatcher();
  4599. }
  4600. return defaultInstance$4.reverse.apply(defaultInstance$4, arguments);
  4601. }
  4602. function clone$1() {
  4603. if (!defaultInstance$4) {
  4604. defaultInstance$4 = new DiffPatcher();
  4605. }
  4606. return defaultInstance$4.clone.apply(defaultInstance$4, arguments);
  4607. }
  4608. //# sourceMappingURL=jsondiffpatch.esm.js.map
  4609. /***/ })
  4610. };
  4611. ;
  4612. //# sourceMappingURL=384.index.js.map