qunit-2.17.2.js 242 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392
  1. /*!
  2. * QUnit 2.17.2
  3. * https://qunitjs.com/
  4. *
  5. * Copyright OpenJS Foundation and other contributors
  6. * Released under the MIT license
  7. * https://jquery.org/license
  8. */
  9. (function () {
  10. 'use strict';
  11. // Support IE 9-10, Safari 7, PhantomJS: Partial Map fallback.
  12. // Used by html.js (via fuzzysort.js), and test.js.
  13. //
  14. // FIXME: This check is broken. This file is embedded in the qunit.js closure,
  15. // thus the Map var is hoisted in that scope, and starts undefined (not a function).
  16. var Map = typeof Map === "function" ? Map : function StringMap() {
  17. var store = Object.create( null );
  18. var hasOwn = Object.prototype.hasOwnProperty;
  19. this.get = function( strKey ) {
  20. return store[ strKey ];
  21. };
  22. this.set = function( strKey, val ) {
  23. if ( !hasOwn.call( store, strKey ) ) {
  24. this.size++;
  25. }
  26. store[ strKey ] = val;
  27. return this;
  28. };
  29. this.delete = function( strKey ) {
  30. if ( hasOwn.call( store, strKey ) ) {
  31. delete store[ strKey ];
  32. this.size--;
  33. }
  34. };
  35. this.forEach = function( callback ) {
  36. for ( var strKey in store ) {
  37. callback( store[ strKey ], strKey );
  38. }
  39. };
  40. this.clear = function() {
  41. store = Object.create( null );
  42. this.size = 0;
  43. };
  44. this.size = 0;
  45. };
  46. function _typeof(obj) {
  47. "@babel/helpers - typeof";
  48. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  49. _typeof = function (obj) {
  50. return typeof obj;
  51. };
  52. } else {
  53. _typeof = function (obj) {
  54. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  55. };
  56. }
  57. return _typeof(obj);
  58. }
  59. function _classCallCheck(instance, Constructor) {
  60. if (!(instance instanceof Constructor)) {
  61. throw new TypeError("Cannot call a class as a function");
  62. }
  63. }
  64. function _defineProperties(target, props) {
  65. for (var i = 0; i < props.length; i++) {
  66. var descriptor = props[i];
  67. descriptor.enumerable = descriptor.enumerable || false;
  68. descriptor.configurable = true;
  69. if ("value" in descriptor) descriptor.writable = true;
  70. Object.defineProperty(target, descriptor.key, descriptor);
  71. }
  72. }
  73. function _createClass(Constructor, protoProps, staticProps) {
  74. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  75. if (staticProps) _defineProperties(Constructor, staticProps);
  76. return Constructor;
  77. }
  78. function _slicedToArray(arr, i) {
  79. return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
  80. }
  81. function _toConsumableArray(arr) {
  82. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  83. }
  84. function _arrayWithoutHoles(arr) {
  85. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  86. }
  87. function _arrayWithHoles(arr) {
  88. if (Array.isArray(arr)) return arr;
  89. }
  90. function _iterableToArray(iter) {
  91. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  92. }
  93. function _iterableToArrayLimit(arr, i) {
  94. var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  95. if (_i == null) return;
  96. var _arr = [];
  97. var _n = true;
  98. var _d = false;
  99. var _s, _e;
  100. try {
  101. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  102. _arr.push(_s.value);
  103. if (i && _arr.length === i) break;
  104. }
  105. } catch (err) {
  106. _d = true;
  107. _e = err;
  108. } finally {
  109. try {
  110. if (!_n && _i["return"] != null) _i["return"]();
  111. } finally {
  112. if (_d) throw _e;
  113. }
  114. }
  115. return _arr;
  116. }
  117. function _unsupportedIterableToArray(o, minLen) {
  118. if (!o) return;
  119. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  120. var n = Object.prototype.toString.call(o).slice(8, -1);
  121. if (n === "Object" && o.constructor) n = o.constructor.name;
  122. if (n === "Map" || n === "Set") return Array.from(o);
  123. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  124. }
  125. function _arrayLikeToArray(arr, len) {
  126. if (len == null || len > arr.length) len = arr.length;
  127. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  128. return arr2;
  129. }
  130. function _nonIterableSpread() {
  131. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  132. }
  133. function _nonIterableRest() {
  134. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  135. }
  136. function _createForOfIteratorHelper(o, allowArrayLike) {
  137. var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  138. if (!it) {
  139. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  140. if (it) o = it;
  141. var i = 0;
  142. var F = function () {};
  143. return {
  144. s: F,
  145. n: function () {
  146. if (i >= o.length) return {
  147. done: true
  148. };
  149. return {
  150. done: false,
  151. value: o[i++]
  152. };
  153. },
  154. e: function (e) {
  155. throw e;
  156. },
  157. f: F
  158. };
  159. }
  160. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  161. }
  162. var normalCompletion = true,
  163. didErr = false,
  164. err;
  165. return {
  166. s: function () {
  167. it = it.call(o);
  168. },
  169. n: function () {
  170. var step = it.next();
  171. normalCompletion = step.done;
  172. return step;
  173. },
  174. e: function (e) {
  175. didErr = true;
  176. err = e;
  177. },
  178. f: function () {
  179. try {
  180. if (!normalCompletion && it.return != null) it.return();
  181. } finally {
  182. if (didErr) throw err;
  183. }
  184. }
  185. };
  186. }
  187. /*
  188. https://github.com/ungap/global-this/blob/v0.4.4/esm/index.js
  189. Copyright (c) 2020, Andrea Giammarchi, @WebReflection
  190. Permission to use, copy, modify, and/or distribute this software for any
  191. purpose with or without fee is hereby granted, provided that the above
  192. copyright notice and this permission notice appear in all copies.
  193. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  194. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  195. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  196. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  197. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  198. OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  199. PERFORMANCE OF THIS SOFTWARE.
  200. -------
  201. Patches for use in QUnit:
  202. - 2021-02-25: Export as module only, don't change global scope as QUnit must not
  203. affect the host context (e.g. people may test their application intentionally
  204. with different or no polyfills and we must not affect that).
  205. */
  206. var foundGlobalThis;
  207. (function (Object) {
  208. if ((typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis)) === "object") {
  209. foundGlobalThis = globalThis;
  210. } else {
  211. var get = function get() {
  212. foundGlobalThis = this || self;
  213. delete Object.prototype._T_;
  214. };
  215. this ? get() : (Object.defineProperty(Object.prototype, "_T_", {
  216. configurable: true,
  217. get: get
  218. }), _T_);
  219. }
  220. })(Object);
  221. var globalThis$1 = foundGlobalThis;
  222. var window$1 = globalThis$1.window;
  223. var self$1 = globalThis$1.self;
  224. var console$1 = globalThis$1.console;
  225. var setTimeout$1 = globalThis$1.setTimeout;
  226. var clearTimeout = globalThis$1.clearTimeout;
  227. var document = window$1 && window$1.document;
  228. var navigator = window$1 && window$1.navigator;
  229. var localSessionStorage = function () {
  230. var x = "qunit-test-string";
  231. try {
  232. globalThis$1.sessionStorage.setItem(x, x);
  233. globalThis$1.sessionStorage.removeItem(x);
  234. return globalThis$1.sessionStorage;
  235. } catch (e) {
  236. return undefined;
  237. }
  238. }();
  239. // Detect if the console object exists and no-op otherwise.
  240. // This allows support for IE 9, which doesn't have a console
  241. // object if the developer tools are not open.
  242. // Support: IE 9
  243. // Function#bind is supported, but no console.log.bind().
  244. // Support: SpiderMonkey (mozjs 68+)
  245. // The console object has a log method, but no warn method.
  246. var Logger = {
  247. warn: console$1 ? Function.prototype.bind.call(console$1.warn || console$1.log, console$1) : function () {}
  248. };
  249. var toString = Object.prototype.toString;
  250. var hasOwn$1 = Object.prototype.hasOwnProperty;
  251. var now = Date.now || function () {
  252. return new Date().getTime();
  253. };
  254. var nativePerf = getNativePerf();
  255. function getNativePerf() {
  256. if (window$1 && typeof window$1.performance !== "undefined" && typeof window$1.performance.mark === "function" && typeof window$1.performance.measure === "function") {
  257. return window$1.performance;
  258. } else {
  259. return undefined;
  260. }
  261. }
  262. var performance = {
  263. now: nativePerf ? nativePerf.now.bind(nativePerf) : now,
  264. measure: nativePerf ? function (comment, startMark, endMark) {
  265. // `performance.measure` may fail if the mark could not be found.
  266. // reasons a specific mark could not be found include: outside code invoking `performance.clearMarks()`
  267. try {
  268. nativePerf.measure(comment, startMark, endMark);
  269. } catch (ex) {
  270. Logger.warn("performance.measure could not be executed because of ", ex.message);
  271. }
  272. } : function () {},
  273. mark: nativePerf ? nativePerf.mark.bind(nativePerf) : function () {}
  274. }; // Returns a new Array with the elements that are in a but not in b
  275. function diff(a, b) {
  276. var result = a.slice();
  277. for (var i = 0; i < result.length; i++) {
  278. for (var j = 0; j < b.length; j++) {
  279. if (result[i] === b[j]) {
  280. result.splice(i, 1);
  281. i--;
  282. break;
  283. }
  284. }
  285. }
  286. return result;
  287. }
  288. /**
  289. * Determines whether an element exists in a given array or not.
  290. *
  291. * @method inArray
  292. * @param {any} elem
  293. * @param {Array} array
  294. * @return {boolean}
  295. */
  296. function inArray(elem, array) {
  297. return array.indexOf(elem) !== -1;
  298. }
  299. /**
  300. * Makes a clone of an object using only Array or Object as base,
  301. * and copies over the own enumerable properties.
  302. *
  303. * @param {Object} obj
  304. * @return {Object} New object with only the own properties (recursively).
  305. */
  306. function objectValues(obj) {
  307. var vals = is("array", obj) ? [] : {};
  308. for (var key in obj) {
  309. if (hasOwn$1.call(obj, key)) {
  310. var val = obj[key];
  311. vals[key] = val === Object(val) ? objectValues(val) : val;
  312. }
  313. }
  314. return vals;
  315. }
  316. function extend(a, b, undefOnly) {
  317. for (var prop in b) {
  318. if (hasOwn$1.call(b, prop)) {
  319. if (b[prop] === undefined) {
  320. delete a[prop];
  321. } else if (!(undefOnly && typeof a[prop] !== "undefined")) {
  322. a[prop] = b[prop];
  323. }
  324. }
  325. }
  326. return a;
  327. }
  328. function objectType(obj) {
  329. if (typeof obj === "undefined") {
  330. return "undefined";
  331. } // Consider: typeof null === object
  332. if (obj === null) {
  333. return "null";
  334. }
  335. var match = toString.call(obj).match(/^\[object\s(.*)\]$/);
  336. var type = match && match[1];
  337. switch (type) {
  338. case "Number":
  339. if (isNaN(obj)) {
  340. return "nan";
  341. }
  342. return "number";
  343. case "String":
  344. case "Boolean":
  345. case "Array":
  346. case "Set":
  347. case "Map":
  348. case "Date":
  349. case "RegExp":
  350. case "Function":
  351. case "Symbol":
  352. return type.toLowerCase();
  353. default:
  354. return _typeof(obj);
  355. }
  356. } // Safe object type checking
  357. function is(type, obj) {
  358. return objectType(obj) === type;
  359. } // Based on Java's String.hashCode, a simple but not
  360. // rigorously collision resistant hashing function
  361. function generateHash(module, testName) {
  362. var str = module + "\x1C" + testName;
  363. var hash = 0;
  364. for (var i = 0; i < str.length; i++) {
  365. hash = (hash << 5) - hash + str.charCodeAt(i);
  366. hash |= 0;
  367. } // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
  368. // strictly necessary but increases user understanding that the id is a SHA-like hash
  369. var hex = (0x100000000 + hash).toString(16);
  370. if (hex.length < 8) {
  371. hex = "0000000" + hex;
  372. }
  373. return hex.slice(-8);
  374. }
  375. /**
  376. * Converts an error into a simple string for comparisons.
  377. *
  378. * @param {Error|any} error
  379. * @return {string}
  380. */
  381. function errorString(error) {
  382. // Use String() instead of toString() to handle non-object values like undefined or null.
  383. var resultErrorString = String(error); // If the error wasn't a subclass of Error but something like
  384. // an object literal with name and message properties...
  385. if (resultErrorString.slice(0, 7) === "[object") {
  386. // Based on https://es5.github.io/#x15.11.4.4
  387. return (error.name || "Error") + (error.message ? ": ".concat(error.message) : "");
  388. } else {
  389. return resultErrorString;
  390. }
  391. }
  392. // Authors: Philippe Rathé <prathe@gmail.com>, David Chan <david@troi.org>
  393. var equiv = (function () {
  394. // Value pairs queued for comparison. Used for breadth-first processing order, recursion
  395. // detection and avoiding repeated comparison (see below for details).
  396. // Elements are { a: val, b: val }.
  397. var pairs = [];
  398. var getProto = Object.getPrototypeOf || function (obj) {
  399. return obj.__proto__;
  400. };
  401. function useStrictEquality(a, b) {
  402. // This only gets called if a and b are not strict equal, and is used to compare on
  403. // the primitive values inside object wrappers. For example:
  404. // `var i = 1;`
  405. // `var j = new Number(1);`
  406. // Neither a nor b can be null, as a !== b and they have the same type.
  407. if (_typeof(a) === "object") {
  408. a = a.valueOf();
  409. }
  410. if (_typeof(b) === "object") {
  411. b = b.valueOf();
  412. }
  413. return a === b;
  414. }
  415. function compareConstructors(a, b) {
  416. var protoA = getProto(a);
  417. var protoB = getProto(b); // Comparing constructors is more strict than using `instanceof`
  418. if (a.constructor === b.constructor) {
  419. return true;
  420. } // Ref #851
  421. // If the obj prototype descends from a null constructor, treat it
  422. // as a null prototype.
  423. if (protoA && protoA.constructor === null) {
  424. protoA = null;
  425. }
  426. if (protoB && protoB.constructor === null) {
  427. protoB = null;
  428. } // Allow objects with no prototype to be equivalent to
  429. // objects with Object as their constructor.
  430. if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) {
  431. return true;
  432. }
  433. return false;
  434. }
  435. function getRegExpFlags(regexp) {
  436. return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0];
  437. }
  438. function isContainer(val) {
  439. return ["object", "array", "map", "set"].indexOf(objectType(val)) !== -1;
  440. }
  441. function breadthFirstCompareChild(a, b) {
  442. // If a is a container not reference-equal to b, postpone the comparison to the
  443. // end of the pairs queue -- unless (a, b) has been seen before, in which case skip
  444. // over the pair.
  445. if (a === b) {
  446. return true;
  447. }
  448. if (!isContainer(a)) {
  449. return typeEquiv(a, b);
  450. }
  451. if (pairs.every(function (pair) {
  452. return pair.a !== a || pair.b !== b;
  453. })) {
  454. // Not yet started comparing this pair
  455. pairs.push({
  456. a: a,
  457. b: b
  458. });
  459. }
  460. return true;
  461. }
  462. var callbacks = {
  463. "string": useStrictEquality,
  464. "boolean": useStrictEquality,
  465. "number": useStrictEquality,
  466. "null": useStrictEquality,
  467. "undefined": useStrictEquality,
  468. "symbol": useStrictEquality,
  469. "date": useStrictEquality,
  470. "nan": function nan() {
  471. return true;
  472. },
  473. "regexp": function regexp(a, b) {
  474. return a.source === b.source && // Include flags in the comparison
  475. getRegExpFlags(a) === getRegExpFlags(b);
  476. },
  477. // abort (identical references / instance methods were skipped earlier)
  478. "function": function _function() {
  479. return false;
  480. },
  481. "array": function array(a, b) {
  482. var len = a.length;
  483. if (len !== b.length) {
  484. // Safe and faster
  485. return false;
  486. }
  487. for (var i = 0; i < len; i++) {
  488. // Compare non-containers; queue non-reference-equal containers
  489. if (!breadthFirstCompareChild(a[i], b[i])) {
  490. return false;
  491. }
  492. }
  493. return true;
  494. },
  495. // Define sets a and b to be equivalent if for each element aVal in a, there
  496. // is some element bVal in b such that aVal and bVal are equivalent. Element
  497. // repetitions are not counted, so these are equivalent:
  498. // a = new Set( [ {}, [], [] ] );
  499. // b = new Set( [ {}, {}, [] ] );
  500. "set": function set(a, b) {
  501. if (a.size !== b.size) {
  502. // This optimization has certain quirks because of the lack of
  503. // repetition counting. For instance, adding the same
  504. // (reference-identical) element to two equivalent sets can
  505. // make them non-equivalent.
  506. return false;
  507. }
  508. var outerEq = true;
  509. a.forEach(function (aVal) {
  510. // Short-circuit if the result is already known. (Using for...of
  511. // with a break clause would be cleaner here, but it would cause
  512. // a syntax error on older JavaScript implementations even if
  513. // Set is unused)
  514. if (!outerEq) {
  515. return;
  516. }
  517. var innerEq = false;
  518. b.forEach(function (bVal) {
  519. // Likewise, short-circuit if the result is already known
  520. if (innerEq) {
  521. return;
  522. } // Swap out the global pairs list, as the nested call to
  523. // innerEquiv will clobber its contents
  524. var parentPairs = pairs;
  525. if (innerEquiv(bVal, aVal)) {
  526. innerEq = true;
  527. } // Replace the global pairs list
  528. pairs = parentPairs;
  529. });
  530. if (!innerEq) {
  531. outerEq = false;
  532. }
  533. });
  534. return outerEq;
  535. },
  536. // Define maps a and b to be equivalent if for each key-value pair (aKey, aVal)
  537. // in a, there is some key-value pair (bKey, bVal) in b such that
  538. // [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not
  539. // counted, so these are equivalent:
  540. // a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] );
  541. // b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] );
  542. "map": function map(a, b) {
  543. if (a.size !== b.size) {
  544. // This optimization has certain quirks because of the lack of
  545. // repetition counting. For instance, adding the same
  546. // (reference-identical) key-value pair to two equivalent maps
  547. // can make them non-equivalent.
  548. return false;
  549. }
  550. var outerEq = true;
  551. a.forEach(function (aVal, aKey) {
  552. // Short-circuit if the result is already known. (Using for...of
  553. // with a break clause would be cleaner here, but it would cause
  554. // a syntax error on older JavaScript implementations even if
  555. // Map is unused)
  556. if (!outerEq) {
  557. return;
  558. }
  559. var innerEq = false;
  560. b.forEach(function (bVal, bKey) {
  561. // Likewise, short-circuit if the result is already known
  562. if (innerEq) {
  563. return;
  564. } // Swap out the global pairs list, as the nested call to
  565. // innerEquiv will clobber its contents
  566. var parentPairs = pairs;
  567. if (innerEquiv([bVal, bKey], [aVal, aKey])) {
  568. innerEq = true;
  569. } // Replace the global pairs list
  570. pairs = parentPairs;
  571. });
  572. if (!innerEq) {
  573. outerEq = false;
  574. }
  575. });
  576. return outerEq;
  577. },
  578. "object": function object(a, b) {
  579. if (compareConstructors(a, b) === false) {
  580. return false;
  581. }
  582. var aProperties = [];
  583. var bProperties = []; // Be strict: don't ensure hasOwnProperty and go deep
  584. for (var i in a) {
  585. // Collect a's properties
  586. aProperties.push(i); // Skip OOP methods that look the same
  587. if (a.constructor !== Object && typeof a.constructor !== "undefined" && typeof a[i] === "function" && typeof b[i] === "function" && a[i].toString() === b[i].toString()) {
  588. continue;
  589. } // Compare non-containers; queue non-reference-equal containers
  590. if (!breadthFirstCompareChild(a[i], b[i])) {
  591. return false;
  592. }
  593. }
  594. for (var _i in b) {
  595. // Collect b's properties
  596. bProperties.push(_i);
  597. } // Ensures identical properties name
  598. return typeEquiv(aProperties.sort(), bProperties.sort());
  599. }
  600. };
  601. function typeEquiv(a, b) {
  602. var type = objectType(a); // Callbacks for containers will append to the pairs queue to achieve breadth-first
  603. // search order. The pairs queue is also used to avoid reprocessing any pair of
  604. // containers that are reference-equal to a previously visited pair (a special case
  605. // this being recursion detection).
  606. //
  607. // Because of this approach, once typeEquiv returns a false value, it should not be
  608. // called again without clearing the pair queue else it may wrongly report a visited
  609. // pair as being equivalent.
  610. return objectType(b) === type && callbacks[type](a, b);
  611. }
  612. function innerEquiv(a, b) {
  613. // We're done when there's nothing more to compare
  614. if (arguments.length < 2) {
  615. return true;
  616. } // Clear the global pair queue and add the top-level values being compared
  617. pairs = [{
  618. a: a,
  619. b: b
  620. }];
  621. for (var i = 0; i < pairs.length; i++) {
  622. var pair = pairs[i]; // Perform type-specific comparison on any pairs that are not strictly
  623. // equal. For container types, that comparison will postpone comparison
  624. // of any sub-container pair to the end of the pair queue. This gives
  625. // breadth-first search order. It also avoids the reprocessing of
  626. // reference-equal siblings, cousins etc, which can have a significant speed
  627. // impact when comparing a container of small objects each of which has a
  628. // reference to the same (singleton) large object.
  629. if (pair.a !== pair.b && !typeEquiv(pair.a, pair.b)) {
  630. return false;
  631. }
  632. } // ...across all consecutive argument pairs
  633. return arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1));
  634. }
  635. return function () {
  636. var result = innerEquiv.apply(void 0, arguments); // Release any retained objects
  637. pairs.length = 0;
  638. return result;
  639. };
  640. })();
  641. /**
  642. * Config object: Maintain internal state
  643. * Later exposed as QUnit.config
  644. * `config` initialized at top of scope
  645. */
  646. var config = {
  647. // The queue of tests to run
  648. queue: [],
  649. stats: {
  650. all: 0,
  651. bad: 0,
  652. testCount: 0
  653. },
  654. // Block until document ready
  655. blocking: true,
  656. // whether or not to fail when there are zero tests
  657. // defaults to `true`
  658. failOnZeroTests: true,
  659. // By default, run previously failed tests first
  660. // very useful in combination with "Hide passed tests" checked
  661. reorder: true,
  662. // By default, modify document.title when suite is done
  663. altertitle: true,
  664. // HTML Reporter: collapse every test except the first failing test
  665. // If false, all failing tests will be expanded
  666. collapse: true,
  667. // By default, scroll to top of the page when suite is done
  668. scrolltop: true,
  669. // Depth up-to which object will be dumped
  670. maxDepth: 5,
  671. // When enabled, all tests must call expect()
  672. requireExpects: false,
  673. // Placeholder for user-configurable form-exposed URL parameters
  674. urlConfig: [],
  675. // Set of all modules.
  676. modules: [],
  677. // The first unnamed module
  678. currentModule: {
  679. name: "",
  680. tests: [],
  681. childModules: [],
  682. testsRun: 0,
  683. testsIgnored: 0,
  684. hooks: {
  685. before: [],
  686. beforeEach: [],
  687. afterEach: [],
  688. after: []
  689. }
  690. },
  691. callbacks: {},
  692. // The storage module to use for reordering tests
  693. storage: localSessionStorage
  694. }; // take a predefined QUnit.config and extend the defaults
  695. var globalConfig = window$1 && window$1.QUnit && window$1.QUnit.config; // only extend the global config if there is no QUnit overload
  696. if (window$1 && window$1.QUnit && !window$1.QUnit.version) {
  697. extend(config, globalConfig);
  698. } // Push a loose unnamed module to the modules collection
  699. config.modules.push(config.currentModule);
  700. var dump = (function () {
  701. function quote(str) {
  702. return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
  703. }
  704. function literal(o) {
  705. return o + "";
  706. }
  707. function join(pre, arr, post) {
  708. var s = dump.separator();
  709. var inner = dump.indent(1);
  710. if (arr.join) {
  711. arr = arr.join("," + s + inner);
  712. }
  713. if (!arr) {
  714. return pre + post;
  715. }
  716. var base = dump.indent();
  717. return [pre, inner + arr, base + post].join(s);
  718. }
  719. function array(arr, stack) {
  720. if (dump.maxDepth && dump.depth > dump.maxDepth) {
  721. return "[object Array]";
  722. }
  723. this.up();
  724. var i = arr.length;
  725. var ret = new Array(i);
  726. while (i--) {
  727. ret[i] = this.parse(arr[i], undefined, stack);
  728. }
  729. this.down();
  730. return join("[", ret, "]");
  731. }
  732. function isArray(obj) {
  733. return (//Native Arrays
  734. toString.call(obj) === "[object Array]" || // NodeList objects
  735. typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined)
  736. );
  737. }
  738. var reName = /^function (\w+)/;
  739. var dump = {
  740. // The objType is used mostly internally, you can fix a (custom) type in advance
  741. parse: function parse(obj, objType, stack) {
  742. stack = stack || [];
  743. var objIndex = stack.indexOf(obj);
  744. if (objIndex !== -1) {
  745. return "recursion(".concat(objIndex - stack.length, ")");
  746. }
  747. objType = objType || this.typeOf(obj);
  748. var parser = this.parsers[objType];
  749. var parserType = _typeof(parser);
  750. if (parserType === "function") {
  751. stack.push(obj);
  752. var res = parser.call(this, obj, stack);
  753. stack.pop();
  754. return res;
  755. }
  756. if (parserType === "string") {
  757. return parser;
  758. }
  759. return "[ERROR: Missing QUnit.dump formatter for type " + objType + "]";
  760. },
  761. typeOf: function typeOf(obj) {
  762. var type;
  763. if (obj === null) {
  764. type = "null";
  765. } else if (typeof obj === "undefined") {
  766. type = "undefined";
  767. } else if (is("regexp", obj)) {
  768. type = "regexp";
  769. } else if (is("date", obj)) {
  770. type = "date";
  771. } else if (is("function", obj)) {
  772. type = "function";
  773. } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) {
  774. type = "window";
  775. } else if (obj.nodeType === 9) {
  776. type = "document";
  777. } else if (obj.nodeType) {
  778. type = "node";
  779. } else if (isArray(obj)) {
  780. type = "array";
  781. } else if (obj.constructor === Error.prototype.constructor) {
  782. type = "error";
  783. } else {
  784. type = _typeof(obj);
  785. }
  786. return type;
  787. },
  788. separator: function separator() {
  789. if (this.multiline) {
  790. return this.HTML ? "<br />" : "\n";
  791. } else {
  792. return this.HTML ? "&#160;" : " ";
  793. }
  794. },
  795. // Extra can be a number, shortcut for increasing-calling-decreasing
  796. indent: function indent(extra) {
  797. if (!this.multiline) {
  798. return "";
  799. }
  800. var chr = this.indentChar;
  801. if (this.HTML) {
  802. chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;");
  803. }
  804. return new Array(this.depth + (extra || 0)).join(chr);
  805. },
  806. up: function up(a) {
  807. this.depth += a || 1;
  808. },
  809. down: function down(a) {
  810. this.depth -= a || 1;
  811. },
  812. setParser: function setParser(name, parser) {
  813. this.parsers[name] = parser;
  814. },
  815. // The next 3 are exposed so you can use them
  816. quote: quote,
  817. literal: literal,
  818. join: join,
  819. depth: 1,
  820. maxDepth: config.maxDepth,
  821. // This is the list of parsers, to modify them, use dump.setParser
  822. parsers: {
  823. window: "[Window]",
  824. document: "[Document]",
  825. error: function error(_error) {
  826. return "Error(\"" + _error.message + "\")";
  827. },
  828. // This has been unused since QUnit 1.0.0.
  829. // @todo Deprecate and remove.
  830. unknown: "[Unknown]",
  831. "null": "null",
  832. "undefined": "undefined",
  833. "function": function _function(fn) {
  834. var ret = "function"; // Functions never have name in IE
  835. var name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
  836. if (name) {
  837. ret += " " + name;
  838. }
  839. ret += "(";
  840. ret = [ret, dump.parse(fn, "functionArgs"), "){"].join("");
  841. return join(ret, dump.parse(fn, "functionCode"), "}");
  842. },
  843. array: array,
  844. nodelist: array,
  845. "arguments": array,
  846. object: function object(map, stack) {
  847. var ret = [];
  848. if (dump.maxDepth && dump.depth > dump.maxDepth) {
  849. return "[object Object]";
  850. }
  851. dump.up();
  852. var keys = [];
  853. for (var key in map) {
  854. keys.push(key);
  855. } // Some properties are not always enumerable on Error objects.
  856. var nonEnumerableProperties = ["message", "name"];
  857. for (var i in nonEnumerableProperties) {
  858. var _key = nonEnumerableProperties[i];
  859. if (_key in map && !inArray(_key, keys)) {
  860. keys.push(_key);
  861. }
  862. }
  863. keys.sort();
  864. for (var _i = 0; _i < keys.length; _i++) {
  865. var _key2 = keys[_i];
  866. var val = map[_key2];
  867. ret.push(dump.parse(_key2, "key") + ": " + dump.parse(val, undefined, stack));
  868. }
  869. dump.down();
  870. return join("{", ret, "}");
  871. },
  872. node: function node(_node) {
  873. var open = dump.HTML ? "&lt;" : "<";
  874. var close = dump.HTML ? "&gt;" : ">";
  875. var tag = _node.nodeName.toLowerCase();
  876. var ret = open + tag;
  877. var attrs = _node.attributes;
  878. if (attrs) {
  879. for (var i = 0, len = attrs.length; i < len; i++) {
  880. var val = attrs[i].nodeValue; // IE6 includes all attributes in .attributes, even ones not explicitly
  881. // set. Those have values like undefined, null, 0, false, "" or
  882. // "inherit".
  883. if (val && val !== "inherit") {
  884. ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute");
  885. }
  886. }
  887. }
  888. ret += close; // Show content of TextNode or CDATASection
  889. if (_node.nodeType === 3 || _node.nodeType === 4) {
  890. ret += _node.nodeValue;
  891. }
  892. return ret + open + "/" + tag + close;
  893. },
  894. // Function calls it internally, it's the arguments part of the function
  895. functionArgs: function functionArgs(fn) {
  896. var l = fn.length;
  897. if (!l) {
  898. return "";
  899. }
  900. var args = new Array(l);
  901. while (l--) {
  902. // 97 is 'a'
  903. args[l] = String.fromCharCode(97 + l);
  904. }
  905. return " " + args.join(", ") + " ";
  906. },
  907. // Object calls it internally, the key part of an item in a map
  908. key: quote,
  909. // Function calls it internally, it's the content of the function
  910. functionCode: "[code]",
  911. // Node calls it internally, it's a html attribute value
  912. attribute: quote,
  913. string: quote,
  914. date: quote,
  915. regexp: literal,
  916. number: literal,
  917. "boolean": literal,
  918. symbol: function symbol(sym) {
  919. return sym.toString();
  920. }
  921. },
  922. // If true, entities are escaped ( <, >, \t, space and \n )
  923. HTML: false,
  924. // Indentation unit
  925. indentChar: " ",
  926. // If true, items in a collection, are separated by a \n, else just a space.
  927. multiline: true
  928. };
  929. return dump;
  930. })();
  931. var SuiteReport = /*#__PURE__*/function () {
  932. function SuiteReport(name, parentSuite) {
  933. _classCallCheck(this, SuiteReport);
  934. this.name = name;
  935. this.fullName = parentSuite ? parentSuite.fullName.concat(name) : []; // When an "error" event is emitted from onUncaughtException(), the
  936. // "runEnd" event should report the status as failed.
  937. // The "runEnd" event data is made by this class (as "globalSuite").
  938. this.globalFailureCount = 0;
  939. this.tests = [];
  940. this.childSuites = [];
  941. if (parentSuite) {
  942. parentSuite.pushChildSuite(this);
  943. }
  944. }
  945. _createClass(SuiteReport, [{
  946. key: "start",
  947. value: function start(recordTime) {
  948. if (recordTime) {
  949. this._startTime = performance.now();
  950. var suiteLevel = this.fullName.length;
  951. performance.mark("qunit_suite_".concat(suiteLevel, "_start"));
  952. }
  953. return {
  954. name: this.name,
  955. fullName: this.fullName.slice(),
  956. tests: this.tests.map(function (test) {
  957. return test.start();
  958. }),
  959. childSuites: this.childSuites.map(function (suite) {
  960. return suite.start();
  961. }),
  962. testCounts: {
  963. total: this.getTestCounts().total
  964. }
  965. };
  966. }
  967. }, {
  968. key: "end",
  969. value: function end(recordTime) {
  970. if (recordTime) {
  971. this._endTime = performance.now();
  972. var suiteLevel = this.fullName.length;
  973. var suiteName = this.fullName.join(" – ");
  974. performance.mark("qunit_suite_".concat(suiteLevel, "_end"));
  975. performance.measure(suiteLevel === 0 ? "QUnit Test Run" : "QUnit Test Suite: ".concat(suiteName), "qunit_suite_".concat(suiteLevel, "_start"), "qunit_suite_".concat(suiteLevel, "_end"));
  976. }
  977. return {
  978. name: this.name,
  979. fullName: this.fullName.slice(),
  980. tests: this.tests.map(function (test) {
  981. return test.end();
  982. }),
  983. childSuites: this.childSuites.map(function (suite) {
  984. return suite.end();
  985. }),
  986. testCounts: this.getTestCounts(),
  987. runtime: this.getRuntime(),
  988. status: this.getStatus()
  989. };
  990. }
  991. }, {
  992. key: "pushChildSuite",
  993. value: function pushChildSuite(suite) {
  994. this.childSuites.push(suite);
  995. }
  996. }, {
  997. key: "pushTest",
  998. value: function pushTest(test) {
  999. this.tests.push(test);
  1000. }
  1001. }, {
  1002. key: "getRuntime",
  1003. value: function getRuntime() {
  1004. return this._endTime - this._startTime;
  1005. }
  1006. }, {
  1007. key: "getTestCounts",
  1008. value: function getTestCounts() {
  1009. var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1010. passed: 0,
  1011. failed: 0,
  1012. skipped: 0,
  1013. todo: 0,
  1014. total: 0
  1015. };
  1016. counts.failed += this.globalFailureCount;
  1017. counts.total += this.globalFailureCount;
  1018. counts = this.tests.reduce(function (counts, test) {
  1019. if (test.valid) {
  1020. counts[test.getStatus()]++;
  1021. counts.total++;
  1022. }
  1023. return counts;
  1024. }, counts);
  1025. return this.childSuites.reduce(function (counts, suite) {
  1026. return suite.getTestCounts(counts);
  1027. }, counts);
  1028. }
  1029. }, {
  1030. key: "getStatus",
  1031. value: function getStatus() {
  1032. var _this$getTestCounts = this.getTestCounts(),
  1033. total = _this$getTestCounts.total,
  1034. failed = _this$getTestCounts.failed,
  1035. skipped = _this$getTestCounts.skipped,
  1036. todo = _this$getTestCounts.todo;
  1037. if (failed) {
  1038. return "failed";
  1039. } else {
  1040. if (skipped === total) {
  1041. return "skipped";
  1042. } else if (todo === total) {
  1043. return "todo";
  1044. } else {
  1045. return "passed";
  1046. }
  1047. }
  1048. }
  1049. }]);
  1050. return SuiteReport;
  1051. }();
  1052. var moduleStack = [];
  1053. function isParentModuleInQueue() {
  1054. var modulesInQueue = config.modules.filter(function (module) {
  1055. return !module.ignored;
  1056. }).map(function (module) {
  1057. return module.moduleId;
  1058. });
  1059. return moduleStack.some(function (module) {
  1060. return modulesInQueue.includes(module.moduleId);
  1061. });
  1062. }
  1063. function createModule(name, testEnvironment, modifiers) {
  1064. var parentModule = moduleStack.length ? moduleStack.slice(-1)[0] : null;
  1065. var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name;
  1066. var parentSuite = parentModule ? parentModule.suiteReport : globalSuite;
  1067. var skip = parentModule !== null && parentModule.skip || modifiers.skip;
  1068. var todo = parentModule !== null && parentModule.todo || modifiers.todo;
  1069. var module = {
  1070. name: moduleName,
  1071. parentModule: parentModule,
  1072. tests: [],
  1073. moduleId: generateHash(moduleName),
  1074. testsRun: 0,
  1075. testsIgnored: 0,
  1076. childModules: [],
  1077. suiteReport: new SuiteReport(name, parentSuite),
  1078. // Pass along `skip` and `todo` properties from parent module, in case
  1079. // there is one, to childs. And use own otherwise.
  1080. // This property will be used to mark own tests and tests of child suites
  1081. // as either `skipped` or `todo`.
  1082. skip: skip,
  1083. todo: skip ? false : todo,
  1084. ignored: modifiers.ignored || false
  1085. };
  1086. var env = {};
  1087. if (parentModule) {
  1088. parentModule.childModules.push(module);
  1089. extend(env, parentModule.testEnvironment);
  1090. }
  1091. extend(env, testEnvironment);
  1092. module.testEnvironment = env;
  1093. config.modules.push(module);
  1094. return module;
  1095. }
  1096. function processModule(name, options, executeNow) {
  1097. var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1098. if (objectType(options) === "function") {
  1099. executeNow = options;
  1100. options = undefined;
  1101. }
  1102. var module = createModule(name, options, modifiers); // Move any hooks to a 'hooks' object
  1103. var testEnvironment = module.testEnvironment;
  1104. var hooks = module.hooks = {};
  1105. setHookFromEnvironment(hooks, testEnvironment, "before");
  1106. setHookFromEnvironment(hooks, testEnvironment, "beforeEach");
  1107. setHookFromEnvironment(hooks, testEnvironment, "afterEach");
  1108. setHookFromEnvironment(hooks, testEnvironment, "after");
  1109. var moduleFns = {
  1110. before: setHookFunction(module, "before"),
  1111. beforeEach: setHookFunction(module, "beforeEach"),
  1112. afterEach: setHookFunction(module, "afterEach"),
  1113. after: setHookFunction(module, "after")
  1114. };
  1115. var prevModule = config.currentModule;
  1116. config.currentModule = module;
  1117. if (objectType(executeNow) === "function") {
  1118. moduleStack.push(module);
  1119. try {
  1120. var cbReturnValue = executeNow.call(module.testEnvironment, moduleFns);
  1121. if (cbReturnValue != null && objectType(cbReturnValue.then) === "function") {
  1122. Logger.warn("Returning a promise from a module callback is not supported. " + "Instead, use hooks for async behavior. " + "This will become an error in QUnit 3.0.");
  1123. }
  1124. } finally {
  1125. // If the module closure threw an uncaught error during the load phase,
  1126. // we let this bubble up to global error handlers. But, not until after
  1127. // we teardown internal state to ensure correct module nesting.
  1128. // Ref https://github.com/qunitjs/qunit/issues/1478.
  1129. moduleStack.pop();
  1130. config.currentModule = module.parentModule || prevModule;
  1131. }
  1132. }
  1133. function setHookFromEnvironment(hooks, environment, name) {
  1134. var potentialHook = environment[name];
  1135. hooks[name] = typeof potentialHook === "function" ? [potentialHook] : [];
  1136. delete environment[name];
  1137. }
  1138. function setHookFunction(module, hookName) {
  1139. return function setHook(callback) {
  1140. if (config.currentModule !== module) {
  1141. Logger.warn("The `" + hookName + "` hook was called inside the wrong module (`" + config.currentModule.name + "`). " + "Instead, use hooks provided by the callback to the containing module (`" + module.name + "`). " + "This will become an error in QUnit 3.0.");
  1142. }
  1143. module.hooks[hookName].push(callback);
  1144. };
  1145. }
  1146. }
  1147. var focused$1 = false; // indicates that the "only" filter was used
  1148. function module$1(name, options, executeNow) {
  1149. var ignored = focused$1 && !isParentModuleInQueue();
  1150. processModule(name, options, executeNow, {
  1151. ignored: ignored
  1152. });
  1153. }
  1154. module$1.only = function () {
  1155. if (!focused$1) {
  1156. // Upon the first module.only() call,
  1157. // delete any and all previously registered modules and tests.
  1158. config.modules.length = 0;
  1159. config.queue.length = 0; // Ignore any tests declared after this block within the same
  1160. // module parent. https://github.com/qunitjs/qunit/issues/1645
  1161. config.currentModule.ignored = true;
  1162. }
  1163. focused$1 = true;
  1164. processModule.apply(void 0, arguments);
  1165. };
  1166. module$1.skip = function (name, options, executeNow) {
  1167. if (focused$1) {
  1168. return;
  1169. }
  1170. processModule(name, options, executeNow, {
  1171. skip: true
  1172. });
  1173. };
  1174. module$1.todo = function (name, options, executeNow) {
  1175. if (focused$1) {
  1176. return;
  1177. }
  1178. processModule(name, options, executeNow, {
  1179. todo: true
  1180. });
  1181. };
  1182. var LISTENERS = Object.create(null);
  1183. var SUPPORTED_EVENTS = ["error", "runStart", "suiteStart", "testStart", "assertion", "testEnd", "suiteEnd", "runEnd"];
  1184. /**
  1185. * Emits an event with the specified data to all currently registered listeners.
  1186. * Callbacks will fire in the order in which they are registered (FIFO). This
  1187. * function is not exposed publicly; it is used by QUnit internals to emit
  1188. * logging events.
  1189. *
  1190. * @private
  1191. * @method emit
  1192. * @param {string} eventName
  1193. * @param {Object} data
  1194. * @return {void}
  1195. */
  1196. function emit(eventName, data) {
  1197. if (objectType(eventName) !== "string") {
  1198. throw new TypeError("eventName must be a string when emitting an event");
  1199. } // Clone the callbacks in case one of them registers a new callback
  1200. var originalCallbacks = LISTENERS[eventName];
  1201. var callbacks = originalCallbacks ? _toConsumableArray(originalCallbacks) : [];
  1202. for (var i = 0; i < callbacks.length; i++) {
  1203. callbacks[i](data);
  1204. }
  1205. }
  1206. /**
  1207. * Registers a callback as a listener to the specified event.
  1208. *
  1209. * @public
  1210. * @method on
  1211. * @param {string} eventName
  1212. * @param {Function} callback
  1213. * @return {void}
  1214. */
  1215. function on(eventName, callback) {
  1216. if (objectType(eventName) !== "string") {
  1217. throw new TypeError("eventName must be a string when registering a listener");
  1218. } else if (!inArray(eventName, SUPPORTED_EVENTS)) {
  1219. var events = SUPPORTED_EVENTS.join(", ");
  1220. throw new Error("\"".concat(eventName, "\" is not a valid event; must be one of: ").concat(events, "."));
  1221. } else if (objectType(callback) !== "function") {
  1222. throw new TypeError("callback must be a function when registering a listener");
  1223. }
  1224. if (!LISTENERS[eventName]) {
  1225. LISTENERS[eventName] = [];
  1226. } // Don't register the same callback more than once
  1227. if (!inArray(callback, LISTENERS[eventName])) {
  1228. LISTENERS[eventName].push(callback);
  1229. }
  1230. }
  1231. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  1232. function commonjsRequire (path) {
  1233. throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  1234. }
  1235. var promisePolyfill = {exports: {}};
  1236. (function () {
  1237. /** @suppress {undefinedVars} */
  1238. var globalNS = function () {
  1239. // the only reliable means to get the global object is
  1240. // `Function('return this')()`
  1241. // However, this causes CSP violations in Chrome apps.
  1242. if (typeof globalThis !== 'undefined') {
  1243. return globalThis;
  1244. }
  1245. if (typeof self !== 'undefined') {
  1246. return self;
  1247. }
  1248. if (typeof window !== 'undefined') {
  1249. return window;
  1250. }
  1251. if (typeof commonjsGlobal !== 'undefined') {
  1252. return commonjsGlobal;
  1253. }
  1254. throw new Error('unable to locate global object');
  1255. }(); // Expose the polyfill if Promise is undefined or set to a
  1256. // non-function value. The latter can be due to a named HTMLElement
  1257. // being exposed by browsers for legacy reasons.
  1258. // https://github.com/taylorhakes/promise-polyfill/issues/114
  1259. if (typeof globalNS['Promise'] === 'function') {
  1260. promisePolyfill.exports = globalNS['Promise'];
  1261. return;
  1262. }
  1263. /**
  1264. * @this {Promise}
  1265. */
  1266. function finallyConstructor(callback) {
  1267. var constructor = this.constructor;
  1268. return this.then(function (value) {
  1269. // @ts-ignore
  1270. return constructor.resolve(callback()).then(function () {
  1271. return value;
  1272. });
  1273. }, function (reason) {
  1274. // @ts-ignore
  1275. return constructor.resolve(callback()).then(function () {
  1276. // @ts-ignore
  1277. return constructor.reject(reason);
  1278. });
  1279. });
  1280. }
  1281. function allSettled(arr) {
  1282. var P = this;
  1283. return new P(function (resolve, reject) {
  1284. if (!(arr && typeof arr.length !== 'undefined')) {
  1285. return reject(new TypeError(_typeof(arr) + ' ' + arr + ' is not iterable(cannot read property Symbol(Symbol.iterator))'));
  1286. }
  1287. var args = Array.prototype.slice.call(arr);
  1288. if (args.length === 0) return resolve([]);
  1289. var remaining = args.length;
  1290. function res(i, val) {
  1291. if (val && (_typeof(val) === 'object' || typeof val === 'function')) {
  1292. var then = val.then;
  1293. if (typeof then === 'function') {
  1294. then.call(val, function (val) {
  1295. res(i, val);
  1296. }, function (e) {
  1297. args[i] = {
  1298. status: 'rejected',
  1299. reason: e
  1300. };
  1301. if (--remaining === 0) {
  1302. resolve(args);
  1303. }
  1304. });
  1305. return;
  1306. }
  1307. }
  1308. args[i] = {
  1309. status: 'fulfilled',
  1310. value: val
  1311. };
  1312. if (--remaining === 0) {
  1313. resolve(args);
  1314. }
  1315. }
  1316. for (var i = 0; i < args.length; i++) {
  1317. res(i, args[i]);
  1318. }
  1319. });
  1320. } // Store setTimeout reference so promise-polyfill will be unaffected by
  1321. // other code modifying setTimeout (like sinon.useFakeTimers())
  1322. var setTimeoutFunc = setTimeout;
  1323. function isArray(x) {
  1324. return Boolean(x && typeof x.length !== 'undefined');
  1325. }
  1326. function noop() {} // Polyfill for Function.prototype.bind
  1327. function bind(fn, thisArg) {
  1328. return function () {
  1329. fn.apply(thisArg, arguments);
  1330. };
  1331. }
  1332. /**
  1333. * @constructor
  1334. * @param {Function} fn
  1335. */
  1336. function Promise(fn) {
  1337. if (!(this instanceof Promise)) throw new TypeError('Promises must be constructed via new');
  1338. if (typeof fn !== 'function') throw new TypeError('not a function');
  1339. /** @type {!number} */
  1340. this._state = 0;
  1341. /** @type {!boolean} */
  1342. this._handled = false;
  1343. /** @type {Promise|undefined} */
  1344. this._value = undefined;
  1345. /** @type {!Array<!Function>} */
  1346. this._deferreds = [];
  1347. doResolve(fn, this);
  1348. }
  1349. function handle(self, deferred) {
  1350. while (self._state === 3) {
  1351. self = self._value;
  1352. }
  1353. if (self._state === 0) {
  1354. self._deferreds.push(deferred);
  1355. return;
  1356. }
  1357. self._handled = true;
  1358. Promise._immediateFn(function () {
  1359. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  1360. if (cb === null) {
  1361. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  1362. return;
  1363. }
  1364. var ret;
  1365. try {
  1366. ret = cb(self._value);
  1367. } catch (e) {
  1368. reject(deferred.promise, e);
  1369. return;
  1370. }
  1371. resolve(deferred.promise, ret);
  1372. });
  1373. }
  1374. function resolve(self, newValue) {
  1375. try {
  1376. // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  1377. if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
  1378. if (newValue && (_typeof(newValue) === 'object' || typeof newValue === 'function')) {
  1379. var then = newValue.then;
  1380. if (newValue instanceof Promise) {
  1381. self._state = 3;
  1382. self._value = newValue;
  1383. finale(self);
  1384. return;
  1385. } else if (typeof then === 'function') {
  1386. doResolve(bind(then, newValue), self);
  1387. return;
  1388. }
  1389. }
  1390. self._state = 1;
  1391. self._value = newValue;
  1392. finale(self);
  1393. } catch (e) {
  1394. reject(self, e);
  1395. }
  1396. }
  1397. function reject(self, newValue) {
  1398. self._state = 2;
  1399. self._value = newValue;
  1400. finale(self);
  1401. }
  1402. function finale(self) {
  1403. if (self._state === 2 && self._deferreds.length === 0) {
  1404. Promise._immediateFn(function () {
  1405. if (!self._handled) {
  1406. Promise._unhandledRejectionFn(self._value);
  1407. }
  1408. });
  1409. }
  1410. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  1411. handle(self, self._deferreds[i]);
  1412. }
  1413. self._deferreds = null;
  1414. }
  1415. /**
  1416. * @constructor
  1417. */
  1418. function Handler(onFulfilled, onRejected, promise) {
  1419. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  1420. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  1421. this.promise = promise;
  1422. }
  1423. /**
  1424. * Take a potentially misbehaving resolver function and make sure
  1425. * onFulfilled and onRejected are only called once.
  1426. *
  1427. * Makes no guarantees about asynchrony.
  1428. */
  1429. function doResolve(fn, self) {
  1430. var done = false;
  1431. try {
  1432. fn(function (value) {
  1433. if (done) return;
  1434. done = true;
  1435. resolve(self, value);
  1436. }, function (reason) {
  1437. if (done) return;
  1438. done = true;
  1439. reject(self, reason);
  1440. });
  1441. } catch (ex) {
  1442. if (done) return;
  1443. done = true;
  1444. reject(self, ex);
  1445. }
  1446. }
  1447. Promise.prototype['catch'] = function (onRejected) {
  1448. return this.then(null, onRejected);
  1449. };
  1450. Promise.prototype.then = function (onFulfilled, onRejected) {
  1451. // @ts-ignore
  1452. var prom = new this.constructor(noop);
  1453. handle(this, new Handler(onFulfilled, onRejected, prom));
  1454. return prom;
  1455. };
  1456. Promise.prototype['finally'] = finallyConstructor;
  1457. Promise.all = function (arr) {
  1458. return new Promise(function (resolve, reject) {
  1459. if (!isArray(arr)) {
  1460. return reject(new TypeError('Promise.all accepts an array'));
  1461. }
  1462. var args = Array.prototype.slice.call(arr);
  1463. if (args.length === 0) return resolve([]);
  1464. var remaining = args.length;
  1465. function res(i, val) {
  1466. try {
  1467. if (val && (_typeof(val) === 'object' || typeof val === 'function')) {
  1468. var then = val.then;
  1469. if (typeof then === 'function') {
  1470. then.call(val, function (val) {
  1471. res(i, val);
  1472. }, reject);
  1473. return;
  1474. }
  1475. }
  1476. args[i] = val;
  1477. if (--remaining === 0) {
  1478. resolve(args);
  1479. }
  1480. } catch (ex) {
  1481. reject(ex);
  1482. }
  1483. }
  1484. for (var i = 0; i < args.length; i++) {
  1485. res(i, args[i]);
  1486. }
  1487. });
  1488. };
  1489. Promise.allSettled = allSettled;
  1490. Promise.resolve = function (value) {
  1491. if (value && _typeof(value) === 'object' && value.constructor === Promise) {
  1492. return value;
  1493. }
  1494. return new Promise(function (resolve) {
  1495. resolve(value);
  1496. });
  1497. };
  1498. Promise.reject = function (value) {
  1499. return new Promise(function (resolve, reject) {
  1500. reject(value);
  1501. });
  1502. };
  1503. Promise.race = function (arr) {
  1504. return new Promise(function (resolve, reject) {
  1505. if (!isArray(arr)) {
  1506. return reject(new TypeError('Promise.race accepts an array'));
  1507. }
  1508. for (var i = 0, len = arr.length; i < len; i++) {
  1509. Promise.resolve(arr[i]).then(resolve, reject);
  1510. }
  1511. });
  1512. }; // Use polyfill for setImmediate for performance gains
  1513. Promise._immediateFn = // @ts-ignore
  1514. typeof setImmediate === 'function' && function (fn) {
  1515. // @ts-ignore
  1516. setImmediate(fn);
  1517. } || function (fn) {
  1518. setTimeoutFunc(fn, 0);
  1519. };
  1520. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  1521. if (typeof console !== 'undefined' && console) {
  1522. console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  1523. }
  1524. };
  1525. promisePolyfill.exports = Promise;
  1526. })();
  1527. var _Promise = promisePolyfill.exports;
  1528. function registerLoggingCallbacks(obj) {
  1529. var callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"];
  1530. function registerLoggingCallback(key) {
  1531. var loggingCallback = function loggingCallback(callback) {
  1532. if (objectType(callback) !== "function") {
  1533. throw new Error("QUnit logging methods require a callback function as their first parameters.");
  1534. }
  1535. config.callbacks[key].push(callback);
  1536. };
  1537. return loggingCallback;
  1538. }
  1539. for (var i = 0, l = callbackNames.length; i < l; i++) {
  1540. var key = callbackNames[i]; // Initialize key collection of logging callback
  1541. if (objectType(config.callbacks[key]) === "undefined") {
  1542. config.callbacks[key] = [];
  1543. }
  1544. obj[key] = registerLoggingCallback(key);
  1545. }
  1546. }
  1547. function runLoggingCallbacks(key, args) {
  1548. var callbacks = config.callbacks[key]; // Handling 'log' callbacks separately. Unlike the other callbacks,
  1549. // the log callback is not controlled by the processing queue,
  1550. // but rather used by asserts. Hence to promisfy the 'log' callback
  1551. // would mean promisfying each step of a test
  1552. if (key === "log") {
  1553. callbacks.map(function (callback) {
  1554. return callback(args);
  1555. });
  1556. return;
  1557. } // ensure that each callback is executed serially
  1558. return callbacks.reduce(function (promiseChain, callback) {
  1559. return promiseChain.then(function () {
  1560. return _Promise.resolve(callback(args));
  1561. });
  1562. }, _Promise.resolve([]));
  1563. }
  1564. // Doesn't support IE9, it will return undefined on these browsers
  1565. // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
  1566. var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
  1567. function extractStacktrace(e, offset) {
  1568. offset = offset === undefined ? 4 : offset;
  1569. if (e && e.stack) {
  1570. var stack = e.stack.split("\n");
  1571. if (/^error$/i.test(stack[0])) {
  1572. stack.shift();
  1573. }
  1574. if (fileName) {
  1575. var include = [];
  1576. for (var i = offset; i < stack.length; i++) {
  1577. if (stack[i].indexOf(fileName) !== -1) {
  1578. break;
  1579. }
  1580. include.push(stack[i]);
  1581. }
  1582. if (include.length) {
  1583. return include.join("\n");
  1584. }
  1585. }
  1586. return stack[offset];
  1587. }
  1588. }
  1589. function sourceFromStacktrace(offset) {
  1590. var error = new Error(); // Support: Safari <=7 only, IE <=10 - 11 only
  1591. // Not all browsers generate the `stack` property for `new Error()`, see also #636
  1592. if (!error.stack) {
  1593. try {
  1594. throw error;
  1595. } catch (err) {
  1596. error = err;
  1597. }
  1598. }
  1599. return extractStacktrace(error, offset);
  1600. }
  1601. var priorityCount = 0;
  1602. var unitSampler; // This is a queue of functions that are tasks within a single test.
  1603. // After tests are dequeued from config.queue they are expanded into
  1604. // a set of tasks in this queue.
  1605. var taskQueue = [];
  1606. /**
  1607. * Advances the taskQueue to the next task. If the taskQueue is empty,
  1608. * process the testQueue
  1609. */
  1610. function advance() {
  1611. advanceTaskQueue();
  1612. if (!taskQueue.length && !config.blocking && !config.current) {
  1613. advanceTestQueue();
  1614. }
  1615. }
  1616. /**
  1617. * Advances the taskQueue with an increased depth
  1618. */
  1619. function advanceTaskQueue() {
  1620. var start = now();
  1621. config.depth = (config.depth || 0) + 1;
  1622. processTaskQueue(start);
  1623. config.depth--;
  1624. }
  1625. /**
  1626. * Process the first task on the taskQueue as a promise.
  1627. * Each task is a function added by Test#queue() in /src/test.js
  1628. */
  1629. function processTaskQueue(start) {
  1630. if (taskQueue.length && !config.blocking) {
  1631. var elapsedTime = now() - start;
  1632. if (!setTimeout$1 || config.updateRate <= 0 || elapsedTime < config.updateRate) {
  1633. var task = taskQueue.shift();
  1634. _Promise.resolve(task()).then(function () {
  1635. if (!taskQueue.length) {
  1636. advance();
  1637. } else {
  1638. processTaskQueue(start);
  1639. }
  1640. });
  1641. } else {
  1642. setTimeout$1(advance);
  1643. }
  1644. }
  1645. }
  1646. /**
  1647. * Advance the testQueue to the next test to process. Call done() if testQueue completes.
  1648. */
  1649. function advanceTestQueue() {
  1650. if (!config.blocking && !config.queue.length && config.depth === 0) {
  1651. done();
  1652. return;
  1653. }
  1654. var testTasks = config.queue.shift();
  1655. addToTaskQueue(testTasks());
  1656. if (priorityCount > 0) {
  1657. priorityCount--;
  1658. }
  1659. advance();
  1660. }
  1661. /**
  1662. * Enqueue the tasks for a test into the task queue.
  1663. * @param {Array} tasksArray
  1664. */
  1665. function addToTaskQueue(tasksArray) {
  1666. taskQueue.push.apply(taskQueue, _toConsumableArray(tasksArray));
  1667. }
  1668. /**
  1669. * Return the number of tasks remaining in the task queue to be processed.
  1670. * @return {number}
  1671. */
  1672. function taskQueueLength() {
  1673. return taskQueue.length;
  1674. }
  1675. /**
  1676. * Adds a test to the TestQueue for execution.
  1677. * @param {Function} testTasksFunc
  1678. * @param {boolean} prioritize
  1679. * @param {string} seed
  1680. */
  1681. function addToTestQueue(testTasksFunc, prioritize, seed) {
  1682. if (prioritize) {
  1683. config.queue.splice(priorityCount++, 0, testTasksFunc);
  1684. } else if (seed) {
  1685. if (!unitSampler) {
  1686. unitSampler = unitSamplerGenerator(seed);
  1687. } // Insert into a random position after all prioritized items
  1688. var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1));
  1689. config.queue.splice(priorityCount + index, 0, testTasksFunc);
  1690. } else {
  1691. config.queue.push(testTasksFunc);
  1692. }
  1693. }
  1694. /**
  1695. * Creates a seeded "sample" generator which is used for randomizing tests.
  1696. */
  1697. function unitSamplerGenerator(seed) {
  1698. // 32-bit xorshift, requires only a nonzero seed
  1699. // https://excamera.com/sphinx/article-xorshift.html
  1700. var sample = parseInt(generateHash(seed), 16) || -1;
  1701. return function () {
  1702. sample ^= sample << 13;
  1703. sample ^= sample >>> 17;
  1704. sample ^= sample << 5; // ECMAScript has no unsigned number type
  1705. if (sample < 0) {
  1706. sample += 0x100000000;
  1707. }
  1708. return sample / 0x100000000;
  1709. };
  1710. }
  1711. /**
  1712. * This function is called when the ProcessingQueue is done processing all
  1713. * items. It handles emitting the final run events.
  1714. */
  1715. function done() {
  1716. // We have reached the end of the processing queue and are about to emit the
  1717. // "runEnd" event after which reporters typically stop listening and exit
  1718. // the process. First, check if we need to emit one final test.
  1719. if (config.stats.testCount === 0 && config.failOnZeroTests === true) {
  1720. var error;
  1721. if (config.filter && config.filter.length) {
  1722. error = new Error("No tests matched the filter \"".concat(config.filter, "\"."));
  1723. } else if (config.module && config.module.length) {
  1724. error = new Error("No tests matched the module \"".concat(config.module, "\"."));
  1725. } else if (config.moduleId && config.moduleId.length) {
  1726. error = new Error("No tests matched the moduleId \"".concat(config.moduleId, "\"."));
  1727. } else if (config.testId && config.testId.length) {
  1728. error = new Error("No tests matched the testId \"".concat(config.testId, "\"."));
  1729. } else {
  1730. error = new Error("No tests were run.");
  1731. }
  1732. test("global failure", extend(function (assert) {
  1733. assert.pushResult({
  1734. result: false,
  1735. message: error.message,
  1736. source: error.stack
  1737. });
  1738. }, {
  1739. validTest: true
  1740. })); // We do need to call `advance()` in order to resume the processing queue.
  1741. // Once this new test is finished processing, we'll reach `done` again, and
  1742. // that time the above condition will evaluate to false.
  1743. advance();
  1744. return;
  1745. }
  1746. var storage = config.storage;
  1747. var runtime = now() - config.started;
  1748. var passed = config.stats.all - config.stats.bad;
  1749. ProcessingQueue.finished = true;
  1750. emit("runEnd", globalSuite.end(true));
  1751. runLoggingCallbacks("done", {
  1752. passed: passed,
  1753. failed: config.stats.bad,
  1754. total: config.stats.all,
  1755. runtime: runtime
  1756. }).then(function () {
  1757. // Clear own storage items if all tests passed
  1758. if (storage && config.stats.bad === 0) {
  1759. for (var i = storage.length - 1; i >= 0; i--) {
  1760. var key = storage.key(i);
  1761. if (key.indexOf("qunit-test-") === 0) {
  1762. storage.removeItem(key);
  1763. }
  1764. }
  1765. }
  1766. });
  1767. }
  1768. var ProcessingQueue = {
  1769. finished: false,
  1770. add: addToTestQueue,
  1771. advance: advance,
  1772. taskCount: taskQueueLength
  1773. };
  1774. var TestReport = /*#__PURE__*/function () {
  1775. function TestReport(name, suite, options) {
  1776. _classCallCheck(this, TestReport);
  1777. this.name = name;
  1778. this.suiteName = suite.name;
  1779. this.fullName = suite.fullName.concat(name);
  1780. this.runtime = 0;
  1781. this.assertions = [];
  1782. this.skipped = !!options.skip;
  1783. this.todo = !!options.todo;
  1784. this.valid = options.valid;
  1785. this._startTime = 0;
  1786. this._endTime = 0;
  1787. suite.pushTest(this);
  1788. }
  1789. _createClass(TestReport, [{
  1790. key: "start",
  1791. value: function start(recordTime) {
  1792. if (recordTime) {
  1793. this._startTime = performance.now();
  1794. performance.mark("qunit_test_start");
  1795. }
  1796. return {
  1797. name: this.name,
  1798. suiteName: this.suiteName,
  1799. fullName: this.fullName.slice()
  1800. };
  1801. }
  1802. }, {
  1803. key: "end",
  1804. value: function end(recordTime) {
  1805. if (recordTime) {
  1806. this._endTime = performance.now();
  1807. if (performance) {
  1808. performance.mark("qunit_test_end");
  1809. var testName = this.fullName.join(" – ");
  1810. performance.measure("QUnit Test: ".concat(testName), "qunit_test_start", "qunit_test_end");
  1811. }
  1812. }
  1813. return extend(this.start(), {
  1814. runtime: this.getRuntime(),
  1815. status: this.getStatus(),
  1816. errors: this.getFailedAssertions(),
  1817. assertions: this.getAssertions()
  1818. });
  1819. }
  1820. }, {
  1821. key: "pushAssertion",
  1822. value: function pushAssertion(assertion) {
  1823. this.assertions.push(assertion);
  1824. }
  1825. }, {
  1826. key: "getRuntime",
  1827. value: function getRuntime() {
  1828. return this._endTime - this._startTime;
  1829. }
  1830. }, {
  1831. key: "getStatus",
  1832. value: function getStatus() {
  1833. if (this.skipped) {
  1834. return "skipped";
  1835. }
  1836. var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo;
  1837. if (!testPassed) {
  1838. return "failed";
  1839. } else if (this.todo) {
  1840. return "todo";
  1841. } else {
  1842. return "passed";
  1843. }
  1844. }
  1845. }, {
  1846. key: "getFailedAssertions",
  1847. value: function getFailedAssertions() {
  1848. return this.assertions.filter(function (assertion) {
  1849. return !assertion.passed;
  1850. });
  1851. }
  1852. }, {
  1853. key: "getAssertions",
  1854. value: function getAssertions() {
  1855. return this.assertions.slice();
  1856. } // Remove actual and expected values from assertions. This is to prevent
  1857. // leaking memory throughout a test suite.
  1858. }, {
  1859. key: "slimAssertions",
  1860. value: function slimAssertions() {
  1861. this.assertions = this.assertions.map(function (assertion) {
  1862. delete assertion.actual;
  1863. delete assertion.expected;
  1864. return assertion;
  1865. });
  1866. }
  1867. }]);
  1868. return TestReport;
  1869. }();
  1870. function Test(settings) {
  1871. this.expected = null;
  1872. this.assertions = [];
  1873. this.module = config.currentModule;
  1874. this.steps = [];
  1875. this.timeout = undefined;
  1876. this.data = undefined;
  1877. this.withData = false;
  1878. this.pauses = new Map();
  1879. this.nextPauseId = 1;
  1880. extend(this, settings); // If a module is skipped, all its tests and the tests of the child suites
  1881. // should be treated as skipped even if they are defined as `only` or `todo`.
  1882. // As for `todo` module, all its tests will be treated as `todo` except for
  1883. // tests defined as `skip` which will be left intact.
  1884. //
  1885. // So, if a test is defined as `todo` and is inside a skipped module, we should
  1886. // then treat that test as if was defined as `skip`.
  1887. if (this.module.skip) {
  1888. this.skip = true;
  1889. this.todo = false; // Skipped tests should be left intact
  1890. } else if (this.module.todo && !this.skip) {
  1891. this.todo = true;
  1892. } // Queuing a late test after the run has ended is not allowed.
  1893. // This was once supported for internal use by QUnit.onError().
  1894. // Ref https://github.com/qunitjs/qunit/issues/1377
  1895. if (ProcessingQueue.finished) {
  1896. // Using this for anything other than onError(), such as testing in QUnit.done(),
  1897. // is unstable and will likely result in the added tests being ignored by CI.
  1898. // (Meaning the CI passes irregardless of the added tests).
  1899. //
  1900. // TODO: Make this an error in QUnit 3.0
  1901. // throw new Error( "Unexpected new test after the run already ended" );
  1902. Logger.warn("Unexpected test after runEnd. This is unstable and will fail in QUnit 3.0.");
  1903. return;
  1904. }
  1905. if (!this.skip && typeof this.callback !== "function") {
  1906. var method = this.todo ? "QUnit.todo" : "QUnit.test";
  1907. throw new TypeError("You must provide a callback to ".concat(method, "(\"").concat(this.testName, "\")"));
  1908. } // No validation after this. Beyond this point, failures must be recorded as
  1909. // a completed test with errors, instead of early bail out.
  1910. // Otherwise, internals may be left in an inconsistent state.
  1911. // Ref https://github.com/qunitjs/qunit/issues/1514
  1912. ++Test.count;
  1913. this.errorForStack = new Error();
  1914. if (this.callback && this.callback.validTest) {
  1915. // Omit the test-level trace for the internal "No tests" test failure,
  1916. // There is already an assertion-level trace, and that's noisy enough
  1917. // as it is.
  1918. this.errorForStack.stack = undefined;
  1919. }
  1920. this.testReport = new TestReport(this.testName, this.module.suiteReport, {
  1921. todo: this.todo,
  1922. skip: this.skip,
  1923. valid: this.valid()
  1924. }); // Register unique strings
  1925. for (var i = 0, l = this.module.tests; i < l.length; i++) {
  1926. if (this.module.tests[i].name === this.testName) {
  1927. this.testName += " ";
  1928. }
  1929. }
  1930. this.testId = generateHash(this.module.name, this.testName);
  1931. this.module.tests.push({
  1932. name: this.testName,
  1933. testId: this.testId,
  1934. skip: !!this.skip
  1935. });
  1936. if (this.skip) {
  1937. // Skipped tests will fully ignore any sent callback
  1938. this.callback = function () {};
  1939. this.async = false;
  1940. this.expected = 0;
  1941. } else {
  1942. this.assert = new Assert(this);
  1943. }
  1944. }
  1945. Test.count = 0;
  1946. function getNotStartedModules(startModule) {
  1947. var module = startModule;
  1948. var modules = [];
  1949. while (module && module.testsRun === 0) {
  1950. modules.push(module);
  1951. module = module.parentModule;
  1952. } // The above push modules from the child to the parent
  1953. // return a reversed order with the top being the top most parent module
  1954. return modules.reverse();
  1955. }
  1956. Test.prototype = {
  1957. // generating a stack trace can be expensive, so using a getter defers this until we need it
  1958. get stack() {
  1959. return extractStacktrace(this.errorForStack, 2);
  1960. },
  1961. before: function before() {
  1962. var _this = this;
  1963. var module = this.module;
  1964. var notStartedModules = getNotStartedModules(module); // ensure the callbacks are executed serially for each module
  1965. var callbackPromises = notStartedModules.reduce(function (promiseChain, startModule) {
  1966. return promiseChain.then(function () {
  1967. startModule.stats = {
  1968. all: 0,
  1969. bad: 0,
  1970. started: now()
  1971. };
  1972. emit("suiteStart", startModule.suiteReport.start(true));
  1973. return runLoggingCallbacks("moduleStart", {
  1974. name: startModule.name,
  1975. tests: startModule.tests
  1976. });
  1977. });
  1978. }, _Promise.resolve([]));
  1979. return callbackPromises.then(function () {
  1980. config.current = _this;
  1981. _this.testEnvironment = extend({}, module.testEnvironment);
  1982. _this.started = now();
  1983. emit("testStart", _this.testReport.start(true));
  1984. return runLoggingCallbacks("testStart", {
  1985. name: _this.testName,
  1986. module: module.name,
  1987. testId: _this.testId,
  1988. previousFailure: _this.previousFailure
  1989. }).then(function () {
  1990. if (!config.pollution) {
  1991. saveGlobal();
  1992. }
  1993. });
  1994. });
  1995. },
  1996. run: function run() {
  1997. config.current = this;
  1998. this.callbackStarted = now();
  1999. if (config.notrycatch) {
  2000. runTest(this);
  2001. return;
  2002. }
  2003. try {
  2004. runTest(this);
  2005. } catch (e) {
  2006. this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0)); // Else next test will carry the responsibility
  2007. saveGlobal(); // Restart the tests if they're blocking
  2008. if (config.blocking) {
  2009. internalRecover(this);
  2010. }
  2011. }
  2012. function runTest(test) {
  2013. var promise;
  2014. if (test.withData) {
  2015. promise = test.callback.call(test.testEnvironment, test.assert, test.data);
  2016. } else {
  2017. promise = test.callback.call(test.testEnvironment, test.assert);
  2018. }
  2019. test.resolvePromise(promise); // If the test has an async "pause" on it, but the timeout is 0, then we push a
  2020. // failure as the test should be synchronous.
  2021. if (test.timeout === 0 && test.pauses.size > 0) {
  2022. pushFailure("Test did not finish synchronously even though assert.timeout( 0 ) was used.", sourceFromStacktrace(2));
  2023. }
  2024. }
  2025. },
  2026. after: function after() {
  2027. checkPollution();
  2028. },
  2029. queueHook: function queueHook(hook, hookName, hookOwner) {
  2030. var _this2 = this;
  2031. var callHook = function callHook() {
  2032. var promise = hook.call(_this2.testEnvironment, _this2.assert);
  2033. _this2.resolvePromise(promise, hookName);
  2034. };
  2035. var runHook = function runHook() {
  2036. if (hookName === "before") {
  2037. if (hookOwner.testsRun !== 0) {
  2038. return;
  2039. }
  2040. _this2.preserveEnvironment = true;
  2041. } // The 'after' hook should only execute when there are not tests left and
  2042. // when the 'after' and 'finish' tasks are the only tasks left to process
  2043. if (hookName === "after" && !lastTestWithinModuleExecuted(hookOwner) && (config.queue.length > 0 || ProcessingQueue.taskCount() > 2)) {
  2044. return;
  2045. }
  2046. config.current = _this2;
  2047. if (config.notrycatch) {
  2048. callHook();
  2049. return;
  2050. }
  2051. try {
  2052. callHook();
  2053. } catch (error) {
  2054. _this2.pushFailure(hookName + " failed on " + _this2.testName + ": " + (error.message || error), extractStacktrace(error, 0));
  2055. }
  2056. };
  2057. return runHook;
  2058. },
  2059. // Currently only used for module level hooks, can be used to add global level ones
  2060. hooks: function hooks(handler) {
  2061. var hooks = [];
  2062. function processHooks(test, module) {
  2063. if (module.parentModule) {
  2064. processHooks(test, module.parentModule);
  2065. }
  2066. if (module.hooks[handler].length) {
  2067. for (var i = 0; i < module.hooks[handler].length; i++) {
  2068. hooks.push(test.queueHook(module.hooks[handler][i], handler, module));
  2069. }
  2070. }
  2071. } // Hooks are ignored on skipped tests
  2072. if (!this.skip) {
  2073. processHooks(this, this.module);
  2074. }
  2075. return hooks;
  2076. },
  2077. finish: function finish() {
  2078. config.current = this; // Release the test callback to ensure that anything referenced has been
  2079. // released to be garbage collected.
  2080. this.callback = undefined;
  2081. if (this.steps.length) {
  2082. var stepsList = this.steps.join(", ");
  2083. this.pushFailure("Expected assert.verifySteps() to be called before end of test " + "after using assert.step(). Unverified steps: ".concat(stepsList), this.stack);
  2084. }
  2085. if (config.requireExpects && this.expected === null) {
  2086. this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack);
  2087. } else if (this.expected !== null && this.expected !== this.assertions.length) {
  2088. this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack);
  2089. } else if (this.expected === null && !this.assertions.length) {
  2090. this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack);
  2091. }
  2092. var module = this.module;
  2093. var moduleName = module.name;
  2094. var testName = this.testName;
  2095. var skipped = !!this.skip;
  2096. var todo = !!this.todo;
  2097. var bad = 0;
  2098. var storage = config.storage;
  2099. this.runtime = now() - this.started;
  2100. config.stats.all += this.assertions.length;
  2101. config.stats.testCount += 1;
  2102. module.stats.all += this.assertions.length;
  2103. for (var i = 0; i < this.assertions.length; i++) {
  2104. // A failing assertion will counts toward the HTML Reporter's
  2105. // "X assertions, Y failed" line even if it was inside a todo.
  2106. // Inverting this would be similarly confusing since all but the last
  2107. // passing assertion inside a todo test should be considered as good.
  2108. // These stats don't decide the outcome of anything, so counting them
  2109. // as failing seems the most intuitive.
  2110. if (!this.assertions[i].result) {
  2111. bad++;
  2112. config.stats.bad++;
  2113. module.stats.bad++;
  2114. }
  2115. }
  2116. if (skipped) {
  2117. incrementTestsIgnored(module);
  2118. } else {
  2119. incrementTestsRun(module);
  2120. } // Store result when possible.
  2121. // Note that this also marks todo tests as bad, thus they get hoisted,
  2122. // and always run first on refresh.
  2123. if (storage) {
  2124. if (bad) {
  2125. storage.setItem("qunit-test-" + moduleName + "-" + testName, bad);
  2126. } else {
  2127. storage.removeItem("qunit-test-" + moduleName + "-" + testName);
  2128. }
  2129. } // After emitting the js-reporters event we cleanup the assertion data to
  2130. // avoid leaking it. It is not used by the legacy testDone callbacks.
  2131. emit("testEnd", this.testReport.end(true));
  2132. this.testReport.slimAssertions();
  2133. var test = this;
  2134. return runLoggingCallbacks("testDone", {
  2135. name: testName,
  2136. module: moduleName,
  2137. skipped: skipped,
  2138. todo: todo,
  2139. failed: bad,
  2140. passed: this.assertions.length - bad,
  2141. total: this.assertions.length,
  2142. runtime: skipped ? 0 : this.runtime,
  2143. // HTML Reporter use
  2144. assertions: this.assertions,
  2145. testId: this.testId,
  2146. // Source of Test
  2147. // generating stack trace is expensive, so using a getter will help defer this until we need it
  2148. get source() {
  2149. return test.stack;
  2150. }
  2151. }).then(function () {
  2152. if (allTestsExecuted(module)) {
  2153. var completedModules = [module]; // Check if the parent modules, iteratively, are done. If that the case,
  2154. // we emit the `suiteEnd` event and trigger `moduleDone` callback.
  2155. var parent = module.parentModule;
  2156. while (parent && allTestsExecuted(parent)) {
  2157. completedModules.push(parent);
  2158. parent = parent.parentModule;
  2159. }
  2160. return completedModules.reduce(function (promiseChain, completedModule) {
  2161. return promiseChain.then(function () {
  2162. return logSuiteEnd(completedModule);
  2163. });
  2164. }, _Promise.resolve([]));
  2165. }
  2166. }).then(function () {
  2167. config.current = undefined;
  2168. });
  2169. function logSuiteEnd(module) {
  2170. // Reset `module.hooks` to ensure that anything referenced in these hooks
  2171. // has been released to be garbage collected. Descendant modules that were
  2172. // entirely skipped, e.g. due to filtering, will never have this method
  2173. // called for them, but might have hooks with references pinning data in
  2174. // memory (even if the hooks weren't actually executed), so we reset the
  2175. // hooks on all descendant modules here as well. This is safe because we
  2176. // will never call this as long as any descendant modules still have tests
  2177. // to run. This also means that in multi-tiered nesting scenarios we might
  2178. // reset the hooks multiple times on some modules, but that's harmless.
  2179. var modules = [module];
  2180. while (modules.length) {
  2181. var nextModule = modules.shift();
  2182. nextModule.hooks = {};
  2183. modules.push.apply(modules, _toConsumableArray(nextModule.childModules));
  2184. }
  2185. emit("suiteEnd", module.suiteReport.end(true));
  2186. return runLoggingCallbacks("moduleDone", {
  2187. name: module.name,
  2188. tests: module.tests,
  2189. failed: module.stats.bad,
  2190. passed: module.stats.all - module.stats.bad,
  2191. total: module.stats.all,
  2192. runtime: now() - module.stats.started
  2193. });
  2194. }
  2195. },
  2196. preserveTestEnvironment: function preserveTestEnvironment() {
  2197. if (this.preserveEnvironment) {
  2198. this.module.testEnvironment = this.testEnvironment;
  2199. this.testEnvironment = extend({}, this.module.testEnvironment);
  2200. }
  2201. },
  2202. queue: function queue() {
  2203. var test = this;
  2204. if (!this.valid()) {
  2205. incrementTestsIgnored(this.module);
  2206. return;
  2207. }
  2208. function runTest() {
  2209. return [function () {
  2210. return test.before();
  2211. }].concat(_toConsumableArray(test.hooks("before")), [function () {
  2212. test.preserveTestEnvironment();
  2213. }], _toConsumableArray(test.hooks("beforeEach")), [function () {
  2214. test.run();
  2215. }], _toConsumableArray(test.hooks("afterEach").reverse()), _toConsumableArray(test.hooks("after").reverse()), [function () {
  2216. test.after();
  2217. }, function () {
  2218. return test.finish();
  2219. }]);
  2220. }
  2221. var previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName); // Prioritize previously failed tests, detected from storage
  2222. var prioritize = config.reorder && !!previousFailCount;
  2223. this.previousFailure = !!previousFailCount;
  2224. ProcessingQueue.add(runTest, prioritize, config.seed);
  2225. },
  2226. pushResult: function pushResult(resultInfo) {
  2227. if (this !== config.current) {
  2228. var message = resultInfo && resultInfo.message || "";
  2229. var testName = this && this.testName || "";
  2230. var error = "Assertion occurred after test finished.\n" + "> Test: " + testName + "\n" + "> Message: " + message + "\n";
  2231. throw new Error(error);
  2232. } // Destructure of resultInfo = { result, actual, expected, message, negative }
  2233. var details = {
  2234. module: this.module.name,
  2235. name: this.testName,
  2236. result: resultInfo.result,
  2237. message: resultInfo.message,
  2238. actual: resultInfo.actual,
  2239. testId: this.testId,
  2240. negative: resultInfo.negative || false,
  2241. runtime: now() - this.started,
  2242. todo: !!this.todo
  2243. };
  2244. if (hasOwn$1.call(resultInfo, "expected")) {
  2245. details.expected = resultInfo.expected;
  2246. }
  2247. if (!resultInfo.result) {
  2248. var source = resultInfo.source || sourceFromStacktrace();
  2249. if (source) {
  2250. details.source = source;
  2251. }
  2252. }
  2253. this.logAssertion(details);
  2254. this.assertions.push({
  2255. result: !!resultInfo.result,
  2256. message: resultInfo.message
  2257. });
  2258. },
  2259. pushFailure: function pushFailure(message, source, actual) {
  2260. if (!(this instanceof Test)) {
  2261. throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2));
  2262. }
  2263. this.pushResult({
  2264. result: false,
  2265. message: message || "error",
  2266. actual: actual || null,
  2267. source: source
  2268. });
  2269. },
  2270. /**
  2271. * Log assertion details using both the old QUnit.log interface and
  2272. * QUnit.on( "assertion" ) interface.
  2273. *
  2274. * @private
  2275. */
  2276. logAssertion: function logAssertion(details) {
  2277. runLoggingCallbacks("log", details);
  2278. var assertion = {
  2279. passed: details.result,
  2280. actual: details.actual,
  2281. expected: details.expected,
  2282. message: details.message,
  2283. stack: details.source,
  2284. todo: details.todo
  2285. };
  2286. this.testReport.pushAssertion(assertion);
  2287. emit("assertion", assertion);
  2288. },
  2289. resolvePromise: function resolvePromise(promise, phase) {
  2290. if (promise != null) {
  2291. var _test = this;
  2292. var then = promise.then;
  2293. if (objectType(then) === "function") {
  2294. var resume = internalStop(_test);
  2295. var resolve = function resolve() {
  2296. resume();
  2297. };
  2298. if (config.notrycatch) {
  2299. then.call(promise, resolve);
  2300. } else {
  2301. var reject = function reject(error) {
  2302. var message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + _test.testName + "\": " + (error && error.message || error);
  2303. _test.pushFailure(message, extractStacktrace(error, 0)); // Else next test will carry the responsibility
  2304. saveGlobal(); // Unblock
  2305. internalRecover(_test);
  2306. };
  2307. then.call(promise, resolve, reject);
  2308. }
  2309. }
  2310. }
  2311. },
  2312. valid: function valid() {
  2313. var filter = config.filter;
  2314. var regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter);
  2315. var module = config.module && config.module.toLowerCase();
  2316. var fullName = this.module.name + ": " + this.testName;
  2317. function moduleChainNameMatch(testModule) {
  2318. var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
  2319. if (testModuleName === module) {
  2320. return true;
  2321. } else if (testModule.parentModule) {
  2322. return moduleChainNameMatch(testModule.parentModule);
  2323. } else {
  2324. return false;
  2325. }
  2326. }
  2327. function moduleChainIdMatch(testModule) {
  2328. return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
  2329. } // Internally-generated tests are always valid
  2330. if (this.callback && this.callback.validTest) {
  2331. return true;
  2332. }
  2333. if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
  2334. return false;
  2335. }
  2336. if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) {
  2337. return false;
  2338. }
  2339. if (module && !moduleChainNameMatch(this.module)) {
  2340. return false;
  2341. }
  2342. if (!filter) {
  2343. return true;
  2344. }
  2345. return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
  2346. },
  2347. regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
  2348. var regex = new RegExp(pattern, flags);
  2349. var match = regex.test(fullName);
  2350. return match !== exclude;
  2351. },
  2352. stringFilter: function stringFilter(filter, fullName) {
  2353. filter = filter.toLowerCase();
  2354. fullName = fullName.toLowerCase();
  2355. var include = filter.charAt(0) !== "!";
  2356. if (!include) {
  2357. filter = filter.slice(1);
  2358. } // If the filter matches, we need to honour include
  2359. if (fullName.indexOf(filter) !== -1) {
  2360. return include;
  2361. } // Otherwise, do the opposite
  2362. return !include;
  2363. }
  2364. };
  2365. function pushFailure() {
  2366. if (!config.current) {
  2367. throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2));
  2368. } // Gets current test obj
  2369. var currentTest = config.current;
  2370. return currentTest.pushFailure.apply(currentTest, arguments);
  2371. }
  2372. function saveGlobal() {
  2373. config.pollution = [];
  2374. if (config.noglobals) {
  2375. for (var key in globalThis$1) {
  2376. if (hasOwn$1.call(globalThis$1, key)) {
  2377. // In Opera sometimes DOM element ids show up here, ignore them
  2378. if (/^qunit-test-output/.test(key)) {
  2379. continue;
  2380. }
  2381. config.pollution.push(key);
  2382. }
  2383. }
  2384. }
  2385. }
  2386. function checkPollution() {
  2387. var old = config.pollution;
  2388. saveGlobal();
  2389. var newGlobals = diff(config.pollution, old);
  2390. if (newGlobals.length > 0) {
  2391. pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
  2392. }
  2393. var deletedGlobals = diff(old, config.pollution);
  2394. if (deletedGlobals.length > 0) {
  2395. pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
  2396. }
  2397. }
  2398. var focused = false; // indicates that the "only" filter was used
  2399. function addTest(settings) {
  2400. if (focused || config.currentModule.ignored) {
  2401. return;
  2402. }
  2403. var newTest = new Test(settings);
  2404. newTest.queue();
  2405. }
  2406. function addOnlyTest(settings) {
  2407. if (config.currentModule.ignored) {
  2408. return;
  2409. }
  2410. if (!focused) {
  2411. config.queue.length = 0;
  2412. focused = true;
  2413. }
  2414. var newTest = new Test(settings);
  2415. newTest.queue();
  2416. } // Will be exposed as QUnit.test
  2417. function test(testName, callback) {
  2418. addTest({
  2419. testName: testName,
  2420. callback: callback
  2421. });
  2422. }
  2423. function makeEachTestName(testName, argument) {
  2424. return "".concat(testName, " [").concat(argument, "]");
  2425. }
  2426. function runEach(data, eachFn) {
  2427. if (Array.isArray(data)) {
  2428. data.forEach(eachFn);
  2429. } else if (_typeof(data) === "object" && data !== null) {
  2430. var keys = Object.keys(data);
  2431. keys.forEach(function (key) {
  2432. eachFn(data[key], key);
  2433. });
  2434. } else {
  2435. throw new Error("test.each() expects an array or object as input, but\nfound ".concat(_typeof(data), " instead."));
  2436. }
  2437. }
  2438. extend(test, {
  2439. todo: function todo(testName, callback) {
  2440. addTest({
  2441. testName: testName,
  2442. callback: callback,
  2443. todo: true
  2444. });
  2445. },
  2446. skip: function skip(testName) {
  2447. addTest({
  2448. testName: testName,
  2449. skip: true
  2450. });
  2451. },
  2452. only: function only(testName, callback) {
  2453. addOnlyTest({
  2454. testName: testName,
  2455. callback: callback
  2456. });
  2457. },
  2458. each: function each(testName, dataset, callback) {
  2459. runEach(dataset, function (data, testKey) {
  2460. addTest({
  2461. testName: makeEachTestName(testName, testKey),
  2462. callback: callback,
  2463. withData: true,
  2464. data: data
  2465. });
  2466. });
  2467. }
  2468. });
  2469. test.todo.each = function (testName, dataset, callback) {
  2470. runEach(dataset, function (data, testKey) {
  2471. addTest({
  2472. testName: makeEachTestName(testName, testKey),
  2473. callback: callback,
  2474. todo: true,
  2475. withData: true,
  2476. data: data
  2477. });
  2478. });
  2479. };
  2480. test.skip.each = function (testName, dataset) {
  2481. runEach(dataset, function (_, testKey) {
  2482. addTest({
  2483. testName: makeEachTestName(testName, testKey),
  2484. skip: true
  2485. });
  2486. });
  2487. };
  2488. test.only.each = function (testName, dataset, callback) {
  2489. runEach(dataset, function (data, testKey) {
  2490. addOnlyTest({
  2491. testName: makeEachTestName(testName, testKey),
  2492. callback: callback,
  2493. withData: true,
  2494. data: data
  2495. });
  2496. });
  2497. }; // Resets config.timeout with a new timeout duration.
  2498. function resetTestTimeout(timeoutDuration) {
  2499. clearTimeout(config.timeout);
  2500. config.timeout = setTimeout$1(config.timeoutHandler(timeoutDuration), timeoutDuration);
  2501. } // Create a new async pause and return a new function that can release the pause.
  2502. //
  2503. // This mechanism is internally used by:
  2504. //
  2505. // * explicit async pauses, created by calling `assert.async()`,
  2506. // * implicit async pauses, created when `QUnit.test()` or module hook callbacks
  2507. // use async-await or otherwise return a Promise.
  2508. //
  2509. // Happy scenario:
  2510. //
  2511. // * Pause is created by calling internalStop().
  2512. //
  2513. // Pause is released normally by invoking release() during the same test.
  2514. //
  2515. // The release() callback lets internal processing resume.
  2516. //
  2517. // Failure scenarios:
  2518. //
  2519. // * The test fails due to an uncaught exception.
  2520. //
  2521. // In this case, Test.run() will call internalRecover() which empties the clears all
  2522. // async pauses and sets the cancelled flag, which means we silently ignore any
  2523. // late calls to the resume() callback, as we will have moved on to a different
  2524. // test by then, and we don't want to cause an extra "release during a different test"
  2525. // errors that the developer isn't really responsible for. This can happen when a test
  2526. // correctly schedules a call to release(), but also causes an uncaught error. The
  2527. // uncaught error means we will no longer wait for the release (as it might not arrive).
  2528. //
  2529. // * Pause is never released, or called an insufficient number of times.
  2530. //
  2531. // Our timeout handler will kill the pause and resume test processing, basically
  2532. // like internalRecover(), but for one pause instead of any/all.
  2533. //
  2534. // Here, too, any late calls to resume() will be silently ignored to avoid
  2535. // extra errors. We tolerate this since the original test will have already been
  2536. // marked as failure.
  2537. //
  2538. // TODO: QUnit 3 will enable timeouts by default <https://github.com/qunitjs/qunit/issues/1483>,
  2539. // but right now a test will hang indefinitely if async pauses are not released,
  2540. // unless QUnit.config.testTimeout or assert.timeout() is used.
  2541. //
  2542. // * Pause is spontaneously released during a different test,
  2543. // or when no test is currently running.
  2544. //
  2545. // This is close to impossible because this error only happens if the original test
  2546. // succesfully finished first (since other failure scenarios kill pauses and ignore
  2547. // late calls). It can happen if a test ended exactly as expected, but has some
  2548. // external or shared state continuing to hold a reference to the release callback,
  2549. // and either the same test scheduled another call to it in the future, or a later test
  2550. // causes it to be called through some shared state.
  2551. //
  2552. // * Pause release() is called too often, during the same test.
  2553. //
  2554. // This simply throws an error, after which uncaught error handling picks it up
  2555. // and processing resumes.
  2556. function internalStop(test) {
  2557. var requiredCalls = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  2558. config.blocking = true;
  2559. var pauseId = test.nextPauseId++;
  2560. var pause = {
  2561. cancelled: false,
  2562. remaining: requiredCalls
  2563. };
  2564. test.pauses.set(pauseId, pause);
  2565. function release() {
  2566. if (pause.cancelled) {
  2567. return;
  2568. }
  2569. if (config.current === undefined) {
  2570. throw new Error("Unexpected release of async pause after tests finished.\n" + "> Test: ".concat(test.testName, " [async #").concat(pauseId, "]"));
  2571. }
  2572. if (config.current !== test) {
  2573. throw new Error("Unexpected release of async pause during a different test.\n" + "> Test: ".concat(test.testName, " [async #").concat(pauseId, "]"));
  2574. }
  2575. if (pause.remaining <= 0) {
  2576. throw new Error("Tried to release async pause that was already released.\n" + "> Test: ".concat(test.testName, " [async #").concat(pauseId, "]"));
  2577. } // The `requiredCalls` parameter exists to support `assert.async(count)`
  2578. pause.remaining--;
  2579. if (pause.remaining === 0) {
  2580. test.pauses.delete(pauseId);
  2581. }
  2582. internalStart(test);
  2583. } // Set a recovery timeout, if so configured.
  2584. if (setTimeout$1) {
  2585. var timeoutDuration;
  2586. if (typeof test.timeout === "number") {
  2587. timeoutDuration = test.timeout;
  2588. } else if (typeof config.testTimeout === "number") {
  2589. timeoutDuration = config.testTimeout;
  2590. }
  2591. if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
  2592. config.timeoutHandler = function (timeout) {
  2593. return function () {
  2594. config.timeout = null;
  2595. pause.cancelled = true;
  2596. test.pauses.delete(pauseId);
  2597. test.pushFailure("Test took longer than ".concat(timeout, "ms; test timed out."), sourceFromStacktrace(2));
  2598. internalStart(test);
  2599. };
  2600. };
  2601. clearTimeout(config.timeout);
  2602. config.timeout = setTimeout$1(config.timeoutHandler(timeoutDuration), timeoutDuration);
  2603. }
  2604. }
  2605. return release;
  2606. } // Forcefully release all processing holds.
  2607. function internalRecover(test) {
  2608. test.pauses.forEach(function (pause) {
  2609. pause.cancelled = true;
  2610. });
  2611. test.pauses.clear();
  2612. internalStart(test);
  2613. } // Release a processing hold, scheduling a resumption attempt if no holds remain.
  2614. function internalStart(test) {
  2615. // Ignore if other async pauses still exist.
  2616. if (test.pauses.size > 0) {
  2617. return;
  2618. } // Add a slight delay to allow more assertions etc.
  2619. if (setTimeout$1) {
  2620. clearTimeout(config.timeout);
  2621. config.timeout = setTimeout$1(function () {
  2622. if (test.pauses.size > 0) {
  2623. return;
  2624. }
  2625. clearTimeout(config.timeout);
  2626. config.timeout = null;
  2627. begin();
  2628. });
  2629. } else {
  2630. begin();
  2631. }
  2632. }
  2633. function collectTests(module) {
  2634. var tests = [].concat(module.tests);
  2635. var modules = _toConsumableArray(module.childModules); // Do a breadth-first traversal of the child modules
  2636. while (modules.length) {
  2637. var nextModule = modules.shift();
  2638. tests.push.apply(tests, nextModule.tests);
  2639. modules.push.apply(modules, _toConsumableArray(nextModule.childModules));
  2640. }
  2641. return tests;
  2642. } // This returns true after all executable and skippable tests
  2643. // in a module have been proccessed, and informs 'suiteEnd'
  2644. // and moduleDone().
  2645. function allTestsExecuted(module) {
  2646. return module.testsRun + module.testsIgnored === collectTests(module).length;
  2647. } // This returns true during the last executable non-skipped test
  2648. // within a module, and informs the running of the 'after' hook
  2649. // for a given module. This runs only once for a given module,
  2650. // but must run during the last non-skipped test. When it runs,
  2651. // there may be non-zero skipped tests left.
  2652. function lastTestWithinModuleExecuted(module) {
  2653. return module.testsRun === collectTests(module).filter(function (test) {
  2654. return !test.skip;
  2655. }).length - 1;
  2656. }
  2657. function incrementTestsRun(module) {
  2658. module.testsRun++;
  2659. while (module = module.parentModule) {
  2660. module.testsRun++;
  2661. }
  2662. }
  2663. function incrementTestsIgnored(module) {
  2664. module.testsIgnored++;
  2665. while (module = module.parentModule) {
  2666. module.testsIgnored++;
  2667. }
  2668. }
  2669. var Assert = /*#__PURE__*/function () {
  2670. function Assert(testContext) {
  2671. _classCallCheck(this, Assert);
  2672. this.test = testContext;
  2673. } // Assert helpers
  2674. _createClass(Assert, [{
  2675. key: "timeout",
  2676. value: function timeout(duration) {
  2677. if (typeof duration !== "number") {
  2678. throw new Error("You must pass a number as the duration to assert.timeout");
  2679. }
  2680. this.test.timeout = duration; // If a timeout has been set, clear it and reset with the new duration
  2681. if (config.timeout) {
  2682. clearTimeout(config.timeout);
  2683. config.timeout = null;
  2684. if (config.timeoutHandler && this.test.timeout > 0) {
  2685. resetTestTimeout(this.test.timeout);
  2686. }
  2687. }
  2688. } // Documents a "step", which is a string value, in a test as a passing assertion
  2689. }, {
  2690. key: "step",
  2691. value: function step(message) {
  2692. var assertionMessage = message;
  2693. var result = !!message;
  2694. this.test.steps.push(message);
  2695. if (objectType(message) === "undefined" || message === "") {
  2696. assertionMessage = "You must provide a message to assert.step";
  2697. } else if (objectType(message) !== "string") {
  2698. assertionMessage = "You must provide a string value to assert.step";
  2699. result = false;
  2700. }
  2701. this.pushResult({
  2702. result: result,
  2703. message: assertionMessage
  2704. });
  2705. } // Verifies the steps in a test match a given array of string values
  2706. }, {
  2707. key: "verifySteps",
  2708. value: function verifySteps(steps, message) {
  2709. // Since the steps array is just string values, we can clone with slice
  2710. var actualStepsClone = this.test.steps.slice();
  2711. this.deepEqual(actualStepsClone, steps, message);
  2712. this.test.steps.length = 0;
  2713. } // Specify the number of expected assertions to guarantee that failed test
  2714. // (no assertions are run at all) don't slip through.
  2715. }, {
  2716. key: "expect",
  2717. value: function expect(asserts) {
  2718. if (arguments.length === 1) {
  2719. this.test.expected = asserts;
  2720. } else {
  2721. return this.test.expected;
  2722. }
  2723. } // Create a new async pause and return a new function that can release the pause.
  2724. }, {
  2725. key: "async",
  2726. value: function async(count) {
  2727. var requiredCalls = count === undefined ? 1 : count;
  2728. return internalStop(this.test, requiredCalls);
  2729. } // Exports test.push() to the user API
  2730. // Alias of pushResult.
  2731. }, {
  2732. key: "push",
  2733. value: function push(result, actual, expected, message, negative) {
  2734. 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).");
  2735. var currentAssert = this instanceof Assert ? this : config.current.assert;
  2736. return currentAssert.pushResult({
  2737. result: result,
  2738. actual: actual,
  2739. expected: expected,
  2740. message: message,
  2741. negative: negative
  2742. });
  2743. }
  2744. }, {
  2745. key: "pushResult",
  2746. value: function pushResult(resultInfo) {
  2747. // Destructure of resultInfo = { result, actual, expected, message, negative }
  2748. var assert = this;
  2749. var currentTest = assert instanceof Assert && assert.test || config.current; // Backwards compatibility fix.
  2750. // Allows the direct use of global exported assertions and QUnit.assert.*
  2751. // Although, it's use is not recommended as it can leak assertions
  2752. // to other tests from async tests, because we only get a reference to the current test,
  2753. // not exactly the test where assertion were intended to be called.
  2754. if (!currentTest) {
  2755. throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
  2756. }
  2757. if (!(assert instanceof Assert)) {
  2758. assert = currentTest.assert;
  2759. }
  2760. return assert.test.pushResult(resultInfo);
  2761. }
  2762. }, {
  2763. key: "ok",
  2764. value: function ok(result, message) {
  2765. if (!message) {
  2766. message = result ? "okay" : "failed, expected argument to be truthy, was: ".concat(dump.parse(result));
  2767. }
  2768. this.pushResult({
  2769. result: !!result,
  2770. actual: result,
  2771. expected: true,
  2772. message: message
  2773. });
  2774. }
  2775. }, {
  2776. key: "notOk",
  2777. value: function notOk(result, message) {
  2778. if (!message) {
  2779. message = !result ? "okay" : "failed, expected argument to be falsy, was: ".concat(dump.parse(result));
  2780. }
  2781. this.pushResult({
  2782. result: !result,
  2783. actual: result,
  2784. expected: false,
  2785. message: message
  2786. });
  2787. }
  2788. }, {
  2789. key: "true",
  2790. value: function _true(result, message) {
  2791. this.pushResult({
  2792. result: result === true,
  2793. actual: result,
  2794. expected: true,
  2795. message: message
  2796. });
  2797. }
  2798. }, {
  2799. key: "false",
  2800. value: function _false(result, message) {
  2801. this.pushResult({
  2802. result: result === false,
  2803. actual: result,
  2804. expected: false,
  2805. message: message
  2806. });
  2807. }
  2808. }, {
  2809. key: "equal",
  2810. value: function equal(actual, expected, message) {
  2811. // eslint-disable-next-line eqeqeq
  2812. var result = expected == actual;
  2813. this.pushResult({
  2814. result: result,
  2815. actual: actual,
  2816. expected: expected,
  2817. message: message
  2818. });
  2819. }
  2820. }, {
  2821. key: "notEqual",
  2822. value: function notEqual(actual, expected, message) {
  2823. // eslint-disable-next-line eqeqeq
  2824. var result = expected != actual;
  2825. this.pushResult({
  2826. result: result,
  2827. actual: actual,
  2828. expected: expected,
  2829. message: message,
  2830. negative: true
  2831. });
  2832. }
  2833. }, {
  2834. key: "propEqual",
  2835. value: function propEqual(actual, expected, message) {
  2836. actual = objectValues(actual);
  2837. expected = objectValues(expected);
  2838. this.pushResult({
  2839. result: equiv(actual, expected),
  2840. actual: actual,
  2841. expected: expected,
  2842. message: message
  2843. });
  2844. }
  2845. }, {
  2846. key: "notPropEqual",
  2847. value: function notPropEqual(actual, expected, message) {
  2848. actual = objectValues(actual);
  2849. expected = objectValues(expected);
  2850. this.pushResult({
  2851. result: !equiv(actual, expected),
  2852. actual: actual,
  2853. expected: expected,
  2854. message: message,
  2855. negative: true
  2856. });
  2857. }
  2858. }, {
  2859. key: "deepEqual",
  2860. value: function deepEqual(actual, expected, message) {
  2861. this.pushResult({
  2862. result: equiv(actual, expected),
  2863. actual: actual,
  2864. expected: expected,
  2865. message: message
  2866. });
  2867. }
  2868. }, {
  2869. key: "notDeepEqual",
  2870. value: function notDeepEqual(actual, expected, message) {
  2871. this.pushResult({
  2872. result: !equiv(actual, expected),
  2873. actual: actual,
  2874. expected: expected,
  2875. message: message,
  2876. negative: true
  2877. });
  2878. }
  2879. }, {
  2880. key: "strictEqual",
  2881. value: function strictEqual(actual, expected, message) {
  2882. this.pushResult({
  2883. result: expected === actual,
  2884. actual: actual,
  2885. expected: expected,
  2886. message: message
  2887. });
  2888. }
  2889. }, {
  2890. key: "notStrictEqual",
  2891. value: function notStrictEqual(actual, expected, message) {
  2892. this.pushResult({
  2893. result: expected !== actual,
  2894. actual: actual,
  2895. expected: expected,
  2896. message: message,
  2897. negative: true
  2898. });
  2899. }
  2900. }, {
  2901. key: "throws",
  2902. value: function throws(block, expected, message) {
  2903. var _validateExpectedExce = validateExpectedExceptionArgs(expected, message, "throws");
  2904. var _validateExpectedExce2 = _slicedToArray(_validateExpectedExce, 2);
  2905. expected = _validateExpectedExce2[0];
  2906. message = _validateExpectedExce2[1];
  2907. var currentTest = this instanceof Assert && this.test || config.current;
  2908. if (objectType(block) !== "function") {
  2909. var _message = "The value provided to `assert.throws` in " + "\"" + currentTest.testName + "\" was not a function.";
  2910. currentTest.assert.pushResult({
  2911. result: false,
  2912. actual: block,
  2913. message: _message
  2914. });
  2915. return;
  2916. }
  2917. var actual;
  2918. var result = false;
  2919. currentTest.ignoreGlobalErrors = true;
  2920. try {
  2921. block.call(currentTest.testEnvironment);
  2922. } catch (e) {
  2923. actual = e;
  2924. }
  2925. currentTest.ignoreGlobalErrors = false;
  2926. if (actual) {
  2927. var _validateException = validateException(actual, expected, message);
  2928. var _validateException2 = _slicedToArray(_validateException, 3);
  2929. result = _validateException2[0];
  2930. expected = _validateException2[1];
  2931. message = _validateException2[2];
  2932. }
  2933. currentTest.assert.pushResult({
  2934. result: result,
  2935. // undefined if it didn't throw
  2936. actual: actual && errorString(actual),
  2937. expected: expected,
  2938. message: message
  2939. });
  2940. }
  2941. }, {
  2942. key: "rejects",
  2943. value: function rejects(promise, expected, message) {
  2944. var _validateExpectedExce3 = validateExpectedExceptionArgs(expected, message, "rejects");
  2945. var _validateExpectedExce4 = _slicedToArray(_validateExpectedExce3, 2);
  2946. expected = _validateExpectedExce4[0];
  2947. message = _validateExpectedExce4[1];
  2948. var currentTest = this instanceof Assert && this.test || config.current;
  2949. var then = promise && promise.then;
  2950. if (objectType(then) !== "function") {
  2951. var _message2 = "The value provided to `assert.rejects` in " + "\"" + currentTest.testName + "\" was not a promise.";
  2952. currentTest.assert.pushResult({
  2953. result: false,
  2954. message: _message2,
  2955. actual: promise
  2956. });
  2957. return;
  2958. }
  2959. var done = this.async();
  2960. return then.call(promise, function handleFulfillment() {
  2961. var message = "The promise returned by the `assert.rejects` callback in " + "\"" + currentTest.testName + "\" did not reject.";
  2962. currentTest.assert.pushResult({
  2963. result: false,
  2964. message: message,
  2965. actual: promise
  2966. });
  2967. done();
  2968. }, function handleRejection(actual) {
  2969. var result;
  2970. var _validateException3 = validateException(actual, expected, message);
  2971. var _validateException4 = _slicedToArray(_validateException3, 3);
  2972. result = _validateException4[0];
  2973. expected = _validateException4[1];
  2974. message = _validateException4[2];
  2975. currentTest.assert.pushResult({
  2976. result: result,
  2977. // leave rejection value of undefined as-is
  2978. actual: actual && errorString(actual),
  2979. expected: expected,
  2980. message: message
  2981. });
  2982. done();
  2983. });
  2984. }
  2985. }]);
  2986. return Assert;
  2987. }();
  2988. function validateExpectedExceptionArgs(expected, message, assertionMethod) {
  2989. var expectedType = objectType(expected); // 'expected' is optional unless doing string comparison
  2990. if (expectedType === "string") {
  2991. if (message === undefined) {
  2992. message = expected;
  2993. expected = undefined;
  2994. return [expected, message];
  2995. } else {
  2996. throw new Error("assert." + assertionMethod + " does not accept a string value for the expected argument.\n" + "Use a non-string object value (e.g. RegExp or validator function) " + "instead if necessary.");
  2997. }
  2998. }
  2999. var valid = !expected || // TODO: be more explicit here
  3000. expectedType === "regexp" || expectedType === "function" || expectedType === "object";
  3001. if (!valid) {
  3002. var _message3 = "Invalid expected value type (" + expectedType + ") " + "provided to assert." + assertionMethod + ".";
  3003. throw new Error(_message3);
  3004. }
  3005. return [expected, message];
  3006. }
  3007. function validateException(actual, expected, message) {
  3008. var result = false;
  3009. var expectedType = objectType(expected); // These branches should be exhaustive, based on validation done in validateExpectedException
  3010. // We don't want to validate
  3011. if (!expected) {
  3012. result = true; // Expected is a regexp
  3013. } else if (expectedType === "regexp") {
  3014. result = expected.test(errorString(actual)); // Log the string form of the regexp
  3015. expected = String(expected); // Expected is a constructor, maybe an Error constructor.
  3016. // Note the extra check on its prototype - this is an implicit
  3017. // requirement of "instanceof", else it will throw a TypeError.
  3018. } else if (expectedType === "function" && expected.prototype !== undefined && actual instanceof expected) {
  3019. result = true; // Expected is an Error object
  3020. } else if (expectedType === "object") {
  3021. result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message; // Log the string form of the Error object
  3022. expected = errorString(expected); // Expected is a validation function which returns true if validation passed
  3023. } else if (expectedType === "function") {
  3024. // protect against accidental semantics which could hard error in the test
  3025. try {
  3026. result = expected.call({}, actual) === true;
  3027. expected = null;
  3028. } catch (e) {
  3029. // assign the "expected" to a nice error string to communicate the local failure to the user
  3030. expected = errorString(e);
  3031. }
  3032. }
  3033. return [result, expected, message];
  3034. } // Provide an alternative to assert.throws(), for environments that consider throws a reserved word
  3035. // Known to us are: Closure Compiler, Narwhal
  3036. // eslint-disable-next-line dot-notation
  3037. Assert.prototype.raises = Assert.prototype["throws"];
  3038. /* global module, exports, define */
  3039. function exportQUnit(QUnit) {
  3040. var exportedModule = false;
  3041. if (window$1 && document) {
  3042. // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
  3043. if (window$1.QUnit && window$1.QUnit.version) {
  3044. throw new Error("QUnit has already been defined.");
  3045. }
  3046. window$1.QUnit = QUnit;
  3047. exportedModule = true;
  3048. } // For Node.js
  3049. if (typeof module !== "undefined" && module && module.exports) {
  3050. module.exports = QUnit; // For consistency with CommonJS environments' exports
  3051. module.exports.QUnit = QUnit;
  3052. exportedModule = true;
  3053. } // For CommonJS with exports, but without module.exports, like Rhino
  3054. if (typeof exports !== "undefined" && exports) {
  3055. exports.QUnit = QUnit;
  3056. exportedModule = true;
  3057. } // For AMD
  3058. if (typeof define === "function" && define.amd) {
  3059. define(function () {
  3060. return QUnit;
  3061. });
  3062. QUnit.config.autostart = false;
  3063. exportedModule = true;
  3064. } // For Web/Service Workers
  3065. if (self$1 && self$1.WorkerGlobalScope && self$1 instanceof self$1.WorkerGlobalScope) {
  3066. self$1.QUnit = QUnit;
  3067. exportedModule = true;
  3068. } // For other environments, such as SpiderMonkey (mozjs) and other
  3069. // embedded JavaScript engines
  3070. if (!exportedModule) {
  3071. globalThis$1.QUnit = QUnit;
  3072. }
  3073. }
  3074. var ConsoleReporter = /*#__PURE__*/function () {
  3075. function ConsoleReporter(runner) {
  3076. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3077. _classCallCheck(this, ConsoleReporter);
  3078. // Cache references to console methods to ensure we can report failures
  3079. // from tests tests that mock the console object itself.
  3080. // https://github.com/qunitjs/qunit/issues/1340
  3081. // Support IE 9: Function#bind is supported, but no console.log.bind().
  3082. this.log = options.log || Function.prototype.bind.call(console$1.log, console$1);
  3083. runner.on("error", this.onError.bind(this));
  3084. runner.on("runStart", this.onRunStart.bind(this));
  3085. runner.on("testStart", this.onTestStart.bind(this));
  3086. runner.on("testEnd", this.onTestEnd.bind(this));
  3087. runner.on("runEnd", this.onRunEnd.bind(this));
  3088. }
  3089. _createClass(ConsoleReporter, [{
  3090. key: "onError",
  3091. value: function onError(error) {
  3092. this.log("error", error);
  3093. }
  3094. }, {
  3095. key: "onRunStart",
  3096. value: function onRunStart(runStart) {
  3097. this.log("runStart", runStart);
  3098. }
  3099. }, {
  3100. key: "onTestStart",
  3101. value: function onTestStart(test) {
  3102. this.log("testStart", test);
  3103. }
  3104. }, {
  3105. key: "onTestEnd",
  3106. value: function onTestEnd(test) {
  3107. this.log("testEnd", test);
  3108. }
  3109. }, {
  3110. key: "onRunEnd",
  3111. value: function onRunEnd(runEnd) {
  3112. this.log("runEnd", runEnd);
  3113. }
  3114. }], [{
  3115. key: "init",
  3116. value: function init(runner, options) {
  3117. return new ConsoleReporter(runner, options);
  3118. }
  3119. }]);
  3120. return ConsoleReporter;
  3121. }();
  3122. var FORCE_COLOR,
  3123. NODE_DISABLE_COLORS,
  3124. NO_COLOR,
  3125. TERM,
  3126. isTTY = true;
  3127. if (typeof process !== 'undefined') {
  3128. var _process$env = process.env;
  3129. FORCE_COLOR = _process$env.FORCE_COLOR;
  3130. NODE_DISABLE_COLORS = _process$env.NODE_DISABLE_COLORS;
  3131. NO_COLOR = _process$env.NO_COLOR;
  3132. TERM = _process$env.TERM;
  3133. isTTY = process.stdout && process.stdout.isTTY;
  3134. }
  3135. var $ = {
  3136. enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY),
  3137. // modifiers
  3138. reset: init(0, 0),
  3139. bold: init(1, 22),
  3140. dim: init(2, 22),
  3141. italic: init(3, 23),
  3142. underline: init(4, 24),
  3143. inverse: init(7, 27),
  3144. hidden: init(8, 28),
  3145. strikethrough: init(9, 29),
  3146. // colors
  3147. black: init(30, 39),
  3148. red: init(31, 39),
  3149. green: init(32, 39),
  3150. yellow: init(33, 39),
  3151. blue: init(34, 39),
  3152. magenta: init(35, 39),
  3153. cyan: init(36, 39),
  3154. white: init(37, 39),
  3155. gray: init(90, 39),
  3156. grey: init(90, 39),
  3157. // background colors
  3158. bgBlack: init(40, 49),
  3159. bgRed: init(41, 49),
  3160. bgGreen: init(42, 49),
  3161. bgYellow: init(43, 49),
  3162. bgBlue: init(44, 49),
  3163. bgMagenta: init(45, 49),
  3164. bgCyan: init(46, 49),
  3165. bgWhite: init(47, 49)
  3166. };
  3167. function run(arr, str) {
  3168. var i = 0,
  3169. tmp,
  3170. beg = '',
  3171. end = '';
  3172. for (; i < arr.length; i++) {
  3173. tmp = arr[i];
  3174. beg += tmp.open;
  3175. end += tmp.close;
  3176. if (!!~str.indexOf(tmp.close)) {
  3177. str = str.replace(tmp.rgx, tmp.close + tmp.open);
  3178. }
  3179. }
  3180. return beg + str + end;
  3181. }
  3182. function chain(has, keys) {
  3183. var ctx = {
  3184. has: has,
  3185. keys: keys
  3186. };
  3187. ctx.reset = $.reset.bind(ctx);
  3188. ctx.bold = $.bold.bind(ctx);
  3189. ctx.dim = $.dim.bind(ctx);
  3190. ctx.italic = $.italic.bind(ctx);
  3191. ctx.underline = $.underline.bind(ctx);
  3192. ctx.inverse = $.inverse.bind(ctx);
  3193. ctx.hidden = $.hidden.bind(ctx);
  3194. ctx.strikethrough = $.strikethrough.bind(ctx);
  3195. ctx.black = $.black.bind(ctx);
  3196. ctx.red = $.red.bind(ctx);
  3197. ctx.green = $.green.bind(ctx);
  3198. ctx.yellow = $.yellow.bind(ctx);
  3199. ctx.blue = $.blue.bind(ctx);
  3200. ctx.magenta = $.magenta.bind(ctx);
  3201. ctx.cyan = $.cyan.bind(ctx);
  3202. ctx.white = $.white.bind(ctx);
  3203. ctx.gray = $.gray.bind(ctx);
  3204. ctx.grey = $.grey.bind(ctx);
  3205. ctx.bgBlack = $.bgBlack.bind(ctx);
  3206. ctx.bgRed = $.bgRed.bind(ctx);
  3207. ctx.bgGreen = $.bgGreen.bind(ctx);
  3208. ctx.bgYellow = $.bgYellow.bind(ctx);
  3209. ctx.bgBlue = $.bgBlue.bind(ctx);
  3210. ctx.bgMagenta = $.bgMagenta.bind(ctx);
  3211. ctx.bgCyan = $.bgCyan.bind(ctx);
  3212. ctx.bgWhite = $.bgWhite.bind(ctx);
  3213. return ctx;
  3214. }
  3215. function init(open, close) {
  3216. var blk = {
  3217. open: "\x1B[".concat(open, "m"),
  3218. close: "\x1B[".concat(close, "m"),
  3219. rgx: new RegExp("\\x1b\\[".concat(close, "m"), 'g')
  3220. };
  3221. return function (txt) {
  3222. if (this !== void 0 && this.has !== void 0) {
  3223. !!~this.has.indexOf(open) || (this.has.push(open), this.keys.push(blk));
  3224. return txt === void 0 ? this : $.enabled ? run(this.keys, txt + '') : txt + '';
  3225. }
  3226. return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt + '') : txt + '';
  3227. };
  3228. }
  3229. var hasOwn = Object.prototype.hasOwnProperty;
  3230. /**
  3231. * Format a given value into YAML.
  3232. *
  3233. * YAML is a superset of JSON that supports all the same data
  3234. * types and syntax, and more. As such, it is always possible
  3235. * to fallback to JSON.stringfify, but we generally avoid
  3236. * that to make output easier to read for humans.
  3237. *
  3238. * Supported data types:
  3239. *
  3240. * - null
  3241. * - boolean
  3242. * - number
  3243. * - string
  3244. * - array
  3245. * - object
  3246. *
  3247. * Anything else (including NaN, Infinity, and undefined)
  3248. * must be described in strings, for display purposes.
  3249. *
  3250. * Note that quotes are optional in YAML strings if the
  3251. * strings are "simple", and as such we generally prefer
  3252. * that for improved readability. We output strings in
  3253. * one of three ways:
  3254. *
  3255. * - bare unquoted text, for simple one-line strings.
  3256. * - JSON (quoted text), for complex one-line strings.
  3257. * - YAML Block, for complex multi-line strings.
  3258. *
  3259. * Objects with cyclical references will be stringifed as
  3260. * "[Circular]" as they cannot otherwise be represented.
  3261. */
  3262. function prettyYamlValue(value) {
  3263. var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;
  3264. if (value === undefined) {
  3265. // Not supported in JSON/YAML, turn into string
  3266. // and let the below output it as bare string.
  3267. value = String(value);
  3268. } // Support IE 9-11: Use isFinite instead of ES6 Number.isFinite
  3269. if (typeof value === "number" && !isFinite(value)) {
  3270. // Turn NaN and Infinity into simple strings.
  3271. // Paranoia: Don't return directly just in case there's
  3272. // a way to add special characters here.
  3273. value = String(value);
  3274. }
  3275. if (typeof value === "number") {
  3276. // Simple numbers
  3277. return JSON.stringify(value);
  3278. }
  3279. if (typeof value === "string") {
  3280. // If any of these match, then we can't output it
  3281. // as bare unquoted text, because that would either
  3282. // cause data loss or invalid YAML syntax.
  3283. //
  3284. // - Quotes, escapes, line breaks, or JSON-like stuff.
  3285. var rSpecialJson = /['"\\/[{}\]\r\n]/; // - Characters that are special at the start of a YAML value
  3286. var rSpecialYaml = /[-?:,[\]{}#&*!|=>'"%@`]/; // - Leading or trailing whitespace.
  3287. var rUntrimmed = /(^\s|\s$)/; // - Ambiguous as YAML number, e.g. '2', '-1.2', '.2', or '2_000'
  3288. var rNumerical = /^[\d._-]+$/; // - Ambiguous as YAML bool.
  3289. // Use case-insensitive match, although technically only
  3290. // fully-lower, fully-upper, or uppercase-first would be ambiguous.
  3291. // e.g. true/True/TRUE, but not tRUe.
  3292. var rBool = /^(true|false|y|n|yes|no|on|off)$/i; // Is this a complex string?
  3293. if (value === "" || rSpecialJson.test(value) || rSpecialYaml.test(value[0]) || rUntrimmed.test(value) || rNumerical.test(value) || rBool.test(value)) {
  3294. if (!/\n/.test(value)) {
  3295. // Complex one-line string, use JSON (quoted string)
  3296. return JSON.stringify(value);
  3297. } // See also <https://yaml-multiline.info/>
  3298. // Support IE 9-11: Avoid ES6 String#repeat
  3299. var prefix = new Array(indent + 1).join(" ");
  3300. var trailingLinebreakMatch = value.match(/\n+$/);
  3301. var trailingLinebreaks = trailingLinebreakMatch ? trailingLinebreakMatch[0].length : 0;
  3302. if (trailingLinebreaks === 1) {
  3303. // Use the most straight-forward "Block" string in YAML
  3304. // without any "Chomping" indicators.
  3305. var lines = value // Ignore the last new line, since we'll get that one for free
  3306. // with the straight-forward Block syntax.
  3307. .replace(/\n$/, "").split("\n").map(function (line) {
  3308. return prefix + line;
  3309. });
  3310. return "|\n" + lines.join("\n");
  3311. } else {
  3312. // This has either no trailing new lines, or more than 1.
  3313. // Use |+ so that YAML parsers will preserve it exactly.
  3314. var _lines = value.split("\n").map(function (line) {
  3315. return prefix + line;
  3316. });
  3317. return "|+\n" + _lines.join("\n");
  3318. }
  3319. } else {
  3320. // Simple string, use bare unquoted text
  3321. return value;
  3322. }
  3323. } // Handle null, boolean, array, and object
  3324. return JSON.stringify(decycledShallowClone(value), null, 2);
  3325. }
  3326. /**
  3327. * Creates a shallow clone of an object where cycles have
  3328. * been replaced with "[Circular]".
  3329. */
  3330. function decycledShallowClone(object) {
  3331. var ancestors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  3332. if (ancestors.indexOf(object) !== -1) {
  3333. return "[Circular]";
  3334. }
  3335. var clone;
  3336. var type = Object.prototype.toString.call(object).replace(/^\[.+\s(.+?)]$/, "$1").toLowerCase();
  3337. switch (type) {
  3338. case "array":
  3339. ancestors.push(object);
  3340. clone = object.map(function (element) {
  3341. return decycledShallowClone(element, ancestors);
  3342. });
  3343. ancestors.pop();
  3344. break;
  3345. case "object":
  3346. ancestors.push(object);
  3347. clone = {};
  3348. Object.keys(object).forEach(function (key) {
  3349. clone[key] = decycledShallowClone(object[key], ancestors);
  3350. });
  3351. ancestors.pop();
  3352. break;
  3353. default:
  3354. clone = object;
  3355. }
  3356. return clone;
  3357. }
  3358. var TapReporter = /*#__PURE__*/function () {
  3359. function TapReporter(runner) {
  3360. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3361. _classCallCheck(this, TapReporter);
  3362. // Cache references to console methods to ensure we can report failures
  3363. // from tests tests that mock the console object itself.
  3364. // https://github.com/qunitjs/qunit/issues/1340
  3365. // Support IE 9: Function#bind is supported, but no console.log.bind().
  3366. this.log = options.log || Function.prototype.bind.call(console$1.log, console$1);
  3367. this.testCount = 0;
  3368. this.ended = false;
  3369. this.bailed = false;
  3370. runner.on("error", this.onError.bind(this));
  3371. runner.on("runStart", this.onRunStart.bind(this));
  3372. runner.on("testEnd", this.onTestEnd.bind(this));
  3373. runner.on("runEnd", this.onRunEnd.bind(this));
  3374. }
  3375. _createClass(TapReporter, [{
  3376. key: "onRunStart",
  3377. value: function onRunStart(_globalSuite) {
  3378. this.log("TAP version 13");
  3379. }
  3380. }, {
  3381. key: "onError",
  3382. value: function onError(error) {
  3383. if (this.bailed) {
  3384. return;
  3385. }
  3386. this.bailed = true; // Imitate onTestEnd
  3387. // Skip this if we're past "runEnd" as it would look odd
  3388. if (!this.ended) {
  3389. this.testCount = this.testCount + 1;
  3390. this.log($.red("not ok ".concat(this.testCount, " global failure")));
  3391. this.logError(error);
  3392. }
  3393. this.log("Bail out! " + errorString(error).split("\n")[0]);
  3394. if (this.ended) {
  3395. this.logError(error);
  3396. }
  3397. }
  3398. }, {
  3399. key: "onTestEnd",
  3400. value: function onTestEnd(test) {
  3401. var _this = this;
  3402. this.testCount = this.testCount + 1;
  3403. if (test.status === "passed") {
  3404. this.log("ok ".concat(this.testCount, " ").concat(test.fullName.join(" > ")));
  3405. } else if (test.status === "skipped") {
  3406. this.log($.yellow("ok ".concat(this.testCount, " # SKIP ").concat(test.fullName.join(" > "))));
  3407. } else if (test.status === "todo") {
  3408. this.log($.cyan("not ok ".concat(this.testCount, " # TODO ").concat(test.fullName.join(" > "))));
  3409. test.errors.forEach(function (error) {
  3410. return _this.logAssertion(error, "todo");
  3411. });
  3412. } else {
  3413. this.log($.red("not ok ".concat(this.testCount, " ").concat(test.fullName.join(" > "))));
  3414. test.errors.forEach(function (error) {
  3415. return _this.logAssertion(error);
  3416. });
  3417. }
  3418. }
  3419. }, {
  3420. key: "onRunEnd",
  3421. value: function onRunEnd(globalSuite) {
  3422. this.ended = true;
  3423. this.log("1..".concat(globalSuite.testCounts.total));
  3424. this.log("# pass ".concat(globalSuite.testCounts.passed));
  3425. this.log($.yellow("# skip ".concat(globalSuite.testCounts.skipped)));
  3426. this.log($.cyan("# todo ".concat(globalSuite.testCounts.todo)));
  3427. this.log($.red("# fail ".concat(globalSuite.testCounts.failed)));
  3428. }
  3429. }, {
  3430. key: "logAssertion",
  3431. value: function logAssertion(error, severity) {
  3432. var out = " ---";
  3433. out += "\n message: ".concat(prettyYamlValue(error.message || "failed"));
  3434. out += "\n severity: ".concat(prettyYamlValue(severity || "failed"));
  3435. if (hasOwn.call(error, "actual")) {
  3436. out += "\n actual : ".concat(prettyYamlValue(error.actual));
  3437. }
  3438. if (hasOwn.call(error, "expected")) {
  3439. out += "\n expected: ".concat(prettyYamlValue(error.expected));
  3440. }
  3441. if (error.stack) {
  3442. // Since stacks aren't user generated, take a bit of liberty by
  3443. // adding a trailing new line to allow a straight-forward YAML Blocks.
  3444. out += "\n stack: ".concat(prettyYamlValue(error.stack + "\n"));
  3445. }
  3446. out += "\n ...";
  3447. this.log(out);
  3448. }
  3449. }, {
  3450. key: "logError",
  3451. value: function logError(error) {
  3452. var out = " ---";
  3453. out += "\n message: ".concat(prettyYamlValue(errorString(error)));
  3454. out += "\n severity: ".concat(prettyYamlValue("failed"));
  3455. if (error && error.stack) {
  3456. out += "\n stack: ".concat(prettyYamlValue(error.stack + "\n"));
  3457. }
  3458. out += "\n ...";
  3459. this.log(out);
  3460. }
  3461. }], [{
  3462. key: "init",
  3463. value: function init(runner, options) {
  3464. return new TapReporter(runner, options);
  3465. }
  3466. }]);
  3467. return TapReporter;
  3468. }();
  3469. var reporters = {
  3470. console: ConsoleReporter,
  3471. tap: TapReporter
  3472. };
  3473. /**
  3474. * Handle a global error that should result in a failed test run.
  3475. *
  3476. * Summary:
  3477. *
  3478. * - If we're strictly inside a test (or one if its module hooks), the exception
  3479. * becomes a failed assertion.
  3480. *
  3481. * This has the important side-effect that uncaught exceptions (such as
  3482. * calling an undefined function) during a "todo" test do NOT result in
  3483. * a failed test run.
  3484. *
  3485. * - If we're anywhere outside a test (be it in early event callbacks, or
  3486. * internally between tests, or somewhere after "runEnd" if the process is
  3487. * still alive for some reason), then send an "error" event to the reporters.
  3488. *
  3489. * @since 2.17.0
  3490. * @param {Error|any} error
  3491. */
  3492. function onUncaughtException(error) {
  3493. if (config.current) {
  3494. config.current.assert.pushResult({
  3495. result: false,
  3496. message: "global failure: ".concat(errorString(error)),
  3497. // We could let callers specify an offset to subtract a number of frames via
  3498. // sourceFromStacktrace, in case they are a wrapper further away from the error
  3499. // handler, and thus reduce some noise in the stack trace. However, we're not
  3500. // doing this right now because it would almost never be used in practice given
  3501. // the vast majority of error values will be Error objects, and thus have their
  3502. // own stack trace already.
  3503. source: error && error.stack || sourceFromStacktrace(2)
  3504. });
  3505. } else {
  3506. // The "error" event was added in QUnit 2.17.
  3507. // Increase "bad assertion" stats despite no longer pushing an assertion in this case.
  3508. // This ensures "runEnd" and "QUnit.done()" handlers behave as expected, since the "bad"
  3509. // count is typically how reporters decide on the boolean outcome of the test run.
  3510. globalSuite.globalFailureCount++;
  3511. config.stats.bad++;
  3512. config.stats.all++;
  3513. emit("error", error);
  3514. }
  3515. }
  3516. /**
  3517. * Handle a window.onerror error.
  3518. *
  3519. * If there is a current test that sets the internal `ignoreGlobalErrors` field
  3520. * (such as during `assert.throws()`), then the error is ignored and native
  3521. * error reporting is suppressed as well. This is because in browsers, an error
  3522. * can sometimes end up in `window.onerror` instead of in the local try/catch.
  3523. * This ignoring of errors does not apply to our general onUncaughtException
  3524. * method, nor to our `unhandledRejection` handlers, as those are not meant
  3525. * to receive an "expected" error during `assert.throws()`.
  3526. *
  3527. * @see <https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror>
  3528. * @deprecated since 2.17.0 Use QUnit.onUncaughtException instead.
  3529. * @param {Object} details
  3530. * @param {string} details.message
  3531. * @param {string} details.fileName
  3532. * @param {number} details.lineNumber
  3533. * @param {string|undefined} [details.stacktrace]
  3534. * @return {bool} True if native error reporting should be suppressed.
  3535. */
  3536. function onWindowError(details) {
  3537. Logger.warn("QUnit.onError is deprecated and will be removed in QUnit 3.0." + " Please use QUnit.onUncaughtException instead.");
  3538. if (config.current && config.current.ignoreGlobalErrors) {
  3539. return true;
  3540. }
  3541. var err = new Error(details.message);
  3542. err.stack = details.stacktrace || details.fileName + ":" + details.lineNumber;
  3543. onUncaughtException(err);
  3544. return false;
  3545. }
  3546. var QUnit = {};
  3547. var globalSuite = new SuiteReport(); // The initial "currentModule" represents the global (or top-level) module that
  3548. // is not explicitly defined by the user, therefore we add the "globalSuite" to
  3549. // it since each module has a suiteReport associated with it.
  3550. config.currentModule.suiteReport = globalSuite;
  3551. var globalStartCalled = false;
  3552. var runStarted = false; // Figure out if we're running the tests from a server or not
  3553. QUnit.isLocal = window$1 && window$1.location && window$1.location.protocol === "file:"; // Expose the current QUnit version
  3554. QUnit.version = "2.17.2";
  3555. extend(QUnit, {
  3556. config: config,
  3557. dump: dump,
  3558. equiv: equiv,
  3559. reporters: reporters,
  3560. is: is,
  3561. objectType: objectType,
  3562. on: on,
  3563. onError: onWindowError,
  3564. onUncaughtException: onUncaughtException,
  3565. pushFailure: pushFailure,
  3566. assert: Assert.prototype,
  3567. module: module$1,
  3568. test: test,
  3569. // alias other test flavors for easy access
  3570. todo: test.todo,
  3571. skip: test.skip,
  3572. only: test.only,
  3573. start: function start(count) {
  3574. if (config.current) {
  3575. throw new Error("QUnit.start cannot be called inside a test context.");
  3576. }
  3577. var globalStartAlreadyCalled = globalStartCalled;
  3578. globalStartCalled = true;
  3579. if (runStarted) {
  3580. throw new Error("Called start() while test already started running");
  3581. }
  3582. if (globalStartAlreadyCalled || count > 1) {
  3583. throw new Error("Called start() outside of a test context too many times");
  3584. }
  3585. if (config.autostart) {
  3586. throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
  3587. }
  3588. if (!config.pageLoaded) {
  3589. // The page isn't completely loaded yet, so we set autostart and then
  3590. // load if we're in Node or wait for the browser's load event.
  3591. config.autostart = true; // Starts from Node even if .load was not previously called. We still return
  3592. // early otherwise we'll wind up "beginning" twice.
  3593. if (!document) {
  3594. QUnit.load();
  3595. }
  3596. return;
  3597. }
  3598. scheduleBegin();
  3599. },
  3600. onUnhandledRejection: function onUnhandledRejection(reason) {
  3601. Logger.warn("QUnit.onUnhandledRejection is deprecated and will be removed in QUnit 3.0." + " Please use QUnit.onUncaughtException instead.");
  3602. onUncaughtException(reason);
  3603. },
  3604. extend: function extend$1() {
  3605. Logger.warn("QUnit.extend is deprecated and will be removed in QUnit 3.0." + " Please use Object.assign instead."); // delegate to utility implementation, which does not warn and can be used elsewhere internally
  3606. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3607. args[_key] = arguments[_key];
  3608. }
  3609. return extend.apply(this, args);
  3610. },
  3611. load: function load() {
  3612. config.pageLoaded = true; // Initialize the configuration options
  3613. extend(config, {
  3614. started: 0,
  3615. updateRate: 1000,
  3616. autostart: true,
  3617. filter: ""
  3618. }, true);
  3619. if (!runStarted) {
  3620. config.blocking = false;
  3621. if (config.autostart) {
  3622. scheduleBegin();
  3623. }
  3624. }
  3625. },
  3626. stack: function stack(offset) {
  3627. offset = (offset || 0) + 2;
  3628. return sourceFromStacktrace(offset);
  3629. }
  3630. });
  3631. registerLoggingCallbacks(QUnit);
  3632. function scheduleBegin() {
  3633. runStarted = true; // Add a slight delay to allow definition of more modules and tests.
  3634. if (setTimeout$1) {
  3635. setTimeout$1(function () {
  3636. begin();
  3637. });
  3638. } else {
  3639. begin();
  3640. }
  3641. }
  3642. function unblockAndAdvanceQueue() {
  3643. config.blocking = false;
  3644. ProcessingQueue.advance();
  3645. }
  3646. function begin() {
  3647. if (config.started) {
  3648. unblockAndAdvanceQueue();
  3649. return;
  3650. } // The test run hasn't officially begun yet
  3651. // Record the time of the test run's beginning
  3652. config.started = now(); // Delete the loose unnamed module if unused.
  3653. if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
  3654. config.modules.shift();
  3655. } // Avoid unnecessary information by not logging modules' test environments
  3656. var l = config.modules.length;
  3657. var modulesLog = [];
  3658. for (var i = 0; i < l; i++) {
  3659. modulesLog.push({
  3660. name: config.modules[i].name,
  3661. tests: config.modules[i].tests
  3662. });
  3663. } // The test run is officially beginning now
  3664. emit("runStart", globalSuite.start(true));
  3665. runLoggingCallbacks("begin", {
  3666. totalTests: Test.count,
  3667. modules: modulesLog
  3668. }).then(unblockAndAdvanceQueue);
  3669. }
  3670. exportQUnit(QUnit);
  3671. (function () {
  3672. if (!window$1 || !document) {
  3673. return;
  3674. }
  3675. var config = QUnit.config,
  3676. hasOwn = Object.prototype.hasOwnProperty; // Stores fixture HTML for resetting later
  3677. function storeFixture() {
  3678. // Avoid overwriting user-defined values
  3679. if (hasOwn.call(config, "fixture")) {
  3680. return;
  3681. }
  3682. var fixture = document.getElementById("qunit-fixture");
  3683. if (fixture) {
  3684. config.fixture = fixture.cloneNode(true);
  3685. }
  3686. }
  3687. QUnit.begin(storeFixture); // Resets the fixture DOM element if available.
  3688. function resetFixture() {
  3689. if (config.fixture == null) {
  3690. return;
  3691. }
  3692. var fixture = document.getElementById("qunit-fixture");
  3693. var resetFixtureType = _typeof(config.fixture);
  3694. if (resetFixtureType === "string") {
  3695. // support user defined values for `config.fixture`
  3696. var newFixture = document.createElement("div");
  3697. newFixture.setAttribute("id", "qunit-fixture");
  3698. newFixture.innerHTML = config.fixture;
  3699. fixture.parentNode.replaceChild(newFixture, fixture);
  3700. } else {
  3701. var clonedFixture = config.fixture.cloneNode(true);
  3702. fixture.parentNode.replaceChild(clonedFixture, fixture);
  3703. }
  3704. }
  3705. QUnit.testStart(resetFixture);
  3706. })();
  3707. (function () {
  3708. // Only interact with URLs via window.location
  3709. var location = typeof window$1 !== "undefined" && window$1.location;
  3710. if (!location) {
  3711. return;
  3712. }
  3713. var urlParams = getUrlParams();
  3714. QUnit.urlParams = urlParams; // Match module/test by inclusion in an array
  3715. QUnit.config.moduleId = [].concat(urlParams.moduleId || []);
  3716. QUnit.config.testId = [].concat(urlParams.testId || []); // Exact case-insensitive match of the module name
  3717. QUnit.config.module = urlParams.module; // Regular expression or case-insenstive substring match against "moduleName: testName"
  3718. QUnit.config.filter = urlParams.filter; // Test order randomization
  3719. if (urlParams.seed === true) {
  3720. // Generate a random seed if the option is specified without a value
  3721. QUnit.config.seed = Math.random().toString(36).slice(2);
  3722. } else if (urlParams.seed) {
  3723. QUnit.config.seed = urlParams.seed;
  3724. } // Add URL-parameter-mapped config values with UI form rendering data
  3725. QUnit.config.urlConfig.push({
  3726. id: "hidepassed",
  3727. label: "Hide passed tests",
  3728. tooltip: "Only show tests and assertions that fail. Stored as query-strings."
  3729. }, {
  3730. id: "noglobals",
  3731. label: "Check for Globals",
  3732. tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
  3733. }, {
  3734. id: "notrycatch",
  3735. label: "No try-catch",
  3736. tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
  3737. });
  3738. QUnit.begin(function () {
  3739. var i,
  3740. option,
  3741. urlConfig = QUnit.config.urlConfig;
  3742. for (i = 0; i < urlConfig.length; i++) {
  3743. // Options can be either strings or objects with nonempty "id" properties
  3744. option = QUnit.config.urlConfig[i];
  3745. if (typeof option !== "string") {
  3746. option = option.id;
  3747. }
  3748. if (QUnit.config[option] === undefined) {
  3749. QUnit.config[option] = urlParams[option];
  3750. }
  3751. }
  3752. });
  3753. function getUrlParams() {
  3754. var i, param, name, value;
  3755. var urlParams = Object.create(null);
  3756. var params = location.search.slice(1).split("&");
  3757. var length = params.length;
  3758. for (i = 0; i < length; i++) {
  3759. if (params[i]) {
  3760. param = params[i].split("=");
  3761. name = decodeQueryParam(param[0]); // Allow just a key to turn on a flag, e.g., test.html?noglobals
  3762. value = param.length === 1 || decodeQueryParam(param.slice(1).join("="));
  3763. if (name in urlParams) {
  3764. urlParams[name] = [].concat(urlParams[name], value);
  3765. } else {
  3766. urlParams[name] = value;
  3767. }
  3768. }
  3769. }
  3770. return urlParams;
  3771. }
  3772. function decodeQueryParam(param) {
  3773. return decodeURIComponent(param.replace(/\+/g, "%20"));
  3774. }
  3775. })();
  3776. var fuzzysort$1 = {exports: {}};
  3777. (function (module) {
  3778. (function (root, UMD) {
  3779. if (module.exports) module.exports = UMD();else root.fuzzysort = UMD();
  3780. })(commonjsGlobal, function UMD() {
  3781. function fuzzysortNew(instanceOptions) {
  3782. var fuzzysort = {
  3783. single: function single(search, target, options) {
  3784. if (!search) return null;
  3785. if (!isObj(search)) search = fuzzysort.getPreparedSearch(search);
  3786. if (!target) return null;
  3787. if (!isObj(target)) target = fuzzysort.getPrepared(target);
  3788. var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true;
  3789. var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo;
  3790. return algorithm(search, target, search[0]); // var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991
  3791. // var result = algorithm(search, target, search[0])
  3792. // if(result === null) return null
  3793. // if(result.score < threshold) return null
  3794. // return result
  3795. },
  3796. go: function go(search, targets, options) {
  3797. if (!search) return noResults;
  3798. search = fuzzysort.prepareSearch(search);
  3799. var searchLowerCode = search[0];
  3800. var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991;
  3801. var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991;
  3802. var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true;
  3803. var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo;
  3804. var resultsLen = 0;
  3805. var limitedCount = 0;
  3806. var targetsLen = targets.length; // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys]
  3807. // options.keys
  3808. if (options && options.keys) {
  3809. var scoreFn = options.scoreFn || defaultScoreFn;
  3810. var keys = options.keys;
  3811. var keysLen = keys.length;
  3812. for (var i = targetsLen - 1; i >= 0; --i) {
  3813. var obj = targets[i];
  3814. var objResults = new Array(keysLen);
  3815. for (var keyI = keysLen - 1; keyI >= 0; --keyI) {
  3816. var key = keys[keyI];
  3817. var target = getValue(obj, key);
  3818. if (!target) {
  3819. objResults[keyI] = null;
  3820. continue;
  3821. }
  3822. if (!isObj(target)) target = fuzzysort.getPrepared(target);
  3823. objResults[keyI] = algorithm(search, target, searchLowerCode);
  3824. }
  3825. objResults.obj = obj; // before scoreFn so scoreFn can use it
  3826. var score = scoreFn(objResults);
  3827. if (score === null) continue;
  3828. if (score < threshold) continue;
  3829. objResults.score = score;
  3830. if (resultsLen < limit) {
  3831. q.add(objResults);
  3832. ++resultsLen;
  3833. } else {
  3834. ++limitedCount;
  3835. if (score > q.peek().score) q.replaceTop(objResults);
  3836. }
  3837. } // options.key
  3838. } else if (options && options.key) {
  3839. var key = options.key;
  3840. for (var i = targetsLen - 1; i >= 0; --i) {
  3841. var obj = targets[i];
  3842. var target = getValue(obj, key);
  3843. if (!target) continue;
  3844. if (!isObj(target)) target = fuzzysort.getPrepared(target);
  3845. var result = algorithm(search, target, searchLowerCode);
  3846. if (result === null) continue;
  3847. if (result.score < threshold) continue; // have to clone result so duplicate targets from different obj can each reference the correct obj
  3848. result = {
  3849. target: result.target,
  3850. _targetLowerCodes: null,
  3851. _nextBeginningIndexes: null,
  3852. score: result.score,
  3853. indexes: result.indexes,
  3854. obj: obj
  3855. }; // hidden
  3856. if (resultsLen < limit) {
  3857. q.add(result);
  3858. ++resultsLen;
  3859. } else {
  3860. ++limitedCount;
  3861. if (result.score > q.peek().score) q.replaceTop(result);
  3862. }
  3863. } // no keys
  3864. } else {
  3865. for (var i = targetsLen - 1; i >= 0; --i) {
  3866. var target = targets[i];
  3867. if (!target) continue;
  3868. if (!isObj(target)) target = fuzzysort.getPrepared(target);
  3869. var result = algorithm(search, target, searchLowerCode);
  3870. if (result === null) continue;
  3871. if (result.score < threshold) continue;
  3872. if (resultsLen < limit) {
  3873. q.add(result);
  3874. ++resultsLen;
  3875. } else {
  3876. ++limitedCount;
  3877. if (result.score > q.peek().score) q.replaceTop(result);
  3878. }
  3879. }
  3880. }
  3881. if (resultsLen === 0) return noResults;
  3882. var results = new Array(resultsLen);
  3883. for (var i = resultsLen - 1; i >= 0; --i) {
  3884. results[i] = q.poll();
  3885. }
  3886. results.total = resultsLen + limitedCount;
  3887. return results;
  3888. },
  3889. goAsync: function goAsync(search, targets, options) {
  3890. var canceled = false;
  3891. var p = new Promise(function (resolve, reject) {
  3892. if (!search) return resolve(noResults);
  3893. search = fuzzysort.prepareSearch(search);
  3894. var searchLowerCode = search[0];
  3895. var q = fastpriorityqueue();
  3896. var iCurrent = targets.length - 1;
  3897. var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991;
  3898. var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991;
  3899. var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true;
  3900. var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo;
  3901. var resultsLen = 0;
  3902. var limitedCount = 0;
  3903. function step() {
  3904. if (canceled) return reject('canceled');
  3905. var startMs = Date.now(); // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys]
  3906. // options.keys
  3907. if (options && options.keys) {
  3908. var scoreFn = options.scoreFn || defaultScoreFn;
  3909. var keys = options.keys;
  3910. var keysLen = keys.length;
  3911. for (; iCurrent >= 0; --iCurrent) {
  3912. var obj = targets[iCurrent];
  3913. var objResults = new Array(keysLen);
  3914. for (var keyI = keysLen - 1; keyI >= 0; --keyI) {
  3915. var key = keys[keyI];
  3916. var target = getValue(obj, key);
  3917. if (!target) {
  3918. objResults[keyI] = null;
  3919. continue;
  3920. }
  3921. if (!isObj(target)) target = fuzzysort.getPrepared(target);
  3922. objResults[keyI] = algorithm(search, target, searchLowerCode);
  3923. }
  3924. objResults.obj = obj; // before scoreFn so scoreFn can use it
  3925. var score = scoreFn(objResults);
  3926. if (score === null) continue;
  3927. if (score < threshold) continue;
  3928. objResults.score = score;
  3929. if (resultsLen < limit) {
  3930. q.add(objResults);
  3931. ++resultsLen;
  3932. } else {
  3933. ++limitedCount;
  3934. if (score > q.peek().score) q.replaceTop(objResults);
  3935. }
  3936. if (iCurrent % 1000
  3937. /*itemsPerCheck*/
  3938. === 0) {
  3939. if (Date.now() - startMs >= 10
  3940. /*asyncInterval*/
  3941. ) {
  3942. isNode ? setImmediate(step) : setTimeout(step);
  3943. return;
  3944. }
  3945. }
  3946. } // options.key
  3947. } else if (options && options.key) {
  3948. var key = options.key;
  3949. for (; iCurrent >= 0; --iCurrent) {
  3950. var obj = targets[iCurrent];
  3951. var target = getValue(obj, key);
  3952. if (!target) continue;
  3953. if (!isObj(target)) target = fuzzysort.getPrepared(target);
  3954. var result = algorithm(search, target, searchLowerCode);
  3955. if (result === null) continue;
  3956. if (result.score < threshold) continue; // have to clone result so duplicate targets from different obj can each reference the correct obj
  3957. result = {
  3958. target: result.target,
  3959. _targetLowerCodes: null,
  3960. _nextBeginningIndexes: null,
  3961. score: result.score,
  3962. indexes: result.indexes,
  3963. obj: obj
  3964. }; // hidden
  3965. if (resultsLen < limit) {
  3966. q.add(result);
  3967. ++resultsLen;
  3968. } else {
  3969. ++limitedCount;
  3970. if (result.score > q.peek().score) q.replaceTop(result);
  3971. }
  3972. if (iCurrent % 1000
  3973. /*itemsPerCheck*/
  3974. === 0) {
  3975. if (Date.now() - startMs >= 10
  3976. /*asyncInterval*/
  3977. ) {
  3978. isNode ? setImmediate(step) : setTimeout(step);
  3979. return;
  3980. }
  3981. }
  3982. } // no keys
  3983. } else {
  3984. for (; iCurrent >= 0; --iCurrent) {
  3985. var target = targets[iCurrent];
  3986. if (!target) continue;
  3987. if (!isObj(target)) target = fuzzysort.getPrepared(target);
  3988. var result = algorithm(search, target, searchLowerCode);
  3989. if (result === null) continue;
  3990. if (result.score < threshold) continue;
  3991. if (resultsLen < limit) {
  3992. q.add(result);
  3993. ++resultsLen;
  3994. } else {
  3995. ++limitedCount;
  3996. if (result.score > q.peek().score) q.replaceTop(result);
  3997. }
  3998. if (iCurrent % 1000
  3999. /*itemsPerCheck*/
  4000. === 0) {
  4001. if (Date.now() - startMs >= 10
  4002. /*asyncInterval*/
  4003. ) {
  4004. isNode ? setImmediate(step) : setTimeout(step);
  4005. return;
  4006. }
  4007. }
  4008. }
  4009. }
  4010. if (resultsLen === 0) return resolve(noResults);
  4011. var results = new Array(resultsLen);
  4012. for (var i = resultsLen - 1; i >= 0; --i) {
  4013. results[i] = q.poll();
  4014. }
  4015. results.total = resultsLen + limitedCount;
  4016. resolve(results);
  4017. }
  4018. isNode ? setImmediate(step) : step();
  4019. });
  4020. p.cancel = function () {
  4021. canceled = true;
  4022. };
  4023. return p;
  4024. },
  4025. highlight: function highlight(result, hOpen, hClose) {
  4026. if (result === null) return null;
  4027. if (hOpen === undefined) hOpen = '<b>';
  4028. if (hClose === undefined) hClose = '</b>';
  4029. var highlighted = '';
  4030. var matchesIndex = 0;
  4031. var opened = false;
  4032. var target = result.target;
  4033. var targetLen = target.length;
  4034. var matchesBest = result.indexes;
  4035. for (var i = 0; i < targetLen; ++i) {
  4036. var char = target[i];
  4037. if (matchesBest[matchesIndex] === i) {
  4038. ++matchesIndex;
  4039. if (!opened) {
  4040. opened = true;
  4041. highlighted += hOpen;
  4042. }
  4043. if (matchesIndex === matchesBest.length) {
  4044. highlighted += char + hClose + target.substr(i + 1);
  4045. break;
  4046. }
  4047. } else {
  4048. if (opened) {
  4049. opened = false;
  4050. highlighted += hClose;
  4051. }
  4052. }
  4053. highlighted += char;
  4054. }
  4055. return highlighted;
  4056. },
  4057. prepare: function prepare(target) {
  4058. if (!target) return;
  4059. return {
  4060. target: target,
  4061. _targetLowerCodes: fuzzysort.prepareLowerCodes(target),
  4062. _nextBeginningIndexes: null,
  4063. score: null,
  4064. indexes: null,
  4065. obj: null
  4066. }; // hidden
  4067. },
  4068. prepareSlow: function prepareSlow(target) {
  4069. if (!target) return;
  4070. return {
  4071. target: target,
  4072. _targetLowerCodes: fuzzysort.prepareLowerCodes(target),
  4073. _nextBeginningIndexes: fuzzysort.prepareNextBeginningIndexes(target),
  4074. score: null,
  4075. indexes: null,
  4076. obj: null
  4077. }; // hidden
  4078. },
  4079. prepareSearch: function prepareSearch(search) {
  4080. if (!search) return;
  4081. return fuzzysort.prepareLowerCodes(search);
  4082. },
  4083. // Below this point is only internal code
  4084. // Below this point is only internal code
  4085. // Below this point is only internal code
  4086. // Below this point is only internal code
  4087. getPrepared: function getPrepared(target) {
  4088. if (target.length > 999) return fuzzysort.prepare(target); // don't cache huge targets
  4089. var targetPrepared = preparedCache.get(target);
  4090. if (targetPrepared !== undefined) return targetPrepared;
  4091. targetPrepared = fuzzysort.prepare(target);
  4092. preparedCache.set(target, targetPrepared);
  4093. return targetPrepared;
  4094. },
  4095. getPreparedSearch: function getPreparedSearch(search) {
  4096. if (search.length > 999) return fuzzysort.prepareSearch(search); // don't cache huge searches
  4097. var searchPrepared = preparedSearchCache.get(search);
  4098. if (searchPrepared !== undefined) return searchPrepared;
  4099. searchPrepared = fuzzysort.prepareSearch(search);
  4100. preparedSearchCache.set(search, searchPrepared);
  4101. return searchPrepared;
  4102. },
  4103. algorithm: function algorithm(searchLowerCodes, prepared, searchLowerCode) {
  4104. var targetLowerCodes = prepared._targetLowerCodes;
  4105. var searchLen = searchLowerCodes.length;
  4106. var targetLen = targetLowerCodes.length;
  4107. var searchI = 0; // where we at
  4108. var targetI = 0; // where you at
  4109. var typoSimpleI = 0;
  4110. var matchesSimpleLen = 0; // very basic fuzzy match; to remove non-matching targets ASAP!
  4111. // walk through target. find sequential matches.
  4112. // if all chars aren't found then exit
  4113. for (;;) {
  4114. var isMatch = searchLowerCode === targetLowerCodes[targetI];
  4115. if (isMatch) {
  4116. matchesSimple[matchesSimpleLen++] = targetI;
  4117. ++searchI;
  4118. if (searchI === searchLen) break;
  4119. searchLowerCode = searchLowerCodes[typoSimpleI === 0 ? searchI : typoSimpleI === searchI ? searchI + 1 : typoSimpleI === searchI - 1 ? searchI - 1 : searchI];
  4120. }
  4121. ++targetI;
  4122. if (targetI >= targetLen) {
  4123. // Failed to find searchI
  4124. // Check for typo or exit
  4125. // we go as far as possible before trying to transpose
  4126. // then we transpose backwards until we reach the beginning
  4127. for (;;) {
  4128. if (searchI <= 1) return null; // not allowed to transpose first char
  4129. if (typoSimpleI === 0) {
  4130. // we haven't tried to transpose yet
  4131. --searchI;
  4132. var searchLowerCodeNew = searchLowerCodes[searchI];
  4133. if (searchLowerCode === searchLowerCodeNew) continue; // doesn't make sense to transpose a repeat char
  4134. typoSimpleI = searchI;
  4135. } else {
  4136. if (typoSimpleI === 1) return null; // reached the end of the line for transposing
  4137. --typoSimpleI;
  4138. searchI = typoSimpleI;
  4139. searchLowerCode = searchLowerCodes[searchI + 1];
  4140. var searchLowerCodeNew = searchLowerCodes[searchI];
  4141. if (searchLowerCode === searchLowerCodeNew) continue; // doesn't make sense to transpose a repeat char
  4142. }
  4143. matchesSimpleLen = searchI;
  4144. targetI = matchesSimple[matchesSimpleLen - 1] + 1;
  4145. break;
  4146. }
  4147. }
  4148. }
  4149. var searchI = 0;
  4150. var typoStrictI = 0;
  4151. var successStrict = false;
  4152. var matchesStrictLen = 0;
  4153. var nextBeginningIndexes = prepared._nextBeginningIndexes;
  4154. if (nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target);
  4155. var firstPossibleI = targetI = matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[matchesSimple[0] - 1]; // Our target string successfully matched all characters in sequence!
  4156. // Let's try a more advanced and strict test to improve the score
  4157. // only count it as a match if it's consecutive or a beginning character!
  4158. if (targetI !== targetLen) for (;;) {
  4159. if (targetI >= targetLen) {
  4160. // We failed to find a good spot for this search char, go back to the previous search char and force it forward
  4161. if (searchI <= 0) {
  4162. // We failed to push chars forward for a better match
  4163. // transpose, starting from the beginning
  4164. ++typoStrictI;
  4165. if (typoStrictI > searchLen - 2) break;
  4166. if (searchLowerCodes[typoStrictI] === searchLowerCodes[typoStrictI + 1]) continue; // doesn't make sense to transpose a repeat char
  4167. targetI = firstPossibleI;
  4168. continue;
  4169. }
  4170. --searchI;
  4171. var lastMatch = matchesStrict[--matchesStrictLen];
  4172. targetI = nextBeginningIndexes[lastMatch];
  4173. } else {
  4174. var isMatch = searchLowerCodes[typoStrictI === 0 ? searchI : typoStrictI === searchI ? searchI + 1 : typoStrictI === searchI - 1 ? searchI - 1 : searchI] === targetLowerCodes[targetI];
  4175. if (isMatch) {
  4176. matchesStrict[matchesStrictLen++] = targetI;
  4177. ++searchI;
  4178. if (searchI === searchLen) {
  4179. successStrict = true;
  4180. break;
  4181. }
  4182. ++targetI;
  4183. } else {
  4184. targetI = nextBeginningIndexes[targetI];
  4185. }
  4186. }
  4187. }
  4188. {
  4189. // tally up the score & keep track of matches for highlighting later
  4190. if (successStrict) {
  4191. var matchesBest = matchesStrict;
  4192. var matchesBestLen = matchesStrictLen;
  4193. } else {
  4194. var matchesBest = matchesSimple;
  4195. var matchesBestLen = matchesSimpleLen;
  4196. }
  4197. var score = 0;
  4198. var lastTargetI = -1;
  4199. for (var i = 0; i < searchLen; ++i) {
  4200. var targetI = matchesBest[i]; // score only goes down if they're not consecutive
  4201. if (lastTargetI !== targetI - 1) score -= targetI;
  4202. lastTargetI = targetI;
  4203. }
  4204. if (!successStrict) {
  4205. score *= 1000;
  4206. if (typoSimpleI !== 0) score += -20;
  4207. /*typoPenalty*/
  4208. } else {
  4209. if (typoStrictI !== 0) score += -20;
  4210. /*typoPenalty*/
  4211. }
  4212. score -= targetLen - searchLen;
  4213. prepared.score = score;
  4214. prepared.indexes = new Array(matchesBestLen);
  4215. for (var i = matchesBestLen - 1; i >= 0; --i) {
  4216. prepared.indexes[i] = matchesBest[i];
  4217. }
  4218. return prepared;
  4219. }
  4220. },
  4221. algorithmNoTypo: function algorithmNoTypo(searchLowerCodes, prepared, searchLowerCode) {
  4222. var targetLowerCodes = prepared._targetLowerCodes;
  4223. var searchLen = searchLowerCodes.length;
  4224. var targetLen = targetLowerCodes.length;
  4225. var searchI = 0; // where we at
  4226. var targetI = 0; // where you at
  4227. var matchesSimpleLen = 0; // very basic fuzzy match; to remove non-matching targets ASAP!
  4228. // walk through target. find sequential matches.
  4229. // if all chars aren't found then exit
  4230. for (;;) {
  4231. var isMatch = searchLowerCode === targetLowerCodes[targetI];
  4232. if (isMatch) {
  4233. matchesSimple[matchesSimpleLen++] = targetI;
  4234. ++searchI;
  4235. if (searchI === searchLen) break;
  4236. searchLowerCode = searchLowerCodes[searchI];
  4237. }
  4238. ++targetI;
  4239. if (targetI >= targetLen) return null; // Failed to find searchI
  4240. }
  4241. var searchI = 0;
  4242. var successStrict = false;
  4243. var matchesStrictLen = 0;
  4244. var nextBeginningIndexes = prepared._nextBeginningIndexes;
  4245. if (nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target);
  4246. targetI = matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[matchesSimple[0] - 1]; // Our target string successfully matched all characters in sequence!
  4247. // Let's try a more advanced and strict test to improve the score
  4248. // only count it as a match if it's consecutive or a beginning character!
  4249. if (targetI !== targetLen) for (;;) {
  4250. if (targetI >= targetLen) {
  4251. // We failed to find a good spot for this search char, go back to the previous search char and force it forward
  4252. if (searchI <= 0) break; // We failed to push chars forward for a better match
  4253. --searchI;
  4254. var lastMatch = matchesStrict[--matchesStrictLen];
  4255. targetI = nextBeginningIndexes[lastMatch];
  4256. } else {
  4257. var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI];
  4258. if (isMatch) {
  4259. matchesStrict[matchesStrictLen++] = targetI;
  4260. ++searchI;
  4261. if (searchI === searchLen) {
  4262. successStrict = true;
  4263. break;
  4264. }
  4265. ++targetI;
  4266. } else {
  4267. targetI = nextBeginningIndexes[targetI];
  4268. }
  4269. }
  4270. }
  4271. {
  4272. // tally up the score & keep track of matches for highlighting later
  4273. if (successStrict) {
  4274. var matchesBest = matchesStrict;
  4275. var matchesBestLen = matchesStrictLen;
  4276. } else {
  4277. var matchesBest = matchesSimple;
  4278. var matchesBestLen = matchesSimpleLen;
  4279. }
  4280. var score = 0;
  4281. var lastTargetI = -1;
  4282. for (var i = 0; i < searchLen; ++i) {
  4283. var targetI = matchesBest[i]; // score only goes down if they're not consecutive
  4284. if (lastTargetI !== targetI - 1) score -= targetI;
  4285. lastTargetI = targetI;
  4286. }
  4287. if (!successStrict) score *= 1000;
  4288. score -= targetLen - searchLen;
  4289. prepared.score = score;
  4290. prepared.indexes = new Array(matchesBestLen);
  4291. for (var i = matchesBestLen - 1; i >= 0; --i) {
  4292. prepared.indexes[i] = matchesBest[i];
  4293. }
  4294. return prepared;
  4295. }
  4296. },
  4297. prepareLowerCodes: function prepareLowerCodes(str) {
  4298. var strLen = str.length;
  4299. var lowerCodes = []; // new Array(strLen) sparse array is too slow
  4300. var lower = str.toLowerCase();
  4301. for (var i = 0; i < strLen; ++i) {
  4302. lowerCodes[i] = lower.charCodeAt(i);
  4303. }
  4304. return lowerCodes;
  4305. },
  4306. prepareBeginningIndexes: function prepareBeginningIndexes(target) {
  4307. var targetLen = target.length;
  4308. var beginningIndexes = [];
  4309. var beginningIndexesLen = 0;
  4310. var wasUpper = false;
  4311. var wasAlphanum = false;
  4312. for (var i = 0; i < targetLen; ++i) {
  4313. var targetCode = target.charCodeAt(i);
  4314. var isUpper = targetCode >= 65 && targetCode <= 90;
  4315. var isAlphanum = isUpper || targetCode >= 97 && targetCode <= 122 || targetCode >= 48 && targetCode <= 57;
  4316. var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum;
  4317. wasUpper = isUpper;
  4318. wasAlphanum = isAlphanum;
  4319. if (isBeginning) beginningIndexes[beginningIndexesLen++] = i;
  4320. }
  4321. return beginningIndexes;
  4322. },
  4323. prepareNextBeginningIndexes: function prepareNextBeginningIndexes(target) {
  4324. var targetLen = target.length;
  4325. var beginningIndexes = fuzzysort.prepareBeginningIndexes(target);
  4326. var nextBeginningIndexes = []; // new Array(targetLen) sparse array is too slow
  4327. var lastIsBeginning = beginningIndexes[0];
  4328. var lastIsBeginningI = 0;
  4329. for (var i = 0; i < targetLen; ++i) {
  4330. if (lastIsBeginning > i) {
  4331. nextBeginningIndexes[i] = lastIsBeginning;
  4332. } else {
  4333. lastIsBeginning = beginningIndexes[++lastIsBeginningI];
  4334. nextBeginningIndexes[i] = lastIsBeginning === undefined ? targetLen : lastIsBeginning;
  4335. }
  4336. }
  4337. return nextBeginningIndexes;
  4338. },
  4339. cleanup: cleanup,
  4340. new: fuzzysortNew
  4341. };
  4342. return fuzzysort;
  4343. } // fuzzysortNew
  4344. // This stuff is outside fuzzysortNew, because it's shared with instances of fuzzysort.new()
  4345. var isNode = typeof commonjsRequire !== 'undefined' && typeof window === 'undefined'; // var MAX_INT = Number.MAX_SAFE_INTEGER
  4346. // var MIN_INT = Number.MIN_VALUE
  4347. var preparedCache = new Map();
  4348. var preparedSearchCache = new Map();
  4349. var noResults = [];
  4350. noResults.total = 0;
  4351. var matchesSimple = [];
  4352. var matchesStrict = [];
  4353. function cleanup() {
  4354. preparedCache.clear();
  4355. preparedSearchCache.clear();
  4356. matchesSimple = [];
  4357. matchesStrict = [];
  4358. }
  4359. function defaultScoreFn(a) {
  4360. var max = -9007199254740991;
  4361. for (var i = a.length - 1; i >= 0; --i) {
  4362. var result = a[i];
  4363. if (result === null) continue;
  4364. var score = result.score;
  4365. if (score > max) max = score;
  4366. }
  4367. if (max === -9007199254740991) return null;
  4368. return max;
  4369. } // prop = 'key' 2.5ms optimized for this case, seems to be about as fast as direct obj[prop]
  4370. // prop = 'key1.key2' 10ms
  4371. // prop = ['key1', 'key2'] 27ms
  4372. function getValue(obj, prop) {
  4373. var tmp = obj[prop];
  4374. if (tmp !== undefined) return tmp;
  4375. var segs = prop;
  4376. if (!Array.isArray(prop)) segs = prop.split('.');
  4377. var len = segs.length;
  4378. var i = -1;
  4379. while (obj && ++i < len) {
  4380. obj = obj[segs[i]];
  4381. }
  4382. return obj;
  4383. }
  4384. function isObj(x) {
  4385. return _typeof(x) === 'object';
  4386. } // faster as a function
  4387. // Hacked version of https://github.com/lemire/FastPriorityQueue.js
  4388. var fastpriorityqueue = function fastpriorityqueue() {
  4389. var r = [],
  4390. o = 0,
  4391. e = {};
  4392. function n() {
  4393. for (var e = 0, n = r[e], c = 1; c < o;) {
  4394. var f = c + 1;
  4395. e = c, f < o && r[f].score < r[c].score && (e = f), r[e - 1 >> 1] = r[e], c = 1 + (e << 1);
  4396. }
  4397. for (var a = e - 1 >> 1; e > 0 && n.score < r[a].score; a = (e = a) - 1 >> 1) {
  4398. r[e] = r[a];
  4399. }
  4400. r[e] = n;
  4401. }
  4402. return e.add = function (e) {
  4403. var n = o;
  4404. r[o++] = e;
  4405. for (var c = n - 1 >> 1; n > 0 && e.score < r[c].score; c = (n = c) - 1 >> 1) {
  4406. r[n] = r[c];
  4407. }
  4408. r[n] = e;
  4409. }, e.poll = function () {
  4410. if (0 !== o) {
  4411. var e = r[0];
  4412. return r[0] = r[--o], n(), e;
  4413. }
  4414. }, e.peek = function (e) {
  4415. if (0 !== o) return r[0];
  4416. }, e.replaceTop = function (o) {
  4417. r[0] = o, n();
  4418. }, e;
  4419. };
  4420. var q = fastpriorityqueue(); // reuse this, except for async, it needs to make its own
  4421. return fuzzysortNew();
  4422. }); // UMD
  4423. // TODO: (performance) wasm version!?
  4424. // TODO: (performance) layout memory in an optimal way to go fast by avoiding cache misses
  4425. // TODO: (performance) preparedCache is a memory leak
  4426. // TODO: (like sublime) backslash === forwardslash
  4427. // TODO: (performance) i have no idea how well optizmied the allowing typos algorithm is
  4428. })(fuzzysort$1);
  4429. var fuzzysort = fuzzysort$1.exports;
  4430. var stats = {
  4431. failedTests: [],
  4432. defined: 0,
  4433. completed: 0
  4434. }; // Escape text for attribute or text content.
  4435. function escapeText(s) {
  4436. if (!s) {
  4437. return "";
  4438. }
  4439. s = s + ""; // Both single quotes and double quotes (for attributes)
  4440. return s.replace(/['"<>&]/g, function (s) {
  4441. switch (s) {
  4442. case "'":
  4443. return "&#039;";
  4444. case "\"":
  4445. return "&quot;";
  4446. case "<":
  4447. return "&lt;";
  4448. case ">":
  4449. return "&gt;";
  4450. case "&":
  4451. return "&amp;";
  4452. }
  4453. });
  4454. }
  4455. (function () {
  4456. // Don't load the HTML Reporter on non-browser environments
  4457. if (!window$1 || !document) {
  4458. return;
  4459. }
  4460. var config = QUnit.config,
  4461. hiddenTests = [],
  4462. collapseNext = false,
  4463. hasOwn = Object.prototype.hasOwnProperty,
  4464. unfilteredUrl = setUrl({
  4465. filter: undefined,
  4466. module: undefined,
  4467. moduleId: undefined,
  4468. testId: undefined
  4469. });
  4470. function trim(string) {
  4471. if (typeof string.trim === "function") {
  4472. return string.trim();
  4473. } else {
  4474. return string.replace(/^\s+|\s+$/g, "");
  4475. }
  4476. }
  4477. function addEvent(elem, type, fn) {
  4478. elem.addEventListener(type, fn, false);
  4479. }
  4480. function removeEvent(elem, type, fn) {
  4481. elem.removeEventListener(type, fn, false);
  4482. }
  4483. function addEvents(elems, type, fn) {
  4484. var i = elems.length;
  4485. while (i--) {
  4486. addEvent(elems[i], type, fn);
  4487. }
  4488. }
  4489. function hasClass(elem, name) {
  4490. return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0;
  4491. }
  4492. function addClass(elem, name) {
  4493. if (!hasClass(elem, name)) {
  4494. elem.className += (elem.className ? " " : "") + name;
  4495. }
  4496. }
  4497. function toggleClass(elem, name, force) {
  4498. if (force || typeof force === "undefined" && !hasClass(elem, name)) {
  4499. addClass(elem, name);
  4500. } else {
  4501. removeClass(elem, name);
  4502. }
  4503. }
  4504. function removeClass(elem, name) {
  4505. var set = " " + elem.className + " "; // Class name may appear multiple times
  4506. while (set.indexOf(" " + name + " ") >= 0) {
  4507. set = set.replace(" " + name + " ", " ");
  4508. } // Trim for prettiness
  4509. elem.className = trim(set);
  4510. }
  4511. function id(name) {
  4512. return document.getElementById && document.getElementById(name);
  4513. }
  4514. function abortTests() {
  4515. var abortButton = id("qunit-abort-tests-button");
  4516. if (abortButton) {
  4517. abortButton.disabled = true;
  4518. abortButton.innerHTML = "Aborting...";
  4519. }
  4520. QUnit.config.queue.length = 0;
  4521. return false;
  4522. }
  4523. function interceptNavigation(ev) {
  4524. // Trim potential accidental whitespace so that QUnit doesn't throw an error about no tests matching the filter.
  4525. var filterInputElem = id("qunit-filter-input");
  4526. filterInputElem.value = trim(filterInputElem.value);
  4527. applyUrlParams();
  4528. if (ev && ev.preventDefault) {
  4529. ev.preventDefault();
  4530. }
  4531. return false;
  4532. }
  4533. function getUrlConfigHtml() {
  4534. var i,
  4535. j,
  4536. val,
  4537. escaped,
  4538. escapedTooltip,
  4539. selection = false,
  4540. urlConfig = config.urlConfig,
  4541. urlConfigHtml = "";
  4542. for (i = 0; i < urlConfig.length; i++) {
  4543. // Options can be either strings or objects with nonempty "id" properties
  4544. val = config.urlConfig[i];
  4545. if (typeof val === "string") {
  4546. val = {
  4547. id: val,
  4548. label: val
  4549. };
  4550. }
  4551. escaped = escapeText(val.id);
  4552. escapedTooltip = escapeText(val.tooltip);
  4553. if (!val.value || typeof val.value === "string") {
  4554. 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>";
  4555. } else {
  4556. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
  4557. if (Array.isArray(val.value)) {
  4558. for (j = 0; j < val.value.length; j++) {
  4559. escaped = escapeText(val.value[j]);
  4560. urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>";
  4561. }
  4562. } else {
  4563. for (j in val.value) {
  4564. if (hasOwn.call(val.value, j)) {
  4565. urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>";
  4566. }
  4567. }
  4568. }
  4569. if (config[val.id] && !selection) {
  4570. escaped = escapeText(config[val.id]);
  4571. urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>";
  4572. }
  4573. urlConfigHtml += "</select>";
  4574. }
  4575. }
  4576. return urlConfigHtml;
  4577. } // Handle "click" events on toolbar checkboxes and "change" for select menus.
  4578. // Updates the URL with the new state of `config.urlConfig` values.
  4579. function toolbarChanged() {
  4580. var updatedUrl,
  4581. value,
  4582. tests,
  4583. field = this,
  4584. params = {}; // Detect if field is a select menu or a checkbox
  4585. if ("selectedIndex" in field) {
  4586. value = field.options[field.selectedIndex].value || undefined;
  4587. } else {
  4588. value = field.checked ? field.defaultValue || true : undefined;
  4589. }
  4590. params[field.name] = value;
  4591. updatedUrl = setUrl(params); // Check if we can apply the change without a page refresh
  4592. if ("hidepassed" === field.name && "replaceState" in window$1.history) {
  4593. QUnit.urlParams[field.name] = value;
  4594. config[field.name] = value || false;
  4595. tests = id("qunit-tests");
  4596. if (tests) {
  4597. var length = tests.children.length;
  4598. var children = tests.children;
  4599. if (field.checked) {
  4600. for (var i = 0; i < length; i++) {
  4601. var test = children[i];
  4602. var className = test ? test.className : "";
  4603. var classNameHasPass = className.indexOf("pass") > -1;
  4604. var classNameHasSkipped = className.indexOf("skipped") > -1;
  4605. if (classNameHasPass || classNameHasSkipped) {
  4606. hiddenTests.push(test);
  4607. }
  4608. }
  4609. var _iterator = _createForOfIteratorHelper(hiddenTests),
  4610. _step;
  4611. try {
  4612. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  4613. var hiddenTest = _step.value;
  4614. tests.removeChild(hiddenTest);
  4615. }
  4616. } catch (err) {
  4617. _iterator.e(err);
  4618. } finally {
  4619. _iterator.f();
  4620. }
  4621. } else {
  4622. while ((test = hiddenTests.pop()) != null) {
  4623. tests.appendChild(test);
  4624. }
  4625. }
  4626. }
  4627. window$1.history.replaceState(null, "", updatedUrl);
  4628. } else {
  4629. window$1.location = updatedUrl;
  4630. }
  4631. }
  4632. function setUrl(params) {
  4633. var key,
  4634. arrValue,
  4635. i,
  4636. querystring = "?",
  4637. location = window$1.location;
  4638. params = extend(extend({}, QUnit.urlParams), params);
  4639. for (key in params) {
  4640. // Skip inherited or undefined properties
  4641. if (hasOwn.call(params, key) && params[key] !== undefined) {
  4642. // Output a parameter for each value of this key
  4643. // (but usually just one)
  4644. arrValue = [].concat(params[key]);
  4645. for (i = 0; i < arrValue.length; i++) {
  4646. querystring += encodeURIComponent(key);
  4647. if (arrValue[i] !== true) {
  4648. querystring += "=" + encodeURIComponent(arrValue[i]);
  4649. }
  4650. querystring += "&";
  4651. }
  4652. }
  4653. }
  4654. return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1);
  4655. }
  4656. function applyUrlParams() {
  4657. var i,
  4658. selectedModules = [],
  4659. modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
  4660. filter = id("qunit-filter-input").value;
  4661. for (i = 0; i < modulesList.length; i++) {
  4662. if (modulesList[i].checked) {
  4663. selectedModules.push(modulesList[i].value);
  4664. }
  4665. }
  4666. window$1.location = setUrl({
  4667. filter: filter === "" ? undefined : filter,
  4668. moduleId: selectedModules.length === 0 ? undefined : selectedModules,
  4669. // Remove module and testId filter
  4670. module: undefined,
  4671. testId: undefined
  4672. });
  4673. }
  4674. function toolbarUrlConfigContainer() {
  4675. var urlConfigContainer = document.createElement("span");
  4676. urlConfigContainer.innerHTML = getUrlConfigHtml();
  4677. addClass(urlConfigContainer, "qunit-url-config");
  4678. addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged);
  4679. addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
  4680. return urlConfigContainer;
  4681. }
  4682. function abortTestsButton() {
  4683. var button = document.createElement("button");
  4684. button.id = "qunit-abort-tests-button";
  4685. button.innerHTML = "Abort";
  4686. addEvent(button, "click", abortTests);
  4687. return button;
  4688. }
  4689. function toolbarLooseFilter() {
  4690. var filter = document.createElement("form"),
  4691. label = document.createElement("label"),
  4692. input = document.createElement("input"),
  4693. button = document.createElement("button");
  4694. addClass(filter, "qunit-filter");
  4695. label.innerHTML = "Filter: ";
  4696. input.type = "text";
  4697. input.value = config.filter || "";
  4698. input.name = "filter";
  4699. input.id = "qunit-filter-input";
  4700. button.innerHTML = "Go";
  4701. label.appendChild(input);
  4702. filter.appendChild(label);
  4703. filter.appendChild(document.createTextNode(" "));
  4704. filter.appendChild(button);
  4705. addEvent(filter, "submit", interceptNavigation);
  4706. return filter;
  4707. }
  4708. function moduleListHtml(modules) {
  4709. var i,
  4710. checked,
  4711. html = "";
  4712. for (i = 0; i < modules.length; i++) {
  4713. if (modules[i].name !== "") {
  4714. checked = config.moduleId.indexOf(modules[i].moduleId) > -1;
  4715. html += "<li><label class='clickable" + (checked ? " checked" : "") + "'><input type='checkbox' " + "value='" + modules[i].moduleId + "'" + (checked ? " checked='checked'" : "") + " />" + escapeText(modules[i].name) + "</label></li>";
  4716. }
  4717. }
  4718. return html;
  4719. }
  4720. function toolbarModuleFilter() {
  4721. var commit,
  4722. reset,
  4723. moduleFilter = document.createElement("form"),
  4724. label = document.createElement("label"),
  4725. moduleSearch = document.createElement("input"),
  4726. dropDown = document.createElement("div"),
  4727. actions = document.createElement("span"),
  4728. applyButton = document.createElement("button"),
  4729. resetButton = document.createElement("button"),
  4730. allModulesLabel = document.createElement("label"),
  4731. allCheckbox = document.createElement("input"),
  4732. dropDownList = document.createElement("ul"),
  4733. dirty = false;
  4734. moduleSearch.id = "qunit-modulefilter-search";
  4735. moduleSearch.autocomplete = "off";
  4736. addEvent(moduleSearch, "input", searchInput);
  4737. addEvent(moduleSearch, "input", searchFocus);
  4738. addEvent(moduleSearch, "focus", searchFocus);
  4739. addEvent(moduleSearch, "click", searchFocus);
  4740. config.modules.forEach(function (module) {
  4741. return module.namePrepared = fuzzysort.prepare(module.name);
  4742. });
  4743. label.id = "qunit-modulefilter-search-container";
  4744. label.innerHTML = "Module: ";
  4745. label.appendChild(moduleSearch);
  4746. applyButton.textContent = "Apply";
  4747. applyButton.style.display = "none";
  4748. resetButton.textContent = "Reset";
  4749. resetButton.type = "reset";
  4750. resetButton.style.display = "none";
  4751. allCheckbox.type = "checkbox";
  4752. allCheckbox.checked = config.moduleId.length === 0;
  4753. allModulesLabel.className = "clickable";
  4754. if (config.moduleId.length) {
  4755. allModulesLabel.className = "checked";
  4756. }
  4757. allModulesLabel.appendChild(allCheckbox);
  4758. allModulesLabel.appendChild(document.createTextNode("All modules"));
  4759. actions.id = "qunit-modulefilter-actions";
  4760. actions.appendChild(applyButton);
  4761. actions.appendChild(resetButton);
  4762. actions.appendChild(allModulesLabel);
  4763. commit = actions.firstChild;
  4764. reset = commit.nextSibling;
  4765. addEvent(commit, "click", applyUrlParams);
  4766. dropDownList.id = "qunit-modulefilter-dropdown-list";
  4767. dropDownList.innerHTML = moduleListHtml(config.modules);
  4768. dropDown.id = "qunit-modulefilter-dropdown";
  4769. dropDown.style.display = "none";
  4770. dropDown.appendChild(actions);
  4771. dropDown.appendChild(dropDownList);
  4772. addEvent(dropDown, "change", selectionChange);
  4773. selectionChange();
  4774. moduleFilter.id = "qunit-modulefilter";
  4775. moduleFilter.appendChild(label);
  4776. moduleFilter.appendChild(dropDown);
  4777. addEvent(moduleFilter, "submit", interceptNavigation);
  4778. addEvent(moduleFilter, "reset", function () {
  4779. // Let the reset happen, then update styles
  4780. window$1.setTimeout(selectionChange);
  4781. }); // Enables show/hide for the dropdown
  4782. function searchFocus() {
  4783. if (dropDown.style.display !== "none") {
  4784. return;
  4785. }
  4786. dropDown.style.display = "block";
  4787. addEvent(document, "click", hideHandler);
  4788. addEvent(document, "keydown", hideHandler); // Hide on Escape keydown or outside-container click
  4789. function hideHandler(e) {
  4790. var inContainer = moduleFilter.contains(e.target);
  4791. if (e.keyCode === 27 || !inContainer) {
  4792. if (e.keyCode === 27 && inContainer) {
  4793. moduleSearch.focus();
  4794. }
  4795. dropDown.style.display = "none";
  4796. removeEvent(document, "click", hideHandler);
  4797. removeEvent(document, "keydown", hideHandler);
  4798. moduleSearch.value = "";
  4799. searchInput();
  4800. }
  4801. }
  4802. }
  4803. function filterModules(searchText) {
  4804. if (searchText === "") {
  4805. return config.modules;
  4806. }
  4807. return fuzzysort.go(searchText, config.modules, {
  4808. key: "namePrepared",
  4809. threshold: -10000
  4810. }).map(function (module) {
  4811. return module.obj;
  4812. });
  4813. } // Processes module search box input
  4814. var searchInputTimeout;
  4815. function searchInput() {
  4816. window$1.clearTimeout(searchInputTimeout);
  4817. searchInputTimeout = window$1.setTimeout(function () {
  4818. var searchText = moduleSearch.value.toLowerCase(),
  4819. filteredModules = filterModules(searchText);
  4820. dropDownList.innerHTML = moduleListHtml(filteredModules);
  4821. }, 200);
  4822. } // Processes selection changes
  4823. function selectionChange(evt) {
  4824. var i,
  4825. item,
  4826. checkbox = evt && evt.target || allCheckbox,
  4827. modulesList = dropDownList.getElementsByTagName("input"),
  4828. selectedNames = [];
  4829. toggleClass(checkbox.parentNode, "checked", checkbox.checked);
  4830. dirty = false;
  4831. if (checkbox.checked && checkbox !== allCheckbox) {
  4832. allCheckbox.checked = false;
  4833. removeClass(allCheckbox.parentNode, "checked");
  4834. }
  4835. for (i = 0; i < modulesList.length; i++) {
  4836. item = modulesList[i];
  4837. if (!evt) {
  4838. toggleClass(item.parentNode, "checked", item.checked);
  4839. } else if (checkbox === allCheckbox && checkbox.checked) {
  4840. item.checked = false;
  4841. removeClass(item.parentNode, "checked");
  4842. }
  4843. dirty = dirty || item.checked !== item.defaultChecked;
  4844. if (item.checked) {
  4845. selectedNames.push(item.parentNode.textContent);
  4846. }
  4847. }
  4848. commit.style.display = reset.style.display = dirty ? "" : "none";
  4849. moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent;
  4850. moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent);
  4851. }
  4852. return moduleFilter;
  4853. }
  4854. function toolbarFilters() {
  4855. var toolbarFilters = document.createElement("span");
  4856. toolbarFilters.id = "qunit-toolbar-filters";
  4857. toolbarFilters.appendChild(toolbarLooseFilter());
  4858. toolbarFilters.appendChild(toolbarModuleFilter());
  4859. return toolbarFilters;
  4860. }
  4861. function appendToolbar() {
  4862. var toolbar = id("qunit-testrunner-toolbar");
  4863. if (toolbar) {
  4864. toolbar.appendChild(toolbarUrlConfigContainer());
  4865. toolbar.appendChild(toolbarFilters());
  4866. toolbar.appendChild(document.createElement("div")).className = "clearfix";
  4867. }
  4868. }
  4869. function appendHeader() {
  4870. var header = id("qunit-header");
  4871. if (header) {
  4872. header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> ";
  4873. }
  4874. }
  4875. function appendBanner() {
  4876. var banner = id("qunit-banner");
  4877. if (banner) {
  4878. banner.className = "";
  4879. }
  4880. }
  4881. function appendTestResults() {
  4882. var tests = id("qunit-tests"),
  4883. result = id("qunit-testresult"),
  4884. controls;
  4885. if (result) {
  4886. result.parentNode.removeChild(result);
  4887. }
  4888. if (tests) {
  4889. tests.innerHTML = "";
  4890. result = document.createElement("p");
  4891. result.id = "qunit-testresult";
  4892. result.className = "result";
  4893. tests.parentNode.insertBefore(result, tests);
  4894. result.innerHTML = "<div id=\"qunit-testresult-display\">Running...<br />&#160;</div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>";
  4895. controls = id("qunit-testresult-controls");
  4896. }
  4897. if (controls) {
  4898. controls.appendChild(abortTestsButton());
  4899. }
  4900. }
  4901. function appendFilteredTest() {
  4902. var testId = QUnit.config.testId;
  4903. if (!testId || testId.length <= 0) {
  4904. return "";
  4905. }
  4906. return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>";
  4907. }
  4908. function appendUserAgent() {
  4909. var userAgent = id("qunit-userAgent");
  4910. if (userAgent) {
  4911. userAgent.innerHTML = "";
  4912. userAgent.appendChild(document.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent));
  4913. }
  4914. }
  4915. function appendInterface() {
  4916. var qunit = id("qunit"); // For compat with QUnit 1.2, and to support fully custom theme HTML,
  4917. // we will use any existing elements if no id="qunit" element exists.
  4918. //
  4919. // Note that we don't fail or fallback to creating it ourselves,
  4920. // because not having id="qunit" (and not having the below elements)
  4921. // simply means QUnit acts headless, allowing users to use their own
  4922. // reporters, or for a test runner to listen for events directly without
  4923. // having the HTML reporter actively render anything.
  4924. if (qunit) {
  4925. qunit.setAttribute("role", "main"); // Since QUnit 1.3, these are created automatically if the page
  4926. // contains id="qunit".
  4927. qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText(document.title) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar' role='navigation'></div>" + appendFilteredTest() + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>";
  4928. }
  4929. appendHeader();
  4930. appendBanner();
  4931. appendTestResults();
  4932. appendUserAgent();
  4933. appendToolbar();
  4934. }
  4935. function appendTest(name, testId, moduleName) {
  4936. var title,
  4937. rerunTrigger,
  4938. testBlock,
  4939. assertList,
  4940. tests = id("qunit-tests");
  4941. if (!tests) {
  4942. return;
  4943. }
  4944. title = document.createElement("strong");
  4945. title.innerHTML = getNameHtml(name, moduleName);
  4946. testBlock = document.createElement("li");
  4947. testBlock.appendChild(title); // No ID or rerun link for "global failure" blocks
  4948. if (testId !== undefined) {
  4949. rerunTrigger = document.createElement("a");
  4950. rerunTrigger.innerHTML = "Rerun";
  4951. rerunTrigger.href = setUrl({
  4952. testId: testId
  4953. });
  4954. testBlock.id = "qunit-test-output-" + testId;
  4955. testBlock.appendChild(rerunTrigger);
  4956. }
  4957. assertList = document.createElement("ol");
  4958. assertList.className = "qunit-assert-list";
  4959. testBlock.appendChild(assertList);
  4960. tests.appendChild(testBlock);
  4961. return testBlock;
  4962. } // HTML Reporter initialization and load
  4963. QUnit.on("runStart", function (runStart) {
  4964. stats.defined = runStart.testCounts.total;
  4965. });
  4966. QUnit.begin(function () {
  4967. // Initialize QUnit elements
  4968. // This is done from begin() instead of runStart, because
  4969. // urlparams.js uses begin(), which we need to wait for.
  4970. // urlparams.js in turn uses begin() to allow plugins to
  4971. // add entries to QUnit.config.urlConfig, which may be done
  4972. // asynchronously.
  4973. // <https://github.com/qunitjs/qunit/issues/1657>
  4974. appendInterface();
  4975. });
  4976. function getRerunFailedHtml(failedTests) {
  4977. if (failedTests.length === 0) {
  4978. return "";
  4979. }
  4980. var href = setUrl({
  4981. testId: failedTests
  4982. });
  4983. return ["<br /><a href='" + escapeText(href) + "'>", failedTests.length === 1 ? "Rerun 1 failed test" : "Rerun " + failedTests.length + " failed tests", "</a>"].join("");
  4984. }
  4985. QUnit.on("runEnd", function (runEnd) {
  4986. var banner = id("qunit-banner"),
  4987. tests = id("qunit-tests"),
  4988. abortButton = id("qunit-abort-tests-button"),
  4989. assertPassed = config.stats.all - config.stats.bad,
  4990. html = [runEnd.testCounts.total, " tests completed in ", runEnd.runtime, " milliseconds, with ", runEnd.testCounts.failed, " failed, ", runEnd.testCounts.skipped, " skipped, and ", runEnd.testCounts.todo, " todo.<br />", "<span class='passed'>", assertPassed, "</span> assertions of <span class='total'>", config.stats.all, "</span> passed, <span class='failed'>", config.stats.bad, "</span> failed.", getRerunFailedHtml(stats.failedTests)].join(""),
  4991. test,
  4992. assertLi,
  4993. assertList; // Update remaining tests to aborted
  4994. if (abortButton && abortButton.disabled) {
  4995. html = "Tests aborted after " + runEnd.runtime + " milliseconds.";
  4996. for (var i = 0; i < tests.children.length; i++) {
  4997. test = tests.children[i];
  4998. if (test.className === "" || test.className === "running") {
  4999. test.className = "aborted";
  5000. assertList = test.getElementsByTagName("ol")[0];
  5001. assertLi = document.createElement("li");
  5002. assertLi.className = "fail";
  5003. assertLi.innerHTML = "Test aborted.";
  5004. assertList.appendChild(assertLi);
  5005. }
  5006. }
  5007. }
  5008. if (banner && (!abortButton || abortButton.disabled === false)) {
  5009. banner.className = runEnd.status === "failed" ? "qunit-fail" : "qunit-pass";
  5010. }
  5011. if (abortButton) {
  5012. abortButton.parentNode.removeChild(abortButton);
  5013. }
  5014. if (tests) {
  5015. id("qunit-testresult-display").innerHTML = html;
  5016. }
  5017. if (config.altertitle && document.title) {
  5018. // Show ✖ for good, ✔ for bad suite result in title
  5019. // use escape sequences in case file gets loaded with non-utf-8
  5020. // charset
  5021. document.title = [runEnd.status === "failed" ? "\u2716" : "\u2714", document.title.replace(/^[\u2714\u2716] /i, "")].join(" ");
  5022. } // Scroll back to top to show results
  5023. if (config.scrolltop && window$1.scrollTo) {
  5024. window$1.scrollTo(0, 0);
  5025. }
  5026. });
  5027. function getNameHtml(name, module) {
  5028. var nameHtml = "";
  5029. if (module) {
  5030. nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
  5031. }
  5032. nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
  5033. return nameHtml;
  5034. }
  5035. function getProgressHtml(stats) {
  5036. return [stats.completed, " / ", stats.defined, " tests completed.<br />"].join("");
  5037. }
  5038. QUnit.testStart(function (details) {
  5039. var running, bad;
  5040. appendTest(details.name, details.testId, details.module);
  5041. running = id("qunit-testresult-display");
  5042. if (running) {
  5043. addClass(running, "running");
  5044. bad = QUnit.config.reorder && details.previousFailure;
  5045. running.innerHTML = [getProgressHtml(stats), bad ? "Rerunning previously failed test: <br />" : "Running: ", getNameHtml(details.name, details.module), getRerunFailedHtml(stats.failedTests)].join("");
  5046. }
  5047. });
  5048. function stripHtml(string) {
  5049. // Strip tags, html entity and whitespaces
  5050. return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/&quot;/g, "").replace(/\s+/g, "");
  5051. }
  5052. QUnit.log(function (details) {
  5053. var assertList,
  5054. assertLi,
  5055. message,
  5056. expected,
  5057. actual,
  5058. diff,
  5059. showDiff = false,
  5060. testItem = id("qunit-test-output-" + details.testId);
  5061. if (!testItem) {
  5062. return;
  5063. }
  5064. message = escapeText(details.message) || (details.result ? "okay" : "failed");
  5065. message = "<span class='test-message'>" + message + "</span>";
  5066. message += "<span class='runtime'>@ " + details.runtime + " ms</span>"; // The pushFailure doesn't provide details.expected
  5067. // when it calls, it's implicit to also not show expected and diff stuff
  5068. // Also, we need to check details.expected existence, as it can exist and be undefined
  5069. if (!details.result && hasOwn.call(details, "expected")) {
  5070. if (details.negative) {
  5071. expected = "NOT " + QUnit.dump.parse(details.expected);
  5072. } else {
  5073. expected = QUnit.dump.parse(details.expected);
  5074. }
  5075. actual = QUnit.dump.parse(details.actual);
  5076. message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>";
  5077. if (actual !== expected) {
  5078. message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>";
  5079. if (typeof details.actual === "number" && typeof details.expected === "number") {
  5080. if (!isNaN(details.actual) && !isNaN(details.expected)) {
  5081. showDiff = true;
  5082. diff = details.actual - details.expected;
  5083. diff = (diff > 0 ? "+" : "") + diff;
  5084. }
  5085. } else if (typeof details.actual !== "boolean" && typeof details.expected !== "boolean") {
  5086. diff = QUnit.diff(expected, actual); // don't show diff if there is zero overlap
  5087. showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length;
  5088. }
  5089. if (showDiff) {
  5090. message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>";
  5091. }
  5092. } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) {
  5093. 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({
  5094. maxDepth: -1
  5095. })) + "'>" + "Rerun</a> without max depth.</p></td></tr>";
  5096. } else {
  5097. message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
  5098. }
  5099. if (details.source) {
  5100. message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>";
  5101. }
  5102. message += "</table>"; // This occurs when pushFailure is set and we have an extracted stack trace
  5103. } else if (!details.result && details.source) {
  5104. message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>";
  5105. }
  5106. assertList = testItem.getElementsByTagName("ol")[0];
  5107. assertLi = document.createElement("li");
  5108. assertLi.className = details.result ? "pass" : "fail";
  5109. assertLi.innerHTML = message;
  5110. assertList.appendChild(assertLi);
  5111. });
  5112. QUnit.testDone(function (details) {
  5113. var testTitle,
  5114. time,
  5115. assertList,
  5116. status,
  5117. good,
  5118. bad,
  5119. testCounts,
  5120. skipped,
  5121. sourceName,
  5122. tests = id("qunit-tests"),
  5123. testItem = id("qunit-test-output-" + details.testId);
  5124. if (!tests || !testItem) {
  5125. return;
  5126. }
  5127. removeClass(testItem, "running");
  5128. if (details.failed > 0) {
  5129. status = "failed";
  5130. } else if (details.todo) {
  5131. status = "todo";
  5132. } else {
  5133. status = details.skipped ? "skipped" : "passed";
  5134. }
  5135. assertList = testItem.getElementsByTagName("ol")[0];
  5136. good = details.passed;
  5137. bad = details.failed; // This test passed if it has no unexpected failed assertions
  5138. var testPassed = details.failed > 0 ? details.todo : !details.todo;
  5139. if (testPassed) {
  5140. // Collapse the passing tests
  5141. addClass(assertList, "qunit-collapsed");
  5142. } else {
  5143. stats.failedTests.push(details.testId);
  5144. if (config.collapse) {
  5145. if (!collapseNext) {
  5146. // Skip collapsing the first failing test
  5147. collapseNext = true;
  5148. } else {
  5149. // Collapse remaining tests
  5150. addClass(assertList, "qunit-collapsed");
  5151. }
  5152. }
  5153. } // The testItem.firstChild is the test name
  5154. testTitle = testItem.firstChild;
  5155. testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : "";
  5156. testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>";
  5157. stats.completed++;
  5158. if (details.skipped) {
  5159. testItem.className = "skipped";
  5160. skipped = document.createElement("em");
  5161. skipped.className = "qunit-skipped-label";
  5162. skipped.innerHTML = "skipped";
  5163. testItem.insertBefore(skipped, testTitle);
  5164. } else {
  5165. addEvent(testTitle, "click", function () {
  5166. toggleClass(assertList, "qunit-collapsed");
  5167. });
  5168. testItem.className = testPassed ? "pass" : "fail";
  5169. if (details.todo) {
  5170. var todoLabel = document.createElement("em");
  5171. todoLabel.className = "qunit-todo-label";
  5172. todoLabel.innerHTML = "todo";
  5173. testItem.className += " todo";
  5174. testItem.insertBefore(todoLabel, testTitle);
  5175. }
  5176. time = document.createElement("span");
  5177. time.className = "runtime";
  5178. time.innerHTML = details.runtime + " ms";
  5179. testItem.insertBefore(time, assertList);
  5180. } // Show the source of the test when showing assertions
  5181. if (details.source) {
  5182. sourceName = document.createElement("p");
  5183. sourceName.innerHTML = "<strong>Source: </strong>" + escapeText(details.source);
  5184. addClass(sourceName, "qunit-source");
  5185. if (testPassed) {
  5186. addClass(sourceName, "qunit-collapsed");
  5187. }
  5188. addEvent(testTitle, "click", function () {
  5189. toggleClass(sourceName, "qunit-collapsed");
  5190. });
  5191. testItem.appendChild(sourceName);
  5192. }
  5193. if (config.hidepassed && (status === "passed" || details.skipped)) {
  5194. // use removeChild instead of remove because of support
  5195. hiddenTests.push(testItem);
  5196. tests.removeChild(testItem);
  5197. }
  5198. });
  5199. QUnit.on("error", function (error) {
  5200. var testItem = appendTest("global failure");
  5201. if (!testItem) {
  5202. // HTML Reporter is probably disabled or not yet initialized.
  5203. return;
  5204. } // Render similar to a failed assertion (see above QUnit.log callback)
  5205. var message = escapeText(errorString(error));
  5206. message = "<span class='test-message'>" + message + "</span>";
  5207. if (error && error.stack) {
  5208. message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(error.stack) + "</pre></td></tr>" + "</table>";
  5209. }
  5210. var assertList = testItem.getElementsByTagName("ol")[0];
  5211. var assertLi = document.createElement("li");
  5212. assertLi.className = "fail";
  5213. assertLi.innerHTML = message;
  5214. assertList.appendChild(assertLi); // Make it visible
  5215. testItem.className = "fail";
  5216. }); // Avoid readyState issue with phantomjs
  5217. // Ref: #818
  5218. var usingPhantom = function (p) {
  5219. return p && p.version && p.version.major > 0;
  5220. }(window$1.phantom);
  5221. if (usingPhantom) {
  5222. console$1.warn("Support for PhantomJS is deprecated and will be removed in QUnit 3.0.");
  5223. }
  5224. if (!usingPhantom && document.readyState === "complete") {
  5225. QUnit.load();
  5226. } else {
  5227. addEvent(window$1, "load", QUnit.load);
  5228. } // Wrap window.onerror. We will call the original window.onerror to see if
  5229. // the existing handler fully handles the error; if not, we will call the
  5230. // QUnit.onError function.
  5231. var originalWindowOnError = window$1.onerror; // Cover uncaught exceptions
  5232. // Returning true will suppress the default browser handler,
  5233. // returning false will let it run.
  5234. window$1.onerror = function (message, fileName, lineNumber, columnNumber, errorObj) {
  5235. var ret = false;
  5236. if (originalWindowOnError) {
  5237. for (var _len = arguments.length, args = new Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {
  5238. args[_key - 5] = arguments[_key];
  5239. }
  5240. ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber, columnNumber, errorObj].concat(args));
  5241. } // Treat return value as window.onerror itself does,
  5242. // Only do our handling if not suppressed.
  5243. if (ret !== true) {
  5244. // If there is a current test that sets the internal `ignoreGlobalErrors` field
  5245. // (such as during `assert.throws()`), then the error is ignored and native
  5246. // error reporting is suppressed as well. This is because in browsers, an error
  5247. // can sometimes end up in `window.onerror` instead of in the local try/catch.
  5248. // This ignoring of errors does not apply to our general onUncaughtException
  5249. // method, nor to our `unhandledRejection` handlers, as those are not meant
  5250. // to receive an "expected" error during `assert.throws()`.
  5251. if (config.current && config.current.ignoreGlobalErrors) {
  5252. return true;
  5253. } // According to
  5254. // https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror,
  5255. // most modern browsers support an errorObj argument; use that to
  5256. // get a full stack trace if it's available.
  5257. var error = errorObj || new Error(message);
  5258. if (!error.stack && fileName && lineNumber) {
  5259. error.stack = "".concat(fileName, ":").concat(lineNumber);
  5260. }
  5261. QUnit.onUncaughtException(error);
  5262. }
  5263. return ret;
  5264. };
  5265. window$1.addEventListener("unhandledrejection", function (event) {
  5266. QUnit.onUncaughtException(event.reason);
  5267. });
  5268. })();
  5269. /*
  5270. * This file is a modified version of google-diff-match-patch's JavaScript implementation
  5271. * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
  5272. * modifications are licensed as more fully set forth in LICENSE.txt.
  5273. *
  5274. * The original source of google-diff-match-patch is attributable and licensed as follows:
  5275. *
  5276. * Copyright 2006 Google Inc.
  5277. * https://code.google.com/p/google-diff-match-patch/
  5278. *
  5279. * Licensed under the Apache License, Version 2.0 (the "License");
  5280. * you may not use this file except in compliance with the License.
  5281. * You may obtain a copy of the License at
  5282. *
  5283. * https://www.apache.org/licenses/LICENSE-2.0
  5284. *
  5285. * Unless required by applicable law or agreed to in writing, software
  5286. * distributed under the License is distributed on an "AS IS" BASIS,
  5287. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5288. * See the License for the specific language governing permissions and
  5289. * limitations under the License.
  5290. *
  5291. * More Info:
  5292. * https://code.google.com/p/google-diff-match-patch/
  5293. *
  5294. * Usage: QUnit.diff(expected, actual)
  5295. *
  5296. */
  5297. QUnit.diff = function () {
  5298. function DiffMatchPatch() {} // DIFF FUNCTIONS
  5299. /**
  5300. * The data structure representing a diff is an array of tuples:
  5301. * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
  5302. * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
  5303. */
  5304. var DIFF_DELETE = -1,
  5305. DIFF_INSERT = 1,
  5306. DIFF_EQUAL = 0,
  5307. hasOwn = Object.prototype.hasOwnProperty;
  5308. /**
  5309. * Find the differences between two texts. Simplifies the problem by stripping
  5310. * any common prefix or suffix off the texts before diffing.
  5311. * @param {string} text1 Old string to be diffed.
  5312. * @param {string} text2 New string to be diffed.
  5313. * @param {boolean=} optChecklines Optional speedup flag. If present and false,
  5314. * then don't run a line-level diff first to identify the changed areas.
  5315. * Defaults to true, which does a faster, slightly less optimal diff.
  5316. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  5317. */
  5318. DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
  5319. var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs; // The diff must be complete in up to 1 second.
  5320. deadline = new Date().getTime() + 1000; // Check for null inputs.
  5321. if (text1 === null || text2 === null) {
  5322. throw new Error("Null input. (DiffMain)");
  5323. } // Check for equality (speedup).
  5324. if (text1 === text2) {
  5325. if (text1) {
  5326. return [[DIFF_EQUAL, text1]];
  5327. }
  5328. return [];
  5329. }
  5330. if (typeof optChecklines === "undefined") {
  5331. optChecklines = true;
  5332. }
  5333. checklines = optChecklines; // Trim off common prefix (speedup).
  5334. commonlength = this.diffCommonPrefix(text1, text2);
  5335. commonprefix = text1.substring(0, commonlength);
  5336. text1 = text1.substring(commonlength);
  5337. text2 = text2.substring(commonlength); // Trim off common suffix (speedup).
  5338. commonlength = this.diffCommonSuffix(text1, text2);
  5339. commonsuffix = text1.substring(text1.length - commonlength);
  5340. text1 = text1.substring(0, text1.length - commonlength);
  5341. text2 = text2.substring(0, text2.length - commonlength); // Compute the diff on the middle block.
  5342. diffs = this.diffCompute(text1, text2, checklines, deadline); // Restore the prefix and suffix.
  5343. if (commonprefix) {
  5344. diffs.unshift([DIFF_EQUAL, commonprefix]);
  5345. }
  5346. if (commonsuffix) {
  5347. diffs.push([DIFF_EQUAL, commonsuffix]);
  5348. }
  5349. this.diffCleanupMerge(diffs);
  5350. return diffs;
  5351. };
  5352. /**
  5353. * Reduce the number of edits by eliminating operationally trivial equalities.
  5354. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  5355. */
  5356. DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
  5357. var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel;
  5358. changes = false;
  5359. equalities = []; // Stack of indices where equalities are found.
  5360. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  5361. /** @type {?string} */
  5362. lastequality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  5363. pointer = 0; // Index of current position.
  5364. // Is there an insertion operation before the last equality.
  5365. preIns = false; // Is there a deletion operation before the last equality.
  5366. preDel = false; // Is there an insertion operation after the last equality.
  5367. postIns = false; // Is there a deletion operation after the last equality.
  5368. postDel = false;
  5369. while (pointer < diffs.length) {
  5370. // Equality found.
  5371. if (diffs[pointer][0] === DIFF_EQUAL) {
  5372. if (diffs[pointer][1].length < 4 && (postIns || postDel)) {
  5373. // Candidate found.
  5374. equalities[equalitiesLength++] = pointer;
  5375. preIns = postIns;
  5376. preDel = postDel;
  5377. lastequality = diffs[pointer][1];
  5378. } else {
  5379. // Not a candidate, and can never become one.
  5380. equalitiesLength = 0;
  5381. lastequality = null;
  5382. }
  5383. postIns = postDel = false; // An insertion or deletion.
  5384. } else {
  5385. if (diffs[pointer][0] === DIFF_DELETE) {
  5386. postDel = true;
  5387. } else {
  5388. postIns = true;
  5389. }
  5390. /*
  5391. * Five types to be split:
  5392. * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  5393. * <ins>A</ins>X<ins>C</ins><del>D</del>
  5394. * <ins>A</ins><del>B</del>X<ins>C</ins>
  5395. * <ins>A</del>X<ins>C</ins><del>D</del>
  5396. * <ins>A</ins><del>B</del>X<del>C</del>
  5397. */
  5398. if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) {
  5399. // Duplicate record.
  5400. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); // Change second copy to insert.
  5401. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  5402. equalitiesLength--; // Throw away the equality we just deleted;
  5403. lastequality = null;
  5404. if (preIns && preDel) {
  5405. // No changes made which could affect previous entry, keep going.
  5406. postIns = postDel = true;
  5407. equalitiesLength = 0;
  5408. } else {
  5409. equalitiesLength--; // Throw away the previous equality.
  5410. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  5411. postIns = postDel = false;
  5412. }
  5413. changes = true;
  5414. }
  5415. }
  5416. pointer++;
  5417. }
  5418. if (changes) {
  5419. this.diffCleanupMerge(diffs);
  5420. }
  5421. };
  5422. /**
  5423. * Convert a diff array into a pretty HTML report.
  5424. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  5425. * @param {integer} string to be beautified.
  5426. * @return {string} HTML representation.
  5427. */
  5428. DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
  5429. var op,
  5430. data,
  5431. x,
  5432. html = [];
  5433. for (x = 0; x < diffs.length; x++) {
  5434. op = diffs[x][0]; // Operation (insert, delete, equal)
  5435. data = diffs[x][1]; // Text of change.
  5436. switch (op) {
  5437. case DIFF_INSERT:
  5438. html[x] = "<ins>" + escapeText(data) + "</ins>";
  5439. break;
  5440. case DIFF_DELETE:
  5441. html[x] = "<del>" + escapeText(data) + "</del>";
  5442. break;
  5443. case DIFF_EQUAL:
  5444. html[x] = "<span>" + escapeText(data) + "</span>";
  5445. break;
  5446. }
  5447. }
  5448. return html.join("");
  5449. };
  5450. /**
  5451. * Determine the common prefix of two strings.
  5452. * @param {string} text1 First string.
  5453. * @param {string} text2 Second string.
  5454. * @return {number} The number of characters common to the start of each
  5455. * string.
  5456. */
  5457. DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
  5458. var pointermid, pointermax, pointermin, pointerstart; // Quick check for common null cases.
  5459. if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
  5460. return 0;
  5461. } // Binary search.
  5462. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  5463. pointermin = 0;
  5464. pointermax = Math.min(text1.length, text2.length);
  5465. pointermid = pointermax;
  5466. pointerstart = 0;
  5467. while (pointermin < pointermid) {
  5468. if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
  5469. pointermin = pointermid;
  5470. pointerstart = pointermin;
  5471. } else {
  5472. pointermax = pointermid;
  5473. }
  5474. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  5475. }
  5476. return pointermid;
  5477. };
  5478. /**
  5479. * Determine the common suffix of two strings.
  5480. * @param {string} text1 First string.
  5481. * @param {string} text2 Second string.
  5482. * @return {number} The number of characters common to the end of each string.
  5483. */
  5484. DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
  5485. var pointermid, pointermax, pointermin, pointerend; // Quick check for common null cases.
  5486. if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
  5487. return 0;
  5488. } // Binary search.
  5489. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  5490. pointermin = 0;
  5491. pointermax = Math.min(text1.length, text2.length);
  5492. pointermid = pointermax;
  5493. pointerend = 0;
  5494. while (pointermin < pointermid) {
  5495. if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
  5496. pointermin = pointermid;
  5497. pointerend = pointermin;
  5498. } else {
  5499. pointermax = pointermid;
  5500. }
  5501. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  5502. }
  5503. return pointermid;
  5504. };
  5505. /**
  5506. * Find the differences between two texts. Assumes that the texts do not
  5507. * have any common prefix or suffix.
  5508. * @param {string} text1 Old string to be diffed.
  5509. * @param {string} text2 New string to be diffed.
  5510. * @param {boolean} checklines Speedup flag. If false, then don't run a
  5511. * line-level diff first to identify the changed areas.
  5512. * If true, then run a faster, slightly less optimal diff.
  5513. * @param {number} deadline Time when the diff should be complete by.
  5514. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  5515. * @private
  5516. */
  5517. DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
  5518. var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB;
  5519. if (!text1) {
  5520. // Just add some text (speedup).
  5521. return [[DIFF_INSERT, text2]];
  5522. }
  5523. if (!text2) {
  5524. // Just delete some text (speedup).
  5525. return [[DIFF_DELETE, text1]];
  5526. }
  5527. longtext = text1.length > text2.length ? text1 : text2;
  5528. shorttext = text1.length > text2.length ? text2 : text1;
  5529. i = longtext.indexOf(shorttext);
  5530. if (i !== -1) {
  5531. // Shorter text is inside the longer text (speedup).
  5532. diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; // Swap insertions for deletions if diff is reversed.
  5533. if (text1.length > text2.length) {
  5534. diffs[0][0] = diffs[2][0] = DIFF_DELETE;
  5535. }
  5536. return diffs;
  5537. }
  5538. if (shorttext.length === 1) {
  5539. // Single character string.
  5540. // After the previous speedup, the character can't be an equality.
  5541. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  5542. } // Check to see if the problem can be split in two.
  5543. hm = this.diffHalfMatch(text1, text2);
  5544. if (hm) {
  5545. // A half-match was found, sort out the return data.
  5546. text1A = hm[0];
  5547. text1B = hm[1];
  5548. text2A = hm[2];
  5549. text2B = hm[3];
  5550. midCommon = hm[4]; // Send both pairs off for separate processing.
  5551. diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
  5552. diffsB = this.DiffMain(text1B, text2B, checklines, deadline); // Merge the results.
  5553. return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
  5554. }
  5555. if (checklines && text1.length > 100 && text2.length > 100) {
  5556. return this.diffLineMode(text1, text2, deadline);
  5557. }
  5558. return this.diffBisect(text1, text2, deadline);
  5559. };
  5560. /**
  5561. * Do the two texts share a substring which is at least half the length of the
  5562. * longer text?
  5563. * This speedup can produce non-minimal diffs.
  5564. * @param {string} text1 First string.
  5565. * @param {string} text2 Second string.
  5566. * @return {Array.<string>} Five element Array, containing the prefix of
  5567. * text1, the suffix of text1, the prefix of text2, the suffix of
  5568. * text2 and the common middle. Or null if there was no match.
  5569. * @private
  5570. */
  5571. DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
  5572. var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm;
  5573. longtext = text1.length > text2.length ? text1 : text2;
  5574. shorttext = text1.length > text2.length ? text2 : text1;
  5575. if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
  5576. return null; // Pointless.
  5577. }
  5578. dmp = this; // 'this' becomes 'window' in a closure.
  5579. /**
  5580. * Does a substring of shorttext exist within longtext such that the substring
  5581. * is at least half the length of longtext?
  5582. * Closure, but does not reference any external variables.
  5583. * @param {string} longtext Longer string.
  5584. * @param {string} shorttext Shorter string.
  5585. * @param {number} i Start index of quarter length substring within longtext.
  5586. * @return {Array.<string>} Five element Array, containing the prefix of
  5587. * longtext, the suffix of longtext, the prefix of shorttext, the suffix
  5588. * of shorttext and the common middle. Or null if there was no match.
  5589. * @private
  5590. */
  5591. function diffHalfMatchI(longtext, shorttext, i) {
  5592. var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB; // Start with a 1/4 length substring at position i as a seed.
  5593. seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
  5594. j = -1;
  5595. bestCommon = "";
  5596. while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
  5597. prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j));
  5598. suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j));
  5599. if (bestCommon.length < suffixLength + prefixLength) {
  5600. bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
  5601. bestLongtextA = longtext.substring(0, i - suffixLength);
  5602. bestLongtextB = longtext.substring(i + prefixLength);
  5603. bestShorttextA = shorttext.substring(0, j - suffixLength);
  5604. bestShorttextB = shorttext.substring(j + prefixLength);
  5605. }
  5606. }
  5607. if (bestCommon.length * 2 >= longtext.length) {
  5608. return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon];
  5609. } else {
  5610. return null;
  5611. }
  5612. } // First check if the second quarter is the seed for a half-match.
  5613. hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4)); // Check again based on the third quarter.
  5614. hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2));
  5615. if (!hm1 && !hm2) {
  5616. return null;
  5617. } else if (!hm2) {
  5618. hm = hm1;
  5619. } else if (!hm1) {
  5620. hm = hm2;
  5621. } else {
  5622. // Both matched. Select the longest.
  5623. hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
  5624. } // A half-match was found, sort out the return data.
  5625. if (text1.length > text2.length) {
  5626. text1A = hm[0];
  5627. text1B = hm[1];
  5628. text2A = hm[2];
  5629. text2B = hm[3];
  5630. } else {
  5631. text2A = hm[0];
  5632. text2B = hm[1];
  5633. text1A = hm[2];
  5634. text1B = hm[3];
  5635. }
  5636. midCommon = hm[4];
  5637. return [text1A, text1B, text2A, text2B, midCommon];
  5638. };
  5639. /**
  5640. * Do a quick line-level diff on both strings, then rediff the parts for
  5641. * greater accuracy.
  5642. * This speedup can produce non-minimal diffs.
  5643. * @param {string} text1 Old string to be diffed.
  5644. * @param {string} text2 New string to be diffed.
  5645. * @param {number} deadline Time when the diff should be complete by.
  5646. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  5647. * @private
  5648. */
  5649. DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
  5650. var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j; // Scan the text on a line-by-line basis first.
  5651. a = this.diffLinesToChars(text1, text2);
  5652. text1 = a.chars1;
  5653. text2 = a.chars2;
  5654. linearray = a.lineArray;
  5655. diffs = this.DiffMain(text1, text2, false, deadline); // Convert the diff back to original text.
  5656. this.diffCharsToLines(diffs, linearray); // Eliminate freak matches (e.g. blank lines)
  5657. this.diffCleanupSemantic(diffs); // Rediff any replacement blocks, this time character-by-character.
  5658. // Add a dummy entry at the end.
  5659. diffs.push([DIFF_EQUAL, ""]);
  5660. pointer = 0;
  5661. countDelete = 0;
  5662. countInsert = 0;
  5663. textDelete = "";
  5664. textInsert = "";
  5665. while (pointer < diffs.length) {
  5666. switch (diffs[pointer][0]) {
  5667. case DIFF_INSERT:
  5668. countInsert++;
  5669. textInsert += diffs[pointer][1];
  5670. break;
  5671. case DIFF_DELETE:
  5672. countDelete++;
  5673. textDelete += diffs[pointer][1];
  5674. break;
  5675. case DIFF_EQUAL:
  5676. // Upon reaching an equality, check for prior redundancies.
  5677. if (countDelete >= 1 && countInsert >= 1) {
  5678. // Delete the offending records and add the merged ones.
  5679. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);
  5680. pointer = pointer - countDelete - countInsert;
  5681. a = this.DiffMain(textDelete, textInsert, false, deadline);
  5682. for (j = a.length - 1; j >= 0; j--) {
  5683. diffs.splice(pointer, 0, a[j]);
  5684. }
  5685. pointer = pointer + a.length;
  5686. }
  5687. countInsert = 0;
  5688. countDelete = 0;
  5689. textDelete = "";
  5690. textInsert = "";
  5691. break;
  5692. }
  5693. pointer++;
  5694. }
  5695. diffs.pop(); // Remove the dummy entry at the end.
  5696. return diffs;
  5697. };
  5698. /**
  5699. * Find the 'middle snake' of a diff, split the problem in two
  5700. * and return the recursively constructed diff.
  5701. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  5702. * @param {string} text1 Old string to be diffed.
  5703. * @param {string} text2 New string to be diffed.
  5704. * @param {number} deadline Time at which to bail if not yet complete.
  5705. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  5706. * @private
  5707. */
  5708. DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
  5709. var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2; // Cache the text lengths to prevent multiple calls.
  5710. text1Length = text1.length;
  5711. text2Length = text2.length;
  5712. maxD = Math.ceil((text1Length + text2Length) / 2);
  5713. vOffset = maxD;
  5714. vLength = 2 * maxD;
  5715. v1 = new Array(vLength);
  5716. v2 = new Array(vLength); // Setting all elements to -1 is faster in Chrome & Firefox than mixing
  5717. // integers and undefined.
  5718. for (x = 0; x < vLength; x++) {
  5719. v1[x] = -1;
  5720. v2[x] = -1;
  5721. }
  5722. v1[vOffset + 1] = 0;
  5723. v2[vOffset + 1] = 0;
  5724. delta = text1Length - text2Length; // If the total number of characters is odd, then the front path will collide
  5725. // with the reverse path.
  5726. front = delta % 2 !== 0; // Offsets for start and end of k loop.
  5727. // Prevents mapping of space beyond the grid.
  5728. k1start = 0;
  5729. k1end = 0;
  5730. k2start = 0;
  5731. k2end = 0;
  5732. for (d = 0; d < maxD; d++) {
  5733. // Bail out if deadline is reached.
  5734. if (new Date().getTime() > deadline) {
  5735. break;
  5736. } // Walk the front path one step.
  5737. for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
  5738. k1Offset = vOffset + k1;
  5739. if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {
  5740. x1 = v1[k1Offset + 1];
  5741. } else {
  5742. x1 = v1[k1Offset - 1] + 1;
  5743. }
  5744. y1 = x1 - k1;
  5745. while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
  5746. x1++;
  5747. y1++;
  5748. }
  5749. v1[k1Offset] = x1;
  5750. if (x1 > text1Length) {
  5751. // Ran off the right of the graph.
  5752. k1end += 2;
  5753. } else if (y1 > text2Length) {
  5754. // Ran off the bottom of the graph.
  5755. k1start += 2;
  5756. } else if (front) {
  5757. k2Offset = vOffset + delta - k1;
  5758. if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
  5759. // Mirror x2 onto top-left coordinate system.
  5760. x2 = text1Length - v2[k2Offset];
  5761. if (x1 >= x2) {
  5762. // Overlap detected.
  5763. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  5764. }
  5765. }
  5766. }
  5767. } // Walk the reverse path one step.
  5768. for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
  5769. k2Offset = vOffset + k2;
  5770. if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {
  5771. x2 = v2[k2Offset + 1];
  5772. } else {
  5773. x2 = v2[k2Offset - 1] + 1;
  5774. }
  5775. y2 = x2 - k2;
  5776. while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {
  5777. x2++;
  5778. y2++;
  5779. }
  5780. v2[k2Offset] = x2;
  5781. if (x2 > text1Length) {
  5782. // Ran off the left of the graph.
  5783. k2end += 2;
  5784. } else if (y2 > text2Length) {
  5785. // Ran off the top of the graph.
  5786. k2start += 2;
  5787. } else if (!front) {
  5788. k1Offset = vOffset + delta - k2;
  5789. if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
  5790. x1 = v1[k1Offset];
  5791. y1 = vOffset + x1 - k1Offset; // Mirror x2 onto top-left coordinate system.
  5792. x2 = text1Length - x2;
  5793. if (x1 >= x2) {
  5794. // Overlap detected.
  5795. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  5796. }
  5797. }
  5798. }
  5799. }
  5800. } // Diff took too long and hit the deadline or
  5801. // number of diffs equals number of characters, no commonality at all.
  5802. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  5803. };
  5804. /**
  5805. * Given the location of the 'middle snake', split the diff in two parts
  5806. * and recurse.
  5807. * @param {string} text1 Old string to be diffed.
  5808. * @param {string} text2 New string to be diffed.
  5809. * @param {number} x Index of split point in text1.
  5810. * @param {number} y Index of split point in text2.
  5811. * @param {number} deadline Time at which to bail if not yet complete.
  5812. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  5813. * @private
  5814. */
  5815. DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
  5816. var text1a, text1b, text2a, text2b, diffs, diffsb;
  5817. text1a = text1.substring(0, x);
  5818. text2a = text2.substring(0, y);
  5819. text1b = text1.substring(x);
  5820. text2b = text2.substring(y); // Compute both diffs serially.
  5821. diffs = this.DiffMain(text1a, text2a, false, deadline);
  5822. diffsb = this.DiffMain(text1b, text2b, false, deadline);
  5823. return diffs.concat(diffsb);
  5824. };
  5825. /**
  5826. * Reduce the number of edits by eliminating semantically trivial equalities.
  5827. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  5828. */
  5829. DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
  5830. var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
  5831. changes = false;
  5832. equalities = []; // Stack of indices where equalities are found.
  5833. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  5834. /** @type {?string} */
  5835. lastequality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  5836. pointer = 0; // Index of current position.
  5837. // Number of characters that changed prior to the equality.
  5838. lengthInsertions1 = 0;
  5839. lengthDeletions1 = 0; // Number of characters that changed after the equality.
  5840. lengthInsertions2 = 0;
  5841. lengthDeletions2 = 0;
  5842. while (pointer < diffs.length) {
  5843. if (diffs[pointer][0] === DIFF_EQUAL) {
  5844. // Equality found.
  5845. equalities[equalitiesLength++] = pointer;
  5846. lengthInsertions1 = lengthInsertions2;
  5847. lengthDeletions1 = lengthDeletions2;
  5848. lengthInsertions2 = 0;
  5849. lengthDeletions2 = 0;
  5850. lastequality = diffs[pointer][1];
  5851. } else {
  5852. // An insertion or deletion.
  5853. if (diffs[pointer][0] === DIFF_INSERT) {
  5854. lengthInsertions2 += diffs[pointer][1].length;
  5855. } else {
  5856. lengthDeletions2 += diffs[pointer][1].length;
  5857. } // Eliminate an equality that is smaller or equal to the edits on both
  5858. // sides of it.
  5859. if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {
  5860. // Duplicate record.
  5861. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); // Change second copy to insert.
  5862. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; // Throw away the equality we just deleted.
  5863. equalitiesLength--; // Throw away the previous equality (it needs to be reevaluated).
  5864. equalitiesLength--;
  5865. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; // Reset the counters.
  5866. lengthInsertions1 = 0;
  5867. lengthDeletions1 = 0;
  5868. lengthInsertions2 = 0;
  5869. lengthDeletions2 = 0;
  5870. lastequality = null;
  5871. changes = true;
  5872. }
  5873. }
  5874. pointer++;
  5875. } // Normalize the diff.
  5876. if (changes) {
  5877. this.diffCleanupMerge(diffs);
  5878. } // Find any overlaps between deletions and insertions.
  5879. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  5880. // -> <del>abc</del>xxx<ins>def</ins>
  5881. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  5882. // -> <ins>def</ins>xxx<del>abc</del>
  5883. // Only extract an overlap if it is as big as the edit ahead or behind it.
  5884. pointer = 1;
  5885. while (pointer < diffs.length) {
  5886. if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
  5887. deletion = diffs[pointer - 1][1];
  5888. insertion = diffs[pointer][1];
  5889. overlapLength1 = this.diffCommonOverlap(deletion, insertion);
  5890. overlapLength2 = this.diffCommonOverlap(insertion, deletion);
  5891. if (overlapLength1 >= overlapLength2) {
  5892. if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {
  5893. // Overlap found. Insert an equality and trim the surrounding edits.
  5894. diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);
  5895. diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);
  5896. diffs[pointer + 1][1] = insertion.substring(overlapLength1);
  5897. pointer++;
  5898. }
  5899. } else {
  5900. if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {
  5901. // Reverse overlap found.
  5902. // Insert an equality and swap and trim the surrounding edits.
  5903. diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);
  5904. diffs[pointer - 1][0] = DIFF_INSERT;
  5905. diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);
  5906. diffs[pointer + 1][0] = DIFF_DELETE;
  5907. diffs[pointer + 1][1] = deletion.substring(overlapLength2);
  5908. pointer++;
  5909. }
  5910. }
  5911. pointer++;
  5912. }
  5913. pointer++;
  5914. }
  5915. };
  5916. /**
  5917. * Determine if the suffix of one string is the prefix of another.
  5918. * @param {string} text1 First string.
  5919. * @param {string} text2 Second string.
  5920. * @return {number} The number of characters common to the end of the first
  5921. * string and the start of the second string.
  5922. * @private
  5923. */
  5924. DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
  5925. var text1Length, text2Length, textLength, best, length, pattern, found; // Cache the text lengths to prevent multiple calls.
  5926. text1Length = text1.length;
  5927. text2Length = text2.length; // Eliminate the null case.
  5928. if (text1Length === 0 || text2Length === 0) {
  5929. return 0;
  5930. } // Truncate the longer string.
  5931. if (text1Length > text2Length) {
  5932. text1 = text1.substring(text1Length - text2Length);
  5933. } else if (text1Length < text2Length) {
  5934. text2 = text2.substring(0, text1Length);
  5935. }
  5936. textLength = Math.min(text1Length, text2Length); // Quick check for the worst case.
  5937. if (text1 === text2) {
  5938. return textLength;
  5939. } // Start by looking for a single character match
  5940. // and increase length until no match is found.
  5941. // Performance analysis: https://neil.fraser.name/news/2010/11/04/
  5942. best = 0;
  5943. length = 1;
  5944. while (true) {
  5945. pattern = text1.substring(textLength - length);
  5946. found = text2.indexOf(pattern);
  5947. if (found === -1) {
  5948. return best;
  5949. }
  5950. length += found;
  5951. if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {
  5952. best = length;
  5953. length++;
  5954. }
  5955. }
  5956. };
  5957. /**
  5958. * Split two texts into an array of strings. Reduce the texts to a string of
  5959. * hashes where each Unicode character represents one line.
  5960. * @param {string} text1 First string.
  5961. * @param {string} text2 Second string.
  5962. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
  5963. * An object containing the encoded text1, the encoded text2 and
  5964. * the array of unique strings.
  5965. * The zeroth element of the array of unique strings is intentionally blank.
  5966. * @private
  5967. */
  5968. DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
  5969. var lineArray, lineHash, chars1, chars2;
  5970. lineArray = []; // E.g. lineArray[4] === 'Hello\n'
  5971. lineHash = {}; // E.g. lineHash['Hello\n'] === 4
  5972. // '\x00' is a valid character, but various debuggers don't like it.
  5973. // So we'll insert a junk entry to avoid generating a null character.
  5974. lineArray[0] = "";
  5975. /**
  5976. * Split a text into an array of strings. Reduce the texts to a string of
  5977. * hashes where each Unicode character represents one line.
  5978. * Modifies linearray and linehash through being a closure.
  5979. * @param {string} text String to encode.
  5980. * @return {string} Encoded string.
  5981. * @private
  5982. */
  5983. function diffLinesToCharsMunge(text) {
  5984. var chars, lineStart, lineEnd, lineArrayLength, line;
  5985. chars = ""; // Walk the text, pulling out a substring for each line.
  5986. // text.split('\n') would would temporarily double our memory footprint.
  5987. // Modifying text would create many large strings to garbage collect.
  5988. lineStart = 0;
  5989. lineEnd = -1; // Keeping our own length variable is faster than looking it up.
  5990. lineArrayLength = lineArray.length;
  5991. while (lineEnd < text.length - 1) {
  5992. lineEnd = text.indexOf("\n", lineStart);
  5993. if (lineEnd === -1) {
  5994. lineEnd = text.length - 1;
  5995. }
  5996. line = text.substring(lineStart, lineEnd + 1);
  5997. lineStart = lineEnd + 1;
  5998. if (hasOwn.call(lineHash, line)) {
  5999. chars += String.fromCharCode(lineHash[line]);
  6000. } else {
  6001. chars += String.fromCharCode(lineArrayLength);
  6002. lineHash[line] = lineArrayLength;
  6003. lineArray[lineArrayLength++] = line;
  6004. }
  6005. }
  6006. return chars;
  6007. }
  6008. chars1 = diffLinesToCharsMunge(text1);
  6009. chars2 = diffLinesToCharsMunge(text2);
  6010. return {
  6011. chars1: chars1,
  6012. chars2: chars2,
  6013. lineArray: lineArray
  6014. };
  6015. };
  6016. /**
  6017. * Rehydrate the text in a diff from a string of line hashes to real lines of
  6018. * text.
  6019. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  6020. * @param {!Array.<string>} lineArray Array of unique strings.
  6021. * @private
  6022. */
  6023. DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
  6024. var x, chars, text, y;
  6025. for (x = 0; x < diffs.length; x++) {
  6026. chars = diffs[x][1];
  6027. text = [];
  6028. for (y = 0; y < chars.length; y++) {
  6029. text[y] = lineArray[chars.charCodeAt(y)];
  6030. }
  6031. diffs[x][1] = text.join("");
  6032. }
  6033. };
  6034. /**
  6035. * Reorder and merge like edit sections. Merge equalities.
  6036. * Any edit section can move as long as it doesn't cross an equality.
  6037. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  6038. */
  6039. DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
  6040. var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position;
  6041. diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
  6042. pointer = 0;
  6043. countDelete = 0;
  6044. countInsert = 0;
  6045. textDelete = "";
  6046. textInsert = "";
  6047. while (pointer < diffs.length) {
  6048. switch (diffs[pointer][0]) {
  6049. case DIFF_INSERT:
  6050. countInsert++;
  6051. textInsert += diffs[pointer][1];
  6052. pointer++;
  6053. break;
  6054. case DIFF_DELETE:
  6055. countDelete++;
  6056. textDelete += diffs[pointer][1];
  6057. pointer++;
  6058. break;
  6059. case DIFF_EQUAL:
  6060. // Upon reaching an equality, check for prior redundancies.
  6061. if (countDelete + countInsert > 1) {
  6062. if (countDelete !== 0 && countInsert !== 0) {
  6063. // Factor out any common prefixes.
  6064. commonlength = this.diffCommonPrefix(textInsert, textDelete);
  6065. if (commonlength !== 0) {
  6066. if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {
  6067. diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);
  6068. } else {
  6069. diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);
  6070. pointer++;
  6071. }
  6072. textInsert = textInsert.substring(commonlength);
  6073. textDelete = textDelete.substring(commonlength);
  6074. } // Factor out any common suffixies.
  6075. commonlength = this.diffCommonSuffix(textInsert, textDelete);
  6076. if (commonlength !== 0) {
  6077. diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];
  6078. textInsert = textInsert.substring(0, textInsert.length - commonlength);
  6079. textDelete = textDelete.substring(0, textDelete.length - commonlength);
  6080. }
  6081. } // Delete the offending records and add the merged ones.
  6082. if (countDelete === 0) {
  6083. diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]);
  6084. } else if (countInsert === 0) {
  6085. diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]);
  6086. } else {
  6087. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]);
  6088. }
  6089. pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
  6090. } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
  6091. // Merge this equality with the previous one.
  6092. diffs[pointer - 1][1] += diffs[pointer][1];
  6093. diffs.splice(pointer, 1);
  6094. } else {
  6095. pointer++;
  6096. }
  6097. countInsert = 0;
  6098. countDelete = 0;
  6099. textDelete = "";
  6100. textInsert = "";
  6101. break;
  6102. }
  6103. }
  6104. if (diffs[diffs.length - 1][1] === "") {
  6105. diffs.pop(); // Remove the dummy entry at the end.
  6106. } // Second pass: look for single edits surrounded on both sides by equalities
  6107. // which can be shifted sideways to eliminate an equality.
  6108. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  6109. changes = false;
  6110. pointer = 1; // Intentionally ignore the first and last element (don't need checking).
  6111. while (pointer < diffs.length - 1) {
  6112. if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
  6113. diffPointer = diffs[pointer][1];
  6114. position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length); // This is a single edit surrounded by equalities.
  6115. if (position === diffs[pointer - 1][1]) {
  6116. // Shift the edit over the previous equality.
  6117. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
  6118. diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
  6119. diffs.splice(pointer - 1, 1);
  6120. changes = true;
  6121. } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
  6122. // Shift the edit over the next equality.
  6123. diffs[pointer - 1][1] += diffs[pointer + 1][1];
  6124. diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
  6125. diffs.splice(pointer + 1, 1);
  6126. changes = true;
  6127. }
  6128. }
  6129. pointer++;
  6130. } // If shifts were made, the diff needs reordering and another shift sweep.
  6131. if (changes) {
  6132. this.diffCleanupMerge(diffs);
  6133. }
  6134. };
  6135. return function (o, n) {
  6136. var diff, output, text;
  6137. diff = new DiffMatchPatch();
  6138. output = diff.DiffMain(o, n);
  6139. diff.diffCleanupEfficiency(output);
  6140. text = diff.diffPrettyHtml(output);
  6141. return text;
  6142. };
  6143. }();
  6144. }());