qunit-2.5.0.js 146 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188
  1. /*!
  2. * QUnit 2.5.0
  3. * https://qunitjs.com/
  4. *
  5. * Copyright jQuery Foundation and other contributors
  6. * Released under the MIT license
  7. * https://jquery.org/license
  8. *
  9. * Date: 2018-01-10T02:56Z
  10. */
  11. (function (global$1) {
  12. 'use strict';
  13. global$1 = global$1 && global$1.hasOwnProperty('default') ? global$1['default'] : global$1;
  14. var window = global$1.window;
  15. var self$1 = global$1.self;
  16. var console = global$1.console;
  17. var setTimeout = global$1.setTimeout;
  18. var clearTimeout = global$1.clearTimeout;
  19. var document = window && window.document;
  20. var navigator = window && window.navigator;
  21. var localSessionStorage = function () {
  22. var x = "qunit-test-string";
  23. try {
  24. global$1.sessionStorage.setItem(x, x);
  25. global$1.sessionStorage.removeItem(x);
  26. return global$1.sessionStorage;
  27. } catch (e) {
  28. return undefined;
  29. }
  30. }();
  31. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  32. return typeof obj;
  33. } : function (obj) {
  34. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  35. };
  36. var classCallCheck = function (instance, Constructor) {
  37. if (!(instance instanceof Constructor)) {
  38. throw new TypeError("Cannot call a class as a function");
  39. }
  40. };
  41. var createClass = function () {
  42. function defineProperties(target, props) {
  43. for (var i = 0; i < props.length; i++) {
  44. var descriptor = props[i];
  45. descriptor.enumerable = descriptor.enumerable || false;
  46. descriptor.configurable = true;
  47. if ("value" in descriptor) descriptor.writable = true;
  48. Object.defineProperty(target, descriptor.key, descriptor);
  49. }
  50. }
  51. return function (Constructor, protoProps, staticProps) {
  52. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  53. if (staticProps) defineProperties(Constructor, staticProps);
  54. return Constructor;
  55. };
  56. }();
  57. var toConsumableArray = function (arr) {
  58. if (Array.isArray(arr)) {
  59. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  60. return arr2;
  61. } else {
  62. return Array.from(arr);
  63. }
  64. };
  65. var toString = Object.prototype.toString;
  66. var hasOwn = Object.prototype.hasOwnProperty;
  67. var now = Date.now || function () {
  68. return new Date().getTime();
  69. };
  70. var defined = {
  71. document: window && window.document !== undefined,
  72. setTimeout: setTimeout !== undefined
  73. };
  74. // Returns a new Array with the elements that are in a but not in b
  75. function diff(a, b) {
  76. var i,
  77. j,
  78. result = a.slice();
  79. for (i = 0; i < result.length; i++) {
  80. for (j = 0; j < b.length; j++) {
  81. if (result[i] === b[j]) {
  82. result.splice(i, 1);
  83. i--;
  84. break;
  85. }
  86. }
  87. }
  88. return result;
  89. }
  90. /**
  91. * Determines whether an element exists in a given array or not.
  92. *
  93. * @method inArray
  94. * @param {Any} elem
  95. * @param {Array} array
  96. * @return {Boolean}
  97. */
  98. function inArray(elem, array) {
  99. return array.indexOf(elem) !== -1;
  100. }
  101. /**
  102. * Makes a clone of an object using only Array or Object as base,
  103. * and copies over the own enumerable properties.
  104. *
  105. * @param {Object} obj
  106. * @return {Object} New object with only the own properties (recursively).
  107. */
  108. function objectValues(obj) {
  109. var key,
  110. val,
  111. vals = is("array", obj) ? [] : {};
  112. for (key in obj) {
  113. if (hasOwn.call(obj, key)) {
  114. val = obj[key];
  115. vals[key] = val === Object(val) ? objectValues(val) : val;
  116. }
  117. }
  118. return vals;
  119. }
  120. function extend(a, b, undefOnly) {
  121. for (var prop in b) {
  122. if (hasOwn.call(b, prop)) {
  123. if (b[prop] === undefined) {
  124. delete a[prop];
  125. } else if (!(undefOnly && typeof a[prop] !== "undefined")) {
  126. a[prop] = b[prop];
  127. }
  128. }
  129. }
  130. return a;
  131. }
  132. function objectType(obj) {
  133. if (typeof obj === "undefined") {
  134. return "undefined";
  135. }
  136. // Consider: typeof null === object
  137. if (obj === null) {
  138. return "null";
  139. }
  140. var match = toString.call(obj).match(/^\[object\s(.*)\]$/),
  141. type = match && match[1];
  142. switch (type) {
  143. case "Number":
  144. if (isNaN(obj)) {
  145. return "nan";
  146. }
  147. return "number";
  148. case "String":
  149. case "Boolean":
  150. case "Array":
  151. case "Set":
  152. case "Map":
  153. case "Date":
  154. case "RegExp":
  155. case "Function":
  156. case "Symbol":
  157. return type.toLowerCase();
  158. default:
  159. return typeof obj === "undefined" ? "undefined" : _typeof(obj);
  160. }
  161. }
  162. // Safe object type checking
  163. function is(type, obj) {
  164. return objectType(obj) === type;
  165. }
  166. // Based on Java's String.hashCode, a simple but not
  167. // rigorously collision resistant hashing function
  168. function generateHash(module, testName) {
  169. var str = module + "\x1C" + testName;
  170. var hash = 0;
  171. for (var i = 0; i < str.length; i++) {
  172. hash = (hash << 5) - hash + str.charCodeAt(i);
  173. hash |= 0;
  174. }
  175. // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
  176. // strictly necessary but increases user understanding that the id is a SHA-like hash
  177. var hex = (0x100000000 + hash).toString(16);
  178. if (hex.length < 8) {
  179. hex = "0000000" + hex;
  180. }
  181. return hex.slice(-8);
  182. }
  183. // Test for equality any JavaScript type.
  184. // Authors: Philippe Rathé <prathe@gmail.com>, David Chan <david@troi.org>
  185. var equiv = (function () {
  186. // Value pairs queued for comparison. Used for breadth-first processing order, recursion
  187. // detection and avoiding repeated comparison (see below for details).
  188. // Elements are { a: val, b: val }.
  189. var pairs = [];
  190. var getProto = Object.getPrototypeOf || function (obj) {
  191. return obj.__proto__;
  192. };
  193. function useStrictEquality(a, b) {
  194. // This only gets called if a and b are not strict equal, and is used to compare on
  195. // the primitive values inside object wrappers. For example:
  196. // `var i = 1;`
  197. // `var j = new Number(1);`
  198. // Neither a nor b can be null, as a !== b and they have the same type.
  199. if ((typeof a === "undefined" ? "undefined" : _typeof(a)) === "object") {
  200. a = a.valueOf();
  201. }
  202. if ((typeof b === "undefined" ? "undefined" : _typeof(b)) === "object") {
  203. b = b.valueOf();
  204. }
  205. return a === b;
  206. }
  207. function compareConstructors(a, b) {
  208. var protoA = getProto(a);
  209. var protoB = getProto(b);
  210. // Comparing constructors is more strict than using `instanceof`
  211. if (a.constructor === b.constructor) {
  212. return true;
  213. }
  214. // Ref #851
  215. // If the obj prototype descends from a null constructor, treat it
  216. // as a null prototype.
  217. if (protoA && protoA.constructor === null) {
  218. protoA = null;
  219. }
  220. if (protoB && protoB.constructor === null) {
  221. protoB = null;
  222. }
  223. // Allow objects with no prototype to be equivalent to
  224. // objects with Object as their constructor.
  225. if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) {
  226. return true;
  227. }
  228. return false;
  229. }
  230. function getRegExpFlags(regexp) {
  231. return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0];
  232. }
  233. function isContainer(val) {
  234. return ["object", "array", "map", "set"].indexOf(objectType(val)) !== -1;
  235. }
  236. function breadthFirstCompareChild(a, b) {
  237. // If a is a container not reference-equal to b, postpone the comparison to the
  238. // end of the pairs queue -- unless (a, b) has been seen before, in which case skip
  239. // over the pair.
  240. if (a === b) {
  241. return true;
  242. }
  243. if (!isContainer(a)) {
  244. return typeEquiv(a, b);
  245. }
  246. if (pairs.every(function (pair) {
  247. return pair.a !== a || pair.b !== b;
  248. })) {
  249. // Not yet started comparing this pair
  250. pairs.push({ a: a, b: b });
  251. }
  252. return true;
  253. }
  254. var callbacks = {
  255. "string": useStrictEquality,
  256. "boolean": useStrictEquality,
  257. "number": useStrictEquality,
  258. "null": useStrictEquality,
  259. "undefined": useStrictEquality,
  260. "symbol": useStrictEquality,
  261. "date": useStrictEquality,
  262. "nan": function nan() {
  263. return true;
  264. },
  265. "regexp": function regexp(a, b) {
  266. return a.source === b.source &&
  267. // Include flags in the comparison
  268. getRegExpFlags(a) === getRegExpFlags(b);
  269. },
  270. // abort (identical references / instance methods were skipped earlier)
  271. "function": function _function() {
  272. return false;
  273. },
  274. "array": function array(a, b) {
  275. var i, len;
  276. len = a.length;
  277. if (len !== b.length) {
  278. // Safe and faster
  279. return false;
  280. }
  281. for (i = 0; i < len; i++) {
  282. // Compare non-containers; queue non-reference-equal containers
  283. if (!breadthFirstCompareChild(a[i], b[i])) {
  284. return false;
  285. }
  286. }
  287. return true;
  288. },
  289. // Define sets a and b to be equivalent if for each element aVal in a, there
  290. // is some element bVal in b such that aVal and bVal are equivalent. Element
  291. // repetitions are not counted, so these are equivalent:
  292. // a = new Set( [ {}, [], [] ] );
  293. // b = new Set( [ {}, {}, [] ] );
  294. "set": function set$$1(a, b) {
  295. var innerEq,
  296. outerEq = true;
  297. if (a.size !== b.size) {
  298. // This optimization has certain quirks because of the lack of
  299. // repetition counting. For instance, adding the same
  300. // (reference-identical) element to two equivalent sets can
  301. // make them non-equivalent.
  302. return false;
  303. }
  304. a.forEach(function (aVal) {
  305. // Short-circuit if the result is already known. (Using for...of
  306. // with a break clause would be cleaner here, but it would cause
  307. // a syntax error on older Javascript implementations even if
  308. // Set is unused)
  309. if (!outerEq) {
  310. return;
  311. }
  312. innerEq = false;
  313. b.forEach(function (bVal) {
  314. var parentPairs;
  315. // Likewise, short-circuit if the result is already known
  316. if (innerEq) {
  317. return;
  318. }
  319. // Swap out the global pairs list, as the nested call to
  320. // innerEquiv will clobber its contents
  321. parentPairs = pairs;
  322. if (innerEquiv(bVal, aVal)) {
  323. innerEq = true;
  324. }
  325. // Replace the global pairs list
  326. pairs = parentPairs;
  327. });
  328. if (!innerEq) {
  329. outerEq = false;
  330. }
  331. });
  332. return outerEq;
  333. },
  334. // Define maps a and b to be equivalent if for each key-value pair (aKey, aVal)
  335. // in a, there is some key-value pair (bKey, bVal) in b such that
  336. // [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not
  337. // counted, so these are equivalent:
  338. // a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] );
  339. // b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] );
  340. "map": function map(a, b) {
  341. var innerEq,
  342. outerEq = true;
  343. if (a.size !== b.size) {
  344. // This optimization has certain quirks because of the lack of
  345. // repetition counting. For instance, adding the same
  346. // (reference-identical) key-value pair to two equivalent maps
  347. // can make them non-equivalent.
  348. return false;
  349. }
  350. a.forEach(function (aVal, aKey) {
  351. // Short-circuit if the result is already known. (Using for...of
  352. // with a break clause would be cleaner here, but it would cause
  353. // a syntax error on older Javascript implementations even if
  354. // Map is unused)
  355. if (!outerEq) {
  356. return;
  357. }
  358. innerEq = false;
  359. b.forEach(function (bVal, bKey) {
  360. var parentPairs;
  361. // Likewise, short-circuit if the result is already known
  362. if (innerEq) {
  363. return;
  364. }
  365. // Swap out the global pairs list, as the nested call to
  366. // innerEquiv will clobber its contents
  367. parentPairs = pairs;
  368. if (innerEquiv([bVal, bKey], [aVal, aKey])) {
  369. innerEq = true;
  370. }
  371. // Replace the global pairs list
  372. pairs = parentPairs;
  373. });
  374. if (!innerEq) {
  375. outerEq = false;
  376. }
  377. });
  378. return outerEq;
  379. },
  380. "object": function object(a, b) {
  381. var i,
  382. aProperties = [],
  383. bProperties = [];
  384. if (compareConstructors(a, b) === false) {
  385. return false;
  386. }
  387. // Be strict: don't ensure hasOwnProperty and go deep
  388. for (i in a) {
  389. // Collect a's properties
  390. aProperties.push(i);
  391. // Skip OOP methods that look the same
  392. if (a.constructor !== Object && typeof a.constructor !== "undefined" && typeof a[i] === "function" && typeof b[i] === "function" && a[i].toString() === b[i].toString()) {
  393. continue;
  394. }
  395. // Compare non-containers; queue non-reference-equal containers
  396. if (!breadthFirstCompareChild(a[i], b[i])) {
  397. return false;
  398. }
  399. }
  400. for (i in b) {
  401. // Collect b's properties
  402. bProperties.push(i);
  403. }
  404. // Ensures identical properties name
  405. return typeEquiv(aProperties.sort(), bProperties.sort());
  406. }
  407. };
  408. function typeEquiv(a, b) {
  409. var type = objectType(a);
  410. // Callbacks for containers will append to the pairs queue to achieve breadth-first
  411. // search order. The pairs queue is also used to avoid reprocessing any pair of
  412. // containers that are reference-equal to a previously visited pair (a special case
  413. // this being recursion detection).
  414. //
  415. // Because of this approach, once typeEquiv returns a false value, it should not be
  416. // called again without clearing the pair queue else it may wrongly report a visited
  417. // pair as being equivalent.
  418. return objectType(b) === type && callbacks[type](a, b);
  419. }
  420. function innerEquiv(a, b) {
  421. var i, pair;
  422. // We're done when there's nothing more to compare
  423. if (arguments.length < 2) {
  424. return true;
  425. }
  426. // Clear the global pair queue and add the top-level values being compared
  427. pairs = [{ a: a, b: b }];
  428. for (i = 0; i < pairs.length; i++) {
  429. pair = pairs[i];
  430. // Perform type-specific comparison on any pairs that are not strictly
  431. // equal. For container types, that comparison will postpone comparison
  432. // of any sub-container pair to the end of the pair queue. This gives
  433. // breadth-first search order. It also avoids the reprocessing of
  434. // reference-equal siblings, cousins etc, which can have a significant speed
  435. // impact when comparing a container of small objects each of which has a
  436. // reference to the same (singleton) large object.
  437. if (pair.a !== pair.b && !typeEquiv(pair.a, pair.b)) {
  438. return false;
  439. }
  440. }
  441. // ...across all consecutive argument pairs
  442. return arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1));
  443. }
  444. return function () {
  445. var result = innerEquiv.apply(undefined, arguments);
  446. // Release any retained objects
  447. pairs.length = 0;
  448. return result;
  449. };
  450. })();
  451. /**
  452. * Config object: Maintain internal state
  453. * Later exposed as QUnit.config
  454. * `config` initialized at top of scope
  455. */
  456. var config = {
  457. // The queue of tests to run
  458. queue: [],
  459. // Block until document ready
  460. blocking: true,
  461. // By default, run previously failed tests first
  462. // very useful in combination with "Hide passed tests" checked
  463. reorder: true,
  464. // By default, modify document.title when suite is done
  465. altertitle: true,
  466. // HTML Reporter: collapse every test except the first failing test
  467. // If false, all failing tests will be expanded
  468. collapse: true,
  469. // By default, scroll to top of the page when suite is done
  470. scrolltop: true,
  471. // Depth up-to which object will be dumped
  472. maxDepth: 5,
  473. // When enabled, all tests must call expect()
  474. requireExpects: false,
  475. // Placeholder for user-configurable form-exposed URL parameters
  476. urlConfig: [],
  477. // Set of all modules.
  478. modules: [],
  479. // The first unnamed module
  480. currentModule: {
  481. name: "",
  482. tests: [],
  483. childModules: [],
  484. testsRun: 0,
  485. unskippedTestsRun: 0,
  486. hooks: {
  487. before: [],
  488. beforeEach: [],
  489. afterEach: [],
  490. after: []
  491. }
  492. },
  493. callbacks: {},
  494. // The storage module to use for reordering tests
  495. storage: localSessionStorage
  496. };
  497. // take a predefined QUnit.config and extend the defaults
  498. var globalConfig = window && window.QUnit && window.QUnit.config;
  499. // only extend the global config if there is no QUnit overload
  500. if (window && window.QUnit && !window.QUnit.version) {
  501. extend(config, globalConfig);
  502. }
  503. // Push a loose unnamed module to the modules collection
  504. config.modules.push(config.currentModule);
  505. // Based on jsDump by Ariel Flesler
  506. // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
  507. var dump = (function () {
  508. function quote(str) {
  509. return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
  510. }
  511. function literal(o) {
  512. return o + "";
  513. }
  514. function join(pre, arr, post) {
  515. var s = dump.separator(),
  516. base = dump.indent(),
  517. inner = dump.indent(1);
  518. if (arr.join) {
  519. arr = arr.join("," + s + inner);
  520. }
  521. if (!arr) {
  522. return pre + post;
  523. }
  524. return [pre, inner + arr, base + post].join(s);
  525. }
  526. function array(arr, stack) {
  527. var i = arr.length,
  528. ret = new Array(i);
  529. if (dump.maxDepth && dump.depth > dump.maxDepth) {
  530. return "[object Array]";
  531. }
  532. this.up();
  533. while (i--) {
  534. ret[i] = this.parse(arr[i], undefined, stack);
  535. }
  536. this.down();
  537. return join("[", ret, "]");
  538. }
  539. function isArray(obj) {
  540. return (
  541. //Native Arrays
  542. toString.call(obj) === "[object Array]" ||
  543. // NodeList objects
  544. typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined)
  545. );
  546. }
  547. var reName = /^function (\w+)/,
  548. dump = {
  549. // The objType is used mostly internally, you can fix a (custom) type in advance
  550. parse: function parse(obj, objType, stack) {
  551. stack = stack || [];
  552. var res,
  553. parser,
  554. parserType,
  555. objIndex = stack.indexOf(obj);
  556. if (objIndex !== -1) {
  557. return "recursion(" + (objIndex - stack.length) + ")";
  558. }
  559. objType = objType || this.typeOf(obj);
  560. parser = this.parsers[objType];
  561. parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser);
  562. if (parserType === "function") {
  563. stack.push(obj);
  564. res = parser.call(this, obj, stack);
  565. stack.pop();
  566. return res;
  567. }
  568. return parserType === "string" ? parser : this.parsers.error;
  569. },
  570. typeOf: function typeOf(obj) {
  571. var type;
  572. if (obj === null) {
  573. type = "null";
  574. } else if (typeof obj === "undefined") {
  575. type = "undefined";
  576. } else if (is("regexp", obj)) {
  577. type = "regexp";
  578. } else if (is("date", obj)) {
  579. type = "date";
  580. } else if (is("function", obj)) {
  581. type = "function";
  582. } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) {
  583. type = "window";
  584. } else if (obj.nodeType === 9) {
  585. type = "document";
  586. } else if (obj.nodeType) {
  587. type = "node";
  588. } else if (isArray(obj)) {
  589. type = "array";
  590. } else if (obj.constructor === Error.prototype.constructor) {
  591. type = "error";
  592. } else {
  593. type = typeof obj === "undefined" ? "undefined" : _typeof(obj);
  594. }
  595. return type;
  596. },
  597. separator: function separator() {
  598. if (this.multiline) {
  599. return this.HTML ? "<br />" : "\n";
  600. } else {
  601. return this.HTML ? "&#160;" : " ";
  602. }
  603. },
  604. // Extra can be a number, shortcut for increasing-calling-decreasing
  605. indent: function indent(extra) {
  606. if (!this.multiline) {
  607. return "";
  608. }
  609. var chr = this.indentChar;
  610. if (this.HTML) {
  611. chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;");
  612. }
  613. return new Array(this.depth + (extra || 0)).join(chr);
  614. },
  615. up: function up(a) {
  616. this.depth += a || 1;
  617. },
  618. down: function down(a) {
  619. this.depth -= a || 1;
  620. },
  621. setParser: function setParser(name, parser) {
  622. this.parsers[name] = parser;
  623. },
  624. // The next 3 are exposed so you can use them
  625. quote: quote,
  626. literal: literal,
  627. join: join,
  628. depth: 1,
  629. maxDepth: config.maxDepth,
  630. // This is the list of parsers, to modify them, use dump.setParser
  631. parsers: {
  632. window: "[Window]",
  633. document: "[Document]",
  634. error: function error(_error) {
  635. return "Error(\"" + _error.message + "\")";
  636. },
  637. unknown: "[Unknown]",
  638. "null": "null",
  639. "undefined": "undefined",
  640. "function": function _function(fn) {
  641. var ret = "function",
  642. // Functions never have name in IE
  643. name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
  644. if (name) {
  645. ret += " " + name;
  646. }
  647. ret += "(";
  648. ret = [ret, dump.parse(fn, "functionArgs"), "){"].join("");
  649. return join(ret, dump.parse(fn, "functionCode"), "}");
  650. },
  651. array: array,
  652. nodelist: array,
  653. "arguments": array,
  654. object: function object(map, stack) {
  655. var keys,
  656. key,
  657. val,
  658. i,
  659. nonEnumerableProperties,
  660. ret = [];
  661. if (dump.maxDepth && dump.depth > dump.maxDepth) {
  662. return "[object Object]";
  663. }
  664. dump.up();
  665. keys = [];
  666. for (key in map) {
  667. keys.push(key);
  668. }
  669. // Some properties are not always enumerable on Error objects.
  670. nonEnumerableProperties = ["message", "name"];
  671. for (i in nonEnumerableProperties) {
  672. key = nonEnumerableProperties[i];
  673. if (key in map && !inArray(key, keys)) {
  674. keys.push(key);
  675. }
  676. }
  677. keys.sort();
  678. for (i = 0; i < keys.length; i++) {
  679. key = keys[i];
  680. val = map[key];
  681. ret.push(dump.parse(key, "key") + ": " + dump.parse(val, undefined, stack));
  682. }
  683. dump.down();
  684. return join("{", ret, "}");
  685. },
  686. node: function node(_node) {
  687. var len,
  688. i,
  689. val,
  690. open = dump.HTML ? "&lt;" : "<",
  691. close = dump.HTML ? "&gt;" : ">",
  692. tag = _node.nodeName.toLowerCase(),
  693. ret = open + tag,
  694. attrs = _node.attributes;
  695. if (attrs) {
  696. for (i = 0, len = attrs.length; i < len; i++) {
  697. val = attrs[i].nodeValue;
  698. // IE6 includes all attributes in .attributes, even ones not explicitly
  699. // set. Those have values like undefined, null, 0, false, "" or
  700. // "inherit".
  701. if (val && val !== "inherit") {
  702. ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute");
  703. }
  704. }
  705. }
  706. ret += close;
  707. // Show content of TextNode or CDATASection
  708. if (_node.nodeType === 3 || _node.nodeType === 4) {
  709. ret += _node.nodeValue;
  710. }
  711. return ret + open + "/" + tag + close;
  712. },
  713. // Function calls it internally, it's the arguments part of the function
  714. functionArgs: function functionArgs(fn) {
  715. var args,
  716. l = fn.length;
  717. if (!l) {
  718. return "";
  719. }
  720. args = new Array(l);
  721. while (l--) {
  722. // 97 is 'a'
  723. args[l] = String.fromCharCode(97 + l);
  724. }
  725. return " " + args.join(", ") + " ";
  726. },
  727. // Object calls it internally, the key part of an item in a map
  728. key: quote,
  729. // Function calls it internally, it's the content of the function
  730. functionCode: "[code]",
  731. // Node calls it internally, it's a html attribute value
  732. attribute: quote,
  733. string: quote,
  734. date: quote,
  735. regexp: literal,
  736. number: literal,
  737. "boolean": literal,
  738. symbol: function symbol(sym) {
  739. return sym.toString();
  740. }
  741. },
  742. // If true, entities are escaped ( <, >, \t, space and \n )
  743. HTML: false,
  744. // Indentation unit
  745. indentChar: " ",
  746. // If true, items in a collection, are separated by a \n, else just a space.
  747. multiline: true
  748. };
  749. return dump;
  750. })();
  751. var LISTENERS = Object.create(null);
  752. var SUPPORTED_EVENTS = ["runStart", "suiteStart", "testStart", "assertion", "testEnd", "suiteEnd", "runEnd"];
  753. /**
  754. * Emits an event with the specified data to all currently registered listeners.
  755. * Callbacks will fire in the order in which they are registered (FIFO). This
  756. * function is not exposed publicly; it is used by QUnit internals to emit
  757. * logging events.
  758. *
  759. * @private
  760. * @method emit
  761. * @param {String} eventName
  762. * @param {Object} data
  763. * @return {Void}
  764. */
  765. function emit(eventName, data) {
  766. if (objectType(eventName) !== "string") {
  767. throw new TypeError("eventName must be a string when emitting an event");
  768. }
  769. // Clone the callbacks in case one of them registers a new callback
  770. var originalCallbacks = LISTENERS[eventName];
  771. var callbacks = originalCallbacks ? [].concat(toConsumableArray(originalCallbacks)) : [];
  772. for (var i = 0; i < callbacks.length; i++) {
  773. callbacks[i](data);
  774. }
  775. }
  776. /**
  777. * Registers a callback as a listener to the specified event.
  778. *
  779. * @public
  780. * @method on
  781. * @param {String} eventName
  782. * @param {Function} callback
  783. * @return {Void}
  784. */
  785. function on(eventName, callback) {
  786. if (objectType(eventName) !== "string") {
  787. throw new TypeError("eventName must be a string when registering a listener");
  788. } else if (!inArray(eventName, SUPPORTED_EVENTS)) {
  789. var events = SUPPORTED_EVENTS.join(", ");
  790. throw new Error("\"" + eventName + "\" is not a valid event; must be one of: " + events + ".");
  791. } else if (objectType(callback) !== "function") {
  792. throw new TypeError("callback must be a function when registering a listener");
  793. }
  794. if (!LISTENERS[eventName]) {
  795. LISTENERS[eventName] = [];
  796. }
  797. // Don't register the same callback more than once
  798. if (!inArray(callback, LISTENERS[eventName])) {
  799. LISTENERS[eventName].push(callback);
  800. }
  801. }
  802. // Register logging callbacks
  803. function registerLoggingCallbacks(obj) {
  804. var i,
  805. l,
  806. key,
  807. callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"];
  808. function registerLoggingCallback(key) {
  809. var loggingCallback = function loggingCallback(callback) {
  810. if (objectType(callback) !== "function") {
  811. throw new Error("QUnit logging methods require a callback function as their first parameters.");
  812. }
  813. config.callbacks[key].push(callback);
  814. };
  815. return loggingCallback;
  816. }
  817. for (i = 0, l = callbackNames.length; i < l; i++) {
  818. key = callbackNames[i];
  819. // Initialize key collection of logging callback
  820. if (objectType(config.callbacks[key]) === "undefined") {
  821. config.callbacks[key] = [];
  822. }
  823. obj[key] = registerLoggingCallback(key);
  824. }
  825. }
  826. function runLoggingCallbacks(key, args) {
  827. var i, l, callbacks;
  828. callbacks = config.callbacks[key];
  829. for (i = 0, l = callbacks.length; i < l; i++) {
  830. callbacks[i](args);
  831. }
  832. }
  833. // Doesn't support IE9, it will return undefined on these browsers
  834. // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
  835. var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
  836. function extractStacktrace(e, offset) {
  837. offset = offset === undefined ? 4 : offset;
  838. var stack, include, i;
  839. if (e && e.stack) {
  840. stack = e.stack.split("\n");
  841. if (/^error$/i.test(stack[0])) {
  842. stack.shift();
  843. }
  844. if (fileName) {
  845. include = [];
  846. for (i = offset; i < stack.length; i++) {
  847. if (stack[i].indexOf(fileName) !== -1) {
  848. break;
  849. }
  850. include.push(stack[i]);
  851. }
  852. if (include.length) {
  853. return include.join("\n");
  854. }
  855. }
  856. return stack[offset];
  857. }
  858. }
  859. function sourceFromStacktrace(offset) {
  860. var error = new Error();
  861. // Support: Safari <=7 only, IE <=10 - 11 only
  862. // Not all browsers generate the `stack` property for `new Error()`, see also #636
  863. if (!error.stack) {
  864. try {
  865. throw error;
  866. } catch (err) {
  867. error = err;
  868. }
  869. }
  870. return extractStacktrace(error, offset);
  871. }
  872. var priorityCount = 0;
  873. var unitSampler = void 0;
  874. /**
  875. * Advances the ProcessingQueue to the next item if it is ready.
  876. * @param {Boolean} last
  877. */
  878. function advance() {
  879. var start = now();
  880. config.depth = (config.depth || 0) + 1;
  881. while (config.queue.length && !config.blocking) {
  882. var elapsedTime = now() - start;
  883. if (!defined.setTimeout || config.updateRate <= 0 || elapsedTime < config.updateRate) {
  884. if (priorityCount > 0) {
  885. priorityCount--;
  886. }
  887. config.queue.shift()();
  888. } else {
  889. setTimeout(advance);
  890. break;
  891. }
  892. }
  893. config.depth--;
  894. if (!config.blocking && !config.queue.length && config.depth === 0) {
  895. done();
  896. }
  897. }
  898. function addToQueueImmediate(callback) {
  899. if (objectType(callback) === "array") {
  900. while (callback.length) {
  901. addToQueueImmediate(callback.pop());
  902. }
  903. return;
  904. }
  905. config.queue.unshift(callback);
  906. priorityCount++;
  907. }
  908. /**
  909. * Adds a function to the ProcessingQueue for execution.
  910. * @param {Function|Array} callback
  911. * @param {Boolean} priority
  912. * @param {String} seed
  913. */
  914. function addToQueue(callback, prioritize, seed) {
  915. if (prioritize) {
  916. config.queue.splice(priorityCount++, 0, callback);
  917. } else if (seed) {
  918. if (!unitSampler) {
  919. unitSampler = unitSamplerGenerator(seed);
  920. }
  921. // Insert into a random position after all prioritized items
  922. var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1));
  923. config.queue.splice(priorityCount + index, 0, callback);
  924. } else {
  925. config.queue.push(callback);
  926. }
  927. }
  928. /**
  929. * Creates a seeded "sample" generator which is used for randomizing tests.
  930. */
  931. function unitSamplerGenerator(seed) {
  932. // 32-bit xorshift, requires only a nonzero seed
  933. // http://excamera.com/sphinx/article-xorshift.html
  934. var sample = parseInt(generateHash(seed), 16) || -1;
  935. return function () {
  936. sample ^= sample << 13;
  937. sample ^= sample >>> 17;
  938. sample ^= sample << 5;
  939. // ECMAScript has no unsigned number type
  940. if (sample < 0) {
  941. sample += 0x100000000;
  942. }
  943. return sample / 0x100000000;
  944. };
  945. }
  946. /**
  947. * This function is called when the ProcessingQueue is done processing all
  948. * items. It handles emitting the final run events.
  949. */
  950. function done() {
  951. var storage = config.storage;
  952. ProcessingQueue.finished = true;
  953. var runtime = now() - config.started;
  954. var passed = config.stats.all - config.stats.bad;
  955. emit("runEnd", globalSuite.end(true));
  956. runLoggingCallbacks("done", {
  957. passed: passed,
  958. failed: config.stats.bad,
  959. total: config.stats.all,
  960. runtime: runtime
  961. });
  962. // Clear own storage items if all tests passed
  963. if (storage && config.stats.bad === 0) {
  964. for (var i = storage.length - 1; i >= 0; i--) {
  965. var key = storage.key(i);
  966. if (key.indexOf("qunit-test-") === 0) {
  967. storage.removeItem(key);
  968. }
  969. }
  970. }
  971. }
  972. var ProcessingQueue = {
  973. finished: false,
  974. add: addToQueue,
  975. addImmediate: addToQueueImmediate,
  976. advance: advance
  977. };
  978. var TestReport = function () {
  979. function TestReport(name, suite, options) {
  980. classCallCheck(this, TestReport);
  981. this.name = name;
  982. this.suiteName = suite.name;
  983. this.fullName = suite.fullName.concat(name);
  984. this.runtime = 0;
  985. this.assertions = [];
  986. this.skipped = !!options.skip;
  987. this.todo = !!options.todo;
  988. this.valid = options.valid;
  989. this._startTime = 0;
  990. this._endTime = 0;
  991. suite.pushTest(this);
  992. }
  993. createClass(TestReport, [{
  994. key: "start",
  995. value: function start(recordTime) {
  996. if (recordTime) {
  997. this._startTime = Date.now();
  998. }
  999. return {
  1000. name: this.name,
  1001. suiteName: this.suiteName,
  1002. fullName: this.fullName.slice()
  1003. };
  1004. }
  1005. }, {
  1006. key: "end",
  1007. value: function end(recordTime) {
  1008. if (recordTime) {
  1009. this._endTime = Date.now();
  1010. }
  1011. return extend(this.start(), {
  1012. runtime: this.getRuntime(),
  1013. status: this.getStatus(),
  1014. errors: this.getFailedAssertions(),
  1015. assertions: this.getAssertions()
  1016. });
  1017. }
  1018. }, {
  1019. key: "pushAssertion",
  1020. value: function pushAssertion(assertion) {
  1021. this.assertions.push(assertion);
  1022. }
  1023. }, {
  1024. key: "getRuntime",
  1025. value: function getRuntime() {
  1026. return this._endTime - this._startTime;
  1027. }
  1028. }, {
  1029. key: "getStatus",
  1030. value: function getStatus() {
  1031. if (this.skipped) {
  1032. return "skipped";
  1033. }
  1034. var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo;
  1035. if (!testPassed) {
  1036. return "failed";
  1037. } else if (this.todo) {
  1038. return "todo";
  1039. } else {
  1040. return "passed";
  1041. }
  1042. }
  1043. }, {
  1044. key: "getFailedAssertions",
  1045. value: function getFailedAssertions() {
  1046. return this.assertions.filter(function (assertion) {
  1047. return !assertion.passed;
  1048. });
  1049. }
  1050. }, {
  1051. key: "getAssertions",
  1052. value: function getAssertions() {
  1053. return this.assertions.slice();
  1054. }
  1055. // Remove actual and expected values from assertions. This is to prevent
  1056. // leaking memory throughout a test suite.
  1057. }, {
  1058. key: "slimAssertions",
  1059. value: function slimAssertions() {
  1060. this.assertions = this.assertions.map(function (assertion) {
  1061. delete assertion.actual;
  1062. delete assertion.expected;
  1063. return assertion;
  1064. });
  1065. }
  1066. }]);
  1067. return TestReport;
  1068. }();
  1069. var focused$1 = false;
  1070. function Test(settings) {
  1071. var i, l;
  1072. ++Test.count;
  1073. this.expected = null;
  1074. this.assertions = [];
  1075. this.semaphore = 0;
  1076. this.module = config.currentModule;
  1077. this.stack = sourceFromStacktrace(3);
  1078. this.steps = [];
  1079. this.timeout = undefined;
  1080. // If a module is skipped, all its tests and the tests of the child suites
  1081. // should be treated as skipped even if they are defined as `only` or `todo`.
  1082. // As for `todo` module, all its tests will be treated as `todo` except for
  1083. // tests defined as `skip` which will be left intact.
  1084. //
  1085. // So, if a test is defined as `todo` and is inside a skipped module, we should
  1086. // then treat that test as if was defined as `skip`.
  1087. if (this.module.skip) {
  1088. settings.skip = true;
  1089. settings.todo = false;
  1090. // Skipped tests should be left intact
  1091. } else if (this.module.todo && !settings.skip) {
  1092. settings.todo = true;
  1093. }
  1094. extend(this, settings);
  1095. this.testReport = new TestReport(settings.testName, this.module.suiteReport, {
  1096. todo: settings.todo,
  1097. skip: settings.skip,
  1098. valid: this.valid()
  1099. });
  1100. // Register unique strings
  1101. for (i = 0, l = this.module.tests; i < l.length; i++) {
  1102. if (this.module.tests[i].name === this.testName) {
  1103. this.testName += " ";
  1104. }
  1105. }
  1106. this.testId = generateHash(this.module.name, this.testName);
  1107. this.module.tests.push({
  1108. name: this.testName,
  1109. testId: this.testId,
  1110. skip: !!settings.skip
  1111. });
  1112. if (settings.skip) {
  1113. // Skipped tests will fully ignore any sent callback
  1114. this.callback = function () {};
  1115. this.async = false;
  1116. this.expected = 0;
  1117. } else {
  1118. if (typeof this.callback !== "function") {
  1119. var method = this.todo ? "todo" : "test";
  1120. // eslint-disable-next-line max-len
  1121. throw new TypeError("You must provide a function as a test callback to QUnit." + method + "(\"" + settings.testName + "\")");
  1122. }
  1123. this.assert = new Assert(this);
  1124. }
  1125. }
  1126. Test.count = 0;
  1127. function getNotStartedModules(startModule) {
  1128. var module = startModule,
  1129. modules = [];
  1130. while (module && module.testsRun === 0) {
  1131. modules.push(module);
  1132. module = module.parentModule;
  1133. }
  1134. return modules;
  1135. }
  1136. Test.prototype = {
  1137. before: function before() {
  1138. var i,
  1139. startModule,
  1140. module = this.module,
  1141. notStartedModules = getNotStartedModules(module);
  1142. for (i = notStartedModules.length - 1; i >= 0; i--) {
  1143. startModule = notStartedModules[i];
  1144. startModule.stats = { all: 0, bad: 0, started: now() };
  1145. emit("suiteStart", startModule.suiteReport.start(true));
  1146. runLoggingCallbacks("moduleStart", {
  1147. name: startModule.name,
  1148. tests: startModule.tests
  1149. });
  1150. }
  1151. config.current = this;
  1152. this.testEnvironment = extend({}, module.testEnvironment);
  1153. this.started = now();
  1154. emit("testStart", this.testReport.start(true));
  1155. runLoggingCallbacks("testStart", {
  1156. name: this.testName,
  1157. module: module.name,
  1158. testId: this.testId,
  1159. previousFailure: this.previousFailure
  1160. });
  1161. if (!config.pollution) {
  1162. saveGlobal();
  1163. }
  1164. },
  1165. run: function run() {
  1166. var promise;
  1167. config.current = this;
  1168. this.callbackStarted = now();
  1169. if (config.notrycatch) {
  1170. runTest(this);
  1171. return;
  1172. }
  1173. try {
  1174. runTest(this);
  1175. } catch (e) {
  1176. this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0));
  1177. // Else next test will carry the responsibility
  1178. saveGlobal();
  1179. // Restart the tests if they're blocking
  1180. if (config.blocking) {
  1181. internalRecover(this);
  1182. }
  1183. }
  1184. function runTest(test) {
  1185. promise = test.callback.call(test.testEnvironment, test.assert);
  1186. test.resolvePromise(promise);
  1187. // If the test has a "lock" on it, but the timeout is 0, then we push a
  1188. // failure as the test should be synchronous.
  1189. if (test.timeout === 0 && test.semaphore !== 0) {
  1190. pushFailure("Test did not finish synchronously even though assert.timeout( 0 ) was used.", sourceFromStacktrace(2));
  1191. }
  1192. }
  1193. },
  1194. after: function after() {
  1195. checkPollution();
  1196. },
  1197. queueHook: function queueHook(hook, hookName, hookOwner) {
  1198. var _this = this;
  1199. var callHook = function callHook() {
  1200. var promise = hook.call(_this.testEnvironment, _this.assert);
  1201. _this.resolvePromise(promise, hookName);
  1202. };
  1203. var runHook = function runHook() {
  1204. if (hookName === "before") {
  1205. if (hookOwner.unskippedTestsRun !== 0) {
  1206. return;
  1207. }
  1208. _this.preserveEnvironment = true;
  1209. }
  1210. if (hookName === "after" && hookOwner.unskippedTestsRun !== numberOfUnskippedTests(hookOwner) - 1 && config.queue.length > 2) {
  1211. return;
  1212. }
  1213. config.current = _this;
  1214. if (config.notrycatch) {
  1215. callHook();
  1216. return;
  1217. }
  1218. try {
  1219. callHook();
  1220. } catch (error) {
  1221. _this.pushFailure(hookName + " failed on " + _this.testName + ": " + (error.message || error), extractStacktrace(error, 0));
  1222. }
  1223. };
  1224. return runHook;
  1225. },
  1226. // Currently only used for module level hooks, can be used to add global level ones
  1227. hooks: function hooks(handler) {
  1228. var hooks = [];
  1229. function processHooks(test, module) {
  1230. if (module.parentModule) {
  1231. processHooks(test, module.parentModule);
  1232. }
  1233. if (module.hooks[handler].length) {
  1234. for (var i = 0; i < module.hooks[handler].length; i++) {
  1235. hooks.push(test.queueHook(module.hooks[handler][i], handler, module));
  1236. }
  1237. }
  1238. }
  1239. // Hooks are ignored on skipped tests
  1240. if (!this.skip) {
  1241. processHooks(this, this.module);
  1242. }
  1243. return hooks;
  1244. },
  1245. finish: function finish() {
  1246. config.current = this;
  1247. if (config.requireExpects && this.expected === null) {
  1248. this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack);
  1249. } else if (this.expected !== null && this.expected !== this.assertions.length) {
  1250. this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack);
  1251. } else if (this.expected === null && !this.assertions.length) {
  1252. this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack);
  1253. }
  1254. var i,
  1255. module = this.module,
  1256. moduleName = module.name,
  1257. testName = this.testName,
  1258. skipped = !!this.skip,
  1259. todo = !!this.todo,
  1260. bad = 0,
  1261. storage = config.storage;
  1262. this.runtime = now() - this.started;
  1263. config.stats.all += this.assertions.length;
  1264. module.stats.all += this.assertions.length;
  1265. for (i = 0; i < this.assertions.length; i++) {
  1266. if (!this.assertions[i].result) {
  1267. bad++;
  1268. config.stats.bad++;
  1269. module.stats.bad++;
  1270. }
  1271. }
  1272. notifyTestsRan(module, skipped);
  1273. // Store result when possible
  1274. if (storage) {
  1275. if (bad) {
  1276. storage.setItem("qunit-test-" + moduleName + "-" + testName, bad);
  1277. } else {
  1278. storage.removeItem("qunit-test-" + moduleName + "-" + testName);
  1279. }
  1280. }
  1281. // After emitting the js-reporters event we cleanup the assertion data to
  1282. // avoid leaking it. It is not used by the legacy testDone callbacks.
  1283. emit("testEnd", this.testReport.end(true));
  1284. this.testReport.slimAssertions();
  1285. runLoggingCallbacks("testDone", {
  1286. name: testName,
  1287. module: moduleName,
  1288. skipped: skipped,
  1289. todo: todo,
  1290. failed: bad,
  1291. passed: this.assertions.length - bad,
  1292. total: this.assertions.length,
  1293. runtime: skipped ? 0 : this.runtime,
  1294. // HTML Reporter use
  1295. assertions: this.assertions,
  1296. testId: this.testId,
  1297. // Source of Test
  1298. source: this.stack
  1299. });
  1300. if (module.testsRun === numberOfTests(module)) {
  1301. logSuiteEnd(module);
  1302. // Check if the parent modules, iteratively, are done. If that the case,
  1303. // we emit the `suiteEnd` event and trigger `moduleDone` callback.
  1304. var parent = module.parentModule;
  1305. while (parent && parent.testsRun === numberOfTests(parent)) {
  1306. logSuiteEnd(parent);
  1307. parent = parent.parentModule;
  1308. }
  1309. }
  1310. config.current = undefined;
  1311. function logSuiteEnd(module) {
  1312. emit("suiteEnd", module.suiteReport.end(true));
  1313. runLoggingCallbacks("moduleDone", {
  1314. name: module.name,
  1315. tests: module.tests,
  1316. failed: module.stats.bad,
  1317. passed: module.stats.all - module.stats.bad,
  1318. total: module.stats.all,
  1319. runtime: now() - module.stats.started
  1320. });
  1321. }
  1322. },
  1323. preserveTestEnvironment: function preserveTestEnvironment() {
  1324. if (this.preserveEnvironment) {
  1325. this.module.testEnvironment = this.testEnvironment;
  1326. this.testEnvironment = extend({}, this.module.testEnvironment);
  1327. }
  1328. },
  1329. queue: function queue() {
  1330. var test = this;
  1331. if (!this.valid()) {
  1332. return;
  1333. }
  1334. function runTest() {
  1335. // Each of these can by async
  1336. ProcessingQueue.addImmediate([function () {
  1337. test.before();
  1338. }, test.hooks("before"), function () {
  1339. test.preserveTestEnvironment();
  1340. }, test.hooks("beforeEach"), function () {
  1341. test.run();
  1342. }, test.hooks("afterEach").reverse(), test.hooks("after").reverse(), function () {
  1343. test.after();
  1344. }, function () {
  1345. test.finish();
  1346. }]);
  1347. }
  1348. var previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName);
  1349. // Prioritize previously failed tests, detected from storage
  1350. var prioritize = config.reorder && !!previousFailCount;
  1351. this.previousFailure = !!previousFailCount;
  1352. ProcessingQueue.add(runTest, prioritize, config.seed);
  1353. // If the queue has already finished, we manually process the new test
  1354. if (ProcessingQueue.finished) {
  1355. ProcessingQueue.advance();
  1356. }
  1357. },
  1358. pushResult: function pushResult(resultInfo) {
  1359. if (this !== config.current) {
  1360. throw new Error("Assertion occurred after test had finished.");
  1361. }
  1362. // Destructure of resultInfo = { result, actual, expected, message, negative }
  1363. var source,
  1364. details = {
  1365. module: this.module.name,
  1366. name: this.testName,
  1367. result: resultInfo.result,
  1368. message: resultInfo.message,
  1369. actual: resultInfo.actual,
  1370. testId: this.testId,
  1371. negative: resultInfo.negative || false,
  1372. runtime: now() - this.started,
  1373. todo: !!this.todo
  1374. };
  1375. if (hasOwn.call(resultInfo, "expected")) {
  1376. details.expected = resultInfo.expected;
  1377. }
  1378. if (!resultInfo.result) {
  1379. source = resultInfo.source || sourceFromStacktrace();
  1380. if (source) {
  1381. details.source = source;
  1382. }
  1383. }
  1384. this.logAssertion(details);
  1385. this.assertions.push({
  1386. result: !!resultInfo.result,
  1387. message: resultInfo.message
  1388. });
  1389. },
  1390. pushFailure: function pushFailure(message, source, actual) {
  1391. if (!(this instanceof Test)) {
  1392. throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2));
  1393. }
  1394. this.pushResult({
  1395. result: false,
  1396. message: message || "error",
  1397. actual: actual || null,
  1398. source: source
  1399. });
  1400. },
  1401. /**
  1402. * Log assertion details using both the old QUnit.log interface and
  1403. * QUnit.on( "assertion" ) interface.
  1404. *
  1405. * @private
  1406. */
  1407. logAssertion: function logAssertion(details) {
  1408. runLoggingCallbacks("log", details);
  1409. var assertion = {
  1410. passed: details.result,
  1411. actual: details.actual,
  1412. expected: details.expected,
  1413. message: details.message,
  1414. stack: details.source,
  1415. todo: details.todo
  1416. };
  1417. this.testReport.pushAssertion(assertion);
  1418. emit("assertion", assertion);
  1419. },
  1420. resolvePromise: function resolvePromise(promise, phase) {
  1421. var then,
  1422. resume,
  1423. message,
  1424. test = this;
  1425. if (promise != null) {
  1426. then = promise.then;
  1427. if (objectType(then) === "function") {
  1428. resume = internalStop(test);
  1429. if (config.notrycatch) {
  1430. then.call(promise, function () {
  1431. resume();
  1432. });
  1433. } else {
  1434. then.call(promise, function () {
  1435. resume();
  1436. }, function (error) {
  1437. message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error);
  1438. test.pushFailure(message, extractStacktrace(error, 0));
  1439. // Else next test will carry the responsibility
  1440. saveGlobal();
  1441. // Unblock
  1442. resume();
  1443. });
  1444. }
  1445. }
  1446. }
  1447. },
  1448. valid: function valid() {
  1449. var filter = config.filter,
  1450. regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter),
  1451. module = config.module && config.module.toLowerCase(),
  1452. fullName = this.module.name + ": " + this.testName;
  1453. function moduleChainNameMatch(testModule) {
  1454. var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
  1455. if (testModuleName === module) {
  1456. return true;
  1457. } else if (testModule.parentModule) {
  1458. return moduleChainNameMatch(testModule.parentModule);
  1459. } else {
  1460. return false;
  1461. }
  1462. }
  1463. function moduleChainIdMatch(testModule) {
  1464. return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
  1465. }
  1466. // Internally-generated tests are always valid
  1467. if (this.callback && this.callback.validTest) {
  1468. return true;
  1469. }
  1470. if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
  1471. return false;
  1472. }
  1473. if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) {
  1474. return false;
  1475. }
  1476. if (module && !moduleChainNameMatch(this.module)) {
  1477. return false;
  1478. }
  1479. if (!filter) {
  1480. return true;
  1481. }
  1482. return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
  1483. },
  1484. regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
  1485. var regex = new RegExp(pattern, flags);
  1486. var match = regex.test(fullName);
  1487. return match !== exclude;
  1488. },
  1489. stringFilter: function stringFilter(filter, fullName) {
  1490. filter = filter.toLowerCase();
  1491. fullName = fullName.toLowerCase();
  1492. var include = filter.charAt(0) !== "!";
  1493. if (!include) {
  1494. filter = filter.slice(1);
  1495. }
  1496. // If the filter matches, we need to honour include
  1497. if (fullName.indexOf(filter) !== -1) {
  1498. return include;
  1499. }
  1500. // Otherwise, do the opposite
  1501. return !include;
  1502. }
  1503. };
  1504. function pushFailure() {
  1505. if (!config.current) {
  1506. throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2));
  1507. }
  1508. // Gets current test obj
  1509. var currentTest = config.current;
  1510. return currentTest.pushFailure.apply(currentTest, arguments);
  1511. }
  1512. function saveGlobal() {
  1513. config.pollution = [];
  1514. if (config.noglobals) {
  1515. for (var key in global$1) {
  1516. if (hasOwn.call(global$1, key)) {
  1517. // In Opera sometimes DOM element ids show up here, ignore them
  1518. if (/^qunit-test-output/.test(key)) {
  1519. continue;
  1520. }
  1521. config.pollution.push(key);
  1522. }
  1523. }
  1524. }
  1525. }
  1526. function checkPollution() {
  1527. var newGlobals,
  1528. deletedGlobals,
  1529. old = config.pollution;
  1530. saveGlobal();
  1531. newGlobals = diff(config.pollution, old);
  1532. if (newGlobals.length > 0) {
  1533. pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
  1534. }
  1535. deletedGlobals = diff(old, config.pollution);
  1536. if (deletedGlobals.length > 0) {
  1537. pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
  1538. }
  1539. }
  1540. // Will be exposed as QUnit.test
  1541. function test(testName, callback) {
  1542. if (focused$1) {
  1543. return;
  1544. }
  1545. var newTest = new Test({
  1546. testName: testName,
  1547. callback: callback
  1548. });
  1549. newTest.queue();
  1550. }
  1551. function todo(testName, callback) {
  1552. if (focused$1) {
  1553. return;
  1554. }
  1555. var newTest = new Test({
  1556. testName: testName,
  1557. callback: callback,
  1558. todo: true
  1559. });
  1560. newTest.queue();
  1561. }
  1562. // Will be exposed as QUnit.skip
  1563. function skip(testName) {
  1564. if (focused$1) {
  1565. return;
  1566. }
  1567. var test = new Test({
  1568. testName: testName,
  1569. skip: true
  1570. });
  1571. test.queue();
  1572. }
  1573. // Will be exposed as QUnit.only
  1574. function only(testName, callback) {
  1575. if (focused$1) {
  1576. return;
  1577. }
  1578. config.queue.length = 0;
  1579. focused$1 = true;
  1580. var newTest = new Test({
  1581. testName: testName,
  1582. callback: callback
  1583. });
  1584. newTest.queue();
  1585. }
  1586. // Put a hold on processing and return a function that will release it.
  1587. function internalStop(test) {
  1588. test.semaphore += 1;
  1589. config.blocking = true;
  1590. // Set a recovery timeout, if so configured.
  1591. if (defined.setTimeout) {
  1592. var timeoutDuration = void 0;
  1593. if (typeof test.timeout === "number") {
  1594. timeoutDuration = test.timeout;
  1595. } else if (typeof config.testTimeout === "number") {
  1596. timeoutDuration = config.testTimeout;
  1597. }
  1598. if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
  1599. clearTimeout(config.timeout);
  1600. config.timeout = setTimeout(function () {
  1601. pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2));
  1602. internalRecover(test);
  1603. }, timeoutDuration);
  1604. }
  1605. }
  1606. var released = false;
  1607. return function resume() {
  1608. if (released) {
  1609. return;
  1610. }
  1611. released = true;
  1612. test.semaphore -= 1;
  1613. internalStart(test);
  1614. };
  1615. }
  1616. // Forcefully release all processing holds.
  1617. function internalRecover(test) {
  1618. test.semaphore = 0;
  1619. internalStart(test);
  1620. }
  1621. // Release a processing hold, scheduling a resumption attempt if no holds remain.
  1622. function internalStart(test) {
  1623. // If semaphore is non-numeric, throw error
  1624. if (isNaN(test.semaphore)) {
  1625. test.semaphore = 0;
  1626. pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2));
  1627. return;
  1628. }
  1629. // Don't start until equal number of stop-calls
  1630. if (test.semaphore > 0) {
  1631. return;
  1632. }
  1633. // Throw an Error if start is called more often than stop
  1634. if (test.semaphore < 0) {
  1635. test.semaphore = 0;
  1636. pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2));
  1637. return;
  1638. }
  1639. // Add a slight delay to allow more assertions etc.
  1640. if (defined.setTimeout) {
  1641. if (config.timeout) {
  1642. clearTimeout(config.timeout);
  1643. }
  1644. config.timeout = setTimeout(function () {
  1645. if (test.semaphore > 0) {
  1646. return;
  1647. }
  1648. if (config.timeout) {
  1649. clearTimeout(config.timeout);
  1650. }
  1651. begin();
  1652. });
  1653. } else {
  1654. begin();
  1655. }
  1656. }
  1657. function collectTests(module) {
  1658. var tests = [].concat(module.tests);
  1659. var modules = [].concat(toConsumableArray(module.childModules));
  1660. // Do a breadth-first traversal of the child modules
  1661. while (modules.length) {
  1662. var nextModule = modules.shift();
  1663. tests.push.apply(tests, nextModule.tests);
  1664. modules.push.apply(modules, toConsumableArray(nextModule.childModules));
  1665. }
  1666. return tests;
  1667. }
  1668. function numberOfTests(module) {
  1669. return collectTests(module).length;
  1670. }
  1671. function numberOfUnskippedTests(module) {
  1672. return collectTests(module).filter(function (test) {
  1673. return !test.skip;
  1674. }).length;
  1675. }
  1676. function notifyTestsRan(module, skipped) {
  1677. module.testsRun++;
  1678. if (!skipped) {
  1679. module.unskippedTestsRun++;
  1680. }
  1681. while (module = module.parentModule) {
  1682. module.testsRun++;
  1683. if (!skipped) {
  1684. module.unskippedTestsRun++;
  1685. }
  1686. }
  1687. }
  1688. /**
  1689. * Returns a function that proxies to the given method name on the globals
  1690. * console object. The proxy will also detect if the console doesn't exist and
  1691. * will appropriately no-op. This allows support for IE9, which doesn't have a
  1692. * console if the developer tools are not open.
  1693. */
  1694. function consoleProxy(method) {
  1695. return function () {
  1696. if (console) {
  1697. console[method].apply(console, arguments);
  1698. }
  1699. };
  1700. }
  1701. var Logger = {
  1702. warn: consoleProxy("warn")
  1703. };
  1704. var Assert = function () {
  1705. function Assert(testContext) {
  1706. classCallCheck(this, Assert);
  1707. this.test = testContext;
  1708. }
  1709. // Assert helpers
  1710. createClass(Assert, [{
  1711. key: "timeout",
  1712. value: function timeout(duration) {
  1713. if (typeof duration !== "number") {
  1714. throw new Error("You must pass a number as the duration to assert.timeout");
  1715. }
  1716. this.test.timeout = duration;
  1717. }
  1718. // Documents a "step", which is a string value, in a test as a passing assertion
  1719. }, {
  1720. key: "step",
  1721. value: function step(message) {
  1722. var result = !!message;
  1723. this.test.steps.push(message);
  1724. return this.pushResult({
  1725. result: result,
  1726. message: message || "You must provide a message to assert.step"
  1727. });
  1728. }
  1729. // Verifies the steps in a test match a given array of string values
  1730. }, {
  1731. key: "verifySteps",
  1732. value: function verifySteps(steps, message) {
  1733. this.deepEqual(this.test.steps, steps, message);
  1734. this.test.steps.length = 0;
  1735. }
  1736. // Specify the number of expected assertions to guarantee that failed test
  1737. // (no assertions are run at all) don't slip through.
  1738. }, {
  1739. key: "expect",
  1740. value: function expect(asserts) {
  1741. if (arguments.length === 1) {
  1742. this.test.expected = asserts;
  1743. } else {
  1744. return this.test.expected;
  1745. }
  1746. }
  1747. // Put a hold on processing and return a function that will release it a maximum of once.
  1748. }, {
  1749. key: "async",
  1750. value: function async(count) {
  1751. var test$$1 = this.test;
  1752. var popped = false,
  1753. acceptCallCount = count;
  1754. if (typeof acceptCallCount === "undefined") {
  1755. acceptCallCount = 1;
  1756. }
  1757. var resume = internalStop(test$$1);
  1758. return function done() {
  1759. if (config.current !== test$$1) {
  1760. throw Error("assert.async callback called after test finished.");
  1761. }
  1762. if (popped) {
  1763. test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2));
  1764. return;
  1765. }
  1766. acceptCallCount -= 1;
  1767. if (acceptCallCount > 0) {
  1768. return;
  1769. }
  1770. popped = true;
  1771. resume();
  1772. };
  1773. }
  1774. // Exports test.push() to the user API
  1775. // Alias of pushResult.
  1776. }, {
  1777. key: "push",
  1778. value: function push(result, actual, expected, message, negative) {
  1779. Logger.warn("assert.push is deprecated and will be removed in QUnit 3.0." + " Please use assert.pushResult instead (https://api.qunitjs.com/assert/pushResult).");
  1780. var currentAssert = this instanceof Assert ? this : config.current.assert;
  1781. return currentAssert.pushResult({
  1782. result: result,
  1783. actual: actual,
  1784. expected: expected,
  1785. message: message,
  1786. negative: negative
  1787. });
  1788. }
  1789. }, {
  1790. key: "pushResult",
  1791. value: function pushResult(resultInfo) {
  1792. // Destructure of resultInfo = { result, actual, expected, message, negative }
  1793. var assert = this;
  1794. var currentTest = assert instanceof Assert && assert.test || config.current;
  1795. // Backwards compatibility fix.
  1796. // Allows the direct use of global exported assertions and QUnit.assert.*
  1797. // Although, it's use is not recommended as it can leak assertions
  1798. // to other tests from async tests, because we only get a reference to the current test,
  1799. // not exactly the test where assertion were intended to be called.
  1800. if (!currentTest) {
  1801. throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
  1802. }
  1803. if (!(assert instanceof Assert)) {
  1804. assert = currentTest.assert;
  1805. }
  1806. return assert.test.pushResult(resultInfo);
  1807. }
  1808. }, {
  1809. key: "ok",
  1810. value: function ok(result, message) {
  1811. if (!message) {
  1812. message = result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result);
  1813. }
  1814. this.pushResult({
  1815. result: !!result,
  1816. actual: result,
  1817. expected: true,
  1818. message: message
  1819. });
  1820. }
  1821. }, {
  1822. key: "notOk",
  1823. value: function notOk(result, message) {
  1824. if (!message) {
  1825. message = !result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result);
  1826. }
  1827. this.pushResult({
  1828. result: !result,
  1829. actual: result,
  1830. expected: false,
  1831. message: message
  1832. });
  1833. }
  1834. }, {
  1835. key: "equal",
  1836. value: function equal(actual, expected, message) {
  1837. // eslint-disable-next-line eqeqeq
  1838. var result = expected == actual;
  1839. this.pushResult({
  1840. result: result,
  1841. actual: actual,
  1842. expected: expected,
  1843. message: message
  1844. });
  1845. }
  1846. }, {
  1847. key: "notEqual",
  1848. value: function notEqual(actual, expected, message) {
  1849. // eslint-disable-next-line eqeqeq
  1850. var result = expected != actual;
  1851. this.pushResult({
  1852. result: result,
  1853. actual: actual,
  1854. expected: expected,
  1855. message: message,
  1856. negative: true
  1857. });
  1858. }
  1859. }, {
  1860. key: "propEqual",
  1861. value: function propEqual(actual, expected, message) {
  1862. actual = objectValues(actual);
  1863. expected = objectValues(expected);
  1864. this.pushResult({
  1865. result: equiv(actual, expected),
  1866. actual: actual,
  1867. expected: expected,
  1868. message: message
  1869. });
  1870. }
  1871. }, {
  1872. key: "notPropEqual",
  1873. value: function notPropEqual(actual, expected, message) {
  1874. actual = objectValues(actual);
  1875. expected = objectValues(expected);
  1876. this.pushResult({
  1877. result: !equiv(actual, expected),
  1878. actual: actual,
  1879. expected: expected,
  1880. message: message,
  1881. negative: true
  1882. });
  1883. }
  1884. }, {
  1885. key: "deepEqual",
  1886. value: function deepEqual(actual, expected, message) {
  1887. this.pushResult({
  1888. result: equiv(actual, expected),
  1889. actual: actual,
  1890. expected: expected,
  1891. message: message
  1892. });
  1893. }
  1894. }, {
  1895. key: "notDeepEqual",
  1896. value: function notDeepEqual(actual, expected, message) {
  1897. this.pushResult({
  1898. result: !equiv(actual, expected),
  1899. actual: actual,
  1900. expected: expected,
  1901. message: message,
  1902. negative: true
  1903. });
  1904. }
  1905. }, {
  1906. key: "strictEqual",
  1907. value: function strictEqual(actual, expected, message) {
  1908. this.pushResult({
  1909. result: expected === actual,
  1910. actual: actual,
  1911. expected: expected,
  1912. message: message
  1913. });
  1914. }
  1915. }, {
  1916. key: "notStrictEqual",
  1917. value: function notStrictEqual(actual, expected, message) {
  1918. this.pushResult({
  1919. result: expected !== actual,
  1920. actual: actual,
  1921. expected: expected,
  1922. message: message,
  1923. negative: true
  1924. });
  1925. }
  1926. }, {
  1927. key: "throws",
  1928. value: function throws(block, expected, message) {
  1929. var actual = void 0,
  1930. result = false;
  1931. var currentTest = this instanceof Assert && this.test || config.current;
  1932. // 'expected' is optional unless doing string comparison
  1933. if (objectType(expected) === "string") {
  1934. if (message == null) {
  1935. message = expected;
  1936. expected = null;
  1937. } else {
  1938. throw new Error("throws/raises does not accept a string value for the expected argument.\n" + "Use a non-string object value (e.g. regExp) instead if it's necessary.");
  1939. }
  1940. }
  1941. currentTest.ignoreGlobalErrors = true;
  1942. try {
  1943. block.call(currentTest.testEnvironment);
  1944. } catch (e) {
  1945. actual = e;
  1946. }
  1947. currentTest.ignoreGlobalErrors = false;
  1948. if (actual) {
  1949. var expectedType = objectType(expected);
  1950. // We don't want to validate thrown error
  1951. if (!expected) {
  1952. result = true;
  1953. expected = null;
  1954. // Expected is a regexp
  1955. } else if (expectedType === "regexp") {
  1956. result = expected.test(errorString(actual));
  1957. // Expected is a constructor, maybe an Error constructor
  1958. } else if (expectedType === "function" && actual instanceof expected) {
  1959. result = true;
  1960. // Expected is an Error object
  1961. } else if (expectedType === "object") {
  1962. result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
  1963. // Expected is a validation function which returns true if validation passed
  1964. } else if (expectedType === "function" && expected.call({}, actual) === true) {
  1965. expected = null;
  1966. result = true;
  1967. }
  1968. }
  1969. currentTest.assert.pushResult({
  1970. result: result,
  1971. actual: actual,
  1972. expected: expected,
  1973. message: message
  1974. });
  1975. }
  1976. }, {
  1977. key: "rejects",
  1978. value: function rejects(promise, expected, message) {
  1979. var result = false;
  1980. var currentTest = this instanceof Assert && this.test || config.current;
  1981. // 'expected' is optional unless doing string comparison
  1982. if (objectType(expected) === "string") {
  1983. if (message === undefined) {
  1984. message = expected;
  1985. expected = undefined;
  1986. } else {
  1987. message = "assert.rejects does not accept a string value for the expected " + "argument.\nUse a non-string object value (e.g. validator function) instead " + "if necessary.";
  1988. currentTest.assert.pushResult({
  1989. result: false,
  1990. message: message
  1991. });
  1992. return;
  1993. }
  1994. }
  1995. var then = promise && promise.then;
  1996. if (objectType(then) !== "function") {
  1997. var _message = "The value provided to `assert.rejects` in " + "\"" + currentTest.testName + "\" was not a promise.";
  1998. currentTest.assert.pushResult({
  1999. result: false,
  2000. message: _message,
  2001. actual: promise
  2002. });
  2003. return;
  2004. }
  2005. var done = this.async();
  2006. return then.call(promise, function handleFulfillment() {
  2007. var message = "The promise returned by the `assert.rejects` callback in " + "\"" + currentTest.testName + "\" did not reject.";
  2008. currentTest.assert.pushResult({
  2009. result: false,
  2010. message: message,
  2011. actual: promise
  2012. });
  2013. done();
  2014. }, function handleRejection(actual) {
  2015. if (actual) {
  2016. var expectedType = objectType(expected);
  2017. // We don't want to validate
  2018. if (expected === undefined) {
  2019. result = true;
  2020. expected = null;
  2021. // Expected is a regexp
  2022. } else if (expectedType === "regexp") {
  2023. result = expected.test(errorString(actual));
  2024. // Expected is a constructor, maybe an Error constructor
  2025. } else if (expectedType === "function" && actual instanceof expected) {
  2026. result = true;
  2027. // Expected is an Error object
  2028. } else if (expectedType === "object") {
  2029. result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
  2030. // Expected is a validation function which returns true if validation passed
  2031. } else {
  2032. if (expectedType === "function") {
  2033. result = expected.call({}, actual) === true;
  2034. expected = null;
  2035. // Expected is some other invalid type
  2036. } else {
  2037. result = false;
  2038. message = "invalid expected value provided to `assert.rejects` " + "callback in \"" + currentTest.testName + "\": " + expectedType + ".";
  2039. }
  2040. }
  2041. }
  2042. currentTest.assert.pushResult({
  2043. result: result,
  2044. actual: actual,
  2045. expected: expected,
  2046. message: message
  2047. });
  2048. done();
  2049. });
  2050. }
  2051. }]);
  2052. return Assert;
  2053. }();
  2054. // Provide an alternative to assert.throws(), for environments that consider throws a reserved word
  2055. // Known to us are: Closure Compiler, Narwhal
  2056. // eslint-disable-next-line dot-notation
  2057. Assert.prototype.raises = Assert.prototype["throws"];
  2058. /**
  2059. * Converts an error into a simple string for comparisons.
  2060. *
  2061. * @param {Error} error
  2062. * @return {String}
  2063. */
  2064. function errorString(error) {
  2065. var resultErrorString = error.toString();
  2066. if (resultErrorString.substring(0, 7) === "[object") {
  2067. var name = error.name ? error.name.toString() : "Error";
  2068. var message = error.message ? error.message.toString() : "";
  2069. if (name && message) {
  2070. return name + ": " + message;
  2071. } else if (name) {
  2072. return name;
  2073. } else if (message) {
  2074. return message;
  2075. } else {
  2076. return "Error";
  2077. }
  2078. } else {
  2079. return resultErrorString;
  2080. }
  2081. }
  2082. /* global module, exports, define */
  2083. function exportQUnit(QUnit) {
  2084. if (defined.document) {
  2085. // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
  2086. if (window.QUnit && window.QUnit.version) {
  2087. throw new Error("QUnit has already been defined.");
  2088. }
  2089. window.QUnit = QUnit;
  2090. }
  2091. // For nodejs
  2092. if (typeof module !== "undefined" && module && module.exports) {
  2093. module.exports = QUnit;
  2094. // For consistency with CommonJS environments' exports
  2095. module.exports.QUnit = QUnit;
  2096. }
  2097. // For CommonJS with exports, but without module.exports, like Rhino
  2098. if (typeof exports !== "undefined" && exports) {
  2099. exports.QUnit = QUnit;
  2100. }
  2101. if (typeof define === "function" && define.amd) {
  2102. define(function () {
  2103. return QUnit;
  2104. });
  2105. QUnit.config.autostart = false;
  2106. }
  2107. // For Web/Service Workers
  2108. if (self$1 && self$1.WorkerGlobalScope && self$1 instanceof self$1.WorkerGlobalScope) {
  2109. self$1.QUnit = QUnit;
  2110. }
  2111. }
  2112. var SuiteReport = function () {
  2113. function SuiteReport(name, parentSuite) {
  2114. classCallCheck(this, SuiteReport);
  2115. this.name = name;
  2116. this.fullName = parentSuite ? parentSuite.fullName.concat(name) : [];
  2117. this.tests = [];
  2118. this.childSuites = [];
  2119. if (parentSuite) {
  2120. parentSuite.pushChildSuite(this);
  2121. }
  2122. }
  2123. createClass(SuiteReport, [{
  2124. key: "start",
  2125. value: function start(recordTime) {
  2126. if (recordTime) {
  2127. this._startTime = Date.now();
  2128. }
  2129. return {
  2130. name: this.name,
  2131. fullName: this.fullName.slice(),
  2132. tests: this.tests.map(function (test) {
  2133. return test.start();
  2134. }),
  2135. childSuites: this.childSuites.map(function (suite) {
  2136. return suite.start();
  2137. }),
  2138. testCounts: {
  2139. total: this.getTestCounts().total
  2140. }
  2141. };
  2142. }
  2143. }, {
  2144. key: "end",
  2145. value: function end(recordTime) {
  2146. if (recordTime) {
  2147. this._endTime = Date.now();
  2148. }
  2149. return {
  2150. name: this.name,
  2151. fullName: this.fullName.slice(),
  2152. tests: this.tests.map(function (test) {
  2153. return test.end();
  2154. }),
  2155. childSuites: this.childSuites.map(function (suite) {
  2156. return suite.end();
  2157. }),
  2158. testCounts: this.getTestCounts(),
  2159. runtime: this.getRuntime(),
  2160. status: this.getStatus()
  2161. };
  2162. }
  2163. }, {
  2164. key: "pushChildSuite",
  2165. value: function pushChildSuite(suite) {
  2166. this.childSuites.push(suite);
  2167. }
  2168. }, {
  2169. key: "pushTest",
  2170. value: function pushTest(test) {
  2171. this.tests.push(test);
  2172. }
  2173. }, {
  2174. key: "getRuntime",
  2175. value: function getRuntime() {
  2176. return this._endTime - this._startTime;
  2177. }
  2178. }, {
  2179. key: "getTestCounts",
  2180. value: function getTestCounts() {
  2181. var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { passed: 0, failed: 0, skipped: 0, todo: 0, total: 0 };
  2182. counts = this.tests.reduce(function (counts, test) {
  2183. if (test.valid) {
  2184. counts[test.getStatus()]++;
  2185. counts.total++;
  2186. }
  2187. return counts;
  2188. }, counts);
  2189. return this.childSuites.reduce(function (counts, suite) {
  2190. return suite.getTestCounts(counts);
  2191. }, counts);
  2192. }
  2193. }, {
  2194. key: "getStatus",
  2195. value: function getStatus() {
  2196. var _getTestCounts = this.getTestCounts(),
  2197. total = _getTestCounts.total,
  2198. failed = _getTestCounts.failed,
  2199. skipped = _getTestCounts.skipped,
  2200. todo = _getTestCounts.todo;
  2201. if (failed) {
  2202. return "failed";
  2203. } else {
  2204. if (skipped === total) {
  2205. return "skipped";
  2206. } else if (todo === total) {
  2207. return "todo";
  2208. } else {
  2209. return "passed";
  2210. }
  2211. }
  2212. }
  2213. }]);
  2214. return SuiteReport;
  2215. }();
  2216. // Handle an unhandled exception. By convention, returns true if further
  2217. // error handling should be suppressed and false otherwise.
  2218. // In this case, we will only suppress further error handling if the
  2219. // "ignoreGlobalErrors" configuration option is enabled.
  2220. function onError(error) {
  2221. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  2222. args[_key - 1] = arguments[_key];
  2223. }
  2224. if (config.current) {
  2225. if (config.current.ignoreGlobalErrors) {
  2226. return true;
  2227. }
  2228. pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  2229. } else {
  2230. test("global failure", extend(function () {
  2231. pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  2232. }, { validTest: true }));
  2233. }
  2234. return false;
  2235. }
  2236. // Handle an unhandled rejection
  2237. function onUnhandledRejection(reason) {
  2238. var resultInfo = {
  2239. result: false,
  2240. message: reason.message || "error",
  2241. actual: reason,
  2242. source: reason.stack || sourceFromStacktrace(3)
  2243. };
  2244. var currentTest = config.current;
  2245. if (currentTest) {
  2246. currentTest.assert.pushResult(resultInfo);
  2247. } else {
  2248. test("global failure", extend(function (assert) {
  2249. assert.pushResult(resultInfo);
  2250. }, { validTest: true }));
  2251. }
  2252. }
  2253. var focused = false;
  2254. var QUnit = {};
  2255. var globalSuite = new SuiteReport();
  2256. // The initial "currentModule" represents the global (or top-level) module that
  2257. // is not explicitly defined by the user, therefore we add the "globalSuite" to
  2258. // it since each module has a suiteReport associated with it.
  2259. config.currentModule.suiteReport = globalSuite;
  2260. var moduleStack = [];
  2261. var globalStartCalled = false;
  2262. var runStarted = false;
  2263. // Figure out if we're running the tests from a server or not
  2264. QUnit.isLocal = !(defined.document && window.location.protocol !== "file:");
  2265. // Expose the current QUnit version
  2266. QUnit.version = "2.5.0";
  2267. function createModule(name, testEnvironment, modifiers) {
  2268. var parentModule = moduleStack.length ? moduleStack.slice(-1)[0] : null;
  2269. var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name;
  2270. var parentSuite = parentModule ? parentModule.suiteReport : globalSuite;
  2271. var skip$$1 = parentModule !== null && parentModule.skip || modifiers.skip;
  2272. var todo$$1 = parentModule !== null && parentModule.todo || modifiers.todo;
  2273. var module = {
  2274. name: moduleName,
  2275. parentModule: parentModule,
  2276. tests: [],
  2277. moduleId: generateHash(moduleName),
  2278. testsRun: 0,
  2279. unskippedTestsRun: 0,
  2280. childModules: [],
  2281. suiteReport: new SuiteReport(name, parentSuite),
  2282. // Pass along `skip` and `todo` properties from parent module, in case
  2283. // there is one, to childs. And use own otherwise.
  2284. // This property will be used to mark own tests and tests of child suites
  2285. // as either `skipped` or `todo`.
  2286. skip: skip$$1,
  2287. todo: skip$$1 ? false : todo$$1
  2288. };
  2289. var env = {};
  2290. if (parentModule) {
  2291. parentModule.childModules.push(module);
  2292. extend(env, parentModule.testEnvironment);
  2293. }
  2294. extend(env, testEnvironment);
  2295. module.testEnvironment = env;
  2296. config.modules.push(module);
  2297. return module;
  2298. }
  2299. function processModule(name, options, executeNow) {
  2300. var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  2301. var module = createModule(name, options, modifiers);
  2302. // Move any hooks to a 'hooks' object
  2303. var testEnvironment = module.testEnvironment;
  2304. var hooks = module.hooks = {};
  2305. setHookFromEnvironment(hooks, testEnvironment, "before");
  2306. setHookFromEnvironment(hooks, testEnvironment, "beforeEach");
  2307. setHookFromEnvironment(hooks, testEnvironment, "afterEach");
  2308. setHookFromEnvironment(hooks, testEnvironment, "after");
  2309. function setHookFromEnvironment(hooks, environment, name) {
  2310. var potentialHook = environment[name];
  2311. hooks[name] = typeof potentialHook === "function" ? [potentialHook] : [];
  2312. delete environment[name];
  2313. }
  2314. var moduleFns = {
  2315. before: setHookFunction(module, "before"),
  2316. beforeEach: setHookFunction(module, "beforeEach"),
  2317. afterEach: setHookFunction(module, "afterEach"),
  2318. after: setHookFunction(module, "after")
  2319. };
  2320. var currentModule = config.currentModule;
  2321. if (objectType(executeNow) === "function") {
  2322. moduleStack.push(module);
  2323. config.currentModule = module;
  2324. executeNow.call(module.testEnvironment, moduleFns);
  2325. moduleStack.pop();
  2326. module = module.parentModule || currentModule;
  2327. }
  2328. config.currentModule = module;
  2329. }
  2330. // TODO: extract this to a new file alongside its related functions
  2331. function module$1(name, options, executeNow) {
  2332. if (focused) {
  2333. return;
  2334. }
  2335. if (arguments.length === 2) {
  2336. if (objectType(options) === "function") {
  2337. executeNow = options;
  2338. options = undefined;
  2339. }
  2340. }
  2341. processModule(name, options, executeNow);
  2342. }
  2343. module$1.only = function () {
  2344. if (focused) {
  2345. return;
  2346. }
  2347. config.modules.length = 0;
  2348. config.queue.length = 0;
  2349. module$1.apply(undefined, arguments);
  2350. focused = true;
  2351. };
  2352. module$1.skip = function (name, options, executeNow) {
  2353. if (focused) {
  2354. return;
  2355. }
  2356. if (arguments.length === 2) {
  2357. if (objectType(options) === "function") {
  2358. executeNow = options;
  2359. options = undefined;
  2360. }
  2361. }
  2362. processModule(name, options, executeNow, { skip: true });
  2363. };
  2364. module$1.todo = function (name, options, executeNow) {
  2365. if (focused) {
  2366. return;
  2367. }
  2368. if (arguments.length === 2) {
  2369. if (objectType(options) === "function") {
  2370. executeNow = options;
  2371. options = undefined;
  2372. }
  2373. }
  2374. processModule(name, options, executeNow, { todo: true });
  2375. };
  2376. extend(QUnit, {
  2377. on: on,
  2378. module: module$1,
  2379. test: test,
  2380. todo: todo,
  2381. skip: skip,
  2382. only: only,
  2383. start: function start(count) {
  2384. var globalStartAlreadyCalled = globalStartCalled;
  2385. if (!config.current) {
  2386. globalStartCalled = true;
  2387. if (runStarted) {
  2388. throw new Error("Called start() while test already started running");
  2389. } else if (globalStartAlreadyCalled || count > 1) {
  2390. throw new Error("Called start() outside of a test context too many times");
  2391. } else if (config.autostart) {
  2392. throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
  2393. } else if (!config.pageLoaded) {
  2394. // The page isn't completely loaded yet, so we set autostart and then
  2395. // load if we're in Node or wait for the browser's load event.
  2396. config.autostart = true;
  2397. // Starts from Node even if .load was not previously called. We still return
  2398. // early otherwise we'll wind up "beginning" twice.
  2399. if (!defined.document) {
  2400. QUnit.load();
  2401. }
  2402. return;
  2403. }
  2404. } else {
  2405. throw new Error("QUnit.start cannot be called inside a test context.");
  2406. }
  2407. scheduleBegin();
  2408. },
  2409. config: config,
  2410. is: is,
  2411. objectType: objectType,
  2412. extend: extend,
  2413. load: function load() {
  2414. config.pageLoaded = true;
  2415. // Initialize the configuration options
  2416. extend(config, {
  2417. stats: { all: 0, bad: 0 },
  2418. started: 0,
  2419. updateRate: 1000,
  2420. autostart: true,
  2421. filter: ""
  2422. }, true);
  2423. if (!runStarted) {
  2424. config.blocking = false;
  2425. if (config.autostart) {
  2426. scheduleBegin();
  2427. }
  2428. }
  2429. },
  2430. stack: function stack(offset) {
  2431. offset = (offset || 0) + 2;
  2432. return sourceFromStacktrace(offset);
  2433. },
  2434. onError: onError,
  2435. onUnhandledRejection: onUnhandledRejection
  2436. });
  2437. QUnit.pushFailure = pushFailure;
  2438. QUnit.assert = Assert.prototype;
  2439. QUnit.equiv = equiv;
  2440. QUnit.dump = dump;
  2441. registerLoggingCallbacks(QUnit);
  2442. function scheduleBegin() {
  2443. runStarted = true;
  2444. // Add a slight delay to allow definition of more modules and tests.
  2445. if (defined.setTimeout) {
  2446. setTimeout(function () {
  2447. begin();
  2448. });
  2449. } else {
  2450. begin();
  2451. }
  2452. }
  2453. function begin() {
  2454. var i,
  2455. l,
  2456. modulesLog = [];
  2457. // If the test run hasn't officially begun yet
  2458. if (!config.started) {
  2459. // Record the time of the test run's beginning
  2460. config.started = now();
  2461. // Delete the loose unnamed module if unused.
  2462. if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
  2463. config.modules.shift();
  2464. }
  2465. // Avoid unnecessary information by not logging modules' test environments
  2466. for (i = 0, l = config.modules.length; i < l; i++) {
  2467. modulesLog.push({
  2468. name: config.modules[i].name,
  2469. tests: config.modules[i].tests
  2470. });
  2471. }
  2472. // The test run is officially beginning now
  2473. emit("runStart", globalSuite.start(true));
  2474. runLoggingCallbacks("begin", {
  2475. totalTests: Test.count,
  2476. modules: modulesLog
  2477. });
  2478. }
  2479. config.blocking = false;
  2480. ProcessingQueue.advance();
  2481. }
  2482. function setHookFunction(module, hookName) {
  2483. return function setHook(callback) {
  2484. module.hooks[hookName].push(callback);
  2485. };
  2486. }
  2487. exportQUnit(QUnit);
  2488. (function () {
  2489. if (typeof window === "undefined" || typeof document === "undefined") {
  2490. return;
  2491. }
  2492. var config = QUnit.config,
  2493. hasOwn = Object.prototype.hasOwnProperty;
  2494. // Stores fixture HTML for resetting later
  2495. function storeFixture() {
  2496. // Avoid overwriting user-defined values
  2497. if (hasOwn.call(config, "fixture")) {
  2498. return;
  2499. }
  2500. var fixture = document.getElementById("qunit-fixture");
  2501. if (fixture) {
  2502. config.fixture = fixture.innerHTML;
  2503. }
  2504. }
  2505. QUnit.begin(storeFixture);
  2506. // Resets the fixture DOM element if available.
  2507. function resetFixture() {
  2508. if (config.fixture == null) {
  2509. return;
  2510. }
  2511. var fixture = document.getElementById("qunit-fixture");
  2512. if (fixture) {
  2513. fixture.innerHTML = config.fixture;
  2514. }
  2515. }
  2516. QUnit.testStart(resetFixture);
  2517. })();
  2518. (function () {
  2519. // Only interact with URLs via window.location
  2520. var location = typeof window !== "undefined" && window.location;
  2521. if (!location) {
  2522. return;
  2523. }
  2524. var urlParams = getUrlParams();
  2525. QUnit.urlParams = urlParams;
  2526. // Match module/test by inclusion in an array
  2527. QUnit.config.moduleId = [].concat(urlParams.moduleId || []);
  2528. QUnit.config.testId = [].concat(urlParams.testId || []);
  2529. // Exact case-insensitive match of the module name
  2530. QUnit.config.module = urlParams.module;
  2531. // Regular expression or case-insenstive substring match against "moduleName: testName"
  2532. QUnit.config.filter = urlParams.filter;
  2533. // Test order randomization
  2534. if (urlParams.seed === true) {
  2535. // Generate a random seed if the option is specified without a value
  2536. QUnit.config.seed = Math.random().toString(36).slice(2);
  2537. } else if (urlParams.seed) {
  2538. QUnit.config.seed = urlParams.seed;
  2539. }
  2540. // Add URL-parameter-mapped config values with UI form rendering data
  2541. QUnit.config.urlConfig.push({
  2542. id: "hidepassed",
  2543. label: "Hide passed tests",
  2544. tooltip: "Only show tests and assertions that fail. Stored as query-strings."
  2545. }, {
  2546. id: "noglobals",
  2547. label: "Check for Globals",
  2548. tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
  2549. }, {
  2550. id: "notrycatch",
  2551. label: "No try-catch",
  2552. tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
  2553. });
  2554. QUnit.begin(function () {
  2555. var i,
  2556. option,
  2557. urlConfig = QUnit.config.urlConfig;
  2558. for (i = 0; i < urlConfig.length; i++) {
  2559. // Options can be either strings or objects with nonempty "id" properties
  2560. option = QUnit.config.urlConfig[i];
  2561. if (typeof option !== "string") {
  2562. option = option.id;
  2563. }
  2564. if (QUnit.config[option] === undefined) {
  2565. QUnit.config[option] = urlParams[option];
  2566. }
  2567. }
  2568. });
  2569. function getUrlParams() {
  2570. var i, param, name, value;
  2571. var urlParams = Object.create(null);
  2572. var params = location.search.slice(1).split("&");
  2573. var length = params.length;
  2574. for (i = 0; i < length; i++) {
  2575. if (params[i]) {
  2576. param = params[i].split("=");
  2577. name = decodeQueryParam(param[0]);
  2578. // Allow just a key to turn on a flag, e.g., test.html?noglobals
  2579. value = param.length === 1 || decodeQueryParam(param.slice(1).join("="));
  2580. if (name in urlParams) {
  2581. urlParams[name] = [].concat(urlParams[name], value);
  2582. } else {
  2583. urlParams[name] = value;
  2584. }
  2585. }
  2586. }
  2587. return urlParams;
  2588. }
  2589. function decodeQueryParam(param) {
  2590. return decodeURIComponent(param.replace(/\+/g, "%20"));
  2591. }
  2592. })();
  2593. var stats = {
  2594. passedTests: 0,
  2595. failedTests: 0,
  2596. skippedTests: 0,
  2597. todoTests: 0
  2598. };
  2599. // Escape text for attribute or text content.
  2600. function escapeText(s) {
  2601. if (!s) {
  2602. return "";
  2603. }
  2604. s = s + "";
  2605. // Both single quotes and double quotes (for attributes)
  2606. return s.replace(/['"<>&]/g, function (s) {
  2607. switch (s) {
  2608. case "'":
  2609. return "&#039;";
  2610. case "\"":
  2611. return "&quot;";
  2612. case "<":
  2613. return "&lt;";
  2614. case ">":
  2615. return "&gt;";
  2616. case "&":
  2617. return "&amp;";
  2618. }
  2619. });
  2620. }
  2621. (function () {
  2622. // Don't load the HTML Reporter on non-browser environments
  2623. if (typeof window === "undefined" || !window.document) {
  2624. return;
  2625. }
  2626. var config = QUnit.config,
  2627. document$$1 = window.document,
  2628. collapseNext = false,
  2629. hasOwn = Object.prototype.hasOwnProperty,
  2630. unfilteredUrl = setUrl({ filter: undefined, module: undefined,
  2631. moduleId: undefined, testId: undefined }),
  2632. modulesList = [];
  2633. function addEvent(elem, type, fn) {
  2634. elem.addEventListener(type, fn, false);
  2635. }
  2636. function removeEvent(elem, type, fn) {
  2637. elem.removeEventListener(type, fn, false);
  2638. }
  2639. function addEvents(elems, type, fn) {
  2640. var i = elems.length;
  2641. while (i--) {
  2642. addEvent(elems[i], type, fn);
  2643. }
  2644. }
  2645. function hasClass(elem, name) {
  2646. return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0;
  2647. }
  2648. function addClass(elem, name) {
  2649. if (!hasClass(elem, name)) {
  2650. elem.className += (elem.className ? " " : "") + name;
  2651. }
  2652. }
  2653. function toggleClass(elem, name, force) {
  2654. if (force || typeof force === "undefined" && !hasClass(elem, name)) {
  2655. addClass(elem, name);
  2656. } else {
  2657. removeClass(elem, name);
  2658. }
  2659. }
  2660. function removeClass(elem, name) {
  2661. var set = " " + elem.className + " ";
  2662. // Class name may appear multiple times
  2663. while (set.indexOf(" " + name + " ") >= 0) {
  2664. set = set.replace(" " + name + " ", " ");
  2665. }
  2666. // Trim for prettiness
  2667. elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
  2668. }
  2669. function id(name) {
  2670. return document$$1.getElementById && document$$1.getElementById(name);
  2671. }
  2672. function abortTests() {
  2673. var abortButton = id("qunit-abort-tests-button");
  2674. if (abortButton) {
  2675. abortButton.disabled = true;
  2676. abortButton.innerHTML = "Aborting...";
  2677. }
  2678. QUnit.config.queue.length = 0;
  2679. return false;
  2680. }
  2681. function interceptNavigation(ev) {
  2682. applyUrlParams();
  2683. if (ev && ev.preventDefault) {
  2684. ev.preventDefault();
  2685. }
  2686. return false;
  2687. }
  2688. function getUrlConfigHtml() {
  2689. var i,
  2690. j,
  2691. val,
  2692. escaped,
  2693. escapedTooltip,
  2694. selection = false,
  2695. urlConfig = config.urlConfig,
  2696. urlConfigHtml = "";
  2697. for (i = 0; i < urlConfig.length; i++) {
  2698. // Options can be either strings or objects with nonempty "id" properties
  2699. val = config.urlConfig[i];
  2700. if (typeof val === "string") {
  2701. val = {
  2702. id: val,
  2703. label: val
  2704. };
  2705. }
  2706. escaped = escapeText(val.id);
  2707. escapedTooltip = escapeText(val.tooltip);
  2708. if (!val.value || typeof val.value === "string") {
  2709. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'><input id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' type='checkbox'" + (val.value ? " value='" + escapeText(val.value) + "'" : "") + (config[val.id] ? " checked='checked'" : "") + " title='" + escapedTooltip + "' />" + escapeText(val.label) + "</label>";
  2710. } else {
  2711. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
  2712. if (QUnit.is("array", val.value)) {
  2713. for (j = 0; j < val.value.length; j++) {
  2714. escaped = escapeText(val.value[j]);
  2715. urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>";
  2716. }
  2717. } else {
  2718. for (j in val.value) {
  2719. if (hasOwn.call(val.value, j)) {
  2720. urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>";
  2721. }
  2722. }
  2723. }
  2724. if (config[val.id] && !selection) {
  2725. escaped = escapeText(config[val.id]);
  2726. urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>";
  2727. }
  2728. urlConfigHtml += "</select>";
  2729. }
  2730. }
  2731. return urlConfigHtml;
  2732. }
  2733. // Handle "click" events on toolbar checkboxes and "change" for select menus.
  2734. // Updates the URL with the new state of `config.urlConfig` values.
  2735. function toolbarChanged() {
  2736. var updatedUrl,
  2737. value,
  2738. tests,
  2739. field = this,
  2740. params = {};
  2741. // Detect if field is a select menu or a checkbox
  2742. if ("selectedIndex" in field) {
  2743. value = field.options[field.selectedIndex].value || undefined;
  2744. } else {
  2745. value = field.checked ? field.defaultValue || true : undefined;
  2746. }
  2747. params[field.name] = value;
  2748. updatedUrl = setUrl(params);
  2749. // Check if we can apply the change without a page refresh
  2750. if ("hidepassed" === field.name && "replaceState" in window.history) {
  2751. QUnit.urlParams[field.name] = value;
  2752. config[field.name] = value || false;
  2753. tests = id("qunit-tests");
  2754. if (tests) {
  2755. toggleClass(tests, "hidepass", value || false);
  2756. }
  2757. window.history.replaceState(null, "", updatedUrl);
  2758. } else {
  2759. window.location = updatedUrl;
  2760. }
  2761. }
  2762. function setUrl(params) {
  2763. var key,
  2764. arrValue,
  2765. i,
  2766. querystring = "?",
  2767. location = window.location;
  2768. params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params);
  2769. for (key in params) {
  2770. // Skip inherited or undefined properties
  2771. if (hasOwn.call(params, key) && params[key] !== undefined) {
  2772. // Output a parameter for each value of this key
  2773. // (but usually just one)
  2774. arrValue = [].concat(params[key]);
  2775. for (i = 0; i < arrValue.length; i++) {
  2776. querystring += encodeURIComponent(key);
  2777. if (arrValue[i] !== true) {
  2778. querystring += "=" + encodeURIComponent(arrValue[i]);
  2779. }
  2780. querystring += "&";
  2781. }
  2782. }
  2783. }
  2784. return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1);
  2785. }
  2786. function applyUrlParams() {
  2787. var i,
  2788. selectedModules = [],
  2789. modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
  2790. filter = id("qunit-filter-input").value;
  2791. for (i = 0; i < modulesList.length; i++) {
  2792. if (modulesList[i].checked) {
  2793. selectedModules.push(modulesList[i].value);
  2794. }
  2795. }
  2796. window.location = setUrl({
  2797. filter: filter === "" ? undefined : filter,
  2798. moduleId: selectedModules.length === 0 ? undefined : selectedModules,
  2799. // Remove module and testId filter
  2800. module: undefined,
  2801. testId: undefined
  2802. });
  2803. }
  2804. function toolbarUrlConfigContainer() {
  2805. var urlConfigContainer = document$$1.createElement("span");
  2806. urlConfigContainer.innerHTML = getUrlConfigHtml();
  2807. addClass(urlConfigContainer, "qunit-url-config");
  2808. addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged);
  2809. addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
  2810. return urlConfigContainer;
  2811. }
  2812. function abortTestsButton() {
  2813. var button = document$$1.createElement("button");
  2814. button.id = "qunit-abort-tests-button";
  2815. button.innerHTML = "Abort";
  2816. addEvent(button, "click", abortTests);
  2817. return button;
  2818. }
  2819. function toolbarLooseFilter() {
  2820. var filter = document$$1.createElement("form"),
  2821. label = document$$1.createElement("label"),
  2822. input = document$$1.createElement("input"),
  2823. button = document$$1.createElement("button");
  2824. addClass(filter, "qunit-filter");
  2825. label.innerHTML = "Filter: ";
  2826. input.type = "text";
  2827. input.value = config.filter || "";
  2828. input.name = "filter";
  2829. input.id = "qunit-filter-input";
  2830. button.innerHTML = "Go";
  2831. label.appendChild(input);
  2832. filter.appendChild(label);
  2833. filter.appendChild(document$$1.createTextNode(" "));
  2834. filter.appendChild(button);
  2835. addEvent(filter, "submit", interceptNavigation);
  2836. return filter;
  2837. }
  2838. function moduleListHtml() {
  2839. var i,
  2840. checked,
  2841. html = "";
  2842. for (i = 0; i < config.modules.length; i++) {
  2843. if (config.modules[i].name !== "") {
  2844. checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1;
  2845. html += "<li><label class='clickable" + (checked ? " checked" : "") + "'><input type='checkbox' " + "value='" + config.modules[i].moduleId + "'" + (checked ? " checked='checked'" : "") + " />" + escapeText(config.modules[i].name) + "</label></li>";
  2846. }
  2847. }
  2848. return html;
  2849. }
  2850. function toolbarModuleFilter() {
  2851. var allCheckbox,
  2852. commit,
  2853. reset,
  2854. moduleFilter = document$$1.createElement("form"),
  2855. label = document$$1.createElement("label"),
  2856. moduleSearch = document$$1.createElement("input"),
  2857. dropDown = document$$1.createElement("div"),
  2858. actions = document$$1.createElement("span"),
  2859. dropDownList = document$$1.createElement("ul"),
  2860. dirty = false;
  2861. moduleSearch.id = "qunit-modulefilter-search";
  2862. addEvent(moduleSearch, "input", searchInput);
  2863. addEvent(moduleSearch, "input", searchFocus);
  2864. addEvent(moduleSearch, "focus", searchFocus);
  2865. addEvent(moduleSearch, "click", searchFocus);
  2866. label.id = "qunit-modulefilter-search-container";
  2867. label.innerHTML = "Module: ";
  2868. label.appendChild(moduleSearch);
  2869. actions.id = "qunit-modulefilter-actions";
  2870. actions.innerHTML = "<button style='display:none'>Apply</button>" + "<button type='reset' style='display:none'>Reset</button>" + "<label class='clickable" + (config.moduleId.length ? "" : " checked") + "'><input type='checkbox'" + (config.moduleId.length ? "" : " checked='checked'") + ">All modules</label>";
  2871. allCheckbox = actions.lastChild.firstChild;
  2872. commit = actions.firstChild;
  2873. reset = commit.nextSibling;
  2874. addEvent(commit, "click", applyUrlParams);
  2875. dropDownList.id = "qunit-modulefilter-dropdown-list";
  2876. dropDownList.innerHTML = moduleListHtml();
  2877. dropDown.id = "qunit-modulefilter-dropdown";
  2878. dropDown.style.display = "none";
  2879. dropDown.appendChild(actions);
  2880. dropDown.appendChild(dropDownList);
  2881. addEvent(dropDown, "change", selectionChange);
  2882. selectionChange();
  2883. moduleFilter.id = "qunit-modulefilter";
  2884. moduleFilter.appendChild(label);
  2885. moduleFilter.appendChild(dropDown);
  2886. addEvent(moduleFilter, "submit", interceptNavigation);
  2887. addEvent(moduleFilter, "reset", function () {
  2888. // Let the reset happen, then update styles
  2889. window.setTimeout(selectionChange);
  2890. });
  2891. // Enables show/hide for the dropdown
  2892. function searchFocus() {
  2893. if (dropDown.style.display !== "none") {
  2894. return;
  2895. }
  2896. dropDown.style.display = "block";
  2897. addEvent(document$$1, "click", hideHandler);
  2898. addEvent(document$$1, "keydown", hideHandler);
  2899. // Hide on Escape keydown or outside-container click
  2900. function hideHandler(e) {
  2901. var inContainer = moduleFilter.contains(e.target);
  2902. if (e.keyCode === 27 || !inContainer) {
  2903. if (e.keyCode === 27 && inContainer) {
  2904. moduleSearch.focus();
  2905. }
  2906. dropDown.style.display = "none";
  2907. removeEvent(document$$1, "click", hideHandler);
  2908. removeEvent(document$$1, "keydown", hideHandler);
  2909. moduleSearch.value = "";
  2910. searchInput();
  2911. }
  2912. }
  2913. }
  2914. // Processes module search box input
  2915. function searchInput() {
  2916. var i,
  2917. item,
  2918. searchText = moduleSearch.value.toLowerCase(),
  2919. listItems = dropDownList.children;
  2920. for (i = 0; i < listItems.length; i++) {
  2921. item = listItems[i];
  2922. if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) {
  2923. item.style.display = "";
  2924. } else {
  2925. item.style.display = "none";
  2926. }
  2927. }
  2928. }
  2929. // Processes selection changes
  2930. function selectionChange(evt) {
  2931. var i,
  2932. item,
  2933. checkbox = evt && evt.target || allCheckbox,
  2934. modulesList = dropDownList.getElementsByTagName("input"),
  2935. selectedNames = [];
  2936. toggleClass(checkbox.parentNode, "checked", checkbox.checked);
  2937. dirty = false;
  2938. if (checkbox.checked && checkbox !== allCheckbox) {
  2939. allCheckbox.checked = false;
  2940. removeClass(allCheckbox.parentNode, "checked");
  2941. }
  2942. for (i = 0; i < modulesList.length; i++) {
  2943. item = modulesList[i];
  2944. if (!evt) {
  2945. toggleClass(item.parentNode, "checked", item.checked);
  2946. } else if (checkbox === allCheckbox && checkbox.checked) {
  2947. item.checked = false;
  2948. removeClass(item.parentNode, "checked");
  2949. }
  2950. dirty = dirty || item.checked !== item.defaultChecked;
  2951. if (item.checked) {
  2952. selectedNames.push(item.parentNode.textContent);
  2953. }
  2954. }
  2955. commit.style.display = reset.style.display = dirty ? "" : "none";
  2956. moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent;
  2957. moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent);
  2958. }
  2959. return moduleFilter;
  2960. }
  2961. function appendToolbar() {
  2962. var toolbar = id("qunit-testrunner-toolbar");
  2963. if (toolbar) {
  2964. toolbar.appendChild(toolbarUrlConfigContainer());
  2965. toolbar.appendChild(toolbarModuleFilter());
  2966. toolbar.appendChild(toolbarLooseFilter());
  2967. toolbar.appendChild(document$$1.createElement("div")).className = "clearfix";
  2968. }
  2969. }
  2970. function appendHeader() {
  2971. var header = id("qunit-header");
  2972. if (header) {
  2973. header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> ";
  2974. }
  2975. }
  2976. function appendBanner() {
  2977. var banner = id("qunit-banner");
  2978. if (banner) {
  2979. banner.className = "";
  2980. }
  2981. }
  2982. function appendTestResults() {
  2983. var tests = id("qunit-tests"),
  2984. result = id("qunit-testresult"),
  2985. controls;
  2986. if (result) {
  2987. result.parentNode.removeChild(result);
  2988. }
  2989. if (tests) {
  2990. tests.innerHTML = "";
  2991. result = document$$1.createElement("p");
  2992. result.id = "qunit-testresult";
  2993. result.className = "result";
  2994. tests.parentNode.insertBefore(result, tests);
  2995. result.innerHTML = "<div id=\"qunit-testresult-display\">Running...<br />&#160;</div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>";
  2996. controls = id("qunit-testresult-controls");
  2997. }
  2998. if (controls) {
  2999. controls.appendChild(abortTestsButton());
  3000. }
  3001. }
  3002. function appendFilteredTest() {
  3003. var testId = QUnit.config.testId;
  3004. if (!testId || testId.length <= 0) {
  3005. return "";
  3006. }
  3007. return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>";
  3008. }
  3009. function appendUserAgent() {
  3010. var userAgent = id("qunit-userAgent");
  3011. if (userAgent) {
  3012. userAgent.innerHTML = "";
  3013. userAgent.appendChild(document$$1.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent));
  3014. }
  3015. }
  3016. function appendInterface() {
  3017. var qunit = id("qunit");
  3018. if (qunit) {
  3019. qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText(document$$1.title) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar'></div>" + appendFilteredTest() + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>";
  3020. }
  3021. appendHeader();
  3022. appendBanner();
  3023. appendTestResults();
  3024. appendUserAgent();
  3025. appendToolbar();
  3026. }
  3027. function appendTestsList(modules) {
  3028. var i, l, x, z, test, moduleObj;
  3029. for (i = 0, l = modules.length; i < l; i++) {
  3030. moduleObj = modules[i];
  3031. for (x = 0, z = moduleObj.tests.length; x < z; x++) {
  3032. test = moduleObj.tests[x];
  3033. appendTest(test.name, test.testId, moduleObj.name);
  3034. }
  3035. }
  3036. }
  3037. function appendTest(name, testId, moduleName) {
  3038. var title,
  3039. rerunTrigger,
  3040. testBlock,
  3041. assertList,
  3042. tests = id("qunit-tests");
  3043. if (!tests) {
  3044. return;
  3045. }
  3046. title = document$$1.createElement("strong");
  3047. title.innerHTML = getNameHtml(name, moduleName);
  3048. rerunTrigger = document$$1.createElement("a");
  3049. rerunTrigger.innerHTML = "Rerun";
  3050. rerunTrigger.href = setUrl({ testId: testId });
  3051. testBlock = document$$1.createElement("li");
  3052. testBlock.appendChild(title);
  3053. testBlock.appendChild(rerunTrigger);
  3054. testBlock.id = "qunit-test-output-" + testId;
  3055. assertList = document$$1.createElement("ol");
  3056. assertList.className = "qunit-assert-list";
  3057. testBlock.appendChild(assertList);
  3058. tests.appendChild(testBlock);
  3059. }
  3060. // HTML Reporter initialization and load
  3061. QUnit.begin(function (details) {
  3062. var i, moduleObj, tests;
  3063. // Sort modules by name for the picker
  3064. for (i = 0; i < details.modules.length; i++) {
  3065. moduleObj = details.modules[i];
  3066. if (moduleObj.name) {
  3067. modulesList.push(moduleObj.name);
  3068. }
  3069. }
  3070. modulesList.sort(function (a, b) {
  3071. return a.localeCompare(b);
  3072. });
  3073. // Initialize QUnit elements
  3074. appendInterface();
  3075. appendTestsList(details.modules);
  3076. tests = id("qunit-tests");
  3077. if (tests && config.hidepassed) {
  3078. addClass(tests, "hidepass");
  3079. }
  3080. });
  3081. QUnit.done(function (details) {
  3082. var banner = id("qunit-banner"),
  3083. tests = id("qunit-tests"),
  3084. abortButton = id("qunit-abort-tests-button"),
  3085. totalTests = stats.passedTests + stats.skippedTests + stats.todoTests + stats.failedTests,
  3086. html = [totalTests, " tests completed in ", details.runtime, " milliseconds, with ", stats.failedTests, " failed, ", stats.skippedTests, " skipped, and ", stats.todoTests, " todo.<br />", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", details.total, "</span> passed, <span class='failed'>", details.failed, "</span> failed."].join(""),
  3087. test,
  3088. assertLi,
  3089. assertList;
  3090. // Update remaing tests to aborted
  3091. if (abortButton && abortButton.disabled) {
  3092. html = "Tests aborted after " + details.runtime + " milliseconds.";
  3093. for (var i = 0; i < tests.children.length; i++) {
  3094. test = tests.children[i];
  3095. if (test.className === "" || test.className === "running") {
  3096. test.className = "aborted";
  3097. assertList = test.getElementsByTagName("ol")[0];
  3098. assertLi = document$$1.createElement("li");
  3099. assertLi.className = "fail";
  3100. assertLi.innerHTML = "Test aborted.";
  3101. assertList.appendChild(assertLi);
  3102. }
  3103. }
  3104. }
  3105. if (banner && (!abortButton || abortButton.disabled === false)) {
  3106. banner.className = stats.failedTests ? "qunit-fail" : "qunit-pass";
  3107. }
  3108. if (abortButton) {
  3109. abortButton.parentNode.removeChild(abortButton);
  3110. }
  3111. if (tests) {
  3112. id("qunit-testresult-display").innerHTML = html;
  3113. }
  3114. if (config.altertitle && document$$1.title) {
  3115. // Show ✖ for good, ✔ for bad suite result in title
  3116. // use escape sequences in case file gets loaded with non-utf-8
  3117. // charset
  3118. document$$1.title = [stats.failedTests ? "\u2716" : "\u2714", document$$1.title.replace(/^[\u2714\u2716] /i, "")].join(" ");
  3119. }
  3120. // Scroll back to top to show results
  3121. if (config.scrolltop && window.scrollTo) {
  3122. window.scrollTo(0, 0);
  3123. }
  3124. });
  3125. function getNameHtml(name, module) {
  3126. var nameHtml = "";
  3127. if (module) {
  3128. nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
  3129. }
  3130. nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
  3131. return nameHtml;
  3132. }
  3133. QUnit.testStart(function (details) {
  3134. var running, testBlock, bad;
  3135. testBlock = id("qunit-test-output-" + details.testId);
  3136. if (testBlock) {
  3137. testBlock.className = "running";
  3138. } else {
  3139. // Report later registered tests
  3140. appendTest(details.name, details.testId, details.module);
  3141. }
  3142. running = id("qunit-testresult-display");
  3143. if (running) {
  3144. bad = QUnit.config.reorder && details.previousFailure;
  3145. running.innerHTML = [bad ? "Rerunning previously failed test: <br />" : "Running: <br />", getNameHtml(details.name, details.module)].join("");
  3146. }
  3147. });
  3148. function stripHtml(string) {
  3149. // Strip tags, html entity and whitespaces
  3150. return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\&quot;/g, "").replace(/\s+/g, "");
  3151. }
  3152. QUnit.log(function (details) {
  3153. var assertList,
  3154. assertLi,
  3155. message,
  3156. expected,
  3157. actual,
  3158. diff,
  3159. showDiff = false,
  3160. testItem = id("qunit-test-output-" + details.testId);
  3161. if (!testItem) {
  3162. return;
  3163. }
  3164. message = escapeText(details.message) || (details.result ? "okay" : "failed");
  3165. message = "<span class='test-message'>" + message + "</span>";
  3166. message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
  3167. // The pushFailure doesn't provide details.expected
  3168. // when it calls, it's implicit to also not show expected and diff stuff
  3169. // Also, we need to check details.expected existence, as it can exist and be undefined
  3170. if (!details.result && hasOwn.call(details, "expected")) {
  3171. if (details.negative) {
  3172. expected = "NOT " + QUnit.dump.parse(details.expected);
  3173. } else {
  3174. expected = QUnit.dump.parse(details.expected);
  3175. }
  3176. actual = QUnit.dump.parse(details.actual);
  3177. message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>";
  3178. if (actual !== expected) {
  3179. message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>";
  3180. if (typeof details.actual === "number" && typeof details.expected === "number") {
  3181. if (!isNaN(details.actual) && !isNaN(details.expected)) {
  3182. showDiff = true;
  3183. diff = details.actual - details.expected;
  3184. diff = (diff > 0 ? "+" : "") + diff;
  3185. }
  3186. } else if (typeof details.actual !== "boolean" && typeof details.expected !== "boolean") {
  3187. diff = QUnit.diff(expected, actual);
  3188. // don't show diff if there is zero overlap
  3189. showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length;
  3190. }
  3191. if (showDiff) {
  3192. message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>";
  3193. }
  3194. } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) {
  3195. message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the depth of object is more than current max depth (" + QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " + " run with a higher max depth or <a href='" + escapeText(setUrl({ maxDepth: -1 })) + "'>" + "Rerun</a> without max depth.</p></td></tr>";
  3196. } else {
  3197. message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
  3198. }
  3199. if (details.source) {
  3200. message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>";
  3201. }
  3202. message += "</table>";
  3203. // This occurs when pushFailure is set and we have an extracted stack trace
  3204. } else if (!details.result && details.source) {
  3205. message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>";
  3206. }
  3207. assertList = testItem.getElementsByTagName("ol")[0];
  3208. assertLi = document$$1.createElement("li");
  3209. assertLi.className = details.result ? "pass" : "fail";
  3210. assertLi.innerHTML = message;
  3211. assertList.appendChild(assertLi);
  3212. });
  3213. QUnit.testDone(function (details) {
  3214. var testTitle,
  3215. time,
  3216. testItem,
  3217. assertList,
  3218. good,
  3219. bad,
  3220. testCounts,
  3221. skipped,
  3222. sourceName,
  3223. tests = id("qunit-tests");
  3224. if (!tests) {
  3225. return;
  3226. }
  3227. testItem = id("qunit-test-output-" + details.testId);
  3228. assertList = testItem.getElementsByTagName("ol")[0];
  3229. good = details.passed;
  3230. bad = details.failed;
  3231. // This test passed if it has no unexpected failed assertions
  3232. var testPassed = details.failed > 0 ? details.todo : !details.todo;
  3233. if (testPassed) {
  3234. // Collapse the passing tests
  3235. addClass(assertList, "qunit-collapsed");
  3236. } else if (config.collapse) {
  3237. if (!collapseNext) {
  3238. // Skip collapsing the first failing test
  3239. collapseNext = true;
  3240. } else {
  3241. // Collapse remaining tests
  3242. addClass(assertList, "qunit-collapsed");
  3243. }
  3244. }
  3245. // The testItem.firstChild is the test name
  3246. testTitle = testItem.firstChild;
  3247. testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : "";
  3248. testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>";
  3249. if (details.skipped) {
  3250. stats.skippedTests++;
  3251. testItem.className = "skipped";
  3252. skipped = document$$1.createElement("em");
  3253. skipped.className = "qunit-skipped-label";
  3254. skipped.innerHTML = "skipped";
  3255. testItem.insertBefore(skipped, testTitle);
  3256. } else {
  3257. addEvent(testTitle, "click", function () {
  3258. toggleClass(assertList, "qunit-collapsed");
  3259. });
  3260. testItem.className = testPassed ? "pass" : "fail";
  3261. if (details.todo) {
  3262. var todoLabel = document$$1.createElement("em");
  3263. todoLabel.className = "qunit-todo-label";
  3264. todoLabel.innerHTML = "todo";
  3265. testItem.className += " todo";
  3266. testItem.insertBefore(todoLabel, testTitle);
  3267. }
  3268. time = document$$1.createElement("span");
  3269. time.className = "runtime";
  3270. time.innerHTML = details.runtime + " ms";
  3271. testItem.insertBefore(time, assertList);
  3272. if (!testPassed) {
  3273. stats.failedTests++;
  3274. } else if (details.todo) {
  3275. stats.todoTests++;
  3276. } else {
  3277. stats.passedTests++;
  3278. }
  3279. }
  3280. // Show the source of the test when showing assertions
  3281. if (details.source) {
  3282. sourceName = document$$1.createElement("p");
  3283. sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
  3284. addClass(sourceName, "qunit-source");
  3285. if (testPassed) {
  3286. addClass(sourceName, "qunit-collapsed");
  3287. }
  3288. addEvent(testTitle, "click", function () {
  3289. toggleClass(sourceName, "qunit-collapsed");
  3290. });
  3291. testItem.appendChild(sourceName);
  3292. }
  3293. });
  3294. // Avoid readyState issue with phantomjs
  3295. // Ref: #818
  3296. var notPhantom = function (p) {
  3297. return !(p && p.version && p.version.major > 0);
  3298. }(window.phantom);
  3299. if (notPhantom && document$$1.readyState === "complete") {
  3300. QUnit.load();
  3301. } else {
  3302. addEvent(window, "load", QUnit.load);
  3303. }
  3304. // Wrap window.onerror. We will call the original window.onerror to see if
  3305. // the existing handler fully handles the error; if not, we will call the
  3306. // QUnit.onError function.
  3307. var originalWindowOnError = window.onerror;
  3308. // Cover uncaught exceptions
  3309. // Returning true will suppress the default browser handler,
  3310. // returning false will let it run.
  3311. window.onerror = function (message, fileName, lineNumber) {
  3312. var ret = false;
  3313. if (originalWindowOnError) {
  3314. for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  3315. args[_key - 3] = arguments[_key];
  3316. }
  3317. ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber].concat(args));
  3318. }
  3319. // Treat return value as window.onerror itself does,
  3320. // Only do our handling if not suppressed.
  3321. if (ret !== true) {
  3322. var error = {
  3323. message: message,
  3324. fileName: fileName,
  3325. lineNumber: lineNumber
  3326. };
  3327. ret = QUnit.onError(error);
  3328. }
  3329. return ret;
  3330. };
  3331. // Listen for unhandled rejections, and call QUnit.onUnhandledRejection
  3332. window.addEventListener("unhandledrejection", function (event) {
  3333. QUnit.onUnhandledRejection(event.reason);
  3334. });
  3335. })();
  3336. /*
  3337. * This file is a modified version of google-diff-match-patch's JavaScript implementation
  3338. * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
  3339. * modifications are licensed as more fully set forth in LICENSE.txt.
  3340. *
  3341. * The original source of google-diff-match-patch is attributable and licensed as follows:
  3342. *
  3343. * Copyright 2006 Google Inc.
  3344. * https://code.google.com/p/google-diff-match-patch/
  3345. *
  3346. * Licensed under the Apache License, Version 2.0 (the "License");
  3347. * you may not use this file except in compliance with the License.
  3348. * You may obtain a copy of the License at
  3349. *
  3350. * https://www.apache.org/licenses/LICENSE-2.0
  3351. *
  3352. * Unless required by applicable law or agreed to in writing, software
  3353. * distributed under the License is distributed on an "AS IS" BASIS,
  3354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3355. * See the License for the specific language governing permissions and
  3356. * limitations under the License.
  3357. *
  3358. * More Info:
  3359. * https://code.google.com/p/google-diff-match-patch/
  3360. *
  3361. * Usage: QUnit.diff(expected, actual)
  3362. *
  3363. */
  3364. QUnit.diff = function () {
  3365. function DiffMatchPatch() {}
  3366. // DIFF FUNCTIONS
  3367. /**
  3368. * The data structure representing a diff is an array of tuples:
  3369. * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
  3370. * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
  3371. */
  3372. var DIFF_DELETE = -1,
  3373. DIFF_INSERT = 1,
  3374. DIFF_EQUAL = 0;
  3375. /**
  3376. * Find the differences between two texts. Simplifies the problem by stripping
  3377. * any common prefix or suffix off the texts before diffing.
  3378. * @param {string} text1 Old string to be diffed.
  3379. * @param {string} text2 New string to be diffed.
  3380. * @param {boolean=} optChecklines Optional speedup flag. If present and false,
  3381. * then don't run a line-level diff first to identify the changed areas.
  3382. * Defaults to true, which does a faster, slightly less optimal diff.
  3383. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3384. */
  3385. DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
  3386. var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs;
  3387. // The diff must be complete in up to 1 second.
  3388. deadline = new Date().getTime() + 1000;
  3389. // Check for null inputs.
  3390. if (text1 === null || text2 === null) {
  3391. throw new Error("Null input. (DiffMain)");
  3392. }
  3393. // Check for equality (speedup).
  3394. if (text1 === text2) {
  3395. if (text1) {
  3396. return [[DIFF_EQUAL, text1]];
  3397. }
  3398. return [];
  3399. }
  3400. if (typeof optChecklines === "undefined") {
  3401. optChecklines = true;
  3402. }
  3403. checklines = optChecklines;
  3404. // Trim off common prefix (speedup).
  3405. commonlength = this.diffCommonPrefix(text1, text2);
  3406. commonprefix = text1.substring(0, commonlength);
  3407. text1 = text1.substring(commonlength);
  3408. text2 = text2.substring(commonlength);
  3409. // Trim off common suffix (speedup).
  3410. commonlength = this.diffCommonSuffix(text1, text2);
  3411. commonsuffix = text1.substring(text1.length - commonlength);
  3412. text1 = text1.substring(0, text1.length - commonlength);
  3413. text2 = text2.substring(0, text2.length - commonlength);
  3414. // Compute the diff on the middle block.
  3415. diffs = this.diffCompute(text1, text2, checklines, deadline);
  3416. // Restore the prefix and suffix.
  3417. if (commonprefix) {
  3418. diffs.unshift([DIFF_EQUAL, commonprefix]);
  3419. }
  3420. if (commonsuffix) {
  3421. diffs.push([DIFF_EQUAL, commonsuffix]);
  3422. }
  3423. this.diffCleanupMerge(diffs);
  3424. return diffs;
  3425. };
  3426. /**
  3427. * Reduce the number of edits by eliminating operationally trivial equalities.
  3428. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3429. */
  3430. DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
  3431. var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel;
  3432. changes = false;
  3433. equalities = []; // Stack of indices where equalities are found.
  3434. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  3435. /** @type {?string} */
  3436. lastequality = null;
  3437. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  3438. pointer = 0; // Index of current position.
  3439. // Is there an insertion operation before the last equality.
  3440. preIns = false;
  3441. // Is there a deletion operation before the last equality.
  3442. preDel = false;
  3443. // Is there an insertion operation after the last equality.
  3444. postIns = false;
  3445. // Is there a deletion operation after the last equality.
  3446. postDel = false;
  3447. while (pointer < diffs.length) {
  3448. // Equality found.
  3449. if (diffs[pointer][0] === DIFF_EQUAL) {
  3450. if (diffs[pointer][1].length < 4 && (postIns || postDel)) {
  3451. // Candidate found.
  3452. equalities[equalitiesLength++] = pointer;
  3453. preIns = postIns;
  3454. preDel = postDel;
  3455. lastequality = diffs[pointer][1];
  3456. } else {
  3457. // Not a candidate, and can never become one.
  3458. equalitiesLength = 0;
  3459. lastequality = null;
  3460. }
  3461. postIns = postDel = false;
  3462. // An insertion or deletion.
  3463. } else {
  3464. if (diffs[pointer][0] === DIFF_DELETE) {
  3465. postDel = true;
  3466. } else {
  3467. postIns = true;
  3468. }
  3469. /*
  3470. * Five types to be split:
  3471. * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  3472. * <ins>A</ins>X<ins>C</ins><del>D</del>
  3473. * <ins>A</ins><del>B</del>X<ins>C</ins>
  3474. * <ins>A</del>X<ins>C</ins><del>D</del>
  3475. * <ins>A</ins><del>B</del>X<del>C</del>
  3476. */
  3477. if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) {
  3478. // Duplicate record.
  3479. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
  3480. // Change second copy to insert.
  3481. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  3482. equalitiesLength--; // Throw away the equality we just deleted;
  3483. lastequality = null;
  3484. if (preIns && preDel) {
  3485. // No changes made which could affect previous entry, keep going.
  3486. postIns = postDel = true;
  3487. equalitiesLength = 0;
  3488. } else {
  3489. equalitiesLength--; // Throw away the previous equality.
  3490. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  3491. postIns = postDel = false;
  3492. }
  3493. changes = true;
  3494. }
  3495. }
  3496. pointer++;
  3497. }
  3498. if (changes) {
  3499. this.diffCleanupMerge(diffs);
  3500. }
  3501. };
  3502. /**
  3503. * Convert a diff array into a pretty HTML report.
  3504. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3505. * @param {integer} string to be beautified.
  3506. * @return {string} HTML representation.
  3507. */
  3508. DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
  3509. var op,
  3510. data,
  3511. x,
  3512. html = [];
  3513. for (x = 0; x < diffs.length; x++) {
  3514. op = diffs[x][0]; // Operation (insert, delete, equal)
  3515. data = diffs[x][1]; // Text of change.
  3516. switch (op) {
  3517. case DIFF_INSERT:
  3518. html[x] = "<ins>" + escapeText(data) + "</ins>";
  3519. break;
  3520. case DIFF_DELETE:
  3521. html[x] = "<del>" + escapeText(data) + "</del>";
  3522. break;
  3523. case DIFF_EQUAL:
  3524. html[x] = "<span>" + escapeText(data) + "</span>";
  3525. break;
  3526. }
  3527. }
  3528. return html.join("");
  3529. };
  3530. /**
  3531. * Determine the common prefix of two strings.
  3532. * @param {string} text1 First string.
  3533. * @param {string} text2 Second string.
  3534. * @return {number} The number of characters common to the start of each
  3535. * string.
  3536. */
  3537. DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
  3538. var pointermid, pointermax, pointermin, pointerstart;
  3539. // Quick check for common null cases.
  3540. if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
  3541. return 0;
  3542. }
  3543. // Binary search.
  3544. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  3545. pointermin = 0;
  3546. pointermax = Math.min(text1.length, text2.length);
  3547. pointermid = pointermax;
  3548. pointerstart = 0;
  3549. while (pointermin < pointermid) {
  3550. if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
  3551. pointermin = pointermid;
  3552. pointerstart = pointermin;
  3553. } else {
  3554. pointermax = pointermid;
  3555. }
  3556. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  3557. }
  3558. return pointermid;
  3559. };
  3560. /**
  3561. * Determine the common suffix of two strings.
  3562. * @param {string} text1 First string.
  3563. * @param {string} text2 Second string.
  3564. * @return {number} The number of characters common to the end of each string.
  3565. */
  3566. DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
  3567. var pointermid, pointermax, pointermin, pointerend;
  3568. // Quick check for common null cases.
  3569. if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
  3570. return 0;
  3571. }
  3572. // Binary search.
  3573. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  3574. pointermin = 0;
  3575. pointermax = Math.min(text1.length, text2.length);
  3576. pointermid = pointermax;
  3577. pointerend = 0;
  3578. while (pointermin < pointermid) {
  3579. if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
  3580. pointermin = pointermid;
  3581. pointerend = pointermin;
  3582. } else {
  3583. pointermax = pointermid;
  3584. }
  3585. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  3586. }
  3587. return pointermid;
  3588. };
  3589. /**
  3590. * Find the differences between two texts. Assumes that the texts do not
  3591. * have any common prefix or suffix.
  3592. * @param {string} text1 Old string to be diffed.
  3593. * @param {string} text2 New string to be diffed.
  3594. * @param {boolean} checklines Speedup flag. If false, then don't run a
  3595. * line-level diff first to identify the changed areas.
  3596. * If true, then run a faster, slightly less optimal diff.
  3597. * @param {number} deadline Time when the diff should be complete by.
  3598. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3599. * @private
  3600. */
  3601. DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
  3602. var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB;
  3603. if (!text1) {
  3604. // Just add some text (speedup).
  3605. return [[DIFF_INSERT, text2]];
  3606. }
  3607. if (!text2) {
  3608. // Just delete some text (speedup).
  3609. return [[DIFF_DELETE, text1]];
  3610. }
  3611. longtext = text1.length > text2.length ? text1 : text2;
  3612. shorttext = text1.length > text2.length ? text2 : text1;
  3613. i = longtext.indexOf(shorttext);
  3614. if (i !== -1) {
  3615. // Shorter text is inside the longer text (speedup).
  3616. diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
  3617. // Swap insertions for deletions if diff is reversed.
  3618. if (text1.length > text2.length) {
  3619. diffs[0][0] = diffs[2][0] = DIFF_DELETE;
  3620. }
  3621. return diffs;
  3622. }
  3623. if (shorttext.length === 1) {
  3624. // Single character string.
  3625. // After the previous speedup, the character can't be an equality.
  3626. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  3627. }
  3628. // Check to see if the problem can be split in two.
  3629. hm = this.diffHalfMatch(text1, text2);
  3630. if (hm) {
  3631. // A half-match was found, sort out the return data.
  3632. text1A = hm[0];
  3633. text1B = hm[1];
  3634. text2A = hm[2];
  3635. text2B = hm[3];
  3636. midCommon = hm[4];
  3637. // Send both pairs off for separate processing.
  3638. diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
  3639. diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
  3640. // Merge the results.
  3641. return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
  3642. }
  3643. if (checklines && text1.length > 100 && text2.length > 100) {
  3644. return this.diffLineMode(text1, text2, deadline);
  3645. }
  3646. return this.diffBisect(text1, text2, deadline);
  3647. };
  3648. /**
  3649. * Do the two texts share a substring which is at least half the length of the
  3650. * longer text?
  3651. * This speedup can produce non-minimal diffs.
  3652. * @param {string} text1 First string.
  3653. * @param {string} text2 Second string.
  3654. * @return {Array.<string>} Five element Array, containing the prefix of
  3655. * text1, the suffix of text1, the prefix of text2, the suffix of
  3656. * text2 and the common middle. Or null if there was no match.
  3657. * @private
  3658. */
  3659. DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
  3660. var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm;
  3661. longtext = text1.length > text2.length ? text1 : text2;
  3662. shorttext = text1.length > text2.length ? text2 : text1;
  3663. if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
  3664. return null; // Pointless.
  3665. }
  3666. dmp = this; // 'this' becomes 'window' in a closure.
  3667. /**
  3668. * Does a substring of shorttext exist within longtext such that the substring
  3669. * is at least half the length of longtext?
  3670. * Closure, but does not reference any external variables.
  3671. * @param {string} longtext Longer string.
  3672. * @param {string} shorttext Shorter string.
  3673. * @param {number} i Start index of quarter length substring within longtext.
  3674. * @return {Array.<string>} Five element Array, containing the prefix of
  3675. * longtext, the suffix of longtext, the prefix of shorttext, the suffix
  3676. * of shorttext and the common middle. Or null if there was no match.
  3677. * @private
  3678. */
  3679. function diffHalfMatchI(longtext, shorttext, i) {
  3680. var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
  3681. // Start with a 1/4 length substring at position i as a seed.
  3682. seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
  3683. j = -1;
  3684. bestCommon = "";
  3685. while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
  3686. prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j));
  3687. suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j));
  3688. if (bestCommon.length < suffixLength + prefixLength) {
  3689. bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
  3690. bestLongtextA = longtext.substring(0, i - suffixLength);
  3691. bestLongtextB = longtext.substring(i + prefixLength);
  3692. bestShorttextA = shorttext.substring(0, j - suffixLength);
  3693. bestShorttextB = shorttext.substring(j + prefixLength);
  3694. }
  3695. }
  3696. if (bestCommon.length * 2 >= longtext.length) {
  3697. return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon];
  3698. } else {
  3699. return null;
  3700. }
  3701. }
  3702. // First check if the second quarter is the seed for a half-match.
  3703. hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4));
  3704. // Check again based on the third quarter.
  3705. hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2));
  3706. if (!hm1 && !hm2) {
  3707. return null;
  3708. } else if (!hm2) {
  3709. hm = hm1;
  3710. } else if (!hm1) {
  3711. hm = hm2;
  3712. } else {
  3713. // Both matched. Select the longest.
  3714. hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
  3715. }
  3716. // A half-match was found, sort out the return data.
  3717. if (text1.length > text2.length) {
  3718. text1A = hm[0];
  3719. text1B = hm[1];
  3720. text2A = hm[2];
  3721. text2B = hm[3];
  3722. } else {
  3723. text2A = hm[0];
  3724. text2B = hm[1];
  3725. text1A = hm[2];
  3726. text1B = hm[3];
  3727. }
  3728. midCommon = hm[4];
  3729. return [text1A, text1B, text2A, text2B, midCommon];
  3730. };
  3731. /**
  3732. * Do a quick line-level diff on both strings, then rediff the parts for
  3733. * greater accuracy.
  3734. * This speedup can produce non-minimal diffs.
  3735. * @param {string} text1 Old string to be diffed.
  3736. * @param {string} text2 New string to be diffed.
  3737. * @param {number} deadline Time when the diff should be complete by.
  3738. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3739. * @private
  3740. */
  3741. DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
  3742. var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j;
  3743. // Scan the text on a line-by-line basis first.
  3744. a = this.diffLinesToChars(text1, text2);
  3745. text1 = a.chars1;
  3746. text2 = a.chars2;
  3747. linearray = a.lineArray;
  3748. diffs = this.DiffMain(text1, text2, false, deadline);
  3749. // Convert the diff back to original text.
  3750. this.diffCharsToLines(diffs, linearray);
  3751. // Eliminate freak matches (e.g. blank lines)
  3752. this.diffCleanupSemantic(diffs);
  3753. // Rediff any replacement blocks, this time character-by-character.
  3754. // Add a dummy entry at the end.
  3755. diffs.push([DIFF_EQUAL, ""]);
  3756. pointer = 0;
  3757. countDelete = 0;
  3758. countInsert = 0;
  3759. textDelete = "";
  3760. textInsert = "";
  3761. while (pointer < diffs.length) {
  3762. switch (diffs[pointer][0]) {
  3763. case DIFF_INSERT:
  3764. countInsert++;
  3765. textInsert += diffs[pointer][1];
  3766. break;
  3767. case DIFF_DELETE:
  3768. countDelete++;
  3769. textDelete += diffs[pointer][1];
  3770. break;
  3771. case DIFF_EQUAL:
  3772. // Upon reaching an equality, check for prior redundancies.
  3773. if (countDelete >= 1 && countInsert >= 1) {
  3774. // Delete the offending records and add the merged ones.
  3775. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);
  3776. pointer = pointer - countDelete - countInsert;
  3777. a = this.DiffMain(textDelete, textInsert, false, deadline);
  3778. for (j = a.length - 1; j >= 0; j--) {
  3779. diffs.splice(pointer, 0, a[j]);
  3780. }
  3781. pointer = pointer + a.length;
  3782. }
  3783. countInsert = 0;
  3784. countDelete = 0;
  3785. textDelete = "";
  3786. textInsert = "";
  3787. break;
  3788. }
  3789. pointer++;
  3790. }
  3791. diffs.pop(); // Remove the dummy entry at the end.
  3792. return diffs;
  3793. };
  3794. /**
  3795. * Find the 'middle snake' of a diff, split the problem in two
  3796. * and return the recursively constructed diff.
  3797. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  3798. * @param {string} text1 Old string to be diffed.
  3799. * @param {string} text2 New string to be diffed.
  3800. * @param {number} deadline Time at which to bail if not yet complete.
  3801. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3802. * @private
  3803. */
  3804. DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
  3805. var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
  3806. // Cache the text lengths to prevent multiple calls.
  3807. text1Length = text1.length;
  3808. text2Length = text2.length;
  3809. maxD = Math.ceil((text1Length + text2Length) / 2);
  3810. vOffset = maxD;
  3811. vLength = 2 * maxD;
  3812. v1 = new Array(vLength);
  3813. v2 = new Array(vLength);
  3814. // Setting all elements to -1 is faster in Chrome & Firefox than mixing
  3815. // integers and undefined.
  3816. for (x = 0; x < vLength; x++) {
  3817. v1[x] = -1;
  3818. v2[x] = -1;
  3819. }
  3820. v1[vOffset + 1] = 0;
  3821. v2[vOffset + 1] = 0;
  3822. delta = text1Length - text2Length;
  3823. // If the total number of characters is odd, then the front path will collide
  3824. // with the reverse path.
  3825. front = delta % 2 !== 0;
  3826. // Offsets for start and end of k loop.
  3827. // Prevents mapping of space beyond the grid.
  3828. k1start = 0;
  3829. k1end = 0;
  3830. k2start = 0;
  3831. k2end = 0;
  3832. for (d = 0; d < maxD; d++) {
  3833. // Bail out if deadline is reached.
  3834. if (new Date().getTime() > deadline) {
  3835. break;
  3836. }
  3837. // Walk the front path one step.
  3838. for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
  3839. k1Offset = vOffset + k1;
  3840. if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {
  3841. x1 = v1[k1Offset + 1];
  3842. } else {
  3843. x1 = v1[k1Offset - 1] + 1;
  3844. }
  3845. y1 = x1 - k1;
  3846. while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
  3847. x1++;
  3848. y1++;
  3849. }
  3850. v1[k1Offset] = x1;
  3851. if (x1 > text1Length) {
  3852. // Ran off the right of the graph.
  3853. k1end += 2;
  3854. } else if (y1 > text2Length) {
  3855. // Ran off the bottom of the graph.
  3856. k1start += 2;
  3857. } else if (front) {
  3858. k2Offset = vOffset + delta - k1;
  3859. if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
  3860. // Mirror x2 onto top-left coordinate system.
  3861. x2 = text1Length - v2[k2Offset];
  3862. if (x1 >= x2) {
  3863. // Overlap detected.
  3864. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  3865. }
  3866. }
  3867. }
  3868. }
  3869. // Walk the reverse path one step.
  3870. for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
  3871. k2Offset = vOffset + k2;
  3872. if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {
  3873. x2 = v2[k2Offset + 1];
  3874. } else {
  3875. x2 = v2[k2Offset - 1] + 1;
  3876. }
  3877. y2 = x2 - k2;
  3878. while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {
  3879. x2++;
  3880. y2++;
  3881. }
  3882. v2[k2Offset] = x2;
  3883. if (x2 > text1Length) {
  3884. // Ran off the left of the graph.
  3885. k2end += 2;
  3886. } else if (y2 > text2Length) {
  3887. // Ran off the top of the graph.
  3888. k2start += 2;
  3889. } else if (!front) {
  3890. k1Offset = vOffset + delta - k2;
  3891. if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
  3892. x1 = v1[k1Offset];
  3893. y1 = vOffset + x1 - k1Offset;
  3894. // Mirror x2 onto top-left coordinate system.
  3895. x2 = text1Length - x2;
  3896. if (x1 >= x2) {
  3897. // Overlap detected.
  3898. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  3899. }
  3900. }
  3901. }
  3902. }
  3903. }
  3904. // Diff took too long and hit the deadline or
  3905. // number of diffs equals number of characters, no commonality at all.
  3906. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  3907. };
  3908. /**
  3909. * Given the location of the 'middle snake', split the diff in two parts
  3910. * and recurse.
  3911. * @param {string} text1 Old string to be diffed.
  3912. * @param {string} text2 New string to be diffed.
  3913. * @param {number} x Index of split point in text1.
  3914. * @param {number} y Index of split point in text2.
  3915. * @param {number} deadline Time at which to bail if not yet complete.
  3916. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3917. * @private
  3918. */
  3919. DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
  3920. var text1a, text1b, text2a, text2b, diffs, diffsb;
  3921. text1a = text1.substring(0, x);
  3922. text2a = text2.substring(0, y);
  3923. text1b = text1.substring(x);
  3924. text2b = text2.substring(y);
  3925. // Compute both diffs serially.
  3926. diffs = this.DiffMain(text1a, text2a, false, deadline);
  3927. diffsb = this.DiffMain(text1b, text2b, false, deadline);
  3928. return diffs.concat(diffsb);
  3929. };
  3930. /**
  3931. * Reduce the number of edits by eliminating semantically trivial equalities.
  3932. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3933. */
  3934. DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
  3935. var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
  3936. changes = false;
  3937. equalities = []; // Stack of indices where equalities are found.
  3938. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  3939. /** @type {?string} */
  3940. lastequality = null;
  3941. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  3942. pointer = 0; // Index of current position.
  3943. // Number of characters that changed prior to the equality.
  3944. lengthInsertions1 = 0;
  3945. lengthDeletions1 = 0;
  3946. // Number of characters that changed after the equality.
  3947. lengthInsertions2 = 0;
  3948. lengthDeletions2 = 0;
  3949. while (pointer < diffs.length) {
  3950. if (diffs[pointer][0] === DIFF_EQUAL) {
  3951. // Equality found.
  3952. equalities[equalitiesLength++] = pointer;
  3953. lengthInsertions1 = lengthInsertions2;
  3954. lengthDeletions1 = lengthDeletions2;
  3955. lengthInsertions2 = 0;
  3956. lengthDeletions2 = 0;
  3957. lastequality = diffs[pointer][1];
  3958. } else {
  3959. // An insertion or deletion.
  3960. if (diffs[pointer][0] === DIFF_INSERT) {
  3961. lengthInsertions2 += diffs[pointer][1].length;
  3962. } else {
  3963. lengthDeletions2 += diffs[pointer][1].length;
  3964. }
  3965. // Eliminate an equality that is smaller or equal to the edits on both
  3966. // sides of it.
  3967. if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {
  3968. // Duplicate record.
  3969. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
  3970. // Change second copy to insert.
  3971. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  3972. // Throw away the equality we just deleted.
  3973. equalitiesLength--;
  3974. // Throw away the previous equality (it needs to be reevaluated).
  3975. equalitiesLength--;
  3976. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  3977. // Reset the counters.
  3978. lengthInsertions1 = 0;
  3979. lengthDeletions1 = 0;
  3980. lengthInsertions2 = 0;
  3981. lengthDeletions2 = 0;
  3982. lastequality = null;
  3983. changes = true;
  3984. }
  3985. }
  3986. pointer++;
  3987. }
  3988. // Normalize the diff.
  3989. if (changes) {
  3990. this.diffCleanupMerge(diffs);
  3991. }
  3992. // Find any overlaps between deletions and insertions.
  3993. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  3994. // -> <del>abc</del>xxx<ins>def</ins>
  3995. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  3996. // -> <ins>def</ins>xxx<del>abc</del>
  3997. // Only extract an overlap if it is as big as the edit ahead or behind it.
  3998. pointer = 1;
  3999. while (pointer < diffs.length) {
  4000. if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
  4001. deletion = diffs[pointer - 1][1];
  4002. insertion = diffs[pointer][1];
  4003. overlapLength1 = this.diffCommonOverlap(deletion, insertion);
  4004. overlapLength2 = this.diffCommonOverlap(insertion, deletion);
  4005. if (overlapLength1 >= overlapLength2) {
  4006. if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {
  4007. // Overlap found. Insert an equality and trim the surrounding edits.
  4008. diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);
  4009. diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);
  4010. diffs[pointer + 1][1] = insertion.substring(overlapLength1);
  4011. pointer++;
  4012. }
  4013. } else {
  4014. if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {
  4015. // Reverse overlap found.
  4016. // Insert an equality and swap and trim the surrounding edits.
  4017. diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);
  4018. diffs[pointer - 1][0] = DIFF_INSERT;
  4019. diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);
  4020. diffs[pointer + 1][0] = DIFF_DELETE;
  4021. diffs[pointer + 1][1] = deletion.substring(overlapLength2);
  4022. pointer++;
  4023. }
  4024. }
  4025. pointer++;
  4026. }
  4027. pointer++;
  4028. }
  4029. };
  4030. /**
  4031. * Determine if the suffix of one string is the prefix of another.
  4032. * @param {string} text1 First string.
  4033. * @param {string} text2 Second string.
  4034. * @return {number} The number of characters common to the end of the first
  4035. * string and the start of the second string.
  4036. * @private
  4037. */
  4038. DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
  4039. var text1Length, text2Length, textLength, best, length, pattern, found;
  4040. // Cache the text lengths to prevent multiple calls.
  4041. text1Length = text1.length;
  4042. text2Length = text2.length;
  4043. // Eliminate the null case.
  4044. if (text1Length === 0 || text2Length === 0) {
  4045. return 0;
  4046. }
  4047. // Truncate the longer string.
  4048. if (text1Length > text2Length) {
  4049. text1 = text1.substring(text1Length - text2Length);
  4050. } else if (text1Length < text2Length) {
  4051. text2 = text2.substring(0, text1Length);
  4052. }
  4053. textLength = Math.min(text1Length, text2Length);
  4054. // Quick check for the worst case.
  4055. if (text1 === text2) {
  4056. return textLength;
  4057. }
  4058. // Start by looking for a single character match
  4059. // and increase length until no match is found.
  4060. // Performance analysis: https://neil.fraser.name/news/2010/11/04/
  4061. best = 0;
  4062. length = 1;
  4063. while (true) {
  4064. pattern = text1.substring(textLength - length);
  4065. found = text2.indexOf(pattern);
  4066. if (found === -1) {
  4067. return best;
  4068. }
  4069. length += found;
  4070. if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {
  4071. best = length;
  4072. length++;
  4073. }
  4074. }
  4075. };
  4076. /**
  4077. * Split two texts into an array of strings. Reduce the texts to a string of
  4078. * hashes where each Unicode character represents one line.
  4079. * @param {string} text1 First string.
  4080. * @param {string} text2 Second string.
  4081. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
  4082. * An object containing the encoded text1, the encoded text2 and
  4083. * the array of unique strings.
  4084. * The zeroth element of the array of unique strings is intentionally blank.
  4085. * @private
  4086. */
  4087. DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
  4088. var lineArray, lineHash, chars1, chars2;
  4089. lineArray = []; // E.g. lineArray[4] === 'Hello\n'
  4090. lineHash = {}; // E.g. lineHash['Hello\n'] === 4
  4091. // '\x00' is a valid character, but various debuggers don't like it.
  4092. // So we'll insert a junk entry to avoid generating a null character.
  4093. lineArray[0] = "";
  4094. /**
  4095. * Split a text into an array of strings. Reduce the texts to a string of
  4096. * hashes where each Unicode character represents one line.
  4097. * Modifies linearray and linehash through being a closure.
  4098. * @param {string} text String to encode.
  4099. * @return {string} Encoded string.
  4100. * @private
  4101. */
  4102. function diffLinesToCharsMunge(text) {
  4103. var chars, lineStart, lineEnd, lineArrayLength, line;
  4104. chars = "";
  4105. // Walk the text, pulling out a substring for each line.
  4106. // text.split('\n') would would temporarily double our memory footprint.
  4107. // Modifying text would create many large strings to garbage collect.
  4108. lineStart = 0;
  4109. lineEnd = -1;
  4110. // Keeping our own length variable is faster than looking it up.
  4111. lineArrayLength = lineArray.length;
  4112. while (lineEnd < text.length - 1) {
  4113. lineEnd = text.indexOf("\n", lineStart);
  4114. if (lineEnd === -1) {
  4115. lineEnd = text.length - 1;
  4116. }
  4117. line = text.substring(lineStart, lineEnd + 1);
  4118. lineStart = lineEnd + 1;
  4119. var lineHashExists = lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined;
  4120. if (lineHashExists) {
  4121. chars += String.fromCharCode(lineHash[line]);
  4122. } else {
  4123. chars += String.fromCharCode(lineArrayLength);
  4124. lineHash[line] = lineArrayLength;
  4125. lineArray[lineArrayLength++] = line;
  4126. }
  4127. }
  4128. return chars;
  4129. }
  4130. chars1 = diffLinesToCharsMunge(text1);
  4131. chars2 = diffLinesToCharsMunge(text2);
  4132. return {
  4133. chars1: chars1,
  4134. chars2: chars2,
  4135. lineArray: lineArray
  4136. };
  4137. };
  4138. /**
  4139. * Rehydrate the text in a diff from a string of line hashes to real lines of
  4140. * text.
  4141. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  4142. * @param {!Array.<string>} lineArray Array of unique strings.
  4143. * @private
  4144. */
  4145. DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
  4146. var x, chars, text, y;
  4147. for (x = 0; x < diffs.length; x++) {
  4148. chars = diffs[x][1];
  4149. text = [];
  4150. for (y = 0; y < chars.length; y++) {
  4151. text[y] = lineArray[chars.charCodeAt(y)];
  4152. }
  4153. diffs[x][1] = text.join("");
  4154. }
  4155. };
  4156. /**
  4157. * Reorder and merge like edit sections. Merge equalities.
  4158. * Any edit section can move as long as it doesn't cross an equality.
  4159. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  4160. */
  4161. DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
  4162. var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position;
  4163. diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
  4164. pointer = 0;
  4165. countDelete = 0;
  4166. countInsert = 0;
  4167. textDelete = "";
  4168. textInsert = "";
  4169. while (pointer < diffs.length) {
  4170. switch (diffs[pointer][0]) {
  4171. case DIFF_INSERT:
  4172. countInsert++;
  4173. textInsert += diffs[pointer][1];
  4174. pointer++;
  4175. break;
  4176. case DIFF_DELETE:
  4177. countDelete++;
  4178. textDelete += diffs[pointer][1];
  4179. pointer++;
  4180. break;
  4181. case DIFF_EQUAL:
  4182. // Upon reaching an equality, check for prior redundancies.
  4183. if (countDelete + countInsert > 1) {
  4184. if (countDelete !== 0 && countInsert !== 0) {
  4185. // Factor out any common prefixes.
  4186. commonlength = this.diffCommonPrefix(textInsert, textDelete);
  4187. if (commonlength !== 0) {
  4188. if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {
  4189. diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);
  4190. } else {
  4191. diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);
  4192. pointer++;
  4193. }
  4194. textInsert = textInsert.substring(commonlength);
  4195. textDelete = textDelete.substring(commonlength);
  4196. }
  4197. // Factor out any common suffixies.
  4198. commonlength = this.diffCommonSuffix(textInsert, textDelete);
  4199. if (commonlength !== 0) {
  4200. diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];
  4201. textInsert = textInsert.substring(0, textInsert.length - commonlength);
  4202. textDelete = textDelete.substring(0, textDelete.length - commonlength);
  4203. }
  4204. }
  4205. // Delete the offending records and add the merged ones.
  4206. if (countDelete === 0) {
  4207. diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]);
  4208. } else if (countInsert === 0) {
  4209. diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]);
  4210. } else {
  4211. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]);
  4212. }
  4213. pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
  4214. } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
  4215. // Merge this equality with the previous one.
  4216. diffs[pointer - 1][1] += diffs[pointer][1];
  4217. diffs.splice(pointer, 1);
  4218. } else {
  4219. pointer++;
  4220. }
  4221. countInsert = 0;
  4222. countDelete = 0;
  4223. textDelete = "";
  4224. textInsert = "";
  4225. break;
  4226. }
  4227. }
  4228. if (diffs[diffs.length - 1][1] === "") {
  4229. diffs.pop(); // Remove the dummy entry at the end.
  4230. }
  4231. // Second pass: look for single edits surrounded on both sides by equalities
  4232. // which can be shifted sideways to eliminate an equality.
  4233. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  4234. changes = false;
  4235. pointer = 1;
  4236. // Intentionally ignore the first and last element (don't need checking).
  4237. while (pointer < diffs.length - 1) {
  4238. if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
  4239. diffPointer = diffs[pointer][1];
  4240. position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length);
  4241. // This is a single edit surrounded by equalities.
  4242. if (position === diffs[pointer - 1][1]) {
  4243. // Shift the edit over the previous equality.
  4244. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
  4245. diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
  4246. diffs.splice(pointer - 1, 1);
  4247. changes = true;
  4248. } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
  4249. // Shift the edit over the next equality.
  4250. diffs[pointer - 1][1] += diffs[pointer + 1][1];
  4251. diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
  4252. diffs.splice(pointer + 1, 1);
  4253. changes = true;
  4254. }
  4255. }
  4256. pointer++;
  4257. }
  4258. // If shifts were made, the diff needs reordering and another shift sweep.
  4259. if (changes) {
  4260. this.diffCleanupMerge(diffs);
  4261. }
  4262. };
  4263. return function (o, n) {
  4264. var diff, output, text;
  4265. diff = new DiffMatchPatch();
  4266. output = diff.DiffMain(o, n);
  4267. diff.diffCleanupEfficiency(output);
  4268. text = diff.diffPrettyHtml(output);
  4269. return text;
  4270. };
  4271. }();
  4272. }((function() { return this; }())));