overpass-layer.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038
  1. (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. const OverpassFrontend = require('overpass-frontend')
  3. const OverpassLayer = require('./src/OverpassLayer')
  4. const OverpassLayerList = require('./src/OverpassLayerList')
  5. if (typeof window !== 'undefined') {
  6. window.OverpassLayer = OverpassLayer
  7. window.OverpassLayerList = OverpassLayerList
  8. window.OverpassFrontend = OverpassFrontend
  9. }
  10. OverpassLayer.List = OverpassLayerList
  11. module.exports = OverpassLayer
  12. },{"./src/OverpassLayer":216,"./src/OverpassLayerList":218,"overpass-frontend":180}],2:[function(require,module,exports){
  13. "use strict";
  14. Object.defineProperty(exports, "__esModule", { value: true });
  15. var meta_1 = require("@turf/meta");
  16. // Note: change RADIUS => earthRadius
  17. var RADIUS = 6378137;
  18. /**
  19. * Takes one or more features and returns their area in square meters.
  20. *
  21. * @name area
  22. * @param {GeoJSON} geojson input GeoJSON feature(s)
  23. * @returns {number} area in square meters
  24. * @example
  25. * var polygon = turf.polygon([[[125, -15], [113, -22], [154, -27], [144, -15], [125, -15]]]);
  26. *
  27. * var area = turf.area(polygon);
  28. *
  29. * //addToMap
  30. * var addToMap = [polygon]
  31. * polygon.properties.area = area
  32. */
  33. function area(geojson) {
  34. return meta_1.geomReduce(geojson, function (value, geom) {
  35. return value + calculateArea(geom);
  36. }, 0);
  37. }
  38. exports.default = area;
  39. /**
  40. * Calculate Area
  41. *
  42. * @private
  43. * @param {Geometry} geom GeoJSON Geometries
  44. * @returns {number} area
  45. */
  46. function calculateArea(geom) {
  47. var total = 0;
  48. var i;
  49. switch (geom.type) {
  50. case "Polygon":
  51. return polygonArea(geom.coordinates);
  52. case "MultiPolygon":
  53. for (i = 0; i < geom.coordinates.length; i++) {
  54. total += polygonArea(geom.coordinates[i]);
  55. }
  56. return total;
  57. case "Point":
  58. case "MultiPoint":
  59. case "LineString":
  60. case "MultiLineString":
  61. return 0;
  62. }
  63. return 0;
  64. }
  65. function polygonArea(coords) {
  66. var total = 0;
  67. if (coords && coords.length > 0) {
  68. total += Math.abs(ringArea(coords[0]));
  69. for (var i = 1; i < coords.length; i++) {
  70. total -= Math.abs(ringArea(coords[i]));
  71. }
  72. }
  73. return total;
  74. }
  75. /**
  76. * @private
  77. * Calculate the approximate area of the polygon were it projected onto the earth.
  78. * Note that this area will be positive if ring is oriented clockwise, otherwise it will be negative.
  79. *
  80. * Reference:
  81. * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for Polygons on a Sphere",
  82. * JPL Publication 07-03, Jet Propulsion
  83. * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
  84. *
  85. * @param {Array<Array<number>>} coords Ring Coordinates
  86. * @returns {number} The approximate signed geodesic area of the polygon in square meters.
  87. */
  88. function ringArea(coords) {
  89. var p1;
  90. var p2;
  91. var p3;
  92. var lowerIndex;
  93. var middleIndex;
  94. var upperIndex;
  95. var i;
  96. var total = 0;
  97. var coordsLength = coords.length;
  98. if (coordsLength > 2) {
  99. for (i = 0; i < coordsLength; i++) {
  100. if (i === coordsLength - 2) {
  101. lowerIndex = coordsLength - 2;
  102. middleIndex = coordsLength - 1;
  103. upperIndex = 0;
  104. }
  105. else if (i === coordsLength - 1) {
  106. lowerIndex = coordsLength - 1;
  107. middleIndex = 0;
  108. upperIndex = 1;
  109. }
  110. else {
  111. lowerIndex = i;
  112. middleIndex = i + 1;
  113. upperIndex = i + 2;
  114. }
  115. p1 = coords[lowerIndex];
  116. p2 = coords[middleIndex];
  117. p3 = coords[upperIndex];
  118. total += (rad(p3[0]) - rad(p1[0])) * Math.sin(rad(p2[1]));
  119. }
  120. total = total * RADIUS * RADIUS / 2;
  121. }
  122. return total;
  123. }
  124. function rad(num) {
  125. return num * Math.PI / 180;
  126. }
  127. },{"@turf/meta":16}],3:[function(require,module,exports){
  128. "use strict";
  129. var __importStar = (this && this.__importStar) || function (mod) {
  130. if (mod && mod.__esModule) return mod;
  131. var result = {};
  132. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  133. result["default"] = mod;
  134. return result;
  135. }
  136. Object.defineProperty(exports, "__esModule", { value: true });
  137. var helpers_1 = require("@turf/helpers");
  138. var invariant_1 = require("@turf/invariant");
  139. var lineclip = __importStar(require("./lib/lineclip"));
  140. /**
  141. * Takes a {@link Feature} and a bbox and clips the feature to the bbox using
  142. * [lineclip](https://github.com/mapbox/lineclip).
  143. * May result in degenerate edges when clipping Polygons.
  144. *
  145. * @name bboxClip
  146. * @param {Feature<LineString|MultiLineString|Polygon|MultiPolygon>} feature feature to clip to the bbox
  147. * @param {BBox} bbox extent in [minX, minY, maxX, maxY] order
  148. * @returns {Feature<LineString|MultiLineString|Polygon|MultiPolygon>} clipped Feature
  149. * @example
  150. * var bbox = [0, 0, 10, 10];
  151. * var poly = turf.polygon([[[2, 2], [8, 4], [12, 8], [3, 7], [2, 2]]]);
  152. *
  153. * var clipped = turf.bboxClip(poly, bbox);
  154. *
  155. * //addToMap
  156. * var addToMap = [bbox, poly, clipped]
  157. */
  158. function bboxClip(feature, bbox) {
  159. var geom = invariant_1.getGeom(feature);
  160. var type = geom.type;
  161. var properties = feature.type === "Feature" ? feature.properties : {};
  162. var coords = geom.coordinates;
  163. switch (type) {
  164. case "LineString":
  165. case "MultiLineString":
  166. var lines_1 = [];
  167. if (type === "LineString") {
  168. coords = [coords];
  169. }
  170. coords.forEach(function (line) {
  171. lineclip.polyline(line, bbox, lines_1);
  172. });
  173. if (lines_1.length === 1) {
  174. return helpers_1.lineString(lines_1[0], properties);
  175. }
  176. return helpers_1.multiLineString(lines_1, properties);
  177. case "Polygon":
  178. return helpers_1.polygon(clipPolygon(coords, bbox), properties);
  179. case "MultiPolygon":
  180. return helpers_1.multiPolygon(coords.map(function (poly) {
  181. return clipPolygon(poly, bbox);
  182. }), properties);
  183. default:
  184. throw new Error("geometry " + type + " not supported");
  185. }
  186. }
  187. exports.default = bboxClip;
  188. function clipPolygon(rings, bbox) {
  189. var outRings = [];
  190. for (var _i = 0, rings_1 = rings; _i < rings_1.length; _i++) {
  191. var ring = rings_1[_i];
  192. var clipped = lineclip.polygon(ring, bbox);
  193. if (clipped.length > 0) {
  194. if (clipped[0][0] !== clipped[clipped.length - 1][0] || clipped[0][1] !== clipped[clipped.length - 1][1]) {
  195. clipped.push(clipped[0]);
  196. }
  197. if (clipped.length >= 4) {
  198. outRings.push(clipped);
  199. }
  200. }
  201. }
  202. return outRings;
  203. }
  204. },{"./lib/lineclip":4,"@turf/helpers":11,"@turf/invariant":13}],4:[function(require,module,exports){
  205. 'use strict';
  206. module.exports = lineclip;
  207. module.exports.default = lineclip;
  208. lineclip.polyline = lineclip;
  209. lineclip.polygon = polygonclip;
  210. // Cohen-Sutherland line clippign algorithm, adapted to efficiently
  211. // handle polylines rather than just segments
  212. function lineclip(points, bbox, result) {
  213. var len = points.length,
  214. codeA = bitCode(points[0], bbox),
  215. part = [],
  216. i, a, b, codeB, lastCode;
  217. if (!result) result = [];
  218. for (i = 1; i < len; i++) {
  219. a = points[i - 1];
  220. b = points[i];
  221. codeB = lastCode = bitCode(b, bbox);
  222. while (true) {
  223. if (!(codeA | codeB)) { // accept
  224. part.push(a);
  225. if (codeB !== lastCode) { // segment went outside
  226. part.push(b);
  227. if (i < len - 1) { // start a new line
  228. result.push(part);
  229. part = [];
  230. }
  231. } else if (i === len - 1) {
  232. part.push(b);
  233. }
  234. break;
  235. } else if (codeA & codeB) { // trivial reject
  236. break;
  237. } else if (codeA) { // a outside, intersect with clip edge
  238. a = intersect(a, b, codeA, bbox);
  239. codeA = bitCode(a, bbox);
  240. } else { // b outside
  241. b = intersect(a, b, codeB, bbox);
  242. codeB = bitCode(b, bbox);
  243. }
  244. }
  245. codeA = lastCode;
  246. }
  247. if (part.length) result.push(part);
  248. return result;
  249. }
  250. // Sutherland-Hodgeman polygon clipping algorithm
  251. function polygonclip(points, bbox) {
  252. var result, edge, prev, prevInside, i, p, inside;
  253. // clip against each side of the clip rectangle
  254. for (edge = 1; edge <= 8; edge *= 2) {
  255. result = [];
  256. prev = points[points.length - 1];
  257. prevInside = !(bitCode(prev, bbox) & edge);
  258. for (i = 0; i < points.length; i++) {
  259. p = points[i];
  260. inside = !(bitCode(p, bbox) & edge);
  261. // if segment goes through the clip window, add an intersection
  262. if (inside !== prevInside) result.push(intersect(prev, p, edge, bbox));
  263. if (inside) result.push(p); // add a point if it's inside
  264. prev = p;
  265. prevInside = inside;
  266. }
  267. points = result;
  268. if (!points.length) break;
  269. }
  270. return result;
  271. }
  272. // intersect a segment against one of the 4 lines that make up the bbox
  273. function intersect(a, b, edge, bbox) {
  274. return edge & 8 ? [a[0] + (b[0] - a[0]) * (bbox[3] - a[1]) / (b[1] - a[1]), bbox[3]] : // top
  275. edge & 4 ? [a[0] + (b[0] - a[0]) * (bbox[1] - a[1]) / (b[1] - a[1]), bbox[1]] : // bottom
  276. edge & 2 ? [bbox[2], a[1] + (b[1] - a[1]) * (bbox[2] - a[0]) / (b[0] - a[0])] : // right
  277. edge & 1 ? [bbox[0], a[1] + (b[1] - a[1]) * (bbox[0] - a[0]) / (b[0] - a[0])] : // left
  278. null;
  279. }
  280. // bit code reflects the point position relative to the bbox:
  281. // left mid right
  282. // top 1001 1000 1010
  283. // mid 0001 0000 0010
  284. // bottom 0101 0100 0110
  285. function bitCode(p, bbox) {
  286. var code = 0;
  287. if (p[0] < bbox[0]) code |= 1; // left
  288. else if (p[0] > bbox[2]) code |= 2; // right
  289. if (p[1] < bbox[1]) code |= 4; // bottom
  290. else if (p[1] > bbox[3]) code |= 8; // top
  291. return code;
  292. }
  293. },{}],5:[function(require,module,exports){
  294. "use strict";
  295. Object.defineProperty(exports, "__esModule", { value: true });
  296. var meta_1 = require("@turf/meta");
  297. /**
  298. * Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
  299. *
  300. * @name bbox
  301. * @param {GeoJSON} geojson any GeoJSON object
  302. * @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order
  303. * @example
  304. * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]);
  305. * var bbox = turf.bbox(line);
  306. * var bboxPolygon = turf.bboxPolygon(bbox);
  307. *
  308. * //addToMap
  309. * var addToMap = [line, bboxPolygon]
  310. */
  311. function bbox(geojson) {
  312. var result = [Infinity, Infinity, -Infinity, -Infinity];
  313. meta_1.coordEach(geojson, function (coord) {
  314. if (result[0] > coord[0]) {
  315. result[0] = coord[0];
  316. }
  317. if (result[1] > coord[1]) {
  318. result[1] = coord[1];
  319. }
  320. if (result[2] < coord[0]) {
  321. result[2] = coord[0];
  322. }
  323. if (result[3] < coord[1]) {
  324. result[3] = coord[1];
  325. }
  326. });
  327. return result;
  328. }
  329. exports.default = bbox;
  330. },{"@turf/meta":16}],6:[function(require,module,exports){
  331. "use strict";
  332. Object.defineProperty(exports, "__esModule", { value: true });
  333. var helpers_1 = require("@turf/helpers");
  334. var invariant_1 = require("@turf/invariant");
  335. // http://en.wikipedia.org/wiki/Haversine_formula
  336. // http://www.movable-type.co.uk/scripts/latlong.html
  337. /**
  338. * Takes two {@link Point|points} and finds the geographic bearing between them,
  339. * i.e. the angle measured in degrees from the north line (0 degrees)
  340. *
  341. * @name bearing
  342. * @param {Coord} start starting Point
  343. * @param {Coord} end ending Point
  344. * @param {Object} [options={}] Optional parameters
  345. * @param {boolean} [options.final=false] calculates the final bearing if true
  346. * @returns {number} bearing in decimal degrees, between -180 and 180 degrees (positive clockwise)
  347. * @example
  348. * var point1 = turf.point([-75.343, 39.984]);
  349. * var point2 = turf.point([-75.534, 39.123]);
  350. *
  351. * var bearing = turf.bearing(point1, point2);
  352. *
  353. * //addToMap
  354. * var addToMap = [point1, point2]
  355. * point1.properties['marker-color'] = '#f00'
  356. * point2.properties['marker-color'] = '#0f0'
  357. * point1.properties.bearing = bearing
  358. */
  359. function bearing(start, end, options) {
  360. if (options === void 0) { options = {}; }
  361. // Reverse calculation
  362. if (options.final === true) {
  363. return calculateFinalBearing(start, end);
  364. }
  365. var coordinates1 = invariant_1.getCoord(start);
  366. var coordinates2 = invariant_1.getCoord(end);
  367. var lon1 = helpers_1.degreesToRadians(coordinates1[0]);
  368. var lon2 = helpers_1.degreesToRadians(coordinates2[0]);
  369. var lat1 = helpers_1.degreesToRadians(coordinates1[1]);
  370. var lat2 = helpers_1.degreesToRadians(coordinates2[1]);
  371. var a = Math.sin(lon2 - lon1) * Math.cos(lat2);
  372. var b = Math.cos(lat1) * Math.sin(lat2) -
  373. Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
  374. return helpers_1.radiansToDegrees(Math.atan2(a, b));
  375. }
  376. /**
  377. * Calculates Final Bearing
  378. *
  379. * @private
  380. * @param {Coord} start starting Point
  381. * @param {Coord} end ending Point
  382. * @returns {number} bearing
  383. */
  384. function calculateFinalBearing(start, end) {
  385. // Swap start & end
  386. var bear = bearing(end, start);
  387. bear = (bear + 180) % 360;
  388. return bear;
  389. }
  390. exports.default = bearing;
  391. },{"@turf/helpers":11,"@turf/invariant":13}],7:[function(require,module,exports){
  392. "use strict";
  393. Object.defineProperty(exports, "__esModule", { value: true });
  394. var invariant_1 = require("@turf/invariant");
  395. // http://en.wikipedia.org/wiki/Even%E2%80%93odd_rule
  396. // modified from: https://github.com/substack/point-in-polygon/blob/master/index.js
  397. // which was modified from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  398. /**
  399. * Takes a {@link Point} and a {@link Polygon} or {@link MultiPolygon} and determines if the point
  400. * resides inside the polygon. The polygon can be convex or concave. The function accounts for holes.
  401. *
  402. * @name booleanPointInPolygon
  403. * @param {Coord} point input point
  404. * @param {Feature<Polygon|MultiPolygon>} polygon input polygon or multipolygon
  405. * @param {Object} [options={}] Optional parameters
  406. * @param {boolean} [options.ignoreBoundary=false] True if polygon boundary should be ignored when determining if
  407. * the point is inside the polygon otherwise false.
  408. * @returns {boolean} `true` if the Point is inside the Polygon; `false` if the Point is not inside the Polygon
  409. * @example
  410. * var pt = turf.point([-77, 44]);
  411. * var poly = turf.polygon([[
  412. * [-81, 41],
  413. * [-81, 47],
  414. * [-72, 47],
  415. * [-72, 41],
  416. * [-81, 41]
  417. * ]]);
  418. *
  419. * turf.booleanPointInPolygon(pt, poly);
  420. * //= true
  421. */
  422. function booleanPointInPolygon(point, polygon, options) {
  423. if (options === void 0) { options = {}; }
  424. // validation
  425. if (!point) {
  426. throw new Error("point is required");
  427. }
  428. if (!polygon) {
  429. throw new Error("polygon is required");
  430. }
  431. var pt = invariant_1.getCoord(point);
  432. var geom = invariant_1.getGeom(polygon);
  433. var type = geom.type;
  434. var bbox = polygon.bbox;
  435. var polys = geom.coordinates;
  436. // Quick elimination if point is not inside bbox
  437. if (bbox && inBBox(pt, bbox) === false) {
  438. return false;
  439. }
  440. // normalize to multipolygon
  441. if (type === "Polygon") {
  442. polys = [polys];
  443. }
  444. var insidePoly = false;
  445. for (var i = 0; i < polys.length && !insidePoly; i++) {
  446. // check if it is in the outer ring first
  447. if (inRing(pt, polys[i][0], options.ignoreBoundary)) {
  448. var inHole = false;
  449. var k = 1;
  450. // check for the point in any of the holes
  451. while (k < polys[i].length && !inHole) {
  452. if (inRing(pt, polys[i][k], !options.ignoreBoundary)) {
  453. inHole = true;
  454. }
  455. k++;
  456. }
  457. if (!inHole) {
  458. insidePoly = true;
  459. }
  460. }
  461. }
  462. return insidePoly;
  463. }
  464. exports.default = booleanPointInPolygon;
  465. /**
  466. * inRing
  467. *
  468. * @private
  469. * @param {Array<number>} pt [x,y]
  470. * @param {Array<Array<number>>} ring [[x,y], [x,y],..]
  471. * @param {boolean} ignoreBoundary ignoreBoundary
  472. * @returns {boolean} inRing
  473. */
  474. function inRing(pt, ring, ignoreBoundary) {
  475. var isInside = false;
  476. if (ring[0][0] === ring[ring.length - 1][0] && ring[0][1] === ring[ring.length - 1][1]) {
  477. ring = ring.slice(0, ring.length - 1);
  478. }
  479. for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
  480. var xi = ring[i][0];
  481. var yi = ring[i][1];
  482. var xj = ring[j][0];
  483. var yj = ring[j][1];
  484. var onBoundary = (pt[1] * (xi - xj) + yi * (xj - pt[0]) + yj * (pt[0] - xi) === 0) &&
  485. ((xi - pt[0]) * (xj - pt[0]) <= 0) && ((yi - pt[1]) * (yj - pt[1]) <= 0);
  486. if (onBoundary) {
  487. return !ignoreBoundary;
  488. }
  489. var intersect = ((yi > pt[1]) !== (yj > pt[1])) &&
  490. (pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi);
  491. if (intersect) {
  492. isInside = !isInside;
  493. }
  494. }
  495. return isInside;
  496. }
  497. /**
  498. * inBBox
  499. *
  500. * @private
  501. * @param {Position} pt point [x,y]
  502. * @param {BBox} bbox BBox [west, south, east, north]
  503. * @returns {boolean} true/false if point is inside BBox
  504. */
  505. function inBBox(pt, bbox) {
  506. return bbox[0] <= pt[0] &&
  507. bbox[1] <= pt[1] &&
  508. bbox[2] >= pt[0] &&
  509. bbox[3] >= pt[1];
  510. }
  511. },{"@turf/invariant":13}],8:[function(require,module,exports){
  512. "use strict";
  513. Object.defineProperty(exports, "__esModule", { value: true });
  514. // http://en.wikipedia.org/wiki/Haversine_formula
  515. // http://www.movable-type.co.uk/scripts/latlong.html
  516. var helpers_1 = require("@turf/helpers");
  517. var invariant_1 = require("@turf/invariant");
  518. /**
  519. * Takes a {@link Point} and calculates the location of a destination point given a distance in
  520. * degrees, radians, miles, or kilometers; and bearing in degrees.
  521. * This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
  522. *
  523. * @name destination
  524. * @param {Coord} origin starting point
  525. * @param {number} distance distance from the origin point
  526. * @param {number} bearing ranging from -180 to 180
  527. * @param {Object} [options={}] Optional parameters
  528. * @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians
  529. * @param {Object} [options.properties={}] Translate properties to Point
  530. * @returns {Feature<Point>} destination point
  531. * @example
  532. * var point = turf.point([-75.343, 39.984]);
  533. * var distance = 50;
  534. * var bearing = 90;
  535. * var options = {units: 'miles'};
  536. *
  537. * var destination = turf.destination(point, distance, bearing, options);
  538. *
  539. * //addToMap
  540. * var addToMap = [point, destination]
  541. * destination.properties['marker-color'] = '#f00';
  542. * point.properties['marker-color'] = '#0f0';
  543. */
  544. function destination(origin, distance, bearing, options) {
  545. if (options === void 0) { options = {}; }
  546. // Handle input
  547. var coordinates1 = invariant_1.getCoord(origin);
  548. var longitude1 = helpers_1.degreesToRadians(coordinates1[0]);
  549. var latitude1 = helpers_1.degreesToRadians(coordinates1[1]);
  550. var bearingRad = helpers_1.degreesToRadians(bearing);
  551. var radians = helpers_1.lengthToRadians(distance, options.units);
  552. // Main
  553. var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) +
  554. Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearingRad));
  555. var longitude2 = longitude1 + Math.atan2(Math.sin(bearingRad) * Math.sin(radians) * Math.cos(latitude1), Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2));
  556. var lng = helpers_1.radiansToDegrees(longitude2);
  557. var lat = helpers_1.radiansToDegrees(latitude2);
  558. return helpers_1.point([lng, lat], options.properties);
  559. }
  560. exports.default = destination;
  561. },{"@turf/helpers":11,"@turf/invariant":13}],9:[function(require,module,exports){
  562. 'use strict';
  563. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  564. var martinez = require('martinez-polygon-clipping');
  565. var area = _interopDefault(require('@turf/area'));
  566. var helpers = require('@turf/helpers');
  567. var invariant = require('@turf/invariant');
  568. var meta = require('@turf/meta');
  569. /**
  570. * Finds the difference between two {@link Polygon|polygons} by clipping the second polygon from the first.
  571. *
  572. * @name difference
  573. * @param {Feature<Polygon|MultiPolygon>} polygon1 input Polygon feature
  574. * @param {Feature<Polygon|MultiPolygon>} polygon2 Polygon feature to difference from polygon1
  575. * @returns {Feature<Polygon|MultiPolygon>|null} a Polygon or MultiPolygon feature showing the area of `polygon1` excluding the area of `polygon2` (if empty returns `null`)
  576. * @example
  577. * var polygon1 = turf.polygon([[
  578. * [128, -26],
  579. * [141, -26],
  580. * [141, -21],
  581. * [128, -21],
  582. * [128, -26]
  583. * ]], {
  584. * "fill": "#F00",
  585. * "fill-opacity": 0.1
  586. * });
  587. * var polygon2 = turf.polygon([[
  588. * [126, -28],
  589. * [140, -28],
  590. * [140, -20],
  591. * [126, -20],
  592. * [126, -28]
  593. * ]], {
  594. * "fill": "#00F",
  595. * "fill-opacity": 0.1
  596. * });
  597. *
  598. * var difference = turf.difference(polygon1, polygon2);
  599. *
  600. * //addToMap
  601. * var addToMap = [polygon1, polygon2, difference];
  602. */
  603. function difference(polygon1, polygon2) {
  604. var geom1 = invariant.getGeom(polygon1);
  605. var geom2 = invariant.getGeom(polygon2);
  606. var properties = polygon1.properties || {};
  607. // Issue #721 - JSTS/Martinez can't handle empty polygons
  608. geom1 = removeEmptyPolygon(geom1);
  609. geom2 = removeEmptyPolygon(geom2);
  610. if (!geom1) return null;
  611. if (!geom2) return helpers.feature(geom1, properties);
  612. var differenced = martinez.diff(geom1.coordinates, geom2.coordinates);
  613. if (differenced.length === 0) return null;
  614. if (differenced.length === 1) return helpers.polygon(differenced[0], properties);
  615. return helpers.multiPolygon(differenced, properties);
  616. }
  617. /**
  618. * Detect Empty Polygon
  619. *
  620. * @private
  621. * @param {Geometry<Polygon|MultiPolygon>} geom Geometry Object
  622. * @returns {Geometry<Polygon|MultiPolygon>|null} removed any polygons with no areas
  623. */
  624. function removeEmptyPolygon(geom) {
  625. switch (geom.type) {
  626. case 'Polygon':
  627. if (area(geom) > 1) return geom;
  628. return null;
  629. case 'MultiPolygon':
  630. var coordinates = [];
  631. meta.flattenEach(geom, function (feature) {
  632. if (area(feature) > 1) coordinates.push(feature.geometry.coordinates);
  633. });
  634. if (coordinates.length) return {type: 'MultiPolygon', coordinates: coordinates};
  635. }
  636. }
  637. module.exports = difference;
  638. },{"@turf/area":2,"@turf/helpers":11,"@turf/invariant":13,"@turf/meta":16,"martinez-polygon-clipping":173}],10:[function(require,module,exports){
  639. "use strict";
  640. Object.defineProperty(exports, "__esModule", { value: true });
  641. var invariant_1 = require("@turf/invariant");
  642. var helpers_1 = require("@turf/helpers");
  643. //http://en.wikipedia.org/wiki/Haversine_formula
  644. //http://www.movable-type.co.uk/scripts/latlong.html
  645. /**
  646. * Calculates the distance between two {@link Point|points} in degrees, radians, miles, or kilometers.
  647. * This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
  648. *
  649. * @name distance
  650. * @param {Coord} from origin point
  651. * @param {Coord} to destination point
  652. * @param {Object} [options={}] Optional parameters
  653. * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers
  654. * @returns {number} distance between the two points
  655. * @example
  656. * var from = turf.point([-75.343, 39.984]);
  657. * var to = turf.point([-75.534, 39.123]);
  658. * var options = {units: 'miles'};
  659. *
  660. * var distance = turf.distance(from, to, options);
  661. *
  662. * //addToMap
  663. * var addToMap = [from, to];
  664. * from.properties.distance = distance;
  665. * to.properties.distance = distance;
  666. */
  667. function distance(from, to, options) {
  668. if (options === void 0) { options = {}; }
  669. var coordinates1 = invariant_1.getCoord(from);
  670. var coordinates2 = invariant_1.getCoord(to);
  671. var dLat = helpers_1.degreesToRadians((coordinates2[1] - coordinates1[1]));
  672. var dLon = helpers_1.degreesToRadians((coordinates2[0] - coordinates1[0]));
  673. var lat1 = helpers_1.degreesToRadians(coordinates1[1]);
  674. var lat2 = helpers_1.degreesToRadians(coordinates2[1]);
  675. var a = Math.pow(Math.sin(dLat / 2), 2) +
  676. Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
  677. return helpers_1.radiansToLength(2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)), options.units);
  678. }
  679. exports.default = distance;
  680. },{"@turf/helpers":11,"@turf/invariant":13}],11:[function(require,module,exports){
  681. "use strict";
  682. Object.defineProperty(exports, "__esModule", { value: true });
  683. /**
  684. * @module helpers
  685. */
  686. /**
  687. * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.
  688. *
  689. * @memberof helpers
  690. * @type {number}
  691. */
  692. exports.earthRadius = 6371008.8;
  693. /**
  694. * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.
  695. *
  696. * @memberof helpers
  697. * @type {Object}
  698. */
  699. exports.factors = {
  700. centimeters: exports.earthRadius * 100,
  701. centimetres: exports.earthRadius * 100,
  702. degrees: exports.earthRadius / 111325,
  703. feet: exports.earthRadius * 3.28084,
  704. inches: exports.earthRadius * 39.370,
  705. kilometers: exports.earthRadius / 1000,
  706. kilometres: exports.earthRadius / 1000,
  707. meters: exports.earthRadius,
  708. metres: exports.earthRadius,
  709. miles: exports.earthRadius / 1609.344,
  710. millimeters: exports.earthRadius * 1000,
  711. millimetres: exports.earthRadius * 1000,
  712. nauticalmiles: exports.earthRadius / 1852,
  713. radians: 1,
  714. yards: exports.earthRadius / 1.0936,
  715. };
  716. /**
  717. * Units of measurement factors based on 1 meter.
  718. *
  719. * @memberof helpers
  720. * @type {Object}
  721. */
  722. exports.unitsFactors = {
  723. centimeters: 100,
  724. centimetres: 100,
  725. degrees: 1 / 111325,
  726. feet: 3.28084,
  727. inches: 39.370,
  728. kilometers: 1 / 1000,
  729. kilometres: 1 / 1000,
  730. meters: 1,
  731. metres: 1,
  732. miles: 1 / 1609.344,
  733. millimeters: 1000,
  734. millimetres: 1000,
  735. nauticalmiles: 1 / 1852,
  736. radians: 1 / exports.earthRadius,
  737. yards: 1 / 1.0936,
  738. };
  739. /**
  740. * Area of measurement factors based on 1 square meter.
  741. *
  742. * @memberof helpers
  743. * @type {Object}
  744. */
  745. exports.areaFactors = {
  746. acres: 0.000247105,
  747. centimeters: 10000,
  748. centimetres: 10000,
  749. feet: 10.763910417,
  750. inches: 1550.003100006,
  751. kilometers: 0.000001,
  752. kilometres: 0.000001,
  753. meters: 1,
  754. metres: 1,
  755. miles: 3.86e-7,
  756. millimeters: 1000000,
  757. millimetres: 1000000,
  758. yards: 1.195990046,
  759. };
  760. /**
  761. * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.
  762. *
  763. * @name feature
  764. * @param {Geometry} geometry input geometry
  765. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  766. * @param {Object} [options={}] Optional Parameters
  767. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  768. * @param {string|number} [options.id] Identifier associated with the Feature
  769. * @returns {Feature} a GeoJSON Feature
  770. * @example
  771. * var geometry = {
  772. * "type": "Point",
  773. * "coordinates": [110, 50]
  774. * };
  775. *
  776. * var feature = turf.feature(geometry);
  777. *
  778. * //=feature
  779. */
  780. function feature(geom, properties, options) {
  781. if (options === void 0) { options = {}; }
  782. var feat = { type: "Feature" };
  783. if (options.id === 0 || options.id) {
  784. feat.id = options.id;
  785. }
  786. if (options.bbox) {
  787. feat.bbox = options.bbox;
  788. }
  789. feat.properties = properties || {};
  790. feat.geometry = geom;
  791. return feat;
  792. }
  793. exports.feature = feature;
  794. /**
  795. * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.
  796. * For GeometryCollection type use `helpers.geometryCollection`
  797. *
  798. * @name geometry
  799. * @param {string} type Geometry Type
  800. * @param {Array<any>} coordinates Coordinates
  801. * @param {Object} [options={}] Optional Parameters
  802. * @returns {Geometry} a GeoJSON Geometry
  803. * @example
  804. * var type = "Point";
  805. * var coordinates = [110, 50];
  806. * var geometry = turf.geometry(type, coordinates);
  807. * // => geometry
  808. */
  809. function geometry(type, coordinates, options) {
  810. if (options === void 0) { options = {}; }
  811. switch (type) {
  812. case "Point": return point(coordinates).geometry;
  813. case "LineString": return lineString(coordinates).geometry;
  814. case "Polygon": return polygon(coordinates).geometry;
  815. case "MultiPoint": return multiPoint(coordinates).geometry;
  816. case "MultiLineString": return multiLineString(coordinates).geometry;
  817. case "MultiPolygon": return multiPolygon(coordinates).geometry;
  818. default: throw new Error(type + " is invalid");
  819. }
  820. }
  821. exports.geometry = geometry;
  822. /**
  823. * Creates a {@link Point} {@link Feature} from a Position.
  824. *
  825. * @name point
  826. * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)
  827. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  828. * @param {Object} [options={}] Optional Parameters
  829. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  830. * @param {string|number} [options.id] Identifier associated with the Feature
  831. * @returns {Feature<Point>} a Point feature
  832. * @example
  833. * var point = turf.point([-75.343, 39.984]);
  834. *
  835. * //=point
  836. */
  837. function point(coordinates, properties, options) {
  838. if (options === void 0) { options = {}; }
  839. var geom = {
  840. type: "Point",
  841. coordinates: coordinates,
  842. };
  843. return feature(geom, properties, options);
  844. }
  845. exports.point = point;
  846. /**
  847. * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.
  848. *
  849. * @name points
  850. * @param {Array<Array<number>>} coordinates an array of Points
  851. * @param {Object} [properties={}] Translate these properties to each Feature
  852. * @param {Object} [options={}] Optional Parameters
  853. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north]
  854. * associated with the FeatureCollection
  855. * @param {string|number} [options.id] Identifier associated with the FeatureCollection
  856. * @returns {FeatureCollection<Point>} Point Feature
  857. * @example
  858. * var points = turf.points([
  859. * [-75, 39],
  860. * [-80, 45],
  861. * [-78, 50]
  862. * ]);
  863. *
  864. * //=points
  865. */
  866. function points(coordinates, properties, options) {
  867. if (options === void 0) { options = {}; }
  868. return featureCollection(coordinates.map(function (coords) {
  869. return point(coords, properties);
  870. }), options);
  871. }
  872. exports.points = points;
  873. /**
  874. * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.
  875. *
  876. * @name polygon
  877. * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings
  878. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  879. * @param {Object} [options={}] Optional Parameters
  880. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  881. * @param {string|number} [options.id] Identifier associated with the Feature
  882. * @returns {Feature<Polygon>} Polygon Feature
  883. * @example
  884. * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });
  885. *
  886. * //=polygon
  887. */
  888. function polygon(coordinates, properties, options) {
  889. if (options === void 0) { options = {}; }
  890. for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {
  891. var ring = coordinates_1[_i];
  892. if (ring.length < 4) {
  893. throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");
  894. }
  895. for (var j = 0; j < ring[ring.length - 1].length; j++) {
  896. // Check if first point of Polygon contains two numbers
  897. if (ring[ring.length - 1][j] !== ring[0][j]) {
  898. throw new Error("First and last Position are not equivalent.");
  899. }
  900. }
  901. }
  902. var geom = {
  903. type: "Polygon",
  904. coordinates: coordinates,
  905. };
  906. return feature(geom, properties, options);
  907. }
  908. exports.polygon = polygon;
  909. /**
  910. * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.
  911. *
  912. * @name polygons
  913. * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates
  914. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  915. * @param {Object} [options={}] Optional Parameters
  916. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  917. * @param {string|number} [options.id] Identifier associated with the FeatureCollection
  918. * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection
  919. * @example
  920. * var polygons = turf.polygons([
  921. * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],
  922. * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],
  923. * ]);
  924. *
  925. * //=polygons
  926. */
  927. function polygons(coordinates, properties, options) {
  928. if (options === void 0) { options = {}; }
  929. return featureCollection(coordinates.map(function (coords) {
  930. return polygon(coords, properties);
  931. }), options);
  932. }
  933. exports.polygons = polygons;
  934. /**
  935. * Creates a {@link LineString} {@link Feature} from an Array of Positions.
  936. *
  937. * @name lineString
  938. * @param {Array<Array<number>>} coordinates an array of Positions
  939. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  940. * @param {Object} [options={}] Optional Parameters
  941. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  942. * @param {string|number} [options.id] Identifier associated with the Feature
  943. * @returns {Feature<LineString>} LineString Feature
  944. * @example
  945. * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});
  946. * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});
  947. *
  948. * //=linestring1
  949. * //=linestring2
  950. */
  951. function lineString(coordinates, properties, options) {
  952. if (options === void 0) { options = {}; }
  953. if (coordinates.length < 2) {
  954. throw new Error("coordinates must be an array of two or more positions");
  955. }
  956. var geom = {
  957. type: "LineString",
  958. coordinates: coordinates,
  959. };
  960. return feature(geom, properties, options);
  961. }
  962. exports.lineString = lineString;
  963. /**
  964. * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.
  965. *
  966. * @name lineStrings
  967. * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings
  968. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  969. * @param {Object} [options={}] Optional Parameters
  970. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north]
  971. * associated with the FeatureCollection
  972. * @param {string|number} [options.id] Identifier associated with the FeatureCollection
  973. * @returns {FeatureCollection<LineString>} LineString FeatureCollection
  974. * @example
  975. * var linestrings = turf.lineStrings([
  976. * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],
  977. * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]
  978. * ]);
  979. *
  980. * //=linestrings
  981. */
  982. function lineStrings(coordinates, properties, options) {
  983. if (options === void 0) { options = {}; }
  984. return featureCollection(coordinates.map(function (coords) {
  985. return lineString(coords, properties);
  986. }), options);
  987. }
  988. exports.lineStrings = lineStrings;
  989. /**
  990. * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.
  991. *
  992. * @name featureCollection
  993. * @param {Feature[]} features input features
  994. * @param {Object} [options={}] Optional Parameters
  995. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  996. * @param {string|number} [options.id] Identifier associated with the Feature
  997. * @returns {FeatureCollection} FeatureCollection of Features
  998. * @example
  999. * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});
  1000. * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});
  1001. * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});
  1002. *
  1003. * var collection = turf.featureCollection([
  1004. * locationA,
  1005. * locationB,
  1006. * locationC
  1007. * ]);
  1008. *
  1009. * //=collection
  1010. */
  1011. function featureCollection(features, options) {
  1012. if (options === void 0) { options = {}; }
  1013. var fc = { type: "FeatureCollection" };
  1014. if (options.id) {
  1015. fc.id = options.id;
  1016. }
  1017. if (options.bbox) {
  1018. fc.bbox = options.bbox;
  1019. }
  1020. fc.features = features;
  1021. return fc;
  1022. }
  1023. exports.featureCollection = featureCollection;
  1024. /**
  1025. * Creates a {@link Feature<MultiLineString>} based on a
  1026. * coordinate array. Properties can be added optionally.
  1027. *
  1028. * @name multiLineString
  1029. * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings
  1030. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  1031. * @param {Object} [options={}] Optional Parameters
  1032. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  1033. * @param {string|number} [options.id] Identifier associated with the Feature
  1034. * @returns {Feature<MultiLineString>} a MultiLineString feature
  1035. * @throws {Error} if no coordinates are passed
  1036. * @example
  1037. * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);
  1038. *
  1039. * //=multiLine
  1040. */
  1041. function multiLineString(coordinates, properties, options) {
  1042. if (options === void 0) { options = {}; }
  1043. var geom = {
  1044. type: "MultiLineString",
  1045. coordinates: coordinates,
  1046. };
  1047. return feature(geom, properties, options);
  1048. }
  1049. exports.multiLineString = multiLineString;
  1050. /**
  1051. * Creates a {@link Feature<MultiPoint>} based on a
  1052. * coordinate array. Properties can be added optionally.
  1053. *
  1054. * @name multiPoint
  1055. * @param {Array<Array<number>>} coordinates an array of Positions
  1056. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  1057. * @param {Object} [options={}] Optional Parameters
  1058. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  1059. * @param {string|number} [options.id] Identifier associated with the Feature
  1060. * @returns {Feature<MultiPoint>} a MultiPoint feature
  1061. * @throws {Error} if no coordinates are passed
  1062. * @example
  1063. * var multiPt = turf.multiPoint([[0,0],[10,10]]);
  1064. *
  1065. * //=multiPt
  1066. */
  1067. function multiPoint(coordinates, properties, options) {
  1068. if (options === void 0) { options = {}; }
  1069. var geom = {
  1070. type: "MultiPoint",
  1071. coordinates: coordinates,
  1072. };
  1073. return feature(geom, properties, options);
  1074. }
  1075. exports.multiPoint = multiPoint;
  1076. /**
  1077. * Creates a {@link Feature<MultiPolygon>} based on a
  1078. * coordinate array. Properties can be added optionally.
  1079. *
  1080. * @name multiPolygon
  1081. * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons
  1082. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  1083. * @param {Object} [options={}] Optional Parameters
  1084. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  1085. * @param {string|number} [options.id] Identifier associated with the Feature
  1086. * @returns {Feature<MultiPolygon>} a multipolygon feature
  1087. * @throws {Error} if no coordinates are passed
  1088. * @example
  1089. * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);
  1090. *
  1091. * //=multiPoly
  1092. *
  1093. */
  1094. function multiPolygon(coordinates, properties, options) {
  1095. if (options === void 0) { options = {}; }
  1096. var geom = {
  1097. type: "MultiPolygon",
  1098. coordinates: coordinates,
  1099. };
  1100. return feature(geom, properties, options);
  1101. }
  1102. exports.multiPolygon = multiPolygon;
  1103. /**
  1104. * Creates a {@link Feature<GeometryCollection>} based on a
  1105. * coordinate array. Properties can be added optionally.
  1106. *
  1107. * @name geometryCollection
  1108. * @param {Array<Geometry>} geometries an array of GeoJSON Geometries
  1109. * @param {Object} [properties={}] an Object of key-value pairs to add as properties
  1110. * @param {Object} [options={}] Optional Parameters
  1111. * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
  1112. * @param {string|number} [options.id] Identifier associated with the Feature
  1113. * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature
  1114. * @example
  1115. * var pt = turf.geometry("Point", [100, 0]);
  1116. * var line = turf.geometry("LineString", [[101, 0], [102, 1]]);
  1117. * var collection = turf.geometryCollection([pt, line]);
  1118. *
  1119. * // => collection
  1120. */
  1121. function geometryCollection(geometries, properties, options) {
  1122. if (options === void 0) { options = {}; }
  1123. var geom = {
  1124. type: "GeometryCollection",
  1125. geometries: geometries,
  1126. };
  1127. return feature(geom, properties, options);
  1128. }
  1129. exports.geometryCollection = geometryCollection;
  1130. /**
  1131. * Round number to precision
  1132. *
  1133. * @param {number} num Number
  1134. * @param {number} [precision=0] Precision
  1135. * @returns {number} rounded number
  1136. * @example
  1137. * turf.round(120.4321)
  1138. * //=120
  1139. *
  1140. * turf.round(120.4321, 2)
  1141. * //=120.43
  1142. */
  1143. function round(num, precision) {
  1144. if (precision === void 0) { precision = 0; }
  1145. if (precision && !(precision >= 0)) {
  1146. throw new Error("precision must be a positive number");
  1147. }
  1148. var multiplier = Math.pow(10, precision || 0);
  1149. return Math.round(num * multiplier) / multiplier;
  1150. }
  1151. exports.round = round;
  1152. /**
  1153. * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.
  1154. * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
  1155. *
  1156. * @name radiansToLength
  1157. * @param {number} radians in radians across the sphere
  1158. * @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
  1159. * meters, kilometres, kilometers.
  1160. * @returns {number} distance
  1161. */
  1162. function radiansToLength(radians, units) {
  1163. if (units === void 0) { units = "kilometers"; }
  1164. var factor = exports.factors[units];
  1165. if (!factor) {
  1166. throw new Error(units + " units is invalid");
  1167. }
  1168. return radians * factor;
  1169. }
  1170. exports.radiansToLength = radiansToLength;
  1171. /**
  1172. * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians
  1173. * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
  1174. *
  1175. * @name lengthToRadians
  1176. * @param {number} distance in real units
  1177. * @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
  1178. * meters, kilometres, kilometers.
  1179. * @returns {number} radians
  1180. */
  1181. function lengthToRadians(distance, units) {
  1182. if (units === void 0) { units = "kilometers"; }
  1183. var factor = exports.factors[units];
  1184. if (!factor) {
  1185. throw new Error(units + " units is invalid");
  1186. }
  1187. return distance / factor;
  1188. }
  1189. exports.lengthToRadians = lengthToRadians;
  1190. /**
  1191. * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees
  1192. * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet
  1193. *
  1194. * @name lengthToDegrees
  1195. * @param {number} distance in real units
  1196. * @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
  1197. * meters, kilometres, kilometers.
  1198. * @returns {number} degrees
  1199. */
  1200. function lengthToDegrees(distance, units) {
  1201. return radiansToDegrees(lengthToRadians(distance, units));
  1202. }
  1203. exports.lengthToDegrees = lengthToDegrees;
  1204. /**
  1205. * Converts any bearing angle from the north line direction (positive clockwise)
  1206. * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line
  1207. *
  1208. * @name bearingToAzimuth
  1209. * @param {number} bearing angle, between -180 and +180 degrees
  1210. * @returns {number} angle between 0 and 360 degrees
  1211. */
  1212. function bearingToAzimuth(bearing) {
  1213. var angle = bearing % 360;
  1214. if (angle < 0) {
  1215. angle += 360;
  1216. }
  1217. return angle;
  1218. }
  1219. exports.bearingToAzimuth = bearingToAzimuth;
  1220. /**
  1221. * Converts an angle in radians to degrees
  1222. *
  1223. * @name radiansToDegrees
  1224. * @param {number} radians angle in radians
  1225. * @returns {number} degrees between 0 and 360 degrees
  1226. */
  1227. function radiansToDegrees(radians) {
  1228. var degrees = radians % (2 * Math.PI);
  1229. return degrees * 180 / Math.PI;
  1230. }
  1231. exports.radiansToDegrees = radiansToDegrees;
  1232. /**
  1233. * Converts an angle in degrees to radians
  1234. *
  1235. * @name degreesToRadians
  1236. * @param {number} degrees angle between 0 and 360 degrees
  1237. * @returns {number} angle in radians
  1238. */
  1239. function degreesToRadians(degrees) {
  1240. var radians = degrees % 360;
  1241. return radians * Math.PI / 180;
  1242. }
  1243. exports.degreesToRadians = degreesToRadians;
  1244. /**
  1245. * Converts a length to the requested unit.
  1246. * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
  1247. *
  1248. * @param {number} length to be converted
  1249. * @param {Units} [originalUnit="kilometers"] of the length
  1250. * @param {Units} [finalUnit="kilometers"] returned unit
  1251. * @returns {number} the converted length
  1252. */
  1253. function convertLength(length, originalUnit, finalUnit) {
  1254. if (originalUnit === void 0) { originalUnit = "kilometers"; }
  1255. if (finalUnit === void 0) { finalUnit = "kilometers"; }
  1256. if (!(length >= 0)) {
  1257. throw new Error("length must be a positive number");
  1258. }
  1259. return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);
  1260. }
  1261. exports.convertLength = convertLength;
  1262. /**
  1263. * Converts a area to the requested unit.
  1264. * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches
  1265. * @param {number} area to be converted
  1266. * @param {Units} [originalUnit="meters"] of the distance
  1267. * @param {Units} [finalUnit="kilometers"] returned unit
  1268. * @returns {number} the converted distance
  1269. */
  1270. function convertArea(area, originalUnit, finalUnit) {
  1271. if (originalUnit === void 0) { originalUnit = "meters"; }
  1272. if (finalUnit === void 0) { finalUnit = "kilometers"; }
  1273. if (!(area >= 0)) {
  1274. throw new Error("area must be a positive number");
  1275. }
  1276. var startFactor = exports.areaFactors[originalUnit];
  1277. if (!startFactor) {
  1278. throw new Error("invalid original units");
  1279. }
  1280. var finalFactor = exports.areaFactors[finalUnit];
  1281. if (!finalFactor) {
  1282. throw new Error("invalid final units");
  1283. }
  1284. return (area / startFactor) * finalFactor;
  1285. }
  1286. exports.convertArea = convertArea;
  1287. /**
  1288. * isNumber
  1289. *
  1290. * @param {*} num Number to validate
  1291. * @returns {boolean} true/false
  1292. * @example
  1293. * turf.isNumber(123)
  1294. * //=true
  1295. * turf.isNumber('foo')
  1296. * //=false
  1297. */
  1298. function isNumber(num) {
  1299. return !isNaN(num) && num !== null && !Array.isArray(num) && !/^\s*$/.test(num);
  1300. }
  1301. exports.isNumber = isNumber;
  1302. /**
  1303. * isObject
  1304. *
  1305. * @param {*} input variable to validate
  1306. * @returns {boolean} true/false
  1307. * @example
  1308. * turf.isObject({elevation: 10})
  1309. * //=true
  1310. * turf.isObject('foo')
  1311. * //=false
  1312. */
  1313. function isObject(input) {
  1314. return (!!input) && (input.constructor === Object);
  1315. }
  1316. exports.isObject = isObject;
  1317. /**
  1318. * Validate BBox
  1319. *
  1320. * @private
  1321. * @param {Array<number>} bbox BBox to validate
  1322. * @returns {void}
  1323. * @throws Error if BBox is not valid
  1324. * @example
  1325. * validateBBox([-180, -40, 110, 50])
  1326. * //=OK
  1327. * validateBBox([-180, -40])
  1328. * //=Error
  1329. * validateBBox('Foo')
  1330. * //=Error
  1331. * validateBBox(5)
  1332. * //=Error
  1333. * validateBBox(null)
  1334. * //=Error
  1335. * validateBBox(undefined)
  1336. * //=Error
  1337. */
  1338. function validateBBox(bbox) {
  1339. if (!bbox) {
  1340. throw new Error("bbox is required");
  1341. }
  1342. if (!Array.isArray(bbox)) {
  1343. throw new Error("bbox must be an Array");
  1344. }
  1345. if (bbox.length !== 4 && bbox.length !== 6) {
  1346. throw new Error("bbox must be an Array of 4 or 6 numbers");
  1347. }
  1348. bbox.forEach(function (num) {
  1349. if (!isNumber(num)) {
  1350. throw new Error("bbox must only contain numbers");
  1351. }
  1352. });
  1353. }
  1354. exports.validateBBox = validateBBox;
  1355. /**
  1356. * Validate Id
  1357. *
  1358. * @private
  1359. * @param {string|number} id Id to validate
  1360. * @returns {void}
  1361. * @throws Error if Id is not valid
  1362. * @example
  1363. * validateId([-180, -40, 110, 50])
  1364. * //=Error
  1365. * validateId([-180, -40])
  1366. * //=Error
  1367. * validateId('Foo')
  1368. * //=OK
  1369. * validateId(5)
  1370. * //=OK
  1371. * validateId(null)
  1372. * //=Error
  1373. * validateId(undefined)
  1374. * //=Error
  1375. */
  1376. function validateId(id) {
  1377. if (!id) {
  1378. throw new Error("id is required");
  1379. }
  1380. if (["string", "number"].indexOf(typeof id) === -1) {
  1381. throw new Error("id must be a number or a string");
  1382. }
  1383. }
  1384. exports.validateId = validateId;
  1385. // Deprecated methods
  1386. function radians2degrees() {
  1387. throw new Error("method has been renamed to `radiansToDegrees`");
  1388. }
  1389. exports.radians2degrees = radians2degrees;
  1390. function degrees2radians() {
  1391. throw new Error("method has been renamed to `degreesToRadians`");
  1392. }
  1393. exports.degrees2radians = degrees2radians;
  1394. function distanceToDegrees() {
  1395. throw new Error("method has been renamed to `lengthToDegrees`");
  1396. }
  1397. exports.distanceToDegrees = distanceToDegrees;
  1398. function distanceToRadians() {
  1399. throw new Error("method has been renamed to `lengthToRadians`");
  1400. }
  1401. exports.distanceToRadians = distanceToRadians;
  1402. function radiansToDistance() {
  1403. throw new Error("method has been renamed to `radiansToLength`");
  1404. }
  1405. exports.radiansToDistance = radiansToDistance;
  1406. function bearingToAngle() {
  1407. throw new Error("method has been renamed to `bearingToAzimuth`");
  1408. }
  1409. exports.bearingToAngle = bearingToAngle;
  1410. function convertDistance() {
  1411. throw new Error("method has been renamed to `convertLength`");
  1412. }
  1413. exports.convertDistance = convertDistance;
  1414. },{}],12:[function(require,module,exports){
  1415. "use strict";
  1416. var __importStar = (this && this.__importStar) || function (mod) {
  1417. if (mod && mod.__esModule) return mod;
  1418. var result = {};
  1419. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  1420. result["default"] = mod;
  1421. return result;
  1422. };
  1423. Object.defineProperty(exports, "__esModule", { value: true });
  1424. var helpers_1 = require("@turf/helpers");
  1425. var invariant_1 = require("@turf/invariant");
  1426. var martinez = __importStar(require("martinez-polygon-clipping"));
  1427. /**
  1428. * Takes two {@link Polygon|polygon} or {@link MultiPolygon|multi-polygon} geometries and
  1429. * finds their polygonal intersection. If they don't intersect, returns null.
  1430. *
  1431. * @name intersect
  1432. * @param {Feature<Polygon | MultiPolygon>} poly1 the first polygon or multipolygon
  1433. * @param {Feature<Polygon | MultiPolygon>} poly2 the second polygon or multipolygon
  1434. * @param {Object} [options={}] Optional Parameters
  1435. * @param {Object} [options.properties={}] Translate GeoJSON Properties to Feature
  1436. * @returns {Feature|null} returns a feature representing the area they share (either a {@link Polygon} or
  1437. * {@link MultiPolygon}). If they do not share any area, returns `null`.
  1438. * @example
  1439. * var poly1 = turf.polygon([[
  1440. * [-122.801742, 45.48565],
  1441. * [-122.801742, 45.60491],
  1442. * [-122.584762, 45.60491],
  1443. * [-122.584762, 45.48565],
  1444. * [-122.801742, 45.48565]
  1445. * ]]);
  1446. *
  1447. * var poly2 = turf.polygon([[
  1448. * [-122.520217, 45.535693],
  1449. * [-122.64038, 45.553967],
  1450. * [-122.720031, 45.526554],
  1451. * [-122.669906, 45.507309],
  1452. * [-122.723464, 45.446643],
  1453. * [-122.532577, 45.408574],
  1454. * [-122.487258, 45.477466],
  1455. * [-122.520217, 45.535693]
  1456. * ]]);
  1457. *
  1458. * var intersection = turf.intersect(poly1, poly2);
  1459. *
  1460. * //addToMap
  1461. * var addToMap = [poly1, poly2, intersection];
  1462. */
  1463. function intersect(poly1, poly2, options) {
  1464. if (options === void 0) { options = {}; }
  1465. var geom1 = invariant_1.getGeom(poly1);
  1466. var geom2 = invariant_1.getGeom(poly2);
  1467. if (geom1.type === "Polygon" && geom2.type === "Polygon") {
  1468. var intersection = martinez.intersection(geom1.coordinates, geom2.coordinates);
  1469. if (intersection === null || intersection.length === 0) {
  1470. return null;
  1471. }
  1472. if (intersection.length === 1) {
  1473. var start = intersection[0][0][0];
  1474. var end = intersection[0][0][intersection[0][0].length - 1];
  1475. if (start[0] === end[0] && start[1] === end[1]) {
  1476. return helpers_1.polygon(intersection[0], options.properties);
  1477. }
  1478. return null;
  1479. }
  1480. return helpers_1.multiPolygon(intersection, options.properties);
  1481. }
  1482. else if (geom1.type === "MultiPolygon") {
  1483. var resultCoords = [];
  1484. // iterate through the polygon and run intersect with each part, adding to the resultCoords.
  1485. for (var _i = 0, _a = geom1.coordinates; _i < _a.length; _i++) {
  1486. var coords = _a[_i];
  1487. var subGeom = invariant_1.getGeom(helpers_1.polygon(coords));
  1488. var subIntersection = intersect(subGeom, geom2);
  1489. if (subIntersection) {
  1490. var subIntGeom = invariant_1.getGeom(subIntersection);
  1491. if (subIntGeom.type === "Polygon") {
  1492. resultCoords.push(subIntGeom.coordinates);
  1493. }
  1494. else if (subIntGeom.type === "MultiPolygon") {
  1495. resultCoords = resultCoords.concat(subIntGeom.coordinates);
  1496. }
  1497. else {
  1498. throw new Error("intersection is invalid");
  1499. }
  1500. }
  1501. }
  1502. // Make a polygon with the result
  1503. if (resultCoords.length === 0) {
  1504. return null;
  1505. }
  1506. if (resultCoords.length === 1) {
  1507. return helpers_1.polygon(resultCoords[0], options.properties);
  1508. }
  1509. else {
  1510. return helpers_1.multiPolygon(resultCoords, options.properties);
  1511. }
  1512. }
  1513. else if (geom2.type === "MultiPolygon") {
  1514. // geom1 is a polygon and geom2 a multiPolygon,
  1515. // put the multiPolygon first and fallback to the previous case.
  1516. return intersect(geom2, geom1);
  1517. }
  1518. else {
  1519. // handle invalid geometry types
  1520. throw new Error("poly1 and poly2 must be either polygons or multiPolygons");
  1521. }
  1522. }
  1523. exports.default = intersect;
  1524. },{"@turf/helpers":11,"@turf/invariant":13,"martinez-polygon-clipping":173}],13:[function(require,module,exports){
  1525. "use strict";
  1526. Object.defineProperty(exports, "__esModule", { value: true });
  1527. var helpers_1 = require("@turf/helpers");
  1528. /**
  1529. * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.
  1530. *
  1531. * @name getCoord
  1532. * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers
  1533. * @returns {Array<number>} coordinates
  1534. * @example
  1535. * var pt = turf.point([10, 10]);
  1536. *
  1537. * var coord = turf.getCoord(pt);
  1538. * //= [10, 10]
  1539. */
  1540. function getCoord(coord) {
  1541. if (!coord) {
  1542. throw new Error("coord is required");
  1543. }
  1544. if (!Array.isArray(coord)) {
  1545. if (coord.type === "Feature" && coord.geometry !== null && coord.geometry.type === "Point") {
  1546. return coord.geometry.coordinates;
  1547. }
  1548. if (coord.type === "Point") {
  1549. return coord.coordinates;
  1550. }
  1551. }
  1552. if (Array.isArray(coord) && coord.length >= 2 && !Array.isArray(coord[0]) && !Array.isArray(coord[1])) {
  1553. return coord;
  1554. }
  1555. throw new Error("coord must be GeoJSON Point or an Array of numbers");
  1556. }
  1557. exports.getCoord = getCoord;
  1558. /**
  1559. * Unwrap coordinates from a Feature, Geometry Object or an Array
  1560. *
  1561. * @name getCoords
  1562. * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array
  1563. * @returns {Array<any>} coordinates
  1564. * @example
  1565. * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);
  1566. *
  1567. * var coords = turf.getCoords(poly);
  1568. * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]
  1569. */
  1570. function getCoords(coords) {
  1571. if (Array.isArray(coords)) {
  1572. return coords;
  1573. }
  1574. // Feature
  1575. if (coords.type === "Feature") {
  1576. if (coords.geometry !== null) {
  1577. return coords.geometry.coordinates;
  1578. }
  1579. }
  1580. else {
  1581. // Geometry
  1582. if (coords.coordinates) {
  1583. return coords.coordinates;
  1584. }
  1585. }
  1586. throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array");
  1587. }
  1588. exports.getCoords = getCoords;
  1589. /**
  1590. * Checks if coordinates contains a number
  1591. *
  1592. * @name containsNumber
  1593. * @param {Array<any>} coordinates GeoJSON Coordinates
  1594. * @returns {boolean} true if Array contains a number
  1595. */
  1596. function containsNumber(coordinates) {
  1597. if (coordinates.length > 1 && helpers_1.isNumber(coordinates[0]) && helpers_1.isNumber(coordinates[1])) {
  1598. return true;
  1599. }
  1600. if (Array.isArray(coordinates[0]) && coordinates[0].length) {
  1601. return containsNumber(coordinates[0]);
  1602. }
  1603. throw new Error("coordinates must only contain numbers");
  1604. }
  1605. exports.containsNumber = containsNumber;
  1606. /**
  1607. * Enforce expectations about types of GeoJSON objects for Turf.
  1608. *
  1609. * @name geojsonType
  1610. * @param {GeoJSON} value any GeoJSON object
  1611. * @param {string} type expected GeoJSON type
  1612. * @param {string} name name of calling function
  1613. * @throws {Error} if value is not the expected type.
  1614. */
  1615. function geojsonType(value, type, name) {
  1616. if (!type || !name) {
  1617. throw new Error("type and name required");
  1618. }
  1619. if (!value || value.type !== type) {
  1620. throw new Error("Invalid input to " + name + ": must be a " + type + ", given " + value.type);
  1621. }
  1622. }
  1623. exports.geojsonType = geojsonType;
  1624. /**
  1625. * Enforce expectations about types of {@link Feature} inputs for Turf.
  1626. * Internally this uses {@link geojsonType} to judge geometry types.
  1627. *
  1628. * @name featureOf
  1629. * @param {Feature} feature a feature with an expected geometry type
  1630. * @param {string} type expected GeoJSON type
  1631. * @param {string} name name of calling function
  1632. * @throws {Error} error if value is not the expected type.
  1633. */
  1634. function featureOf(feature, type, name) {
  1635. if (!feature) {
  1636. throw new Error("No feature passed");
  1637. }
  1638. if (!name) {
  1639. throw new Error(".featureOf() requires a name");
  1640. }
  1641. if (!feature || feature.type !== "Feature" || !feature.geometry) {
  1642. throw new Error("Invalid input to " + name + ", Feature with geometry required");
  1643. }
  1644. if (!feature.geometry || feature.geometry.type !== type) {
  1645. throw new Error("Invalid input to " + name + ": must be a " + type + ", given " + feature.geometry.type);
  1646. }
  1647. }
  1648. exports.featureOf = featureOf;
  1649. /**
  1650. * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.
  1651. * Internally this uses {@link geojsonType} to judge geometry types.
  1652. *
  1653. * @name collectionOf
  1654. * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged
  1655. * @param {string} type expected GeoJSON type
  1656. * @param {string} name name of calling function
  1657. * @throws {Error} if value is not the expected type.
  1658. */
  1659. function collectionOf(featureCollection, type, name) {
  1660. if (!featureCollection) {
  1661. throw new Error("No featureCollection passed");
  1662. }
  1663. if (!name) {
  1664. throw new Error(".collectionOf() requires a name");
  1665. }
  1666. if (!featureCollection || featureCollection.type !== "FeatureCollection") {
  1667. throw new Error("Invalid input to " + name + ", FeatureCollection required");
  1668. }
  1669. for (var _i = 0, _a = featureCollection.features; _i < _a.length; _i++) {
  1670. var feature = _a[_i];
  1671. if (!feature || feature.type !== "Feature" || !feature.geometry) {
  1672. throw new Error("Invalid input to " + name + ", Feature with geometry required");
  1673. }
  1674. if (!feature.geometry || feature.geometry.type !== type) {
  1675. throw new Error("Invalid input to " + name + ": must be a " + type + ", given " + feature.geometry.type);
  1676. }
  1677. }
  1678. }
  1679. exports.collectionOf = collectionOf;
  1680. /**
  1681. * Get Geometry from Feature or Geometry Object
  1682. *
  1683. * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object
  1684. * @returns {Geometry|null} GeoJSON Geometry Object
  1685. * @throws {Error} if geojson is not a Feature or Geometry Object
  1686. * @example
  1687. * var point = {
  1688. * "type": "Feature",
  1689. * "properties": {},
  1690. * "geometry": {
  1691. * "type": "Point",
  1692. * "coordinates": [110, 40]
  1693. * }
  1694. * }
  1695. * var geom = turf.getGeom(point)
  1696. * //={"type": "Point", "coordinates": [110, 40]}
  1697. */
  1698. function getGeom(geojson) {
  1699. if (geojson.type === "Feature") {
  1700. return geojson.geometry;
  1701. }
  1702. return geojson;
  1703. }
  1704. exports.getGeom = getGeom;
  1705. /**
  1706. * Get GeoJSON object's type, Geometry type is prioritize.
  1707. *
  1708. * @param {GeoJSON} geojson GeoJSON object
  1709. * @param {string} [name="geojson"] name of the variable to display in error message
  1710. * @returns {string} GeoJSON type
  1711. * @example
  1712. * var point = {
  1713. * "type": "Feature",
  1714. * "properties": {},
  1715. * "geometry": {
  1716. * "type": "Point",
  1717. * "coordinates": [110, 40]
  1718. * }
  1719. * }
  1720. * var geom = turf.getType(point)
  1721. * //="Point"
  1722. */
  1723. function getType(geojson, name) {
  1724. if (geojson.type === "FeatureCollection") {
  1725. return "FeatureCollection";
  1726. }
  1727. if (geojson.type === "GeometryCollection") {
  1728. return "GeometryCollection";
  1729. }
  1730. if (geojson.type === "Feature" && geojson.geometry !== null) {
  1731. return geojson.geometry.type;
  1732. }
  1733. return geojson.type;
  1734. }
  1735. exports.getType = getType;
  1736. },{"@turf/helpers":11}],14:[function(require,module,exports){
  1737. "use strict";
  1738. var __importDefault = (this && this.__importDefault) || function (mod) {
  1739. return (mod && mod.__esModule) ? mod : { "default": mod };
  1740. }
  1741. Object.defineProperty(exports, "__esModule", { value: true });
  1742. var helpers_1 = require("@turf/helpers");
  1743. var invariant_1 = require("@turf/invariant");
  1744. var line_segment_1 = __importDefault(require("@turf/line-segment"));
  1745. var meta_1 = require("@turf/meta");
  1746. var geojson_rbush_1 = __importDefault(require("geojson-rbush"));
  1747. /**
  1748. * Takes any LineString or Polygon GeoJSON and returns the intersecting point(s).
  1749. *
  1750. * @name lineIntersect
  1751. * @param {GeoJSON} line1 any LineString or Polygon
  1752. * @param {GeoJSON} line2 any LineString or Polygon
  1753. * @returns {FeatureCollection<Point>} point(s) that intersect both
  1754. * @example
  1755. * var line1 = turf.lineString([[126, -11], [129, -21]]);
  1756. * var line2 = turf.lineString([[123, -18], [131, -14]]);
  1757. * var intersects = turf.lineIntersect(line1, line2);
  1758. *
  1759. * //addToMap
  1760. * var addToMap = [line1, line2, intersects]
  1761. */
  1762. function lineIntersect(line1, line2) {
  1763. var unique = {};
  1764. var results = [];
  1765. // First, normalize geometries to features
  1766. // Then, handle simple 2-vertex segments
  1767. if (line1.type === "LineString") {
  1768. line1 = helpers_1.feature(line1);
  1769. }
  1770. if (line2.type === "LineString") {
  1771. line2 = helpers_1.feature(line2);
  1772. }
  1773. if (line1.type === "Feature" &&
  1774. line2.type === "Feature" &&
  1775. line1.geometry !== null &&
  1776. line2.geometry !== null &&
  1777. line1.geometry.type === "LineString" &&
  1778. line2.geometry.type === "LineString" &&
  1779. line1.geometry.coordinates.length === 2 &&
  1780. line2.geometry.coordinates.length === 2) {
  1781. var intersect = intersects(line1, line2);
  1782. if (intersect) {
  1783. results.push(intersect);
  1784. }
  1785. return helpers_1.featureCollection(results);
  1786. }
  1787. // Handles complex GeoJSON Geometries
  1788. var tree = geojson_rbush_1.default();
  1789. tree.load(line_segment_1.default(line2));
  1790. meta_1.featureEach(line_segment_1.default(line1), function (segment) {
  1791. meta_1.featureEach(tree.search(segment), function (match) {
  1792. var intersect = intersects(segment, match);
  1793. if (intersect) {
  1794. // prevent duplicate points https://github.com/Turfjs/turf/issues/688
  1795. var key = invariant_1.getCoords(intersect).join(",");
  1796. if (!unique[key]) {
  1797. unique[key] = true;
  1798. results.push(intersect);
  1799. }
  1800. }
  1801. });
  1802. });
  1803. return helpers_1.featureCollection(results);
  1804. }
  1805. /**
  1806. * Find a point that intersects LineStrings with two coordinates each
  1807. *
  1808. * @private
  1809. * @param {Feature<LineString>} line1 GeoJSON LineString (Must only contain 2 coordinates)
  1810. * @param {Feature<LineString>} line2 GeoJSON LineString (Must only contain 2 coordinates)
  1811. * @returns {Feature<Point>} intersecting GeoJSON Point
  1812. */
  1813. function intersects(line1, line2) {
  1814. var coords1 = invariant_1.getCoords(line1);
  1815. var coords2 = invariant_1.getCoords(line2);
  1816. if (coords1.length !== 2) {
  1817. throw new Error("<intersects> line1 must only contain 2 coordinates");
  1818. }
  1819. if (coords2.length !== 2) {
  1820. throw new Error("<intersects> line2 must only contain 2 coordinates");
  1821. }
  1822. var x1 = coords1[0][0];
  1823. var y1 = coords1[0][1];
  1824. var x2 = coords1[1][0];
  1825. var y2 = coords1[1][1];
  1826. var x3 = coords2[0][0];
  1827. var y3 = coords2[0][1];
  1828. var x4 = coords2[1][0];
  1829. var y4 = coords2[1][1];
  1830. var denom = ((y4 - y3) * (x2 - x1)) - ((x4 - x3) * (y2 - y1));
  1831. var numeA = ((x4 - x3) * (y1 - y3)) - ((y4 - y3) * (x1 - x3));
  1832. var numeB = ((x2 - x1) * (y1 - y3)) - ((y2 - y1) * (x1 - x3));
  1833. if (denom === 0) {
  1834. if (numeA === 0 && numeB === 0) {
  1835. return null;
  1836. }
  1837. return null;
  1838. }
  1839. var uA = numeA / denom;
  1840. var uB = numeB / denom;
  1841. if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {
  1842. var x = x1 + (uA * (x2 - x1));
  1843. var y = y1 + (uA * (y2 - y1));
  1844. return helpers_1.point([x, y]);
  1845. }
  1846. return null;
  1847. }
  1848. exports.default = lineIntersect;
  1849. },{"@turf/helpers":11,"@turf/invariant":13,"@turf/line-segment":15,"@turf/meta":16,"geojson-rbush":44}],15:[function(require,module,exports){
  1850. "use strict";
  1851. Object.defineProperty(exports, "__esModule", { value: true });
  1852. var helpers_1 = require("@turf/helpers");
  1853. var invariant_1 = require("@turf/invariant");
  1854. var meta_1 = require("@turf/meta");
  1855. /**
  1856. * Creates a {@link FeatureCollection} of 2-vertex {@link LineString} segments from a
  1857. * {@link LineString|(Multi)LineString} or {@link Polygon|(Multi)Polygon}.
  1858. *
  1859. * @name lineSegment
  1860. * @param {GeoJSON} geojson GeoJSON Polygon or LineString
  1861. * @returns {FeatureCollection<LineString>} 2-vertex line segments
  1862. * @example
  1863. * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);
  1864. * var segments = turf.lineSegment(polygon);
  1865. *
  1866. * //addToMap
  1867. * var addToMap = [polygon, segments]
  1868. */
  1869. function lineSegment(geojson) {
  1870. if (!geojson) {
  1871. throw new Error("geojson is required");
  1872. }
  1873. var results = [];
  1874. meta_1.flattenEach(geojson, function (feature) {
  1875. lineSegmentFeature(feature, results);
  1876. });
  1877. return helpers_1.featureCollection(results);
  1878. }
  1879. /**
  1880. * Line Segment
  1881. *
  1882. * @private
  1883. * @param {Feature<LineString|Polygon>} geojson Line or polygon feature
  1884. * @param {Array} results push to results
  1885. * @returns {void}
  1886. */
  1887. function lineSegmentFeature(geojson, results) {
  1888. var coords = [];
  1889. var geometry = geojson.geometry;
  1890. if (geometry !== null) {
  1891. switch (geometry.type) {
  1892. case "Polygon":
  1893. coords = invariant_1.getCoords(geometry);
  1894. break;
  1895. case "LineString":
  1896. coords = [invariant_1.getCoords(geometry)];
  1897. }
  1898. coords.forEach(function (coord) {
  1899. var segments = createSegments(coord, geojson.properties);
  1900. segments.forEach(function (segment) {
  1901. segment.id = results.length;
  1902. results.push(segment);
  1903. });
  1904. });
  1905. }
  1906. }
  1907. /**
  1908. * Create Segments from LineString coordinates
  1909. *
  1910. * @private
  1911. * @param {Array<Array<number>>} coords LineString coordinates
  1912. * @param {*} properties GeoJSON properties
  1913. * @returns {Array<Feature<LineString>>} line segments
  1914. */
  1915. function createSegments(coords, properties) {
  1916. var segments = [];
  1917. coords.reduce(function (previousCoords, currentCoords) {
  1918. var segment = helpers_1.lineString([previousCoords, currentCoords], properties);
  1919. segment.bbox = bbox(previousCoords, currentCoords);
  1920. segments.push(segment);
  1921. return currentCoords;
  1922. });
  1923. return segments;
  1924. }
  1925. /**
  1926. * Create BBox between two coordinates (faster than @turf/bbox)
  1927. *
  1928. * @private
  1929. * @param {Array<number>} coords1 Point coordinate
  1930. * @param {Array<number>} coords2 Point coordinate
  1931. * @returns {BBox} [west, south, east, north]
  1932. */
  1933. function bbox(coords1, coords2) {
  1934. var x1 = coords1[0];
  1935. var y1 = coords1[1];
  1936. var x2 = coords2[0];
  1937. var y2 = coords2[1];
  1938. var west = (x1 < x2) ? x1 : x2;
  1939. var south = (y1 < y2) ? y1 : y2;
  1940. var east = (x1 > x2) ? x1 : x2;
  1941. var north = (y1 > y2) ? y1 : y2;
  1942. return [west, south, east, north];
  1943. }
  1944. exports.default = lineSegment;
  1945. },{"@turf/helpers":11,"@turf/invariant":13,"@turf/meta":16}],16:[function(require,module,exports){
  1946. 'use strict';
  1947. Object.defineProperty(exports, '__esModule', { value: true });
  1948. var helpers = require('@turf/helpers');
  1949. /**
  1950. * Callback for coordEach
  1951. *
  1952. * @callback coordEachCallback
  1953. * @param {Array<number>} currentCoord The current coordinate being processed.
  1954. * @param {number} coordIndex The current index of the coordinate being processed.
  1955. * @param {number} featureIndex The current index of the Feature being processed.
  1956. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
  1957. * @param {number} geometryIndex The current index of the Geometry being processed.
  1958. */
  1959. /**
  1960. * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()
  1961. *
  1962. * @name coordEach
  1963. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
  1964. * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex)
  1965. * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.
  1966. * @returns {void}
  1967. * @example
  1968. * var features = turf.featureCollection([
  1969. * turf.point([26, 37], {"foo": "bar"}),
  1970. * turf.point([36, 53], {"hello": "world"})
  1971. * ]);
  1972. *
  1973. * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
  1974. * //=currentCoord
  1975. * //=coordIndex
  1976. * //=featureIndex
  1977. * //=multiFeatureIndex
  1978. * //=geometryIndex
  1979. * });
  1980. */
  1981. function coordEach(geojson, callback, excludeWrapCoord) {
  1982. // Handles null Geometry -- Skips this GeoJSON
  1983. if (geojson === null) return;
  1984. var j, k, l, geometry, stopG, coords,
  1985. geometryMaybeCollection,
  1986. wrapShrink = 0,
  1987. coordIndex = 0,
  1988. isGeometryCollection,
  1989. type = geojson.type,
  1990. isFeatureCollection = type === 'FeatureCollection',
  1991. isFeature = type === 'Feature',
  1992. stop = isFeatureCollection ? geojson.features.length : 1;
  1993. // This logic may look a little weird. The reason why it is that way
  1994. // is because it's trying to be fast. GeoJSON supports multiple kinds
  1995. // of objects at its root: FeatureCollection, Features, Geometries.
  1996. // This function has the responsibility of handling all of them, and that
  1997. // means that some of the `for` loops you see below actually just don't apply
  1998. // to certain inputs. For instance, if you give this just a
  1999. // Point geometry, then both loops are short-circuited and all we do
  2000. // is gradually rename the input until it's called 'geometry'.
  2001. //
  2002. // This also aims to allocate as few resources as possible: just a
  2003. // few numbers and booleans, rather than any temporary arrays as would
  2004. // be required with the normalization approach.
  2005. for (var featureIndex = 0; featureIndex < stop; featureIndex++) {
  2006. geometryMaybeCollection = (isFeatureCollection ? geojson.features[featureIndex].geometry :
  2007. (isFeature ? geojson.geometry : geojson));
  2008. isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;
  2009. stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
  2010. for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {
  2011. var multiFeatureIndex = 0;
  2012. var geometryIndex = 0;
  2013. geometry = isGeometryCollection ?
  2014. geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection;
  2015. // Handles null Geometry -- Skips this geometry
  2016. if (geometry === null) continue;
  2017. coords = geometry.coordinates;
  2018. var geomType = geometry.type;
  2019. wrapShrink = (excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon')) ? 1 : 0;
  2020. switch (geomType) {
  2021. case null:
  2022. break;
  2023. case 'Point':
  2024. if (callback(coords, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
  2025. coordIndex++;
  2026. multiFeatureIndex++;
  2027. break;
  2028. case 'LineString':
  2029. case 'MultiPoint':
  2030. for (j = 0; j < coords.length; j++) {
  2031. if (callback(coords[j], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
  2032. coordIndex++;
  2033. if (geomType === 'MultiPoint') multiFeatureIndex++;
  2034. }
  2035. if (geomType === 'LineString') multiFeatureIndex++;
  2036. break;
  2037. case 'Polygon':
  2038. case 'MultiLineString':
  2039. for (j = 0; j < coords.length; j++) {
  2040. for (k = 0; k < coords[j].length - wrapShrink; k++) {
  2041. if (callback(coords[j][k], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
  2042. coordIndex++;
  2043. }
  2044. if (geomType === 'MultiLineString') multiFeatureIndex++;
  2045. if (geomType === 'Polygon') geometryIndex++;
  2046. }
  2047. if (geomType === 'Polygon') multiFeatureIndex++;
  2048. break;
  2049. case 'MultiPolygon':
  2050. for (j = 0; j < coords.length; j++) {
  2051. geometryIndex = 0;
  2052. for (k = 0; k < coords[j].length; k++) {
  2053. for (l = 0; l < coords[j][k].length - wrapShrink; l++) {
  2054. if (callback(coords[j][k][l], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
  2055. coordIndex++;
  2056. }
  2057. geometryIndex++;
  2058. }
  2059. multiFeatureIndex++;
  2060. }
  2061. break;
  2062. case 'GeometryCollection':
  2063. for (j = 0; j < geometry.geometries.length; j++)
  2064. if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false) return false;
  2065. break;
  2066. default:
  2067. throw new Error('Unknown Geometry Type');
  2068. }
  2069. }
  2070. }
  2071. }
  2072. /**
  2073. * Callback for coordReduce
  2074. *
  2075. * The first time the callback function is called, the values provided as arguments depend
  2076. * on whether the reduce method has an initialValue argument.
  2077. *
  2078. * If an initialValue is provided to the reduce method:
  2079. * - The previousValue argument is initialValue.
  2080. * - The currentValue argument is the value of the first element present in the array.
  2081. *
  2082. * If an initialValue is not provided:
  2083. * - The previousValue argument is the value of the first element present in the array.
  2084. * - The currentValue argument is the value of the second element present in the array.
  2085. *
  2086. * @callback coordReduceCallback
  2087. * @param {*} previousValue The accumulated value previously returned in the last invocation
  2088. * of the callback, or initialValue, if supplied.
  2089. * @param {Array<number>} currentCoord The current coordinate being processed.
  2090. * @param {number} coordIndex The current index of the coordinate being processed.
  2091. * Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
  2092. * @param {number} featureIndex The current index of the Feature being processed.
  2093. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
  2094. * @param {number} geometryIndex The current index of the Geometry being processed.
  2095. */
  2096. /**
  2097. * Reduce coordinates in any GeoJSON object, similar to Array.reduce()
  2098. *
  2099. * @name coordReduce
  2100. * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object
  2101. * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)
  2102. * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
  2103. * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.
  2104. * @returns {*} The value that results from the reduction.
  2105. * @example
  2106. * var features = turf.featureCollection([
  2107. * turf.point([26, 37], {"foo": "bar"}),
  2108. * turf.point([36, 53], {"hello": "world"})
  2109. * ]);
  2110. *
  2111. * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
  2112. * //=previousValue
  2113. * //=currentCoord
  2114. * //=coordIndex
  2115. * //=featureIndex
  2116. * //=multiFeatureIndex
  2117. * //=geometryIndex
  2118. * return currentCoord;
  2119. * });
  2120. */
  2121. function coordReduce(geojson, callback, initialValue, excludeWrapCoord) {
  2122. var previousValue = initialValue;
  2123. coordEach(geojson, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
  2124. if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;
  2125. else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex);
  2126. }, excludeWrapCoord);
  2127. return previousValue;
  2128. }
  2129. /**
  2130. * Callback for propEach
  2131. *
  2132. * @callback propEachCallback
  2133. * @param {Object} currentProperties The current Properties being processed.
  2134. * @param {number} featureIndex The current index of the Feature being processed.
  2135. */
  2136. /**
  2137. * Iterate over properties in any GeoJSON object, similar to Array.forEach()
  2138. *
  2139. * @name propEach
  2140. * @param {FeatureCollection|Feature} geojson any GeoJSON object
  2141. * @param {Function} callback a method that takes (currentProperties, featureIndex)
  2142. * @returns {void}
  2143. * @example
  2144. * var features = turf.featureCollection([
  2145. * turf.point([26, 37], {foo: 'bar'}),
  2146. * turf.point([36, 53], {hello: 'world'})
  2147. * ]);
  2148. *
  2149. * turf.propEach(features, function (currentProperties, featureIndex) {
  2150. * //=currentProperties
  2151. * //=featureIndex
  2152. * });
  2153. */
  2154. function propEach(geojson, callback) {
  2155. var i;
  2156. switch (geojson.type) {
  2157. case 'FeatureCollection':
  2158. for (i = 0; i < geojson.features.length; i++) {
  2159. if (callback(geojson.features[i].properties, i) === false) break;
  2160. }
  2161. break;
  2162. case 'Feature':
  2163. callback(geojson.properties, 0);
  2164. break;
  2165. }
  2166. }
  2167. /**
  2168. * Callback for propReduce
  2169. *
  2170. * The first time the callback function is called, the values provided as arguments depend
  2171. * on whether the reduce method has an initialValue argument.
  2172. *
  2173. * If an initialValue is provided to the reduce method:
  2174. * - The previousValue argument is initialValue.
  2175. * - The currentValue argument is the value of the first element present in the array.
  2176. *
  2177. * If an initialValue is not provided:
  2178. * - The previousValue argument is the value of the first element present in the array.
  2179. * - The currentValue argument is the value of the second element present in the array.
  2180. *
  2181. * @callback propReduceCallback
  2182. * @param {*} previousValue The accumulated value previously returned in the last invocation
  2183. * of the callback, or initialValue, if supplied.
  2184. * @param {*} currentProperties The current Properties being processed.
  2185. * @param {number} featureIndex The current index of the Feature being processed.
  2186. */
  2187. /**
  2188. * Reduce properties in any GeoJSON object into a single value,
  2189. * similar to how Array.reduce works. However, in this case we lazily run
  2190. * the reduction, so an array of all properties is unnecessary.
  2191. *
  2192. * @name propReduce
  2193. * @param {FeatureCollection|Feature} geojson any GeoJSON object
  2194. * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex)
  2195. * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
  2196. * @returns {*} The value that results from the reduction.
  2197. * @example
  2198. * var features = turf.featureCollection([
  2199. * turf.point([26, 37], {foo: 'bar'}),
  2200. * turf.point([36, 53], {hello: 'world'})
  2201. * ]);
  2202. *
  2203. * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) {
  2204. * //=previousValue
  2205. * //=currentProperties
  2206. * //=featureIndex
  2207. * return currentProperties
  2208. * });
  2209. */
  2210. function propReduce(geojson, callback, initialValue) {
  2211. var previousValue = initialValue;
  2212. propEach(geojson, function (currentProperties, featureIndex) {
  2213. if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;
  2214. else previousValue = callback(previousValue, currentProperties, featureIndex);
  2215. });
  2216. return previousValue;
  2217. }
  2218. /**
  2219. * Callback for featureEach
  2220. *
  2221. * @callback featureEachCallback
  2222. * @param {Feature<any>} currentFeature The current Feature being processed.
  2223. * @param {number} featureIndex The current index of the Feature being processed.
  2224. */
  2225. /**
  2226. * Iterate over features in any GeoJSON object, similar to
  2227. * Array.forEach.
  2228. *
  2229. * @name featureEach
  2230. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
  2231. * @param {Function} callback a method that takes (currentFeature, featureIndex)
  2232. * @returns {void}
  2233. * @example
  2234. * var features = turf.featureCollection([
  2235. * turf.point([26, 37], {foo: 'bar'}),
  2236. * turf.point([36, 53], {hello: 'world'})
  2237. * ]);
  2238. *
  2239. * turf.featureEach(features, function (currentFeature, featureIndex) {
  2240. * //=currentFeature
  2241. * //=featureIndex
  2242. * });
  2243. */
  2244. function featureEach(geojson, callback) {
  2245. if (geojson.type === 'Feature') {
  2246. callback(geojson, 0);
  2247. } else if (geojson.type === 'FeatureCollection') {
  2248. for (var i = 0; i < geojson.features.length; i++) {
  2249. if (callback(geojson.features[i], i) === false) break;
  2250. }
  2251. }
  2252. }
  2253. /**
  2254. * Callback for featureReduce
  2255. *
  2256. * The first time the callback function is called, the values provided as arguments depend
  2257. * on whether the reduce method has an initialValue argument.
  2258. *
  2259. * If an initialValue is provided to the reduce method:
  2260. * - The previousValue argument is initialValue.
  2261. * - The currentValue argument is the value of the first element present in the array.
  2262. *
  2263. * If an initialValue is not provided:
  2264. * - The previousValue argument is the value of the first element present in the array.
  2265. * - The currentValue argument is the value of the second element present in the array.
  2266. *
  2267. * @callback featureReduceCallback
  2268. * @param {*} previousValue The accumulated value previously returned in the last invocation
  2269. * of the callback, or initialValue, if supplied.
  2270. * @param {Feature} currentFeature The current Feature being processed.
  2271. * @param {number} featureIndex The current index of the Feature being processed.
  2272. */
  2273. /**
  2274. * Reduce features in any GeoJSON object, similar to Array.reduce().
  2275. *
  2276. * @name featureReduce
  2277. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
  2278. * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)
  2279. * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
  2280. * @returns {*} The value that results from the reduction.
  2281. * @example
  2282. * var features = turf.featureCollection([
  2283. * turf.point([26, 37], {"foo": "bar"}),
  2284. * turf.point([36, 53], {"hello": "world"})
  2285. * ]);
  2286. *
  2287. * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) {
  2288. * //=previousValue
  2289. * //=currentFeature
  2290. * //=featureIndex
  2291. * return currentFeature
  2292. * });
  2293. */
  2294. function featureReduce(geojson, callback, initialValue) {
  2295. var previousValue = initialValue;
  2296. featureEach(geojson, function (currentFeature, featureIndex) {
  2297. if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;
  2298. else previousValue = callback(previousValue, currentFeature, featureIndex);
  2299. });
  2300. return previousValue;
  2301. }
  2302. /**
  2303. * Get all coordinates from any GeoJSON object.
  2304. *
  2305. * @name coordAll
  2306. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
  2307. * @returns {Array<Array<number>>} coordinate position array
  2308. * @example
  2309. * var features = turf.featureCollection([
  2310. * turf.point([26, 37], {foo: 'bar'}),
  2311. * turf.point([36, 53], {hello: 'world'})
  2312. * ]);
  2313. *
  2314. * var coords = turf.coordAll(features);
  2315. * //= [[26, 37], [36, 53]]
  2316. */
  2317. function coordAll(geojson) {
  2318. var coords = [];
  2319. coordEach(geojson, function (coord) {
  2320. coords.push(coord);
  2321. });
  2322. return coords;
  2323. }
  2324. /**
  2325. * Callback for geomEach
  2326. *
  2327. * @callback geomEachCallback
  2328. * @param {Geometry} currentGeometry The current Geometry being processed.
  2329. * @param {number} featureIndex The current index of the Feature being processed.
  2330. * @param {Object} featureProperties The current Feature Properties being processed.
  2331. * @param {Array<number>} featureBBox The current Feature BBox being processed.
  2332. * @param {number|string} featureId The current Feature Id being processed.
  2333. */
  2334. /**
  2335. * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()
  2336. *
  2337. * @name geomEach
  2338. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
  2339. * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId)
  2340. * @returns {void}
  2341. * @example
  2342. * var features = turf.featureCollection([
  2343. * turf.point([26, 37], {foo: 'bar'}),
  2344. * turf.point([36, 53], {hello: 'world'})
  2345. * ]);
  2346. *
  2347. * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {
  2348. * //=currentGeometry
  2349. * //=featureIndex
  2350. * //=featureProperties
  2351. * //=featureBBox
  2352. * //=featureId
  2353. * });
  2354. */
  2355. function geomEach(geojson, callback) {
  2356. var i, j, g, geometry, stopG,
  2357. geometryMaybeCollection,
  2358. isGeometryCollection,
  2359. featureProperties,
  2360. featureBBox,
  2361. featureId,
  2362. featureIndex = 0,
  2363. isFeatureCollection = geojson.type === 'FeatureCollection',
  2364. isFeature = geojson.type === 'Feature',
  2365. stop = isFeatureCollection ? geojson.features.length : 1;
  2366. // This logic may look a little weird. The reason why it is that way
  2367. // is because it's trying to be fast. GeoJSON supports multiple kinds
  2368. // of objects at its root: FeatureCollection, Features, Geometries.
  2369. // This function has the responsibility of handling all of them, and that
  2370. // means that some of the `for` loops you see below actually just don't apply
  2371. // to certain inputs. For instance, if you give this just a
  2372. // Point geometry, then both loops are short-circuited and all we do
  2373. // is gradually rename the input until it's called 'geometry'.
  2374. //
  2375. // This also aims to allocate as few resources as possible: just a
  2376. // few numbers and booleans, rather than any temporary arrays as would
  2377. // be required with the normalization approach.
  2378. for (i = 0; i < stop; i++) {
  2379. geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry :
  2380. (isFeature ? geojson.geometry : geojson));
  2381. featureProperties = (isFeatureCollection ? geojson.features[i].properties :
  2382. (isFeature ? geojson.properties : {}));
  2383. featureBBox = (isFeatureCollection ? geojson.features[i].bbox :
  2384. (isFeature ? geojson.bbox : undefined));
  2385. featureId = (isFeatureCollection ? geojson.features[i].id :
  2386. (isFeature ? geojson.id : undefined));
  2387. isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;
  2388. stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
  2389. for (g = 0; g < stopG; g++) {
  2390. geometry = isGeometryCollection ?
  2391. geometryMaybeCollection.geometries[g] : geometryMaybeCollection;
  2392. // Handle null Geometry
  2393. if (geometry === null) {
  2394. if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false;
  2395. continue;
  2396. }
  2397. switch (geometry.type) {
  2398. case 'Point':
  2399. case 'LineString':
  2400. case 'MultiPoint':
  2401. case 'Polygon':
  2402. case 'MultiLineString':
  2403. case 'MultiPolygon': {
  2404. if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false;
  2405. break;
  2406. }
  2407. case 'GeometryCollection': {
  2408. for (j = 0; j < geometry.geometries.length; j++) {
  2409. if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false;
  2410. }
  2411. break;
  2412. }
  2413. default:
  2414. throw new Error('Unknown Geometry Type');
  2415. }
  2416. }
  2417. // Only increase `featureIndex` per each feature
  2418. featureIndex++;
  2419. }
  2420. }
  2421. /**
  2422. * Callback for geomReduce
  2423. *
  2424. * The first time the callback function is called, the values provided as arguments depend
  2425. * on whether the reduce method has an initialValue argument.
  2426. *
  2427. * If an initialValue is provided to the reduce method:
  2428. * - The previousValue argument is initialValue.
  2429. * - The currentValue argument is the value of the first element present in the array.
  2430. *
  2431. * If an initialValue is not provided:
  2432. * - The previousValue argument is the value of the first element present in the array.
  2433. * - The currentValue argument is the value of the second element present in the array.
  2434. *
  2435. * @callback geomReduceCallback
  2436. * @param {*} previousValue The accumulated value previously returned in the last invocation
  2437. * of the callback, or initialValue, if supplied.
  2438. * @param {Geometry} currentGeometry The current Geometry being processed.
  2439. * @param {number} featureIndex The current index of the Feature being processed.
  2440. * @param {Object} featureProperties The current Feature Properties being processed.
  2441. * @param {Array<number>} featureBBox The current Feature BBox being processed.
  2442. * @param {number|string} featureId The current Feature Id being processed.
  2443. */
  2444. /**
  2445. * Reduce geometry in any GeoJSON object, similar to Array.reduce().
  2446. *
  2447. * @name geomReduce
  2448. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
  2449. * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)
  2450. * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
  2451. * @returns {*} The value that results from the reduction.
  2452. * @example
  2453. * var features = turf.featureCollection([
  2454. * turf.point([26, 37], {foo: 'bar'}),
  2455. * turf.point([36, 53], {hello: 'world'})
  2456. * ]);
  2457. *
  2458. * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {
  2459. * //=previousValue
  2460. * //=currentGeometry
  2461. * //=featureIndex
  2462. * //=featureProperties
  2463. * //=featureBBox
  2464. * //=featureId
  2465. * return currentGeometry
  2466. * });
  2467. */
  2468. function geomReduce(geojson, callback, initialValue) {
  2469. var previousValue = initialValue;
  2470. geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {
  2471. if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry;
  2472. else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId);
  2473. });
  2474. return previousValue;
  2475. }
  2476. /**
  2477. * Callback for flattenEach
  2478. *
  2479. * @callback flattenEachCallback
  2480. * @param {Feature} currentFeature The current flattened feature being processed.
  2481. * @param {number} featureIndex The current index of the Feature being processed.
  2482. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
  2483. */
  2484. /**
  2485. * Iterate over flattened features in any GeoJSON object, similar to
  2486. * Array.forEach.
  2487. *
  2488. * @name flattenEach
  2489. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
  2490. * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)
  2491. * @example
  2492. * var features = turf.featureCollection([
  2493. * turf.point([26, 37], {foo: 'bar'}),
  2494. * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})
  2495. * ]);
  2496. *
  2497. * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) {
  2498. * //=currentFeature
  2499. * //=featureIndex
  2500. * //=multiFeatureIndex
  2501. * });
  2502. */
  2503. function flattenEach(geojson, callback) {
  2504. geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) {
  2505. // Callback for single geometry
  2506. var type = (geometry === null) ? null : geometry.type;
  2507. switch (type) {
  2508. case null:
  2509. case 'Point':
  2510. case 'LineString':
  2511. case 'Polygon':
  2512. if (callback(helpers.feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false;
  2513. return;
  2514. }
  2515. var geomType;
  2516. // Callback for multi-geometry
  2517. switch (type) {
  2518. case 'MultiPoint':
  2519. geomType = 'Point';
  2520. break;
  2521. case 'MultiLineString':
  2522. geomType = 'LineString';
  2523. break;
  2524. case 'MultiPolygon':
  2525. geomType = 'Polygon';
  2526. break;
  2527. }
  2528. for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) {
  2529. var coordinate = geometry.coordinates[multiFeatureIndex];
  2530. var geom = {
  2531. type: geomType,
  2532. coordinates: coordinate
  2533. };
  2534. if (callback(helpers.feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false;
  2535. }
  2536. });
  2537. }
  2538. /**
  2539. * Callback for flattenReduce
  2540. *
  2541. * The first time the callback function is called, the values provided as arguments depend
  2542. * on whether the reduce method has an initialValue argument.
  2543. *
  2544. * If an initialValue is provided to the reduce method:
  2545. * - The previousValue argument is initialValue.
  2546. * - The currentValue argument is the value of the first element present in the array.
  2547. *
  2548. * If an initialValue is not provided:
  2549. * - The previousValue argument is the value of the first element present in the array.
  2550. * - The currentValue argument is the value of the second element present in the array.
  2551. *
  2552. * @callback flattenReduceCallback
  2553. * @param {*} previousValue The accumulated value previously returned in the last invocation
  2554. * of the callback, or initialValue, if supplied.
  2555. * @param {Feature} currentFeature The current Feature being processed.
  2556. * @param {number} featureIndex The current index of the Feature being processed.
  2557. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
  2558. */
  2559. /**
  2560. * Reduce flattened features in any GeoJSON object, similar to Array.reduce().
  2561. *
  2562. * @name flattenReduce
  2563. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
  2564. * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)
  2565. * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
  2566. * @returns {*} The value that results from the reduction.
  2567. * @example
  2568. * var features = turf.featureCollection([
  2569. * turf.point([26, 37], {foo: 'bar'}),
  2570. * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})
  2571. * ]);
  2572. *
  2573. * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) {
  2574. * //=previousValue
  2575. * //=currentFeature
  2576. * //=featureIndex
  2577. * //=multiFeatureIndex
  2578. * return currentFeature
  2579. * });
  2580. */
  2581. function flattenReduce(geojson, callback, initialValue) {
  2582. var previousValue = initialValue;
  2583. flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) {
  2584. if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature;
  2585. else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex);
  2586. });
  2587. return previousValue;
  2588. }
  2589. /**
  2590. * Callback for segmentEach
  2591. *
  2592. * @callback segmentEachCallback
  2593. * @param {Feature<LineString>} currentSegment The current Segment being processed.
  2594. * @param {number} featureIndex The current index of the Feature being processed.
  2595. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
  2596. * @param {number} geometryIndex The current index of the Geometry being processed.
  2597. * @param {number} segmentIndex The current index of the Segment being processed.
  2598. * @returns {void}
  2599. */
  2600. /**
  2601. * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach()
  2602. * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
  2603. *
  2604. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON
  2605. * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex)
  2606. * @returns {void}
  2607. * @example
  2608. * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);
  2609. *
  2610. * // Iterate over GeoJSON by 2-vertex segments
  2611. * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {
  2612. * //=currentSegment
  2613. * //=featureIndex
  2614. * //=multiFeatureIndex
  2615. * //=geometryIndex
  2616. * //=segmentIndex
  2617. * });
  2618. *
  2619. * // Calculate the total number of segments
  2620. * var total = 0;
  2621. * turf.segmentEach(polygon, function () {
  2622. * total++;
  2623. * });
  2624. */
  2625. function segmentEach(geojson, callback) {
  2626. flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) {
  2627. var segmentIndex = 0;
  2628. // Exclude null Geometries
  2629. if (!feature.geometry) return;
  2630. // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
  2631. var type = feature.geometry.type;
  2632. if (type === 'Point' || type === 'MultiPoint') return;
  2633. // Generate 2-vertex line segments
  2634. var previousCoords;
  2635. var previousFeatureIndex = 0;
  2636. var previousMultiIndex = 0;
  2637. var prevGeomIndex = 0;
  2638. if (coordEach(feature, function (currentCoord, coordIndex, featureIndexCoord, multiPartIndexCoord, geometryIndex) {
  2639. // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`
  2640. if (previousCoords === undefined || featureIndex > previousFeatureIndex || multiPartIndexCoord > previousMultiIndex || geometryIndex > prevGeomIndex) {
  2641. previousCoords = currentCoord;
  2642. previousFeatureIndex = featureIndex;
  2643. previousMultiIndex = multiPartIndexCoord;
  2644. prevGeomIndex = geometryIndex;
  2645. segmentIndex = 0;
  2646. return;
  2647. }
  2648. var currentSegment = helpers.lineString([previousCoords, currentCoord], feature.properties);
  2649. if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false;
  2650. segmentIndex++;
  2651. previousCoords = currentCoord;
  2652. }) === false) return false;
  2653. });
  2654. }
  2655. /**
  2656. * Callback for segmentReduce
  2657. *
  2658. * The first time the callback function is called, the values provided as arguments depend
  2659. * on whether the reduce method has an initialValue argument.
  2660. *
  2661. * If an initialValue is provided to the reduce method:
  2662. * - The previousValue argument is initialValue.
  2663. * - The currentValue argument is the value of the first element present in the array.
  2664. *
  2665. * If an initialValue is not provided:
  2666. * - The previousValue argument is the value of the first element present in the array.
  2667. * - The currentValue argument is the value of the second element present in the array.
  2668. *
  2669. * @callback segmentReduceCallback
  2670. * @param {*} previousValue The accumulated value previously returned in the last invocation
  2671. * of the callback, or initialValue, if supplied.
  2672. * @param {Feature<LineString>} currentSegment The current Segment being processed.
  2673. * @param {number} featureIndex The current index of the Feature being processed.
  2674. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
  2675. * @param {number} geometryIndex The current index of the Geometry being processed.
  2676. * @param {number} segmentIndex The current index of the Segment being processed.
  2677. */
  2678. /**
  2679. * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce()
  2680. * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
  2681. *
  2682. * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON
  2683. * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex)
  2684. * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
  2685. * @returns {void}
  2686. * @example
  2687. * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);
  2688. *
  2689. * // Iterate over GeoJSON by 2-vertex segments
  2690. * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {
  2691. * //= previousSegment
  2692. * //= currentSegment
  2693. * //= featureIndex
  2694. * //= multiFeatureIndex
  2695. * //= geometryIndex
  2696. * //= segmentInex
  2697. * return currentSegment
  2698. * });
  2699. *
  2700. * // Calculate the total number of segments
  2701. * var initialValue = 0
  2702. * var total = turf.segmentReduce(polygon, function (previousValue) {
  2703. * previousValue++;
  2704. * return previousValue;
  2705. * }, initialValue);
  2706. */
  2707. function segmentReduce(geojson, callback, initialValue) {
  2708. var previousValue = initialValue;
  2709. var started = false;
  2710. segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {
  2711. if (started === false && initialValue === undefined) previousValue = currentSegment;
  2712. else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex);
  2713. started = true;
  2714. });
  2715. return previousValue;
  2716. }
  2717. /**
  2718. * Callback for lineEach
  2719. *
  2720. * @callback lineEachCallback
  2721. * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed
  2722. * @param {number} featureIndex The current index of the Feature being processed
  2723. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed
  2724. * @param {number} geometryIndex The current index of the Geometry being processed
  2725. */
  2726. /**
  2727. * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries,
  2728. * similar to Array.forEach.
  2729. *
  2730. * @name lineEach
  2731. * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object
  2732. * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)
  2733. * @example
  2734. * var multiLine = turf.multiLineString([
  2735. * [[26, 37], [35, 45]],
  2736. * [[36, 53], [38, 50], [41, 55]]
  2737. * ]);
  2738. *
  2739. * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {
  2740. * //=currentLine
  2741. * //=featureIndex
  2742. * //=multiFeatureIndex
  2743. * //=geometryIndex
  2744. * });
  2745. */
  2746. function lineEach(geojson, callback) {
  2747. // validation
  2748. if (!geojson) throw new Error('geojson is required');
  2749. flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) {
  2750. if (feature.geometry === null) return;
  2751. var type = feature.geometry.type;
  2752. var coords = feature.geometry.coordinates;
  2753. switch (type) {
  2754. case 'LineString':
  2755. if (callback(feature, featureIndex, multiFeatureIndex, 0, 0) === false) return false;
  2756. break;
  2757. case 'Polygon':
  2758. for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) {
  2759. if (callback(helpers.lineString(coords[geometryIndex], feature.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
  2760. }
  2761. break;
  2762. }
  2763. });
  2764. }
  2765. /**
  2766. * Callback for lineReduce
  2767. *
  2768. * The first time the callback function is called, the values provided as arguments depend
  2769. * on whether the reduce method has an initialValue argument.
  2770. *
  2771. * If an initialValue is provided to the reduce method:
  2772. * - The previousValue argument is initialValue.
  2773. * - The currentValue argument is the value of the first element present in the array.
  2774. *
  2775. * If an initialValue is not provided:
  2776. * - The previousValue argument is the value of the first element present in the array.
  2777. * - The currentValue argument is the value of the second element present in the array.
  2778. *
  2779. * @callback lineReduceCallback
  2780. * @param {*} previousValue The accumulated value previously returned in the last invocation
  2781. * of the callback, or initialValue, if supplied.
  2782. * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed.
  2783. * @param {number} featureIndex The current index of the Feature being processed
  2784. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed
  2785. * @param {number} geometryIndex The current index of the Geometry being processed
  2786. */
  2787. /**
  2788. * Reduce features in any GeoJSON object, similar to Array.reduce().
  2789. *
  2790. * @name lineReduce
  2791. * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object
  2792. * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)
  2793. * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
  2794. * @returns {*} The value that results from the reduction.
  2795. * @example
  2796. * var multiPoly = turf.multiPolygon([
  2797. * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]),
  2798. * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]])
  2799. * ]);
  2800. *
  2801. * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) {
  2802. * //=previousValue
  2803. * //=currentLine
  2804. * //=featureIndex
  2805. * //=multiFeatureIndex
  2806. * //=geometryIndex
  2807. * return currentLine
  2808. * });
  2809. */
  2810. function lineReduce(geojson, callback, initialValue) {
  2811. var previousValue = initialValue;
  2812. lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {
  2813. if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine;
  2814. else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex);
  2815. });
  2816. return previousValue;
  2817. }
  2818. /**
  2819. * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes.
  2820. *
  2821. * Negative indexes are permitted.
  2822. * Point & MultiPoint will always return null.
  2823. *
  2824. * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry
  2825. * @param {Object} [options={}] Optional parameters
  2826. * @param {number} [options.featureIndex=0] Feature Index
  2827. * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index
  2828. * @param {number} [options.geometryIndex=0] Geometry Index
  2829. * @param {number} [options.segmentIndex=0] Segment Index
  2830. * @param {Object} [options.properties={}] Translate Properties to output LineString
  2831. * @param {BBox} [options.bbox={}] Translate BBox to output LineString
  2832. * @param {number|string} [options.id={}] Translate Id to output LineString
  2833. * @returns {Feature<LineString>} 2-vertex GeoJSON Feature LineString
  2834. * @example
  2835. * var multiLine = turf.multiLineString([
  2836. * [[10, 10], [50, 30], [30, 40]],
  2837. * [[-10, -10], [-50, -30], [-30, -40]]
  2838. * ]);
  2839. *
  2840. * // First Segment (defaults are 0)
  2841. * turf.findSegment(multiLine);
  2842. * // => Feature<LineString<[[10, 10], [50, 30]]>>
  2843. *
  2844. * // First Segment of 2nd Multi Feature
  2845. * turf.findSegment(multiLine, {multiFeatureIndex: 1});
  2846. * // => Feature<LineString<[[-10, -10], [-50, -30]]>>
  2847. *
  2848. * // Last Segment of Last Multi Feature
  2849. * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1});
  2850. * // => Feature<LineString<[[-50, -30], [-30, -40]]>>
  2851. */
  2852. function findSegment(geojson, options) {
  2853. // Optional Parameters
  2854. options = options || {};
  2855. if (!helpers.isObject(options)) throw new Error('options is invalid');
  2856. var featureIndex = options.featureIndex || 0;
  2857. var multiFeatureIndex = options.multiFeatureIndex || 0;
  2858. var geometryIndex = options.geometryIndex || 0;
  2859. var segmentIndex = options.segmentIndex || 0;
  2860. // Find FeatureIndex
  2861. var properties = options.properties;
  2862. var geometry;
  2863. switch (geojson.type) {
  2864. case 'FeatureCollection':
  2865. if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;
  2866. properties = properties || geojson.features[featureIndex].properties;
  2867. geometry = geojson.features[featureIndex].geometry;
  2868. break;
  2869. case 'Feature':
  2870. properties = properties || geojson.properties;
  2871. geometry = geojson.geometry;
  2872. break;
  2873. case 'Point':
  2874. case 'MultiPoint':
  2875. return null;
  2876. case 'LineString':
  2877. case 'Polygon':
  2878. case 'MultiLineString':
  2879. case 'MultiPolygon':
  2880. geometry = geojson;
  2881. break;
  2882. default:
  2883. throw new Error('geojson is invalid');
  2884. }
  2885. // Find SegmentIndex
  2886. if (geometry === null) return null;
  2887. var coords = geometry.coordinates;
  2888. switch (geometry.type) {
  2889. case 'Point':
  2890. case 'MultiPoint':
  2891. return null;
  2892. case 'LineString':
  2893. if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1;
  2894. return helpers.lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options);
  2895. case 'Polygon':
  2896. if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;
  2897. if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1;
  2898. return helpers.lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options);
  2899. case 'MultiLineString':
  2900. if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
  2901. if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;
  2902. return helpers.lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options);
  2903. case 'MultiPolygon':
  2904. if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
  2905. if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;
  2906. if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;
  2907. return helpers.lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options);
  2908. }
  2909. throw new Error('geojson is invalid');
  2910. }
  2911. /**
  2912. * Finds a particular Point from a GeoJSON using `@turf/meta` indexes.
  2913. *
  2914. * Negative indexes are permitted.
  2915. *
  2916. * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry
  2917. * @param {Object} [options={}] Optional parameters
  2918. * @param {number} [options.featureIndex=0] Feature Index
  2919. * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index
  2920. * @param {number} [options.geometryIndex=0] Geometry Index
  2921. * @param {number} [options.coordIndex=0] Coord Index
  2922. * @param {Object} [options.properties={}] Translate Properties to output Point
  2923. * @param {BBox} [options.bbox={}] Translate BBox to output Point
  2924. * @param {number|string} [options.id={}] Translate Id to output Point
  2925. * @returns {Feature<Point>} 2-vertex GeoJSON Feature Point
  2926. * @example
  2927. * var multiLine = turf.multiLineString([
  2928. * [[10, 10], [50, 30], [30, 40]],
  2929. * [[-10, -10], [-50, -30], [-30, -40]]
  2930. * ]);
  2931. *
  2932. * // First Segment (defaults are 0)
  2933. * turf.findPoint(multiLine);
  2934. * // => Feature<Point<[10, 10]>>
  2935. *
  2936. * // First Segment of the 2nd Multi-Feature
  2937. * turf.findPoint(multiLine, {multiFeatureIndex: 1});
  2938. * // => Feature<Point<[-10, -10]>>
  2939. *
  2940. * // Last Segment of last Multi-Feature
  2941. * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1});
  2942. * // => Feature<Point<[-30, -40]>>
  2943. */
  2944. function findPoint(geojson, options) {
  2945. // Optional Parameters
  2946. options = options || {};
  2947. if (!helpers.isObject(options)) throw new Error('options is invalid');
  2948. var featureIndex = options.featureIndex || 0;
  2949. var multiFeatureIndex = options.multiFeatureIndex || 0;
  2950. var geometryIndex = options.geometryIndex || 0;
  2951. var coordIndex = options.coordIndex || 0;
  2952. // Find FeatureIndex
  2953. var properties = options.properties;
  2954. var geometry;
  2955. switch (geojson.type) {
  2956. case 'FeatureCollection':
  2957. if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;
  2958. properties = properties || geojson.features[featureIndex].properties;
  2959. geometry = geojson.features[featureIndex].geometry;
  2960. break;
  2961. case 'Feature':
  2962. properties = properties || geojson.properties;
  2963. geometry = geojson.geometry;
  2964. break;
  2965. case 'Point':
  2966. case 'MultiPoint':
  2967. return null;
  2968. case 'LineString':
  2969. case 'Polygon':
  2970. case 'MultiLineString':
  2971. case 'MultiPolygon':
  2972. geometry = geojson;
  2973. break;
  2974. default:
  2975. throw new Error('geojson is invalid');
  2976. }
  2977. // Find Coord Index
  2978. if (geometry === null) return null;
  2979. var coords = geometry.coordinates;
  2980. switch (geometry.type) {
  2981. case 'Point':
  2982. return helpers.point(coords, properties, options);
  2983. case 'MultiPoint':
  2984. if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
  2985. return helpers.point(coords[multiFeatureIndex], properties, options);
  2986. case 'LineString':
  2987. if (coordIndex < 0) coordIndex = coords.length + coordIndex;
  2988. return helpers.point(coords[coordIndex], properties, options);
  2989. case 'Polygon':
  2990. if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;
  2991. if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex;
  2992. return helpers.point(coords[geometryIndex][coordIndex], properties, options);
  2993. case 'MultiLineString':
  2994. if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
  2995. if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex;
  2996. return helpers.point(coords[multiFeatureIndex][coordIndex], properties, options);
  2997. case 'MultiPolygon':
  2998. if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
  2999. if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;
  3000. if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex;
  3001. return helpers.point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options);
  3002. }
  3003. throw new Error('geojson is invalid');
  3004. }
  3005. exports.coordEach = coordEach;
  3006. exports.coordReduce = coordReduce;
  3007. exports.propEach = propEach;
  3008. exports.propReduce = propReduce;
  3009. exports.featureEach = featureEach;
  3010. exports.featureReduce = featureReduce;
  3011. exports.coordAll = coordAll;
  3012. exports.geomEach = geomEach;
  3013. exports.geomReduce = geomReduce;
  3014. exports.flattenEach = flattenEach;
  3015. exports.flattenReduce = flattenReduce;
  3016. exports.segmentEach = segmentEach;
  3017. exports.segmentReduce = segmentReduce;
  3018. exports.lineEach = lineEach;
  3019. exports.lineReduce = lineReduce;
  3020. exports.findSegment = findSegment;
  3021. exports.findPoint = findPoint;
  3022. },{"@turf/helpers":11}],17:[function(require,module,exports){
  3023. "use strict";
  3024. Object.defineProperty(exports, "__esModule", { value: true });
  3025. var bearing_1 = require("@turf/bearing");
  3026. var distance_1 = require("@turf/distance");
  3027. var destination_1 = require("@turf/destination");
  3028. var line_intersect_1 = require("@turf/line-intersect");
  3029. var meta_1 = require("@turf/meta");
  3030. var helpers_1 = require("@turf/helpers");
  3031. var invariant_1 = require("@turf/invariant");
  3032. /**
  3033. * Takes a {@link Point} and a {@link LineString} and calculates the closest Point on the (Multi)LineString.
  3034. *
  3035. * @name nearestPointOnLine
  3036. * @param {Geometry|Feature<LineString|MultiLineString>} lines lines to snap to
  3037. * @param {Geometry|Feature<Point>|number[]} pt point to snap from
  3038. * @param {Object} [options={}] Optional parameters
  3039. * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers
  3040. * @returns {Feature<Point>} closest point on the `line` to `point`. The properties object will contain three values: `index`: closest point was found on nth line part, `dist`: distance between pt and the closest point, `location`: distance along the line between start and the closest point.
  3041. * @example
  3042. * var line = turf.lineString([
  3043. * [-77.031669, 38.878605],
  3044. * [-77.029609, 38.881946],
  3045. * [-77.020339, 38.884084],
  3046. * [-77.025661, 38.885821],
  3047. * [-77.021884, 38.889563],
  3048. * [-77.019824, 38.892368]
  3049. * ]);
  3050. * var pt = turf.point([-77.037076, 38.884017]);
  3051. *
  3052. * var snapped = turf.nearestPointOnLine(line, pt, {units: 'miles'});
  3053. *
  3054. * //addToMap
  3055. * var addToMap = [line, pt, snapped];
  3056. * snapped.properties['marker-color'] = '#00f';
  3057. */
  3058. function nearestPointOnLine(lines, pt, options) {
  3059. if (options === void 0) { options = {}; }
  3060. var closestPt = helpers_1.point([Infinity, Infinity], {
  3061. dist: Infinity
  3062. });
  3063. var length = 0.0;
  3064. meta_1.flattenEach(lines, function (line) {
  3065. var coords = invariant_1.getCoords(line);
  3066. for (var i = 0; i < coords.length - 1; i++) {
  3067. //start
  3068. var start = helpers_1.point(coords[i]);
  3069. start.properties.dist = distance_1.default(pt, start, options);
  3070. //stop
  3071. var stop_1 = helpers_1.point(coords[i + 1]);
  3072. stop_1.properties.dist = distance_1.default(pt, stop_1, options);
  3073. // sectionLength
  3074. var sectionLength = distance_1.default(start, stop_1, options);
  3075. //perpendicular
  3076. var heightDistance = Math.max(start.properties.dist, stop_1.properties.dist);
  3077. var direction = bearing_1.default(start, stop_1);
  3078. var perpendicularPt1 = destination_1.default(pt, heightDistance, direction + 90, options);
  3079. var perpendicularPt2 = destination_1.default(pt, heightDistance, direction - 90, options);
  3080. var intersect = line_intersect_1.default(helpers_1.lineString([perpendicularPt1.geometry.coordinates, perpendicularPt2.geometry.coordinates]), helpers_1.lineString([start.geometry.coordinates, stop_1.geometry.coordinates]));
  3081. var intersectPt = null;
  3082. if (intersect.features.length > 0) {
  3083. intersectPt = intersect.features[0];
  3084. intersectPt.properties.dist = distance_1.default(pt, intersectPt, options);
  3085. intersectPt.properties.location = length + distance_1.default(start, intersectPt, options);
  3086. }
  3087. if (start.properties.dist < closestPt.properties.dist) {
  3088. closestPt = start;
  3089. closestPt.properties.index = i;
  3090. closestPt.properties.location = length;
  3091. }
  3092. if (stop_1.properties.dist < closestPt.properties.dist) {
  3093. closestPt = stop_1;
  3094. closestPt.properties.index = i + 1;
  3095. closestPt.properties.location = length + sectionLength;
  3096. }
  3097. if (intersectPt && intersectPt.properties.dist < closestPt.properties.dist) {
  3098. closestPt = intersectPt;
  3099. closestPt.properties.index = i;
  3100. }
  3101. // update length
  3102. length += sectionLength;
  3103. }
  3104. });
  3105. return closestPt;
  3106. }
  3107. exports.default = nearestPointOnLine;
  3108. },{"@turf/bearing":6,"@turf/destination":8,"@turf/distance":10,"@turf/helpers":11,"@turf/invariant":13,"@turf/line-intersect":14,"@turf/meta":16}],18:[function(require,module,exports){
  3109. "use strict";
  3110. Object.defineProperty(exports, "__esModule", { value: true });
  3111. var martinez = require("martinez-polygon-clipping");
  3112. var invariant_1 = require("@turf/invariant");
  3113. var helpers_1 = require("@turf/helpers");
  3114. /**
  3115. * Takes two {@link (Multi)Polygon(s)} and returns a combined polygon. If the input polygons are not contiguous, this function returns a {@link MultiPolygon} feature.
  3116. *
  3117. * @name union
  3118. * @param {Feature<Polygon|MultiPolygon>} polygon1 input Polygon feature
  3119. * @param {Feature<Polygon|MultiPolygon>} polygon2 Polygon feature to difference from polygon1
  3120. * @param {Object} [options={}] Optional Parameters
  3121. * @param {Object} [options.properties={}] Translate Properties to output Feature
  3122. * @returns {Feature<(Polygon|MultiPolygon)>} a combined {@link Polygon} or {@link MultiPolygon} feature
  3123. * @example
  3124. * var poly1 = turf.polygon([[
  3125. * [-82.574787, 35.594087],
  3126. * [-82.574787, 35.615581],
  3127. * [-82.545261, 35.615581],
  3128. * [-82.545261, 35.594087],
  3129. * [-82.574787, 35.594087]
  3130. * ]], {"fill": "#0f0"});
  3131. * var poly2 = turf.polygon([[
  3132. * [-82.560024, 35.585153],
  3133. * [-82.560024, 35.602602],
  3134. * [-82.52964, 35.602602],
  3135. * [-82.52964, 35.585153],
  3136. * [-82.560024, 35.585153]
  3137. * ]], {"fill": "#00f"});
  3138. *
  3139. * var union = turf.union(poly1, poly2);
  3140. *
  3141. * //addToMap
  3142. * var addToMap = [poly1, poly2, union];
  3143. */
  3144. function union(polygon1, polygon2, options) {
  3145. if (options === void 0) { options = {}; }
  3146. var coords1 = invariant_1.getGeom(polygon1).coordinates;
  3147. var coords2 = invariant_1.getGeom(polygon2).coordinates;
  3148. var unioned = martinez.union(coords1, coords2);
  3149. if (unioned.length === 0)
  3150. return null;
  3151. if (unioned.length === 1)
  3152. return helpers_1.polygon(unioned[0], options.properties);
  3153. else
  3154. return helpers_1.multiPolygon(unioned, options.properties);
  3155. }
  3156. exports.default = union;
  3157. },{"@turf/helpers":11,"@turf/invariant":13,"martinez-polygon-clipping":173}],19:[function(require,module,exports){
  3158. (function (process,global,setImmediate){
  3159. (function (global, factory) {
  3160. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3161. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  3162. (factory((global.async = global.async || {})));
  3163. }(this, (function (exports) { 'use strict';
  3164. function slice(arrayLike, start) {
  3165. start = start|0;
  3166. var newLen = Math.max(arrayLike.length - start, 0);
  3167. var newArr = Array(newLen);
  3168. for(var idx = 0; idx < newLen; idx++) {
  3169. newArr[idx] = arrayLike[start + idx];
  3170. }
  3171. return newArr;
  3172. }
  3173. /**
  3174. * Creates a continuation function with some arguments already applied.
  3175. *
  3176. * Useful as a shorthand when combined with other control flow functions. Any
  3177. * arguments passed to the returned function are added to the arguments
  3178. * originally passed to apply.
  3179. *
  3180. * @name apply
  3181. * @static
  3182. * @memberOf module:Utils
  3183. * @method
  3184. * @category Util
  3185. * @param {Function} fn - The function you want to eventually apply all
  3186. * arguments to. Invokes with (arguments...).
  3187. * @param {...*} arguments... - Any number of arguments to automatically apply
  3188. * when the continuation is called.
  3189. * @returns {Function} the partially-applied function
  3190. * @example
  3191. *
  3192. * // using apply
  3193. * async.parallel([
  3194. * async.apply(fs.writeFile, 'testfile1', 'test1'),
  3195. * async.apply(fs.writeFile, 'testfile2', 'test2')
  3196. * ]);
  3197. *
  3198. *
  3199. * // the same process without using apply
  3200. * async.parallel([
  3201. * function(callback) {
  3202. * fs.writeFile('testfile1', 'test1', callback);
  3203. * },
  3204. * function(callback) {
  3205. * fs.writeFile('testfile2', 'test2', callback);
  3206. * }
  3207. * ]);
  3208. *
  3209. * // It's possible to pass any number of additional arguments when calling the
  3210. * // continuation:
  3211. *
  3212. * node> var fn = async.apply(sys.puts, 'one');
  3213. * node> fn('two', 'three');
  3214. * one
  3215. * two
  3216. * three
  3217. */
  3218. var apply = function(fn/*, ...args*/) {
  3219. var args = slice(arguments, 1);
  3220. return function(/*callArgs*/) {
  3221. var callArgs = slice(arguments);
  3222. return fn.apply(null, args.concat(callArgs));
  3223. };
  3224. };
  3225. var initialParams = function (fn) {
  3226. return function (/*...args, callback*/) {
  3227. var args = slice(arguments);
  3228. var callback = args.pop();
  3229. fn.call(this, args, callback);
  3230. };
  3231. };
  3232. /**
  3233. * Checks if `value` is the
  3234. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  3235. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  3236. *
  3237. * @static
  3238. * @memberOf _
  3239. * @since 0.1.0
  3240. * @category Lang
  3241. * @param {*} value The value to check.
  3242. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  3243. * @example
  3244. *
  3245. * _.isObject({});
  3246. * // => true
  3247. *
  3248. * _.isObject([1, 2, 3]);
  3249. * // => true
  3250. *
  3251. * _.isObject(_.noop);
  3252. * // => true
  3253. *
  3254. * _.isObject(null);
  3255. * // => false
  3256. */
  3257. function isObject(value) {
  3258. var type = typeof value;
  3259. return value != null && (type == 'object' || type == 'function');
  3260. }
  3261. var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
  3262. var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
  3263. function fallback(fn) {
  3264. setTimeout(fn, 0);
  3265. }
  3266. function wrap(defer) {
  3267. return function (fn/*, ...args*/) {
  3268. var args = slice(arguments, 1);
  3269. defer(function () {
  3270. fn.apply(null, args);
  3271. });
  3272. };
  3273. }
  3274. var _defer;
  3275. if (hasSetImmediate) {
  3276. _defer = setImmediate;
  3277. } else if (hasNextTick) {
  3278. _defer = process.nextTick;
  3279. } else {
  3280. _defer = fallback;
  3281. }
  3282. var setImmediate$1 = wrap(_defer);
  3283. /**
  3284. * Take a sync function and make it async, passing its return value to a
  3285. * callback. This is useful for plugging sync functions into a waterfall,
  3286. * series, or other async functions. Any arguments passed to the generated
  3287. * function will be passed to the wrapped function (except for the final
  3288. * callback argument). Errors thrown will be passed to the callback.
  3289. *
  3290. * If the function passed to `asyncify` returns a Promise, that promises's
  3291. * resolved/rejected state will be used to call the callback, rather than simply
  3292. * the synchronous return value.
  3293. *
  3294. * This also means you can asyncify ES2017 `async` functions.
  3295. *
  3296. * @name asyncify
  3297. * @static
  3298. * @memberOf module:Utils
  3299. * @method
  3300. * @alias wrapSync
  3301. * @category Util
  3302. * @param {Function} func - The synchronous function, or Promise-returning
  3303. * function to convert to an {@link AsyncFunction}.
  3304. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
  3305. * invoked with `(args..., callback)`.
  3306. * @example
  3307. *
  3308. * // passing a regular synchronous function
  3309. * async.waterfall([
  3310. * async.apply(fs.readFile, filename, "utf8"),
  3311. * async.asyncify(JSON.parse),
  3312. * function (data, next) {
  3313. * // data is the result of parsing the text.
  3314. * // If there was a parsing error, it would have been caught.
  3315. * }
  3316. * ], callback);
  3317. *
  3318. * // passing a function returning a promise
  3319. * async.waterfall([
  3320. * async.apply(fs.readFile, filename, "utf8"),
  3321. * async.asyncify(function (contents) {
  3322. * return db.model.create(contents);
  3323. * }),
  3324. * function (model, next) {
  3325. * // `model` is the instantiated model object.
  3326. * // If there was an error, this function would be skipped.
  3327. * }
  3328. * ], callback);
  3329. *
  3330. * // es2017 example, though `asyncify` is not needed if your JS environment
  3331. * // supports async functions out of the box
  3332. * var q = async.queue(async.asyncify(async function(file) {
  3333. * var intermediateStep = await processFile(file);
  3334. * return await somePromise(intermediateStep)
  3335. * }));
  3336. *
  3337. * q.push(files);
  3338. */
  3339. function asyncify(func) {
  3340. return initialParams(function (args, callback) {
  3341. var result;
  3342. try {
  3343. result = func.apply(this, args);
  3344. } catch (e) {
  3345. return callback(e);
  3346. }
  3347. // if result is Promise object
  3348. if (isObject(result) && typeof result.then === 'function') {
  3349. result.then(function(value) {
  3350. invokeCallback(callback, null, value);
  3351. }, function(err) {
  3352. invokeCallback(callback, err.message ? err : new Error(err));
  3353. });
  3354. } else {
  3355. callback(null, result);
  3356. }
  3357. });
  3358. }
  3359. function invokeCallback(callback, error, value) {
  3360. try {
  3361. callback(error, value);
  3362. } catch (e) {
  3363. setImmediate$1(rethrow, e);
  3364. }
  3365. }
  3366. function rethrow(error) {
  3367. throw error;
  3368. }
  3369. var supportsSymbol = typeof Symbol === 'function';
  3370. function isAsync(fn) {
  3371. return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction';
  3372. }
  3373. function wrapAsync(asyncFn) {
  3374. return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
  3375. }
  3376. function applyEach$1(eachfn) {
  3377. return function(fns/*, ...args*/) {
  3378. var args = slice(arguments, 1);
  3379. var go = initialParams(function(args, callback) {
  3380. var that = this;
  3381. return eachfn(fns, function (fn, cb) {
  3382. wrapAsync(fn).apply(that, args.concat(cb));
  3383. }, callback);
  3384. });
  3385. if (args.length) {
  3386. return go.apply(this, args);
  3387. }
  3388. else {
  3389. return go;
  3390. }
  3391. };
  3392. }
  3393. /** Detect free variable `global` from Node.js. */
  3394. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  3395. /** Detect free variable `self`. */
  3396. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  3397. /** Used as a reference to the global object. */
  3398. var root = freeGlobal || freeSelf || Function('return this')();
  3399. /** Built-in value references. */
  3400. var Symbol$1 = root.Symbol;
  3401. /** Used for built-in method references. */
  3402. var objectProto = Object.prototype;
  3403. /** Used to check objects for own properties. */
  3404. var hasOwnProperty = objectProto.hasOwnProperty;
  3405. /**
  3406. * Used to resolve the
  3407. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  3408. * of values.
  3409. */
  3410. var nativeObjectToString = objectProto.toString;
  3411. /** Built-in value references. */
  3412. var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
  3413. /**
  3414. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  3415. *
  3416. * @private
  3417. * @param {*} value The value to query.
  3418. * @returns {string} Returns the raw `toStringTag`.
  3419. */
  3420. function getRawTag(value) {
  3421. var isOwn = hasOwnProperty.call(value, symToStringTag$1),
  3422. tag = value[symToStringTag$1];
  3423. try {
  3424. value[symToStringTag$1] = undefined;
  3425. var unmasked = true;
  3426. } catch (e) {}
  3427. var result = nativeObjectToString.call(value);
  3428. if (unmasked) {
  3429. if (isOwn) {
  3430. value[symToStringTag$1] = tag;
  3431. } else {
  3432. delete value[symToStringTag$1];
  3433. }
  3434. }
  3435. return result;
  3436. }
  3437. /** Used for built-in method references. */
  3438. var objectProto$1 = Object.prototype;
  3439. /**
  3440. * Used to resolve the
  3441. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  3442. * of values.
  3443. */
  3444. var nativeObjectToString$1 = objectProto$1.toString;
  3445. /**
  3446. * Converts `value` to a string using `Object.prototype.toString`.
  3447. *
  3448. * @private
  3449. * @param {*} value The value to convert.
  3450. * @returns {string} Returns the converted string.
  3451. */
  3452. function objectToString(value) {
  3453. return nativeObjectToString$1.call(value);
  3454. }
  3455. /** `Object#toString` result references. */
  3456. var nullTag = '[object Null]';
  3457. var undefinedTag = '[object Undefined]';
  3458. /** Built-in value references. */
  3459. var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
  3460. /**
  3461. * The base implementation of `getTag` without fallbacks for buggy environments.
  3462. *
  3463. * @private
  3464. * @param {*} value The value to query.
  3465. * @returns {string} Returns the `toStringTag`.
  3466. */
  3467. function baseGetTag(value) {
  3468. if (value == null) {
  3469. return value === undefined ? undefinedTag : nullTag;
  3470. }
  3471. return (symToStringTag && symToStringTag in Object(value))
  3472. ? getRawTag(value)
  3473. : objectToString(value);
  3474. }
  3475. /** `Object#toString` result references. */
  3476. var asyncTag = '[object AsyncFunction]';
  3477. var funcTag = '[object Function]';
  3478. var genTag = '[object GeneratorFunction]';
  3479. var proxyTag = '[object Proxy]';
  3480. /**
  3481. * Checks if `value` is classified as a `Function` object.
  3482. *
  3483. * @static
  3484. * @memberOf _
  3485. * @since 0.1.0
  3486. * @category Lang
  3487. * @param {*} value The value to check.
  3488. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  3489. * @example
  3490. *
  3491. * _.isFunction(_);
  3492. * // => true
  3493. *
  3494. * _.isFunction(/abc/);
  3495. * // => false
  3496. */
  3497. function isFunction(value) {
  3498. if (!isObject(value)) {
  3499. return false;
  3500. }
  3501. // The use of `Object#toString` avoids issues with the `typeof` operator
  3502. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  3503. var tag = baseGetTag(value);
  3504. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  3505. }
  3506. /** Used as references for various `Number` constants. */
  3507. var MAX_SAFE_INTEGER = 9007199254740991;
  3508. /**
  3509. * Checks if `value` is a valid array-like length.
  3510. *
  3511. * **Note:** This method is loosely based on
  3512. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  3513. *
  3514. * @static
  3515. * @memberOf _
  3516. * @since 4.0.0
  3517. * @category Lang
  3518. * @param {*} value The value to check.
  3519. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  3520. * @example
  3521. *
  3522. * _.isLength(3);
  3523. * // => true
  3524. *
  3525. * _.isLength(Number.MIN_VALUE);
  3526. * // => false
  3527. *
  3528. * _.isLength(Infinity);
  3529. * // => false
  3530. *
  3531. * _.isLength('3');
  3532. * // => false
  3533. */
  3534. function isLength(value) {
  3535. return typeof value == 'number' &&
  3536. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  3537. }
  3538. /**
  3539. * Checks if `value` is array-like. A value is considered array-like if it's
  3540. * not a function and has a `value.length` that's an integer greater than or
  3541. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  3542. *
  3543. * @static
  3544. * @memberOf _
  3545. * @since 4.0.0
  3546. * @category Lang
  3547. * @param {*} value The value to check.
  3548. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  3549. * @example
  3550. *
  3551. * _.isArrayLike([1, 2, 3]);
  3552. * // => true
  3553. *
  3554. * _.isArrayLike(document.body.children);
  3555. * // => true
  3556. *
  3557. * _.isArrayLike('abc');
  3558. * // => true
  3559. *
  3560. * _.isArrayLike(_.noop);
  3561. * // => false
  3562. */
  3563. function isArrayLike(value) {
  3564. return value != null && isLength(value.length) && !isFunction(value);
  3565. }
  3566. // A temporary value used to identify if the loop should be broken.
  3567. // See #1064, #1293
  3568. var breakLoop = {};
  3569. /**
  3570. * This method returns `undefined`.
  3571. *
  3572. * @static
  3573. * @memberOf _
  3574. * @since 2.3.0
  3575. * @category Util
  3576. * @example
  3577. *
  3578. * _.times(2, _.noop);
  3579. * // => [undefined, undefined]
  3580. */
  3581. function noop() {
  3582. // No operation performed.
  3583. }
  3584. function once(fn) {
  3585. return function () {
  3586. if (fn === null) return;
  3587. var callFn = fn;
  3588. fn = null;
  3589. callFn.apply(this, arguments);
  3590. };
  3591. }
  3592. var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;
  3593. var getIterator = function (coll) {
  3594. return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();
  3595. };
  3596. /**
  3597. * The base implementation of `_.times` without support for iteratee shorthands
  3598. * or max array length checks.
  3599. *
  3600. * @private
  3601. * @param {number} n The number of times to invoke `iteratee`.
  3602. * @param {Function} iteratee The function invoked per iteration.
  3603. * @returns {Array} Returns the array of results.
  3604. */
  3605. function baseTimes(n, iteratee) {
  3606. var index = -1,
  3607. result = Array(n);
  3608. while (++index < n) {
  3609. result[index] = iteratee(index);
  3610. }
  3611. return result;
  3612. }
  3613. /**
  3614. * Checks if `value` is object-like. A value is object-like if it's not `null`
  3615. * and has a `typeof` result of "object".
  3616. *
  3617. * @static
  3618. * @memberOf _
  3619. * @since 4.0.0
  3620. * @category Lang
  3621. * @param {*} value The value to check.
  3622. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  3623. * @example
  3624. *
  3625. * _.isObjectLike({});
  3626. * // => true
  3627. *
  3628. * _.isObjectLike([1, 2, 3]);
  3629. * // => true
  3630. *
  3631. * _.isObjectLike(_.noop);
  3632. * // => false
  3633. *
  3634. * _.isObjectLike(null);
  3635. * // => false
  3636. */
  3637. function isObjectLike(value) {
  3638. return value != null && typeof value == 'object';
  3639. }
  3640. /** `Object#toString` result references. */
  3641. var argsTag = '[object Arguments]';
  3642. /**
  3643. * The base implementation of `_.isArguments`.
  3644. *
  3645. * @private
  3646. * @param {*} value The value to check.
  3647. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3648. */
  3649. function baseIsArguments(value) {
  3650. return isObjectLike(value) && baseGetTag(value) == argsTag;
  3651. }
  3652. /** Used for built-in method references. */
  3653. var objectProto$3 = Object.prototype;
  3654. /** Used to check objects for own properties. */
  3655. var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
  3656. /** Built-in value references. */
  3657. var propertyIsEnumerable = objectProto$3.propertyIsEnumerable;
  3658. /**
  3659. * Checks if `value` is likely an `arguments` object.
  3660. *
  3661. * @static
  3662. * @memberOf _
  3663. * @since 0.1.0
  3664. * @category Lang
  3665. * @param {*} value The value to check.
  3666. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3667. * else `false`.
  3668. * @example
  3669. *
  3670. * _.isArguments(function() { return arguments; }());
  3671. * // => true
  3672. *
  3673. * _.isArguments([1, 2, 3]);
  3674. * // => false
  3675. */
  3676. var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  3677. return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') &&
  3678. !propertyIsEnumerable.call(value, 'callee');
  3679. };
  3680. /**
  3681. * Checks if `value` is classified as an `Array` object.
  3682. *
  3683. * @static
  3684. * @memberOf _
  3685. * @since 0.1.0
  3686. * @category Lang
  3687. * @param {*} value The value to check.
  3688. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  3689. * @example
  3690. *
  3691. * _.isArray([1, 2, 3]);
  3692. * // => true
  3693. *
  3694. * _.isArray(document.body.children);
  3695. * // => false
  3696. *
  3697. * _.isArray('abc');
  3698. * // => false
  3699. *
  3700. * _.isArray(_.noop);
  3701. * // => false
  3702. */
  3703. var isArray = Array.isArray;
  3704. /**
  3705. * This method returns `false`.
  3706. *
  3707. * @static
  3708. * @memberOf _
  3709. * @since 4.13.0
  3710. * @category Util
  3711. * @returns {boolean} Returns `false`.
  3712. * @example
  3713. *
  3714. * _.times(2, _.stubFalse);
  3715. * // => [false, false]
  3716. */
  3717. function stubFalse() {
  3718. return false;
  3719. }
  3720. /** Detect free variable `exports`. */
  3721. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  3722. /** Detect free variable `module`. */
  3723. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  3724. /** Detect the popular CommonJS extension `module.exports`. */
  3725. var moduleExports = freeModule && freeModule.exports === freeExports;
  3726. /** Built-in value references. */
  3727. var Buffer = moduleExports ? root.Buffer : undefined;
  3728. /* Built-in method references for those with the same name as other `lodash` methods. */
  3729. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  3730. /**
  3731. * Checks if `value` is a buffer.
  3732. *
  3733. * @static
  3734. * @memberOf _
  3735. * @since 4.3.0
  3736. * @category Lang
  3737. * @param {*} value The value to check.
  3738. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  3739. * @example
  3740. *
  3741. * _.isBuffer(new Buffer(2));
  3742. * // => true
  3743. *
  3744. * _.isBuffer(new Uint8Array(2));
  3745. * // => false
  3746. */
  3747. var isBuffer = nativeIsBuffer || stubFalse;
  3748. /** Used as references for various `Number` constants. */
  3749. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  3750. /** Used to detect unsigned integer values. */
  3751. var reIsUint = /^(?:0|[1-9]\d*)$/;
  3752. /**
  3753. * Checks if `value` is a valid array-like index.
  3754. *
  3755. * @private
  3756. * @param {*} value The value to check.
  3757. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  3758. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  3759. */
  3760. function isIndex(value, length) {
  3761. var type = typeof value;
  3762. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  3763. return !!length &&
  3764. (type == 'number' ||
  3765. (type != 'symbol' && reIsUint.test(value))) &&
  3766. (value > -1 && value % 1 == 0 && value < length);
  3767. }
  3768. /** `Object#toString` result references. */
  3769. var argsTag$1 = '[object Arguments]';
  3770. var arrayTag = '[object Array]';
  3771. var boolTag = '[object Boolean]';
  3772. var dateTag = '[object Date]';
  3773. var errorTag = '[object Error]';
  3774. var funcTag$1 = '[object Function]';
  3775. var mapTag = '[object Map]';
  3776. var numberTag = '[object Number]';
  3777. var objectTag = '[object Object]';
  3778. var regexpTag = '[object RegExp]';
  3779. var setTag = '[object Set]';
  3780. var stringTag = '[object String]';
  3781. var weakMapTag = '[object WeakMap]';
  3782. var arrayBufferTag = '[object ArrayBuffer]';
  3783. var dataViewTag = '[object DataView]';
  3784. var float32Tag = '[object Float32Array]';
  3785. var float64Tag = '[object Float64Array]';
  3786. var int8Tag = '[object Int8Array]';
  3787. var int16Tag = '[object Int16Array]';
  3788. var int32Tag = '[object Int32Array]';
  3789. var uint8Tag = '[object Uint8Array]';
  3790. var uint8ClampedTag = '[object Uint8ClampedArray]';
  3791. var uint16Tag = '[object Uint16Array]';
  3792. var uint32Tag = '[object Uint32Array]';
  3793. /** Used to identify `toStringTag` values of typed arrays. */
  3794. var typedArrayTags = {};
  3795. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  3796. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  3797. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  3798. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  3799. typedArrayTags[uint32Tag] = true;
  3800. typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
  3801. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  3802. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  3803. typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
  3804. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  3805. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  3806. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  3807. typedArrayTags[weakMapTag] = false;
  3808. /**
  3809. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3810. *
  3811. * @private
  3812. * @param {*} value The value to check.
  3813. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3814. */
  3815. function baseIsTypedArray(value) {
  3816. return isObjectLike(value) &&
  3817. isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
  3818. }
  3819. /**
  3820. * The base implementation of `_.unary` without support for storing metadata.
  3821. *
  3822. * @private
  3823. * @param {Function} func The function to cap arguments for.
  3824. * @returns {Function} Returns the new capped function.
  3825. */
  3826. function baseUnary(func) {
  3827. return function(value) {
  3828. return func(value);
  3829. };
  3830. }
  3831. /** Detect free variable `exports`. */
  3832. var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
  3833. /** Detect free variable `module`. */
  3834. var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
  3835. /** Detect the popular CommonJS extension `module.exports`. */
  3836. var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
  3837. /** Detect free variable `process` from Node.js. */
  3838. var freeProcess = moduleExports$1 && freeGlobal.process;
  3839. /** Used to access faster Node.js helpers. */
  3840. var nodeUtil = (function() {
  3841. try {
  3842. // Use `util.types` for Node.js 10+.
  3843. var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
  3844. if (types) {
  3845. return types;
  3846. }
  3847. // Legacy `process.binding('util')` for Node.js < 10.
  3848. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  3849. } catch (e) {}
  3850. }());
  3851. /* Node.js helper references. */
  3852. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  3853. /**
  3854. * Checks if `value` is classified as a typed array.
  3855. *
  3856. * @static
  3857. * @memberOf _
  3858. * @since 3.0.0
  3859. * @category Lang
  3860. * @param {*} value The value to check.
  3861. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3862. * @example
  3863. *
  3864. * _.isTypedArray(new Uint8Array);
  3865. * // => true
  3866. *
  3867. * _.isTypedArray([]);
  3868. * // => false
  3869. */
  3870. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  3871. /** Used for built-in method references. */
  3872. var objectProto$2 = Object.prototype;
  3873. /** Used to check objects for own properties. */
  3874. var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
  3875. /**
  3876. * Creates an array of the enumerable property names of the array-like `value`.
  3877. *
  3878. * @private
  3879. * @param {*} value The value to query.
  3880. * @param {boolean} inherited Specify returning inherited property names.
  3881. * @returns {Array} Returns the array of property names.
  3882. */
  3883. function arrayLikeKeys(value, inherited) {
  3884. var isArr = isArray(value),
  3885. isArg = !isArr && isArguments(value),
  3886. isBuff = !isArr && !isArg && isBuffer(value),
  3887. isType = !isArr && !isArg && !isBuff && isTypedArray(value),
  3888. skipIndexes = isArr || isArg || isBuff || isType,
  3889. result = skipIndexes ? baseTimes(value.length, String) : [],
  3890. length = result.length;
  3891. for (var key in value) {
  3892. if ((inherited || hasOwnProperty$1.call(value, key)) &&
  3893. !(skipIndexes && (
  3894. // Safari 9 has enumerable `arguments.length` in strict mode.
  3895. key == 'length' ||
  3896. // Node.js 0.10 has enumerable non-index properties on buffers.
  3897. (isBuff && (key == 'offset' || key == 'parent')) ||
  3898. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  3899. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  3900. // Skip index properties.
  3901. isIndex(key, length)
  3902. ))) {
  3903. result.push(key);
  3904. }
  3905. }
  3906. return result;
  3907. }
  3908. /** Used for built-in method references. */
  3909. var objectProto$5 = Object.prototype;
  3910. /**
  3911. * Checks if `value` is likely a prototype object.
  3912. *
  3913. * @private
  3914. * @param {*} value The value to check.
  3915. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  3916. */
  3917. function isPrototype(value) {
  3918. var Ctor = value && value.constructor,
  3919. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5;
  3920. return value === proto;
  3921. }
  3922. /**
  3923. * Creates a unary function that invokes `func` with its argument transformed.
  3924. *
  3925. * @private
  3926. * @param {Function} func The function to wrap.
  3927. * @param {Function} transform The argument transform.
  3928. * @returns {Function} Returns the new function.
  3929. */
  3930. function overArg(func, transform) {
  3931. return function(arg) {
  3932. return func(transform(arg));
  3933. };
  3934. }
  3935. /* Built-in method references for those with the same name as other `lodash` methods. */
  3936. var nativeKeys = overArg(Object.keys, Object);
  3937. /** Used for built-in method references. */
  3938. var objectProto$4 = Object.prototype;
  3939. /** Used to check objects for own properties. */
  3940. var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
  3941. /**
  3942. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3943. *
  3944. * @private
  3945. * @param {Object} object The object to query.
  3946. * @returns {Array} Returns the array of property names.
  3947. */
  3948. function baseKeys(object) {
  3949. if (!isPrototype(object)) {
  3950. return nativeKeys(object);
  3951. }
  3952. var result = [];
  3953. for (var key in Object(object)) {
  3954. if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
  3955. result.push(key);
  3956. }
  3957. }
  3958. return result;
  3959. }
  3960. /**
  3961. * Creates an array of the own enumerable property names of `object`.
  3962. *
  3963. * **Note:** Non-object values are coerced to objects. See the
  3964. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3965. * for more details.
  3966. *
  3967. * @static
  3968. * @since 0.1.0
  3969. * @memberOf _
  3970. * @category Object
  3971. * @param {Object} object The object to query.
  3972. * @returns {Array} Returns the array of property names.
  3973. * @example
  3974. *
  3975. * function Foo() {
  3976. * this.a = 1;
  3977. * this.b = 2;
  3978. * }
  3979. *
  3980. * Foo.prototype.c = 3;
  3981. *
  3982. * _.keys(new Foo);
  3983. * // => ['a', 'b'] (iteration order is not guaranteed)
  3984. *
  3985. * _.keys('hi');
  3986. * // => ['0', '1']
  3987. */
  3988. function keys(object) {
  3989. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  3990. }
  3991. function createArrayIterator(coll) {
  3992. var i = -1;
  3993. var len = coll.length;
  3994. return function next() {
  3995. return ++i < len ? {value: coll[i], key: i} : null;
  3996. }
  3997. }
  3998. function createES2015Iterator(iterator) {
  3999. var i = -1;
  4000. return function next() {
  4001. var item = iterator.next();
  4002. if (item.done)
  4003. return null;
  4004. i++;
  4005. return {value: item.value, key: i};
  4006. }
  4007. }
  4008. function createObjectIterator(obj) {
  4009. var okeys = keys(obj);
  4010. var i = -1;
  4011. var len = okeys.length;
  4012. return function next() {
  4013. var key = okeys[++i];
  4014. return i < len ? {value: obj[key], key: key} : null;
  4015. };
  4016. }
  4017. function iterator(coll) {
  4018. if (isArrayLike(coll)) {
  4019. return createArrayIterator(coll);
  4020. }
  4021. var iterator = getIterator(coll);
  4022. return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
  4023. }
  4024. function onlyOnce(fn) {
  4025. return function() {
  4026. if (fn === null) throw new Error("Callback was already called.");
  4027. var callFn = fn;
  4028. fn = null;
  4029. callFn.apply(this, arguments);
  4030. };
  4031. }
  4032. function _eachOfLimit(limit) {
  4033. return function (obj, iteratee, callback) {
  4034. callback = once(callback || noop);
  4035. if (limit <= 0 || !obj) {
  4036. return callback(null);
  4037. }
  4038. var nextElem = iterator(obj);
  4039. var done = false;
  4040. var running = 0;
  4041. var looping = false;
  4042. function iterateeCallback(err, value) {
  4043. running -= 1;
  4044. if (err) {
  4045. done = true;
  4046. callback(err);
  4047. }
  4048. else if (value === breakLoop || (done && running <= 0)) {
  4049. done = true;
  4050. return callback(null);
  4051. }
  4052. else if (!looping) {
  4053. replenish();
  4054. }
  4055. }
  4056. function replenish () {
  4057. looping = true;
  4058. while (running < limit && !done) {
  4059. var elem = nextElem();
  4060. if (elem === null) {
  4061. done = true;
  4062. if (running <= 0) {
  4063. callback(null);
  4064. }
  4065. return;
  4066. }
  4067. running += 1;
  4068. iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
  4069. }
  4070. looping = false;
  4071. }
  4072. replenish();
  4073. };
  4074. }
  4075. /**
  4076. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
  4077. * time.
  4078. *
  4079. * @name eachOfLimit
  4080. * @static
  4081. * @memberOf module:Collections
  4082. * @method
  4083. * @see [async.eachOf]{@link module:Collections.eachOf}
  4084. * @alias forEachOfLimit
  4085. * @category Collection
  4086. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4087. * @param {number} limit - The maximum number of async operations at a time.
  4088. * @param {AsyncFunction} iteratee - An async function to apply to each
  4089. * item in `coll`. The `key` is the item's key, or index in the case of an
  4090. * array.
  4091. * Invoked with (item, key, callback).
  4092. * @param {Function} [callback] - A callback which is called when all
  4093. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  4094. */
  4095. function eachOfLimit(coll, limit, iteratee, callback) {
  4096. _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);
  4097. }
  4098. function doLimit(fn, limit) {
  4099. return function (iterable, iteratee, callback) {
  4100. return fn(iterable, limit, iteratee, callback);
  4101. };
  4102. }
  4103. // eachOf implementation optimized for array-likes
  4104. function eachOfArrayLike(coll, iteratee, callback) {
  4105. callback = once(callback || noop);
  4106. var index = 0,
  4107. completed = 0,
  4108. length = coll.length;
  4109. if (length === 0) {
  4110. callback(null);
  4111. }
  4112. function iteratorCallback(err, value) {
  4113. if (err) {
  4114. callback(err);
  4115. } else if ((++completed === length) || value === breakLoop) {
  4116. callback(null);
  4117. }
  4118. }
  4119. for (; index < length; index++) {
  4120. iteratee(coll[index], index, onlyOnce(iteratorCallback));
  4121. }
  4122. }
  4123. // a generic version of eachOf which can handle array, object, and iterator cases.
  4124. var eachOfGeneric = doLimit(eachOfLimit, Infinity);
  4125. /**
  4126. * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
  4127. * to the iteratee.
  4128. *
  4129. * @name eachOf
  4130. * @static
  4131. * @memberOf module:Collections
  4132. * @method
  4133. * @alias forEachOf
  4134. * @category Collection
  4135. * @see [async.each]{@link module:Collections.each}
  4136. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4137. * @param {AsyncFunction} iteratee - A function to apply to each
  4138. * item in `coll`.
  4139. * The `key` is the item's key, or index in the case of an array.
  4140. * Invoked with (item, key, callback).
  4141. * @param {Function} [callback] - A callback which is called when all
  4142. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  4143. * @example
  4144. *
  4145. * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
  4146. * var configs = {};
  4147. *
  4148. * async.forEachOf(obj, function (value, key, callback) {
  4149. * fs.readFile(__dirname + value, "utf8", function (err, data) {
  4150. * if (err) return callback(err);
  4151. * try {
  4152. * configs[key] = JSON.parse(data);
  4153. * } catch (e) {
  4154. * return callback(e);
  4155. * }
  4156. * callback();
  4157. * });
  4158. * }, function (err) {
  4159. * if (err) console.error(err.message);
  4160. * // configs is now a map of JSON data
  4161. * doSomethingWith(configs);
  4162. * });
  4163. */
  4164. var eachOf = function(coll, iteratee, callback) {
  4165. var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
  4166. eachOfImplementation(coll, wrapAsync(iteratee), callback);
  4167. };
  4168. function doParallel(fn) {
  4169. return function (obj, iteratee, callback) {
  4170. return fn(eachOf, obj, wrapAsync(iteratee), callback);
  4171. };
  4172. }
  4173. function _asyncMap(eachfn, arr, iteratee, callback) {
  4174. callback = callback || noop;
  4175. arr = arr || [];
  4176. var results = [];
  4177. var counter = 0;
  4178. var _iteratee = wrapAsync(iteratee);
  4179. eachfn(arr, function (value, _, callback) {
  4180. var index = counter++;
  4181. _iteratee(value, function (err, v) {
  4182. results[index] = v;
  4183. callback(err);
  4184. });
  4185. }, function (err) {
  4186. callback(err, results);
  4187. });
  4188. }
  4189. /**
  4190. * Produces a new collection of values by mapping each value in `coll` through
  4191. * the `iteratee` function. The `iteratee` is called with an item from `coll`
  4192. * and a callback for when it has finished processing. Each of these callback
  4193. * takes 2 arguments: an `error`, and the transformed item from `coll`. If
  4194. * `iteratee` passes an error to its callback, the main `callback` (for the
  4195. * `map` function) is immediately called with the error.
  4196. *
  4197. * Note, that since this function applies the `iteratee` to each item in
  4198. * parallel, there is no guarantee that the `iteratee` functions will complete
  4199. * in order. However, the results array will be in the same order as the
  4200. * original `coll`.
  4201. *
  4202. * If `map` is passed an Object, the results will be an Array. The results
  4203. * will roughly be in the order of the original Objects' keys (but this can
  4204. * vary across JavaScript engines).
  4205. *
  4206. * @name map
  4207. * @static
  4208. * @memberOf module:Collections
  4209. * @method
  4210. * @category Collection
  4211. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4212. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  4213. * `coll`.
  4214. * The iteratee should complete with the transformed item.
  4215. * Invoked with (item, callback).
  4216. * @param {Function} [callback] - A callback which is called when all `iteratee`
  4217. * functions have finished, or an error occurs. Results is an Array of the
  4218. * transformed items from the `coll`. Invoked with (err, results).
  4219. * @example
  4220. *
  4221. * async.map(['file1','file2','file3'], fs.stat, function(err, results) {
  4222. * // results is now an array of stats for each file
  4223. * });
  4224. */
  4225. var map = doParallel(_asyncMap);
  4226. /**
  4227. * Applies the provided arguments to each function in the array, calling
  4228. * `callback` after all functions have completed. If you only provide the first
  4229. * argument, `fns`, then it will return a function which lets you pass in the
  4230. * arguments as if it were a single function call. If more arguments are
  4231. * provided, `callback` is required while `args` is still optional.
  4232. *
  4233. * @name applyEach
  4234. * @static
  4235. * @memberOf module:ControlFlow
  4236. * @method
  4237. * @category Control Flow
  4238. * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s
  4239. * to all call with the same arguments
  4240. * @param {...*} [args] - any number of separate arguments to pass to the
  4241. * function.
  4242. * @param {Function} [callback] - the final argument should be the callback,
  4243. * called when all functions have completed processing.
  4244. * @returns {Function} - If only the first argument, `fns`, is provided, it will
  4245. * return a function which lets you pass in the arguments as if it were a single
  4246. * function call. The signature is `(..args, callback)`. If invoked with any
  4247. * arguments, `callback` is required.
  4248. * @example
  4249. *
  4250. * async.applyEach([enableSearch, updateSchema], 'bucket', callback);
  4251. *
  4252. * // partial application example:
  4253. * async.each(
  4254. * buckets,
  4255. * async.applyEach([enableSearch, updateSchema]),
  4256. * callback
  4257. * );
  4258. */
  4259. var applyEach = applyEach$1(map);
  4260. function doParallelLimit(fn) {
  4261. return function (obj, limit, iteratee, callback) {
  4262. return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback);
  4263. };
  4264. }
  4265. /**
  4266. * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
  4267. *
  4268. * @name mapLimit
  4269. * @static
  4270. * @memberOf module:Collections
  4271. * @method
  4272. * @see [async.map]{@link module:Collections.map}
  4273. * @category Collection
  4274. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4275. * @param {number} limit - The maximum number of async operations at a time.
  4276. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  4277. * `coll`.
  4278. * The iteratee should complete with the transformed item.
  4279. * Invoked with (item, callback).
  4280. * @param {Function} [callback] - A callback which is called when all `iteratee`
  4281. * functions have finished, or an error occurs. Results is an array of the
  4282. * transformed items from the `coll`. Invoked with (err, results).
  4283. */
  4284. var mapLimit = doParallelLimit(_asyncMap);
  4285. /**
  4286. * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
  4287. *
  4288. * @name mapSeries
  4289. * @static
  4290. * @memberOf module:Collections
  4291. * @method
  4292. * @see [async.map]{@link module:Collections.map}
  4293. * @category Collection
  4294. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4295. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  4296. * `coll`.
  4297. * The iteratee should complete with the transformed item.
  4298. * Invoked with (item, callback).
  4299. * @param {Function} [callback] - A callback which is called when all `iteratee`
  4300. * functions have finished, or an error occurs. Results is an array of the
  4301. * transformed items from the `coll`. Invoked with (err, results).
  4302. */
  4303. var mapSeries = doLimit(mapLimit, 1);
  4304. /**
  4305. * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
  4306. *
  4307. * @name applyEachSeries
  4308. * @static
  4309. * @memberOf module:ControlFlow
  4310. * @method
  4311. * @see [async.applyEach]{@link module:ControlFlow.applyEach}
  4312. * @category Control Flow
  4313. * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all
  4314. * call with the same arguments
  4315. * @param {...*} [args] - any number of separate arguments to pass to the
  4316. * function.
  4317. * @param {Function} [callback] - the final argument should be the callback,
  4318. * called when all functions have completed processing.
  4319. * @returns {Function} - If only the first argument is provided, it will return
  4320. * a function which lets you pass in the arguments as if it were a single
  4321. * function call.
  4322. */
  4323. var applyEachSeries = applyEach$1(mapSeries);
  4324. /**
  4325. * A specialized version of `_.forEach` for arrays without support for
  4326. * iteratee shorthands.
  4327. *
  4328. * @private
  4329. * @param {Array} [array] The array to iterate over.
  4330. * @param {Function} iteratee The function invoked per iteration.
  4331. * @returns {Array} Returns `array`.
  4332. */
  4333. function arrayEach(array, iteratee) {
  4334. var index = -1,
  4335. length = array == null ? 0 : array.length;
  4336. while (++index < length) {
  4337. if (iteratee(array[index], index, array) === false) {
  4338. break;
  4339. }
  4340. }
  4341. return array;
  4342. }
  4343. /**
  4344. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  4345. *
  4346. * @private
  4347. * @param {boolean} [fromRight] Specify iterating from right to left.
  4348. * @returns {Function} Returns the new base function.
  4349. */
  4350. function createBaseFor(fromRight) {
  4351. return function(object, iteratee, keysFunc) {
  4352. var index = -1,
  4353. iterable = Object(object),
  4354. props = keysFunc(object),
  4355. length = props.length;
  4356. while (length--) {
  4357. var key = props[fromRight ? length : ++index];
  4358. if (iteratee(iterable[key], key, iterable) === false) {
  4359. break;
  4360. }
  4361. }
  4362. return object;
  4363. };
  4364. }
  4365. /**
  4366. * The base implementation of `baseForOwn` which iterates over `object`
  4367. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  4368. * Iteratee functions may exit iteration early by explicitly returning `false`.
  4369. *
  4370. * @private
  4371. * @param {Object} object The object to iterate over.
  4372. * @param {Function} iteratee The function invoked per iteration.
  4373. * @param {Function} keysFunc The function to get the keys of `object`.
  4374. * @returns {Object} Returns `object`.
  4375. */
  4376. var baseFor = createBaseFor();
  4377. /**
  4378. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  4379. *
  4380. * @private
  4381. * @param {Object} object The object to iterate over.
  4382. * @param {Function} iteratee The function invoked per iteration.
  4383. * @returns {Object} Returns `object`.
  4384. */
  4385. function baseForOwn(object, iteratee) {
  4386. return object && baseFor(object, iteratee, keys);
  4387. }
  4388. /**
  4389. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  4390. * support for iteratee shorthands.
  4391. *
  4392. * @private
  4393. * @param {Array} array The array to inspect.
  4394. * @param {Function} predicate The function invoked per iteration.
  4395. * @param {number} fromIndex The index to search from.
  4396. * @param {boolean} [fromRight] Specify iterating from right to left.
  4397. * @returns {number} Returns the index of the matched value, else `-1`.
  4398. */
  4399. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  4400. var length = array.length,
  4401. index = fromIndex + (fromRight ? 1 : -1);
  4402. while ((fromRight ? index-- : ++index < length)) {
  4403. if (predicate(array[index], index, array)) {
  4404. return index;
  4405. }
  4406. }
  4407. return -1;
  4408. }
  4409. /**
  4410. * The base implementation of `_.isNaN` without support for number objects.
  4411. *
  4412. * @private
  4413. * @param {*} value The value to check.
  4414. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  4415. */
  4416. function baseIsNaN(value) {
  4417. return value !== value;
  4418. }
  4419. /**
  4420. * A specialized version of `_.indexOf` which performs strict equality
  4421. * comparisons of values, i.e. `===`.
  4422. *
  4423. * @private
  4424. * @param {Array} array The array to inspect.
  4425. * @param {*} value The value to search for.
  4426. * @param {number} fromIndex The index to search from.
  4427. * @returns {number} Returns the index of the matched value, else `-1`.
  4428. */
  4429. function strictIndexOf(array, value, fromIndex) {
  4430. var index = fromIndex - 1,
  4431. length = array.length;
  4432. while (++index < length) {
  4433. if (array[index] === value) {
  4434. return index;
  4435. }
  4436. }
  4437. return -1;
  4438. }
  4439. /**
  4440. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  4441. *
  4442. * @private
  4443. * @param {Array} array The array to inspect.
  4444. * @param {*} value The value to search for.
  4445. * @param {number} fromIndex The index to search from.
  4446. * @returns {number} Returns the index of the matched value, else `-1`.
  4447. */
  4448. function baseIndexOf(array, value, fromIndex) {
  4449. return value === value
  4450. ? strictIndexOf(array, value, fromIndex)
  4451. : baseFindIndex(array, baseIsNaN, fromIndex);
  4452. }
  4453. /**
  4454. * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
  4455. * their requirements. Each function can optionally depend on other functions
  4456. * being completed first, and each function is run as soon as its requirements
  4457. * are satisfied.
  4458. *
  4459. * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
  4460. * will stop. Further tasks will not execute (so any other functions depending
  4461. * on it will not run), and the main `callback` is immediately called with the
  4462. * error.
  4463. *
  4464. * {@link AsyncFunction}s also receive an object containing the results of functions which
  4465. * have completed so far as the first argument, if they have dependencies. If a
  4466. * task function has no dependencies, it will only be passed a callback.
  4467. *
  4468. * @name auto
  4469. * @static
  4470. * @memberOf module:ControlFlow
  4471. * @method
  4472. * @category Control Flow
  4473. * @param {Object} tasks - An object. Each of its properties is either a
  4474. * function or an array of requirements, with the {@link AsyncFunction} itself the last item
  4475. * in the array. The object's key of a property serves as the name of the task
  4476. * defined by that property, i.e. can be used when specifying requirements for
  4477. * other tasks. The function receives one or two arguments:
  4478. * * a `results` object, containing the results of the previously executed
  4479. * functions, only passed if the task has any dependencies,
  4480. * * a `callback(err, result)` function, which must be called when finished,
  4481. * passing an `error` (which can be `null`) and the result of the function's
  4482. * execution.
  4483. * @param {number} [concurrency=Infinity] - An optional `integer` for
  4484. * determining the maximum number of tasks that can be run in parallel. By
  4485. * default, as many as possible.
  4486. * @param {Function} [callback] - An optional callback which is called when all
  4487. * the tasks have been completed. It receives the `err` argument if any `tasks`
  4488. * pass an error to their callback. Results are always returned; however, if an
  4489. * error occurs, no further `tasks` will be performed, and the results object
  4490. * will only contain partial results. Invoked with (err, results).
  4491. * @returns undefined
  4492. * @example
  4493. *
  4494. * async.auto({
  4495. * // this function will just be passed a callback
  4496. * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
  4497. * showData: ['readData', function(results, cb) {
  4498. * // results.readData is the file's contents
  4499. * // ...
  4500. * }]
  4501. * }, callback);
  4502. *
  4503. * async.auto({
  4504. * get_data: function(callback) {
  4505. * console.log('in get_data');
  4506. * // async code to get some data
  4507. * callback(null, 'data', 'converted to array');
  4508. * },
  4509. * make_folder: function(callback) {
  4510. * console.log('in make_folder');
  4511. * // async code to create a directory to store a file in
  4512. * // this is run at the same time as getting the data
  4513. * callback(null, 'folder');
  4514. * },
  4515. * write_file: ['get_data', 'make_folder', function(results, callback) {
  4516. * console.log('in write_file', JSON.stringify(results));
  4517. * // once there is some data and the directory exists,
  4518. * // write the data to a file in the directory
  4519. * callback(null, 'filename');
  4520. * }],
  4521. * email_link: ['write_file', function(results, callback) {
  4522. * console.log('in email_link', JSON.stringify(results));
  4523. * // once the file is written let's email a link to it...
  4524. * // results.write_file contains the filename returned by write_file.
  4525. * callback(null, {'file':results.write_file, 'email':'user@example.com'});
  4526. * }]
  4527. * }, function(err, results) {
  4528. * console.log('err = ', err);
  4529. * console.log('results = ', results);
  4530. * });
  4531. */
  4532. var auto = function (tasks, concurrency, callback) {
  4533. if (typeof concurrency === 'function') {
  4534. // concurrency is optional, shift the args.
  4535. callback = concurrency;
  4536. concurrency = null;
  4537. }
  4538. callback = once(callback || noop);
  4539. var keys$$1 = keys(tasks);
  4540. var numTasks = keys$$1.length;
  4541. if (!numTasks) {
  4542. return callback(null);
  4543. }
  4544. if (!concurrency) {
  4545. concurrency = numTasks;
  4546. }
  4547. var results = {};
  4548. var runningTasks = 0;
  4549. var hasError = false;
  4550. var listeners = Object.create(null);
  4551. var readyTasks = [];
  4552. // for cycle detection:
  4553. var readyToCheck = []; // tasks that have been identified as reachable
  4554. // without the possibility of returning to an ancestor task
  4555. var uncheckedDependencies = {};
  4556. baseForOwn(tasks, function (task, key) {
  4557. if (!isArray(task)) {
  4558. // no dependencies
  4559. enqueueTask(key, [task]);
  4560. readyToCheck.push(key);
  4561. return;
  4562. }
  4563. var dependencies = task.slice(0, task.length - 1);
  4564. var remainingDependencies = dependencies.length;
  4565. if (remainingDependencies === 0) {
  4566. enqueueTask(key, task);
  4567. readyToCheck.push(key);
  4568. return;
  4569. }
  4570. uncheckedDependencies[key] = remainingDependencies;
  4571. arrayEach(dependencies, function (dependencyName) {
  4572. if (!tasks[dependencyName]) {
  4573. throw new Error('async.auto task `' + key +
  4574. '` has a non-existent dependency `' +
  4575. dependencyName + '` in ' +
  4576. dependencies.join(', '));
  4577. }
  4578. addListener(dependencyName, function () {
  4579. remainingDependencies--;
  4580. if (remainingDependencies === 0) {
  4581. enqueueTask(key, task);
  4582. }
  4583. });
  4584. });
  4585. });
  4586. checkForDeadlocks();
  4587. processQueue();
  4588. function enqueueTask(key, task) {
  4589. readyTasks.push(function () {
  4590. runTask(key, task);
  4591. });
  4592. }
  4593. function processQueue() {
  4594. if (readyTasks.length === 0 && runningTasks === 0) {
  4595. return callback(null, results);
  4596. }
  4597. while(readyTasks.length && runningTasks < concurrency) {
  4598. var run = readyTasks.shift();
  4599. run();
  4600. }
  4601. }
  4602. function addListener(taskName, fn) {
  4603. var taskListeners = listeners[taskName];
  4604. if (!taskListeners) {
  4605. taskListeners = listeners[taskName] = [];
  4606. }
  4607. taskListeners.push(fn);
  4608. }
  4609. function taskComplete(taskName) {
  4610. var taskListeners = listeners[taskName] || [];
  4611. arrayEach(taskListeners, function (fn) {
  4612. fn();
  4613. });
  4614. processQueue();
  4615. }
  4616. function runTask(key, task) {
  4617. if (hasError) return;
  4618. var taskCallback = onlyOnce(function(err, result) {
  4619. runningTasks--;
  4620. if (arguments.length > 2) {
  4621. result = slice(arguments, 1);
  4622. }
  4623. if (err) {
  4624. var safeResults = {};
  4625. baseForOwn(results, function(val, rkey) {
  4626. safeResults[rkey] = val;
  4627. });
  4628. safeResults[key] = result;
  4629. hasError = true;
  4630. listeners = Object.create(null);
  4631. callback(err, safeResults);
  4632. } else {
  4633. results[key] = result;
  4634. taskComplete(key);
  4635. }
  4636. });
  4637. runningTasks++;
  4638. var taskFn = wrapAsync(task[task.length - 1]);
  4639. if (task.length > 1) {
  4640. taskFn(results, taskCallback);
  4641. } else {
  4642. taskFn(taskCallback);
  4643. }
  4644. }
  4645. function checkForDeadlocks() {
  4646. // Kahn's algorithm
  4647. // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
  4648. // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
  4649. var currentTask;
  4650. var counter = 0;
  4651. while (readyToCheck.length) {
  4652. currentTask = readyToCheck.pop();
  4653. counter++;
  4654. arrayEach(getDependents(currentTask), function (dependent) {
  4655. if (--uncheckedDependencies[dependent] === 0) {
  4656. readyToCheck.push(dependent);
  4657. }
  4658. });
  4659. }
  4660. if (counter !== numTasks) {
  4661. throw new Error(
  4662. 'async.auto cannot execute tasks due to a recursive dependency'
  4663. );
  4664. }
  4665. }
  4666. function getDependents(taskName) {
  4667. var result = [];
  4668. baseForOwn(tasks, function (task, key) {
  4669. if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) {
  4670. result.push(key);
  4671. }
  4672. });
  4673. return result;
  4674. }
  4675. };
  4676. /**
  4677. * A specialized version of `_.map` for arrays without support for iteratee
  4678. * shorthands.
  4679. *
  4680. * @private
  4681. * @param {Array} [array] The array to iterate over.
  4682. * @param {Function} iteratee The function invoked per iteration.
  4683. * @returns {Array} Returns the new mapped array.
  4684. */
  4685. function arrayMap(array, iteratee) {
  4686. var index = -1,
  4687. length = array == null ? 0 : array.length,
  4688. result = Array(length);
  4689. while (++index < length) {
  4690. result[index] = iteratee(array[index], index, array);
  4691. }
  4692. return result;
  4693. }
  4694. /** `Object#toString` result references. */
  4695. var symbolTag = '[object Symbol]';
  4696. /**
  4697. * Checks if `value` is classified as a `Symbol` primitive or object.
  4698. *
  4699. * @static
  4700. * @memberOf _
  4701. * @since 4.0.0
  4702. * @category Lang
  4703. * @param {*} value The value to check.
  4704. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  4705. * @example
  4706. *
  4707. * _.isSymbol(Symbol.iterator);
  4708. * // => true
  4709. *
  4710. * _.isSymbol('abc');
  4711. * // => false
  4712. */
  4713. function isSymbol(value) {
  4714. return typeof value == 'symbol' ||
  4715. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  4716. }
  4717. /** Used as references for various `Number` constants. */
  4718. var INFINITY = 1 / 0;
  4719. /** Used to convert symbols to primitives and strings. */
  4720. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined;
  4721. var symbolToString = symbolProto ? symbolProto.toString : undefined;
  4722. /**
  4723. * The base implementation of `_.toString` which doesn't convert nullish
  4724. * values to empty strings.
  4725. *
  4726. * @private
  4727. * @param {*} value The value to process.
  4728. * @returns {string} Returns the string.
  4729. */
  4730. function baseToString(value) {
  4731. // Exit early for strings to avoid a performance hit in some environments.
  4732. if (typeof value == 'string') {
  4733. return value;
  4734. }
  4735. if (isArray(value)) {
  4736. // Recursively convert values (susceptible to call stack limits).
  4737. return arrayMap(value, baseToString) + '';
  4738. }
  4739. if (isSymbol(value)) {
  4740. return symbolToString ? symbolToString.call(value) : '';
  4741. }
  4742. var result = (value + '');
  4743. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  4744. }
  4745. /**
  4746. * The base implementation of `_.slice` without an iteratee call guard.
  4747. *
  4748. * @private
  4749. * @param {Array} array The array to slice.
  4750. * @param {number} [start=0] The start position.
  4751. * @param {number} [end=array.length] The end position.
  4752. * @returns {Array} Returns the slice of `array`.
  4753. */
  4754. function baseSlice(array, start, end) {
  4755. var index = -1,
  4756. length = array.length;
  4757. if (start < 0) {
  4758. start = -start > length ? 0 : (length + start);
  4759. }
  4760. end = end > length ? length : end;
  4761. if (end < 0) {
  4762. end += length;
  4763. }
  4764. length = start > end ? 0 : ((end - start) >>> 0);
  4765. start >>>= 0;
  4766. var result = Array(length);
  4767. while (++index < length) {
  4768. result[index] = array[index + start];
  4769. }
  4770. return result;
  4771. }
  4772. /**
  4773. * Casts `array` to a slice if it's needed.
  4774. *
  4775. * @private
  4776. * @param {Array} array The array to inspect.
  4777. * @param {number} start The start position.
  4778. * @param {number} [end=array.length] The end position.
  4779. * @returns {Array} Returns the cast slice.
  4780. */
  4781. function castSlice(array, start, end) {
  4782. var length = array.length;
  4783. end = end === undefined ? length : end;
  4784. return (!start && end >= length) ? array : baseSlice(array, start, end);
  4785. }
  4786. /**
  4787. * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
  4788. * that is not found in the character symbols.
  4789. *
  4790. * @private
  4791. * @param {Array} strSymbols The string symbols to inspect.
  4792. * @param {Array} chrSymbols The character symbols to find.
  4793. * @returns {number} Returns the index of the last unmatched string symbol.
  4794. */
  4795. function charsEndIndex(strSymbols, chrSymbols) {
  4796. var index = strSymbols.length;
  4797. while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  4798. return index;
  4799. }
  4800. /**
  4801. * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
  4802. * that is not found in the character symbols.
  4803. *
  4804. * @private
  4805. * @param {Array} strSymbols The string symbols to inspect.
  4806. * @param {Array} chrSymbols The character symbols to find.
  4807. * @returns {number} Returns the index of the first unmatched string symbol.
  4808. */
  4809. function charsStartIndex(strSymbols, chrSymbols) {
  4810. var index = -1,
  4811. length = strSymbols.length;
  4812. while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  4813. return index;
  4814. }
  4815. /**
  4816. * Converts an ASCII `string` to an array.
  4817. *
  4818. * @private
  4819. * @param {string} string The string to convert.
  4820. * @returns {Array} Returns the converted array.
  4821. */
  4822. function asciiToArray(string) {
  4823. return string.split('');
  4824. }
  4825. /** Used to compose unicode character classes. */
  4826. var rsAstralRange = '\\ud800-\\udfff';
  4827. var rsComboMarksRange = '\\u0300-\\u036f';
  4828. var reComboHalfMarksRange = '\\ufe20-\\ufe2f';
  4829. var rsComboSymbolsRange = '\\u20d0-\\u20ff';
  4830. var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
  4831. var rsVarRange = '\\ufe0e\\ufe0f';
  4832. /** Used to compose unicode capture groups. */
  4833. var rsZWJ = '\\u200d';
  4834. /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  4835. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
  4836. /**
  4837. * Checks if `string` contains Unicode symbols.
  4838. *
  4839. * @private
  4840. * @param {string} string The string to inspect.
  4841. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  4842. */
  4843. function hasUnicode(string) {
  4844. return reHasUnicode.test(string);
  4845. }
  4846. /** Used to compose unicode character classes. */
  4847. var rsAstralRange$1 = '\\ud800-\\udfff';
  4848. var rsComboMarksRange$1 = '\\u0300-\\u036f';
  4849. var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f';
  4850. var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff';
  4851. var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
  4852. var rsVarRange$1 = '\\ufe0e\\ufe0f';
  4853. /** Used to compose unicode capture groups. */
  4854. var rsAstral = '[' + rsAstralRange$1 + ']';
  4855. var rsCombo = '[' + rsComboRange$1 + ']';
  4856. var rsFitz = '\\ud83c[\\udffb-\\udfff]';
  4857. var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';
  4858. var rsNonAstral = '[^' + rsAstralRange$1 + ']';
  4859. var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}';
  4860. var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]';
  4861. var rsZWJ$1 = '\\u200d';
  4862. /** Used to compose unicode regexes. */
  4863. var reOptMod = rsModifier + '?';
  4864. var rsOptVar = '[' + rsVarRange$1 + ']?';
  4865. var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';
  4866. var rsSeq = rsOptVar + reOptMod + rsOptJoin;
  4867. var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  4868. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  4869. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  4870. /**
  4871. * Converts a Unicode `string` to an array.
  4872. *
  4873. * @private
  4874. * @param {string} string The string to convert.
  4875. * @returns {Array} Returns the converted array.
  4876. */
  4877. function unicodeToArray(string) {
  4878. return string.match(reUnicode) || [];
  4879. }
  4880. /**
  4881. * Converts `string` to an array.
  4882. *
  4883. * @private
  4884. * @param {string} string The string to convert.
  4885. * @returns {Array} Returns the converted array.
  4886. */
  4887. function stringToArray(string) {
  4888. return hasUnicode(string)
  4889. ? unicodeToArray(string)
  4890. : asciiToArray(string);
  4891. }
  4892. /**
  4893. * Converts `value` to a string. An empty string is returned for `null`
  4894. * and `undefined` values. The sign of `-0` is preserved.
  4895. *
  4896. * @static
  4897. * @memberOf _
  4898. * @since 4.0.0
  4899. * @category Lang
  4900. * @param {*} value The value to convert.
  4901. * @returns {string} Returns the converted string.
  4902. * @example
  4903. *
  4904. * _.toString(null);
  4905. * // => ''
  4906. *
  4907. * _.toString(-0);
  4908. * // => '-0'
  4909. *
  4910. * _.toString([1, 2, 3]);
  4911. * // => '1,2,3'
  4912. */
  4913. function toString(value) {
  4914. return value == null ? '' : baseToString(value);
  4915. }
  4916. /** Used to match leading and trailing whitespace. */
  4917. var reTrim = /^\s+|\s+$/g;
  4918. /**
  4919. * Removes leading and trailing whitespace or specified characters from `string`.
  4920. *
  4921. * @static
  4922. * @memberOf _
  4923. * @since 3.0.0
  4924. * @category String
  4925. * @param {string} [string=''] The string to trim.
  4926. * @param {string} [chars=whitespace] The characters to trim.
  4927. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  4928. * @returns {string} Returns the trimmed string.
  4929. * @example
  4930. *
  4931. * _.trim(' abc ');
  4932. * // => 'abc'
  4933. *
  4934. * _.trim('-_-abc-_-', '_-');
  4935. * // => 'abc'
  4936. *
  4937. * _.map([' foo ', ' bar '], _.trim);
  4938. * // => ['foo', 'bar']
  4939. */
  4940. function trim(string, chars, guard) {
  4941. string = toString(string);
  4942. if (string && (guard || chars === undefined)) {
  4943. return string.replace(reTrim, '');
  4944. }
  4945. if (!string || !(chars = baseToString(chars))) {
  4946. return string;
  4947. }
  4948. var strSymbols = stringToArray(string),
  4949. chrSymbols = stringToArray(chars),
  4950. start = charsStartIndex(strSymbols, chrSymbols),
  4951. end = charsEndIndex(strSymbols, chrSymbols) + 1;
  4952. return castSlice(strSymbols, start, end).join('');
  4953. }
  4954. var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m;
  4955. var FN_ARG_SPLIT = /,/;
  4956. var FN_ARG = /(=.+)?(\s*)$/;
  4957. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  4958. function parseParams(func) {
  4959. func = func.toString().replace(STRIP_COMMENTS, '');
  4960. func = func.match(FN_ARGS)[2].replace(' ', '');
  4961. func = func ? func.split(FN_ARG_SPLIT) : [];
  4962. func = func.map(function (arg){
  4963. return trim(arg.replace(FN_ARG, ''));
  4964. });
  4965. return func;
  4966. }
  4967. /**
  4968. * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
  4969. * tasks are specified as parameters to the function, after the usual callback
  4970. * parameter, with the parameter names matching the names of the tasks it
  4971. * depends on. This can provide even more readable task graphs which can be
  4972. * easier to maintain.
  4973. *
  4974. * If a final callback is specified, the task results are similarly injected,
  4975. * specified as named parameters after the initial error parameter.
  4976. *
  4977. * The autoInject function is purely syntactic sugar and its semantics are
  4978. * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
  4979. *
  4980. * @name autoInject
  4981. * @static
  4982. * @memberOf module:ControlFlow
  4983. * @method
  4984. * @see [async.auto]{@link module:ControlFlow.auto}
  4985. * @category Control Flow
  4986. * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
  4987. * the form 'func([dependencies...], callback). The object's key of a property
  4988. * serves as the name of the task defined by that property, i.e. can be used
  4989. * when specifying requirements for other tasks.
  4990. * * The `callback` parameter is a `callback(err, result)` which must be called
  4991. * when finished, passing an `error` (which can be `null`) and the result of
  4992. * the function's execution. The remaining parameters name other tasks on
  4993. * which the task is dependent, and the results from those tasks are the
  4994. * arguments of those parameters.
  4995. * @param {Function} [callback] - An optional callback which is called when all
  4996. * the tasks have been completed. It receives the `err` argument if any `tasks`
  4997. * pass an error to their callback, and a `results` object with any completed
  4998. * task results, similar to `auto`.
  4999. * @example
  5000. *
  5001. * // The example from `auto` can be rewritten as follows:
  5002. * async.autoInject({
  5003. * get_data: function(callback) {
  5004. * // async code to get some data
  5005. * callback(null, 'data', 'converted to array');
  5006. * },
  5007. * make_folder: function(callback) {
  5008. * // async code to create a directory to store a file in
  5009. * // this is run at the same time as getting the data
  5010. * callback(null, 'folder');
  5011. * },
  5012. * write_file: function(get_data, make_folder, callback) {
  5013. * // once there is some data and the directory exists,
  5014. * // write the data to a file in the directory
  5015. * callback(null, 'filename');
  5016. * },
  5017. * email_link: function(write_file, callback) {
  5018. * // once the file is written let's email a link to it...
  5019. * // write_file contains the filename returned by write_file.
  5020. * callback(null, {'file':write_file, 'email':'user@example.com'});
  5021. * }
  5022. * }, function(err, results) {
  5023. * console.log('err = ', err);
  5024. * console.log('email_link = ', results.email_link);
  5025. * });
  5026. *
  5027. * // If you are using a JS minifier that mangles parameter names, `autoInject`
  5028. * // will not work with plain functions, since the parameter names will be
  5029. * // collapsed to a single letter identifier. To work around this, you can
  5030. * // explicitly specify the names of the parameters your task function needs
  5031. * // in an array, similar to Angular.js dependency injection.
  5032. *
  5033. * // This still has an advantage over plain `auto`, since the results a task
  5034. * // depends on are still spread into arguments.
  5035. * async.autoInject({
  5036. * //...
  5037. * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
  5038. * callback(null, 'filename');
  5039. * }],
  5040. * email_link: ['write_file', function(write_file, callback) {
  5041. * callback(null, {'file':write_file, 'email':'user@example.com'});
  5042. * }]
  5043. * //...
  5044. * }, function(err, results) {
  5045. * console.log('err = ', err);
  5046. * console.log('email_link = ', results.email_link);
  5047. * });
  5048. */
  5049. function autoInject(tasks, callback) {
  5050. var newTasks = {};
  5051. baseForOwn(tasks, function (taskFn, key) {
  5052. var params;
  5053. var fnIsAsync = isAsync(taskFn);
  5054. var hasNoDeps =
  5055. (!fnIsAsync && taskFn.length === 1) ||
  5056. (fnIsAsync && taskFn.length === 0);
  5057. if (isArray(taskFn)) {
  5058. params = taskFn.slice(0, -1);
  5059. taskFn = taskFn[taskFn.length - 1];
  5060. newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
  5061. } else if (hasNoDeps) {
  5062. // no dependencies, use the function as-is
  5063. newTasks[key] = taskFn;
  5064. } else {
  5065. params = parseParams(taskFn);
  5066. if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
  5067. throw new Error("autoInject task functions require explicit parameters.");
  5068. }
  5069. // remove callback param
  5070. if (!fnIsAsync) params.pop();
  5071. newTasks[key] = params.concat(newTask);
  5072. }
  5073. function newTask(results, taskCb) {
  5074. var newArgs = arrayMap(params, function (name) {
  5075. return results[name];
  5076. });
  5077. newArgs.push(taskCb);
  5078. wrapAsync(taskFn).apply(null, newArgs);
  5079. }
  5080. });
  5081. auto(newTasks, callback);
  5082. }
  5083. // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
  5084. // used for queues. This implementation assumes that the node provided by the user can be modified
  5085. // to adjust the next and last properties. We implement only the minimal functionality
  5086. // for queue support.
  5087. function DLL() {
  5088. this.head = this.tail = null;
  5089. this.length = 0;
  5090. }
  5091. function setInitial(dll, node) {
  5092. dll.length = 1;
  5093. dll.head = dll.tail = node;
  5094. }
  5095. DLL.prototype.removeLink = function(node) {
  5096. if (node.prev) node.prev.next = node.next;
  5097. else this.head = node.next;
  5098. if (node.next) node.next.prev = node.prev;
  5099. else this.tail = node.prev;
  5100. node.prev = node.next = null;
  5101. this.length -= 1;
  5102. return node;
  5103. };
  5104. DLL.prototype.empty = function () {
  5105. while(this.head) this.shift();
  5106. return this;
  5107. };
  5108. DLL.prototype.insertAfter = function(node, newNode) {
  5109. newNode.prev = node;
  5110. newNode.next = node.next;
  5111. if (node.next) node.next.prev = newNode;
  5112. else this.tail = newNode;
  5113. node.next = newNode;
  5114. this.length += 1;
  5115. };
  5116. DLL.prototype.insertBefore = function(node, newNode) {
  5117. newNode.prev = node.prev;
  5118. newNode.next = node;
  5119. if (node.prev) node.prev.next = newNode;
  5120. else this.head = newNode;
  5121. node.prev = newNode;
  5122. this.length += 1;
  5123. };
  5124. DLL.prototype.unshift = function(node) {
  5125. if (this.head) this.insertBefore(this.head, node);
  5126. else setInitial(this, node);
  5127. };
  5128. DLL.prototype.push = function(node) {
  5129. if (this.tail) this.insertAfter(this.tail, node);
  5130. else setInitial(this, node);
  5131. };
  5132. DLL.prototype.shift = function() {
  5133. return this.head && this.removeLink(this.head);
  5134. };
  5135. DLL.prototype.pop = function() {
  5136. return this.tail && this.removeLink(this.tail);
  5137. };
  5138. DLL.prototype.toArray = function () {
  5139. var arr = Array(this.length);
  5140. var curr = this.head;
  5141. for(var idx = 0; idx < this.length; idx++) {
  5142. arr[idx] = curr.data;
  5143. curr = curr.next;
  5144. }
  5145. return arr;
  5146. };
  5147. DLL.prototype.remove = function (testFn) {
  5148. var curr = this.head;
  5149. while(!!curr) {
  5150. var next = curr.next;
  5151. if (testFn(curr)) {
  5152. this.removeLink(curr);
  5153. }
  5154. curr = next;
  5155. }
  5156. return this;
  5157. };
  5158. function queue(worker, concurrency, payload) {
  5159. if (concurrency == null) {
  5160. concurrency = 1;
  5161. }
  5162. else if(concurrency === 0) {
  5163. throw new Error('Concurrency must not be zero');
  5164. }
  5165. var _worker = wrapAsync(worker);
  5166. var numRunning = 0;
  5167. var workersList = [];
  5168. var processingScheduled = false;
  5169. function _insert(data, insertAtFront, callback) {
  5170. if (callback != null && typeof callback !== 'function') {
  5171. throw new Error('task callback must be a function');
  5172. }
  5173. q.started = true;
  5174. if (!isArray(data)) {
  5175. data = [data];
  5176. }
  5177. if (data.length === 0 && q.idle()) {
  5178. // call drain immediately if there are no tasks
  5179. return setImmediate$1(function() {
  5180. q.drain();
  5181. });
  5182. }
  5183. for (var i = 0, l = data.length; i < l; i++) {
  5184. var item = {
  5185. data: data[i],
  5186. callback: callback || noop
  5187. };
  5188. if (insertAtFront) {
  5189. q._tasks.unshift(item);
  5190. } else {
  5191. q._tasks.push(item);
  5192. }
  5193. }
  5194. if (!processingScheduled) {
  5195. processingScheduled = true;
  5196. setImmediate$1(function() {
  5197. processingScheduled = false;
  5198. q.process();
  5199. });
  5200. }
  5201. }
  5202. function _next(tasks) {
  5203. return function(err){
  5204. numRunning -= 1;
  5205. for (var i = 0, l = tasks.length; i < l; i++) {
  5206. var task = tasks[i];
  5207. var index = baseIndexOf(workersList, task, 0);
  5208. if (index === 0) {
  5209. workersList.shift();
  5210. } else if (index > 0) {
  5211. workersList.splice(index, 1);
  5212. }
  5213. task.callback.apply(task, arguments);
  5214. if (err != null) {
  5215. q.error(err, task.data);
  5216. }
  5217. }
  5218. if (numRunning <= (q.concurrency - q.buffer) ) {
  5219. q.unsaturated();
  5220. }
  5221. if (q.idle()) {
  5222. q.drain();
  5223. }
  5224. q.process();
  5225. };
  5226. }
  5227. var isProcessing = false;
  5228. var q = {
  5229. _tasks: new DLL(),
  5230. concurrency: concurrency,
  5231. payload: payload,
  5232. saturated: noop,
  5233. unsaturated:noop,
  5234. buffer: concurrency / 4,
  5235. empty: noop,
  5236. drain: noop,
  5237. error: noop,
  5238. started: false,
  5239. paused: false,
  5240. push: function (data, callback) {
  5241. _insert(data, false, callback);
  5242. },
  5243. kill: function () {
  5244. q.drain = noop;
  5245. q._tasks.empty();
  5246. },
  5247. unshift: function (data, callback) {
  5248. _insert(data, true, callback);
  5249. },
  5250. remove: function (testFn) {
  5251. q._tasks.remove(testFn);
  5252. },
  5253. process: function () {
  5254. // Avoid trying to start too many processing operations. This can occur
  5255. // when callbacks resolve synchronously (#1267).
  5256. if (isProcessing) {
  5257. return;
  5258. }
  5259. isProcessing = true;
  5260. while(!q.paused && numRunning < q.concurrency && q._tasks.length){
  5261. var tasks = [], data = [];
  5262. var l = q._tasks.length;
  5263. if (q.payload) l = Math.min(l, q.payload);
  5264. for (var i = 0; i < l; i++) {
  5265. var node = q._tasks.shift();
  5266. tasks.push(node);
  5267. workersList.push(node);
  5268. data.push(node.data);
  5269. }
  5270. numRunning += 1;
  5271. if (q._tasks.length === 0) {
  5272. q.empty();
  5273. }
  5274. if (numRunning === q.concurrency) {
  5275. q.saturated();
  5276. }
  5277. var cb = onlyOnce(_next(tasks));
  5278. _worker(data, cb);
  5279. }
  5280. isProcessing = false;
  5281. },
  5282. length: function () {
  5283. return q._tasks.length;
  5284. },
  5285. running: function () {
  5286. return numRunning;
  5287. },
  5288. workersList: function () {
  5289. return workersList;
  5290. },
  5291. idle: function() {
  5292. return q._tasks.length + numRunning === 0;
  5293. },
  5294. pause: function () {
  5295. q.paused = true;
  5296. },
  5297. resume: function () {
  5298. if (q.paused === false) { return; }
  5299. q.paused = false;
  5300. setImmediate$1(q.process);
  5301. }
  5302. };
  5303. return q;
  5304. }
  5305. /**
  5306. * A cargo of tasks for the worker function to complete. Cargo inherits all of
  5307. * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}.
  5308. * @typedef {Object} CargoObject
  5309. * @memberOf module:ControlFlow
  5310. * @property {Function} length - A function returning the number of items
  5311. * waiting to be processed. Invoke like `cargo.length()`.
  5312. * @property {number} payload - An `integer` for determining how many tasks
  5313. * should be process per round. This property can be changed after a `cargo` is
  5314. * created to alter the payload on-the-fly.
  5315. * @property {Function} push - Adds `task` to the `queue`. The callback is
  5316. * called once the `worker` has finished processing the task. Instead of a
  5317. * single task, an array of `tasks` can be submitted. The respective callback is
  5318. * used for every task in the list. Invoke like `cargo.push(task, [callback])`.
  5319. * @property {Function} saturated - A callback that is called when the
  5320. * `queue.length()` hits the concurrency and further tasks will be queued.
  5321. * @property {Function} empty - A callback that is called when the last item
  5322. * from the `queue` is given to a `worker`.
  5323. * @property {Function} drain - A callback that is called when the last item
  5324. * from the `queue` has returned from the `worker`.
  5325. * @property {Function} idle - a function returning false if there are items
  5326. * waiting or being processed, or true if not. Invoke like `cargo.idle()`.
  5327. * @property {Function} pause - a function that pauses the processing of tasks
  5328. * until `resume()` is called. Invoke like `cargo.pause()`.
  5329. * @property {Function} resume - a function that resumes the processing of
  5330. * queued tasks when the queue is paused. Invoke like `cargo.resume()`.
  5331. * @property {Function} kill - a function that removes the `drain` callback and
  5332. * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`.
  5333. */
  5334. /**
  5335. * Creates a `cargo` object with the specified payload. Tasks added to the
  5336. * cargo will be processed altogether (up to the `payload` limit). If the
  5337. * `worker` is in progress, the task is queued until it becomes available. Once
  5338. * the `worker` has completed some tasks, each callback of those tasks is
  5339. * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
  5340. * for how `cargo` and `queue` work.
  5341. *
  5342. * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
  5343. * at a time, cargo passes an array of tasks to a single worker, repeating
  5344. * when the worker is finished.
  5345. *
  5346. * @name cargo
  5347. * @static
  5348. * @memberOf module:ControlFlow
  5349. * @method
  5350. * @see [async.queue]{@link module:ControlFlow.queue}
  5351. * @category Control Flow
  5352. * @param {AsyncFunction} worker - An asynchronous function for processing an array
  5353. * of queued tasks. Invoked with `(tasks, callback)`.
  5354. * @param {number} [payload=Infinity] - An optional `integer` for determining
  5355. * how many tasks should be processed per round; if omitted, the default is
  5356. * unlimited.
  5357. * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can
  5358. * attached as certain properties to listen for specific events during the
  5359. * lifecycle of the cargo and inner queue.
  5360. * @example
  5361. *
  5362. * // create a cargo object with payload 2
  5363. * var cargo = async.cargo(function(tasks, callback) {
  5364. * for (var i=0; i<tasks.length; i++) {
  5365. * console.log('hello ' + tasks[i].name);
  5366. * }
  5367. * callback();
  5368. * }, 2);
  5369. *
  5370. * // add some items
  5371. * cargo.push({name: 'foo'}, function(err) {
  5372. * console.log('finished processing foo');
  5373. * });
  5374. * cargo.push({name: 'bar'}, function(err) {
  5375. * console.log('finished processing bar');
  5376. * });
  5377. * cargo.push({name: 'baz'}, function(err) {
  5378. * console.log('finished processing baz');
  5379. * });
  5380. */
  5381. function cargo(worker, payload) {
  5382. return queue(worker, 1, payload);
  5383. }
  5384. /**
  5385. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
  5386. *
  5387. * @name eachOfSeries
  5388. * @static
  5389. * @memberOf module:Collections
  5390. * @method
  5391. * @see [async.eachOf]{@link module:Collections.eachOf}
  5392. * @alias forEachOfSeries
  5393. * @category Collection
  5394. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  5395. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  5396. * `coll`.
  5397. * Invoked with (item, key, callback).
  5398. * @param {Function} [callback] - A callback which is called when all `iteratee`
  5399. * functions have finished, or an error occurs. Invoked with (err).
  5400. */
  5401. var eachOfSeries = doLimit(eachOfLimit, 1);
  5402. /**
  5403. * Reduces `coll` into a single value using an async `iteratee` to return each
  5404. * successive step. `memo` is the initial state of the reduction. This function
  5405. * only operates in series.
  5406. *
  5407. * For performance reasons, it may make sense to split a call to this function
  5408. * into a parallel map, and then use the normal `Array.prototype.reduce` on the
  5409. * results. This function is for situations where each step in the reduction
  5410. * needs to be async; if you can get the data before reducing it, then it's
  5411. * probably a good idea to do so.
  5412. *
  5413. * @name reduce
  5414. * @static
  5415. * @memberOf module:Collections
  5416. * @method
  5417. * @alias inject
  5418. * @alias foldl
  5419. * @category Collection
  5420. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  5421. * @param {*} memo - The initial state of the reduction.
  5422. * @param {AsyncFunction} iteratee - A function applied to each item in the
  5423. * array to produce the next step in the reduction.
  5424. * The `iteratee` should complete with the next state of the reduction.
  5425. * If the iteratee complete with an error, the reduction is stopped and the
  5426. * main `callback` is immediately called with the error.
  5427. * Invoked with (memo, item, callback).
  5428. * @param {Function} [callback] - A callback which is called after all the
  5429. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  5430. * (err, result).
  5431. * @example
  5432. *
  5433. * async.reduce([1,2,3], 0, function(memo, item, callback) {
  5434. * // pointless async:
  5435. * process.nextTick(function() {
  5436. * callback(null, memo + item)
  5437. * });
  5438. * }, function(err, result) {
  5439. * // result is now equal to the last value of memo, which is 6
  5440. * });
  5441. */
  5442. function reduce(coll, memo, iteratee, callback) {
  5443. callback = once(callback || noop);
  5444. var _iteratee = wrapAsync(iteratee);
  5445. eachOfSeries(coll, function(x, i, callback) {
  5446. _iteratee(memo, x, function(err, v) {
  5447. memo = v;
  5448. callback(err);
  5449. });
  5450. }, function(err) {
  5451. callback(err, memo);
  5452. });
  5453. }
  5454. /**
  5455. * Version of the compose function that is more natural to read. Each function
  5456. * consumes the return value of the previous function. It is the equivalent of
  5457. * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
  5458. *
  5459. * Each function is executed with the `this` binding of the composed function.
  5460. *
  5461. * @name seq
  5462. * @static
  5463. * @memberOf module:ControlFlow
  5464. * @method
  5465. * @see [async.compose]{@link module:ControlFlow.compose}
  5466. * @category Control Flow
  5467. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  5468. * @returns {Function} a function that composes the `functions` in order
  5469. * @example
  5470. *
  5471. * // Requires lodash (or underscore), express3 and dresende's orm2.
  5472. * // Part of an app, that fetches cats of the logged user.
  5473. * // This example uses `seq` function to avoid overnesting and error
  5474. * // handling clutter.
  5475. * app.get('/cats', function(request, response) {
  5476. * var User = request.models.User;
  5477. * async.seq(
  5478. * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
  5479. * function(user, fn) {
  5480. * user.getCats(fn); // 'getCats' has signature (callback(err, data))
  5481. * }
  5482. * )(req.session.user_id, function (err, cats) {
  5483. * if (err) {
  5484. * console.error(err);
  5485. * response.json({ status: 'error', message: err.message });
  5486. * } else {
  5487. * response.json({ status: 'ok', message: 'Cats found', data: cats });
  5488. * }
  5489. * });
  5490. * });
  5491. */
  5492. function seq(/*...functions*/) {
  5493. var _functions = arrayMap(arguments, wrapAsync);
  5494. return function(/*...args*/) {
  5495. var args = slice(arguments);
  5496. var that = this;
  5497. var cb = args[args.length - 1];
  5498. if (typeof cb == 'function') {
  5499. args.pop();
  5500. } else {
  5501. cb = noop;
  5502. }
  5503. reduce(_functions, args, function(newargs, fn, cb) {
  5504. fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) {
  5505. var nextargs = slice(arguments, 1);
  5506. cb(err, nextargs);
  5507. }));
  5508. },
  5509. function(err, results) {
  5510. cb.apply(that, [err].concat(results));
  5511. });
  5512. };
  5513. }
  5514. /**
  5515. * Creates a function which is a composition of the passed asynchronous
  5516. * functions. Each function consumes the return value of the function that
  5517. * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
  5518. * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
  5519. *
  5520. * Each function is executed with the `this` binding of the composed function.
  5521. *
  5522. * @name compose
  5523. * @static
  5524. * @memberOf module:ControlFlow
  5525. * @method
  5526. * @category Control Flow
  5527. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  5528. * @returns {Function} an asynchronous function that is the composed
  5529. * asynchronous `functions`
  5530. * @example
  5531. *
  5532. * function add1(n, callback) {
  5533. * setTimeout(function () {
  5534. * callback(null, n + 1);
  5535. * }, 10);
  5536. * }
  5537. *
  5538. * function mul3(n, callback) {
  5539. * setTimeout(function () {
  5540. * callback(null, n * 3);
  5541. * }, 10);
  5542. * }
  5543. *
  5544. * var add1mul3 = async.compose(mul3, add1);
  5545. * add1mul3(4, function (err, result) {
  5546. * // result now equals 15
  5547. * });
  5548. */
  5549. var compose = function(/*...args*/) {
  5550. return seq.apply(null, slice(arguments).reverse());
  5551. };
  5552. var _concat = Array.prototype.concat;
  5553. /**
  5554. * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
  5555. *
  5556. * @name concatLimit
  5557. * @static
  5558. * @memberOf module:Collections
  5559. * @method
  5560. * @see [async.concat]{@link module:Collections.concat}
  5561. * @category Collection
  5562. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  5563. * @param {number} limit - The maximum number of async operations at a time.
  5564. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  5565. * which should use an array as its result. Invoked with (item, callback).
  5566. * @param {Function} [callback] - A callback which is called after all the
  5567. * `iteratee` functions have finished, or an error occurs. Results is an array
  5568. * containing the concatenated results of the `iteratee` function. Invoked with
  5569. * (err, results).
  5570. */
  5571. var concatLimit = function(coll, limit, iteratee, callback) {
  5572. callback = callback || noop;
  5573. var _iteratee = wrapAsync(iteratee);
  5574. mapLimit(coll, limit, function(val, callback) {
  5575. _iteratee(val, function(err /*, ...args*/) {
  5576. if (err) return callback(err);
  5577. return callback(null, slice(arguments, 1));
  5578. });
  5579. }, function(err, mapResults) {
  5580. var result = [];
  5581. for (var i = 0; i < mapResults.length; i++) {
  5582. if (mapResults[i]) {
  5583. result = _concat.apply(result, mapResults[i]);
  5584. }
  5585. }
  5586. return callback(err, result);
  5587. });
  5588. };
  5589. /**
  5590. * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
  5591. * the concatenated list. The `iteratee`s are called in parallel, and the
  5592. * results are concatenated as they return. There is no guarantee that the
  5593. * results array will be returned in the original order of `coll` passed to the
  5594. * `iteratee` function.
  5595. *
  5596. * @name concat
  5597. * @static
  5598. * @memberOf module:Collections
  5599. * @method
  5600. * @category Collection
  5601. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  5602. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  5603. * which should use an array as its result. Invoked with (item, callback).
  5604. * @param {Function} [callback(err)] - A callback which is called after all the
  5605. * `iteratee` functions have finished, or an error occurs. Results is an array
  5606. * containing the concatenated results of the `iteratee` function. Invoked with
  5607. * (err, results).
  5608. * @example
  5609. *
  5610. * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
  5611. * // files is now a list of filenames that exist in the 3 directories
  5612. * });
  5613. */
  5614. var concat = doLimit(concatLimit, Infinity);
  5615. /**
  5616. * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
  5617. *
  5618. * @name concatSeries
  5619. * @static
  5620. * @memberOf module:Collections
  5621. * @method
  5622. * @see [async.concat]{@link module:Collections.concat}
  5623. * @category Collection
  5624. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  5625. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
  5626. * The iteratee should complete with an array an array of results.
  5627. * Invoked with (item, callback).
  5628. * @param {Function} [callback(err)] - A callback which is called after all the
  5629. * `iteratee` functions have finished, or an error occurs. Results is an array
  5630. * containing the concatenated results of the `iteratee` function. Invoked with
  5631. * (err, results).
  5632. */
  5633. var concatSeries = doLimit(concatLimit, 1);
  5634. /**
  5635. * Returns a function that when called, calls-back with the values provided.
  5636. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
  5637. * [`auto`]{@link module:ControlFlow.auto}.
  5638. *
  5639. * @name constant
  5640. * @static
  5641. * @memberOf module:Utils
  5642. * @method
  5643. * @category Util
  5644. * @param {...*} arguments... - Any number of arguments to automatically invoke
  5645. * callback with.
  5646. * @returns {AsyncFunction} Returns a function that when invoked, automatically
  5647. * invokes the callback with the previous given arguments.
  5648. * @example
  5649. *
  5650. * async.waterfall([
  5651. * async.constant(42),
  5652. * function (value, next) {
  5653. * // value === 42
  5654. * },
  5655. * //...
  5656. * ], callback);
  5657. *
  5658. * async.waterfall([
  5659. * async.constant(filename, "utf8"),
  5660. * fs.readFile,
  5661. * function (fileData, next) {
  5662. * //...
  5663. * }
  5664. * //...
  5665. * ], callback);
  5666. *
  5667. * async.auto({
  5668. * hostname: async.constant("https://server.net/"),
  5669. * port: findFreePort,
  5670. * launchServer: ["hostname", "port", function (options, cb) {
  5671. * startServer(options, cb);
  5672. * }],
  5673. * //...
  5674. * }, callback);
  5675. */
  5676. var constant = function(/*...values*/) {
  5677. var values = slice(arguments);
  5678. var args = [null].concat(values);
  5679. return function (/*...ignoredArgs, callback*/) {
  5680. var callback = arguments[arguments.length - 1];
  5681. return callback.apply(this, args);
  5682. };
  5683. };
  5684. /**
  5685. * This method returns the first argument it receives.
  5686. *
  5687. * @static
  5688. * @since 0.1.0
  5689. * @memberOf _
  5690. * @category Util
  5691. * @param {*} value Any value.
  5692. * @returns {*} Returns `value`.
  5693. * @example
  5694. *
  5695. * var object = { 'a': 1 };
  5696. *
  5697. * console.log(_.identity(object) === object);
  5698. * // => true
  5699. */
  5700. function identity(value) {
  5701. return value;
  5702. }
  5703. function _createTester(check, getResult) {
  5704. return function(eachfn, arr, iteratee, cb) {
  5705. cb = cb || noop;
  5706. var testPassed = false;
  5707. var testResult;
  5708. eachfn(arr, function(value, _, callback) {
  5709. iteratee(value, function(err, result) {
  5710. if (err) {
  5711. callback(err);
  5712. } else if (check(result) && !testResult) {
  5713. testPassed = true;
  5714. testResult = getResult(true, value);
  5715. callback(null, breakLoop);
  5716. } else {
  5717. callback();
  5718. }
  5719. });
  5720. }, function(err) {
  5721. if (err) {
  5722. cb(err);
  5723. } else {
  5724. cb(null, testPassed ? testResult : getResult(false));
  5725. }
  5726. });
  5727. };
  5728. }
  5729. function _findGetResult(v, x) {
  5730. return x;
  5731. }
  5732. /**
  5733. * Returns the first value in `coll` that passes an async truth test. The
  5734. * `iteratee` is applied in parallel, meaning the first iteratee to return
  5735. * `true` will fire the detect `callback` with that result. That means the
  5736. * result might not be the first item in the original `coll` (in terms of order)
  5737. * that passes the test.
  5738. * If order within the original `coll` is important, then look at
  5739. * [`detectSeries`]{@link module:Collections.detectSeries}.
  5740. *
  5741. * @name detect
  5742. * @static
  5743. * @memberOf module:Collections
  5744. * @method
  5745. * @alias find
  5746. * @category Collections
  5747. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  5748. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  5749. * The iteratee must complete with a boolean value as its result.
  5750. * Invoked with (item, callback).
  5751. * @param {Function} [callback] - A callback which is called as soon as any
  5752. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  5753. * Result will be the first item in the array that passes the truth test
  5754. * (iteratee) or the value `undefined` if none passed. Invoked with
  5755. * (err, result).
  5756. * @example
  5757. *
  5758. * async.detect(['file1','file2','file3'], function(filePath, callback) {
  5759. * fs.access(filePath, function(err) {
  5760. * callback(null, !err)
  5761. * });
  5762. * }, function(err, result) {
  5763. * // result now equals the first file in the list that exists
  5764. * });
  5765. */
  5766. var detect = doParallel(_createTester(identity, _findGetResult));
  5767. /**
  5768. * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
  5769. * time.
  5770. *
  5771. * @name detectLimit
  5772. * @static
  5773. * @memberOf module:Collections
  5774. * @method
  5775. * @see [async.detect]{@link module:Collections.detect}
  5776. * @alias findLimit
  5777. * @category Collections
  5778. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  5779. * @param {number} limit - The maximum number of async operations at a time.
  5780. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  5781. * The iteratee must complete with a boolean value as its result.
  5782. * Invoked with (item, callback).
  5783. * @param {Function} [callback] - A callback which is called as soon as any
  5784. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  5785. * Result will be the first item in the array that passes the truth test
  5786. * (iteratee) or the value `undefined` if none passed. Invoked with
  5787. * (err, result).
  5788. */
  5789. var detectLimit = doParallelLimit(_createTester(identity, _findGetResult));
  5790. /**
  5791. * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
  5792. *
  5793. * @name detectSeries
  5794. * @static
  5795. * @memberOf module:Collections
  5796. * @method
  5797. * @see [async.detect]{@link module:Collections.detect}
  5798. * @alias findSeries
  5799. * @category Collections
  5800. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  5801. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  5802. * The iteratee must complete with a boolean value as its result.
  5803. * Invoked with (item, callback).
  5804. * @param {Function} [callback] - A callback which is called as soon as any
  5805. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  5806. * Result will be the first item in the array that passes the truth test
  5807. * (iteratee) or the value `undefined` if none passed. Invoked with
  5808. * (err, result).
  5809. */
  5810. var detectSeries = doLimit(detectLimit, 1);
  5811. function consoleFunc(name) {
  5812. return function (fn/*, ...args*/) {
  5813. var args = slice(arguments, 1);
  5814. args.push(function (err/*, ...args*/) {
  5815. var args = slice(arguments, 1);
  5816. if (typeof console === 'object') {
  5817. if (err) {
  5818. if (console.error) {
  5819. console.error(err);
  5820. }
  5821. } else if (console[name]) {
  5822. arrayEach(args, function (x) {
  5823. console[name](x);
  5824. });
  5825. }
  5826. }
  5827. });
  5828. wrapAsync(fn).apply(null, args);
  5829. };
  5830. }
  5831. /**
  5832. * Logs the result of an [`async` function]{@link AsyncFunction} to the
  5833. * `console` using `console.dir` to display the properties of the resulting object.
  5834. * Only works in Node.js or in browsers that support `console.dir` and
  5835. * `console.error` (such as FF and Chrome).
  5836. * If multiple arguments are returned from the async function,
  5837. * `console.dir` is called on each argument in order.
  5838. *
  5839. * @name dir
  5840. * @static
  5841. * @memberOf module:Utils
  5842. * @method
  5843. * @category Util
  5844. * @param {AsyncFunction} function - The function you want to eventually apply
  5845. * all arguments to.
  5846. * @param {...*} arguments... - Any number of arguments to apply to the function.
  5847. * @example
  5848. *
  5849. * // in a module
  5850. * var hello = function(name, callback) {
  5851. * setTimeout(function() {
  5852. * callback(null, {hello: name});
  5853. * }, 1000);
  5854. * };
  5855. *
  5856. * // in the node repl
  5857. * node> async.dir(hello, 'world');
  5858. * {hello: 'world'}
  5859. */
  5860. var dir = consoleFunc('dir');
  5861. /**
  5862. * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in
  5863. * the order of operations, the arguments `test` and `fn` are switched.
  5864. *
  5865. * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function.
  5866. * @name doDuring
  5867. * @static
  5868. * @memberOf module:ControlFlow
  5869. * @method
  5870. * @see [async.during]{@link module:ControlFlow.during}
  5871. * @category Control Flow
  5872. * @param {AsyncFunction} fn - An async function which is called each time
  5873. * `test` passes. Invoked with (callback).
  5874. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  5875. * execution of `fn`. Invoked with (...args, callback), where `...args` are the
  5876. * non-error args from the previous callback of `fn`.
  5877. * @param {Function} [callback] - A callback which is called after the test
  5878. * function has failed and repeated execution of `fn` has stopped. `callback`
  5879. * will be passed an error if one occurred, otherwise `null`.
  5880. */
  5881. function doDuring(fn, test, callback) {
  5882. callback = onlyOnce(callback || noop);
  5883. var _fn = wrapAsync(fn);
  5884. var _test = wrapAsync(test);
  5885. function next(err/*, ...args*/) {
  5886. if (err) return callback(err);
  5887. var args = slice(arguments, 1);
  5888. args.push(check);
  5889. _test.apply(this, args);
  5890. }
  5891. function check(err, truth) {
  5892. if (err) return callback(err);
  5893. if (!truth) return callback(null);
  5894. _fn(next);
  5895. }
  5896. check(null, true);
  5897. }
  5898. /**
  5899. * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
  5900. * the order of operations, the arguments `test` and `iteratee` are switched.
  5901. *
  5902. * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
  5903. *
  5904. * @name doWhilst
  5905. * @static
  5906. * @memberOf module:ControlFlow
  5907. * @method
  5908. * @see [async.whilst]{@link module:ControlFlow.whilst}
  5909. * @category Control Flow
  5910. * @param {AsyncFunction} iteratee - A function which is called each time `test`
  5911. * passes. Invoked with (callback).
  5912. * @param {Function} test - synchronous truth test to perform after each
  5913. * execution of `iteratee`. Invoked with any non-error callback results of
  5914. * `iteratee`.
  5915. * @param {Function} [callback] - A callback which is called after the test
  5916. * function has failed and repeated execution of `iteratee` has stopped.
  5917. * `callback` will be passed an error and any arguments passed to the final
  5918. * `iteratee`'s callback. Invoked with (err, [results]);
  5919. */
  5920. function doWhilst(iteratee, test, callback) {
  5921. callback = onlyOnce(callback || noop);
  5922. var _iteratee = wrapAsync(iteratee);
  5923. var next = function(err/*, ...args*/) {
  5924. if (err) return callback(err);
  5925. var args = slice(arguments, 1);
  5926. if (test.apply(this, args)) return _iteratee(next);
  5927. callback.apply(null, [null].concat(args));
  5928. };
  5929. _iteratee(next);
  5930. }
  5931. /**
  5932. * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
  5933. * argument ordering differs from `until`.
  5934. *
  5935. * @name doUntil
  5936. * @static
  5937. * @memberOf module:ControlFlow
  5938. * @method
  5939. * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
  5940. * @category Control Flow
  5941. * @param {AsyncFunction} iteratee - An async function which is called each time
  5942. * `test` fails. Invoked with (callback).
  5943. * @param {Function} test - synchronous truth test to perform after each
  5944. * execution of `iteratee`. Invoked with any non-error callback results of
  5945. * `iteratee`.
  5946. * @param {Function} [callback] - A callback which is called after the test
  5947. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  5948. * will be passed an error and any arguments passed to the final `iteratee`'s
  5949. * callback. Invoked with (err, [results]);
  5950. */
  5951. function doUntil(iteratee, test, callback) {
  5952. doWhilst(iteratee, function() {
  5953. return !test.apply(this, arguments);
  5954. }, callback);
  5955. }
  5956. /**
  5957. * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that
  5958. * is passed a callback in the form of `function (err, truth)`. If error is
  5959. * passed to `test` or `fn`, the main callback is immediately called with the
  5960. * value of the error.
  5961. *
  5962. * @name during
  5963. * @static
  5964. * @memberOf module:ControlFlow
  5965. * @method
  5966. * @see [async.whilst]{@link module:ControlFlow.whilst}
  5967. * @category Control Flow
  5968. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  5969. * execution of `fn`. Invoked with (callback).
  5970. * @param {AsyncFunction} fn - An async function which is called each time
  5971. * `test` passes. Invoked with (callback).
  5972. * @param {Function} [callback] - A callback which is called after the test
  5973. * function has failed and repeated execution of `fn` has stopped. `callback`
  5974. * will be passed an error, if one occurred, otherwise `null`.
  5975. * @example
  5976. *
  5977. * var count = 0;
  5978. *
  5979. * async.during(
  5980. * function (callback) {
  5981. * return callback(null, count < 5);
  5982. * },
  5983. * function (callback) {
  5984. * count++;
  5985. * setTimeout(callback, 1000);
  5986. * },
  5987. * function (err) {
  5988. * // 5 seconds have passed
  5989. * }
  5990. * );
  5991. */
  5992. function during(test, fn, callback) {
  5993. callback = onlyOnce(callback || noop);
  5994. var _fn = wrapAsync(fn);
  5995. var _test = wrapAsync(test);
  5996. function next(err) {
  5997. if (err) return callback(err);
  5998. _test(check);
  5999. }
  6000. function check(err, truth) {
  6001. if (err) return callback(err);
  6002. if (!truth) return callback(null);
  6003. _fn(next);
  6004. }
  6005. _test(check);
  6006. }
  6007. function _withoutIndex(iteratee) {
  6008. return function (value, index, callback) {
  6009. return iteratee(value, callback);
  6010. };
  6011. }
  6012. /**
  6013. * Applies the function `iteratee` to each item in `coll`, in parallel.
  6014. * The `iteratee` is called with an item from the list, and a callback for when
  6015. * it has finished. If the `iteratee` passes an error to its `callback`, the
  6016. * main `callback` (for the `each` function) is immediately called with the
  6017. * error.
  6018. *
  6019. * Note, that since this function applies `iteratee` to each item in parallel,
  6020. * there is no guarantee that the iteratee functions will complete in order.
  6021. *
  6022. * @name each
  6023. * @static
  6024. * @memberOf module:Collections
  6025. * @method
  6026. * @alias forEach
  6027. * @category Collection
  6028. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6029. * @param {AsyncFunction} iteratee - An async function to apply to
  6030. * each item in `coll`. Invoked with (item, callback).
  6031. * The array index is not passed to the iteratee.
  6032. * If you need the index, use `eachOf`.
  6033. * @param {Function} [callback] - A callback which is called when all
  6034. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  6035. * @example
  6036. *
  6037. * // assuming openFiles is an array of file names and saveFile is a function
  6038. * // to save the modified contents of that file:
  6039. *
  6040. * async.each(openFiles, saveFile, function(err){
  6041. * // if any of the saves produced an error, err would equal that error
  6042. * });
  6043. *
  6044. * // assuming openFiles is an array of file names
  6045. * async.each(openFiles, function(file, callback) {
  6046. *
  6047. * // Perform operation on file here.
  6048. * console.log('Processing file ' + file);
  6049. *
  6050. * if( file.length > 32 ) {
  6051. * console.log('This file name is too long');
  6052. * callback('File name too long');
  6053. * } else {
  6054. * // Do work to process file here
  6055. * console.log('File processed');
  6056. * callback();
  6057. * }
  6058. * }, function(err) {
  6059. * // if any of the file processing produced an error, err would equal that error
  6060. * if( err ) {
  6061. * // One of the iterations produced an error.
  6062. * // All processing will now stop.
  6063. * console.log('A file failed to process');
  6064. * } else {
  6065. * console.log('All files have been processed successfully');
  6066. * }
  6067. * });
  6068. */
  6069. function eachLimit(coll, iteratee, callback) {
  6070. eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  6071. }
  6072. /**
  6073. * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
  6074. *
  6075. * @name eachLimit
  6076. * @static
  6077. * @memberOf module:Collections
  6078. * @method
  6079. * @see [async.each]{@link module:Collections.each}
  6080. * @alias forEachLimit
  6081. * @category Collection
  6082. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6083. * @param {number} limit - The maximum number of async operations at a time.
  6084. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  6085. * `coll`.
  6086. * The array index is not passed to the iteratee.
  6087. * If you need the index, use `eachOfLimit`.
  6088. * Invoked with (item, callback).
  6089. * @param {Function} [callback] - A callback which is called when all
  6090. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  6091. */
  6092. function eachLimit$1(coll, limit, iteratee, callback) {
  6093. _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  6094. }
  6095. /**
  6096. * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
  6097. *
  6098. * @name eachSeries
  6099. * @static
  6100. * @memberOf module:Collections
  6101. * @method
  6102. * @see [async.each]{@link module:Collections.each}
  6103. * @alias forEachSeries
  6104. * @category Collection
  6105. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6106. * @param {AsyncFunction} iteratee - An async function to apply to each
  6107. * item in `coll`.
  6108. * The array index is not passed to the iteratee.
  6109. * If you need the index, use `eachOfSeries`.
  6110. * Invoked with (item, callback).
  6111. * @param {Function} [callback] - A callback which is called when all
  6112. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  6113. */
  6114. var eachSeries = doLimit(eachLimit$1, 1);
  6115. /**
  6116. * Wrap an async function and ensure it calls its callback on a later tick of
  6117. * the event loop. If the function already calls its callback on a next tick,
  6118. * no extra deferral is added. This is useful for preventing stack overflows
  6119. * (`RangeError: Maximum call stack size exceeded`) and generally keeping
  6120. * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
  6121. * contained. ES2017 `async` functions are returned as-is -- they are immune
  6122. * to Zalgo's corrupting influences, as they always resolve on a later tick.
  6123. *
  6124. * @name ensureAsync
  6125. * @static
  6126. * @memberOf module:Utils
  6127. * @method
  6128. * @category Util
  6129. * @param {AsyncFunction} fn - an async function, one that expects a node-style
  6130. * callback as its last argument.
  6131. * @returns {AsyncFunction} Returns a wrapped function with the exact same call
  6132. * signature as the function passed in.
  6133. * @example
  6134. *
  6135. * function sometimesAsync(arg, callback) {
  6136. * if (cache[arg]) {
  6137. * return callback(null, cache[arg]); // this would be synchronous!!
  6138. * } else {
  6139. * doSomeIO(arg, callback); // this IO would be asynchronous
  6140. * }
  6141. * }
  6142. *
  6143. * // this has a risk of stack overflows if many results are cached in a row
  6144. * async.mapSeries(args, sometimesAsync, done);
  6145. *
  6146. * // this will defer sometimesAsync's callback if necessary,
  6147. * // preventing stack overflows
  6148. * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
  6149. */
  6150. function ensureAsync(fn) {
  6151. if (isAsync(fn)) return fn;
  6152. return initialParams(function (args, callback) {
  6153. var sync = true;
  6154. args.push(function () {
  6155. var innerArgs = arguments;
  6156. if (sync) {
  6157. setImmediate$1(function () {
  6158. callback.apply(null, innerArgs);
  6159. });
  6160. } else {
  6161. callback.apply(null, innerArgs);
  6162. }
  6163. });
  6164. fn.apply(this, args);
  6165. sync = false;
  6166. });
  6167. }
  6168. function notId(v) {
  6169. return !v;
  6170. }
  6171. /**
  6172. * Returns `true` if every element in `coll` satisfies an async test. If any
  6173. * iteratee call returns `false`, the main `callback` is immediately called.
  6174. *
  6175. * @name every
  6176. * @static
  6177. * @memberOf module:Collections
  6178. * @method
  6179. * @alias all
  6180. * @category Collection
  6181. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6182. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  6183. * in the collection in parallel.
  6184. * The iteratee must complete with a boolean result value.
  6185. * Invoked with (item, callback).
  6186. * @param {Function} [callback] - A callback which is called after all the
  6187. * `iteratee` functions have finished. Result will be either `true` or `false`
  6188. * depending on the values of the async tests. Invoked with (err, result).
  6189. * @example
  6190. *
  6191. * async.every(['file1','file2','file3'], function(filePath, callback) {
  6192. * fs.access(filePath, function(err) {
  6193. * callback(null, !err)
  6194. * });
  6195. * }, function(err, result) {
  6196. * // if result is true then every file exists
  6197. * });
  6198. */
  6199. var every = doParallel(_createTester(notId, notId));
  6200. /**
  6201. * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
  6202. *
  6203. * @name everyLimit
  6204. * @static
  6205. * @memberOf module:Collections
  6206. * @method
  6207. * @see [async.every]{@link module:Collections.every}
  6208. * @alias allLimit
  6209. * @category Collection
  6210. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6211. * @param {number} limit - The maximum number of async operations at a time.
  6212. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  6213. * in the collection in parallel.
  6214. * The iteratee must complete with a boolean result value.
  6215. * Invoked with (item, callback).
  6216. * @param {Function} [callback] - A callback which is called after all the
  6217. * `iteratee` functions have finished. Result will be either `true` or `false`
  6218. * depending on the values of the async tests. Invoked with (err, result).
  6219. */
  6220. var everyLimit = doParallelLimit(_createTester(notId, notId));
  6221. /**
  6222. * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
  6223. *
  6224. * @name everySeries
  6225. * @static
  6226. * @memberOf module:Collections
  6227. * @method
  6228. * @see [async.every]{@link module:Collections.every}
  6229. * @alias allSeries
  6230. * @category Collection
  6231. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6232. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  6233. * in the collection in series.
  6234. * The iteratee must complete with a boolean result value.
  6235. * Invoked with (item, callback).
  6236. * @param {Function} [callback] - A callback which is called after all the
  6237. * `iteratee` functions have finished. Result will be either `true` or `false`
  6238. * depending on the values of the async tests. Invoked with (err, result).
  6239. */
  6240. var everySeries = doLimit(everyLimit, 1);
  6241. /**
  6242. * The base implementation of `_.property` without support for deep paths.
  6243. *
  6244. * @private
  6245. * @param {string} key The key of the property to get.
  6246. * @returns {Function} Returns the new accessor function.
  6247. */
  6248. function baseProperty(key) {
  6249. return function(object) {
  6250. return object == null ? undefined : object[key];
  6251. };
  6252. }
  6253. function filterArray(eachfn, arr, iteratee, callback) {
  6254. var truthValues = new Array(arr.length);
  6255. eachfn(arr, function (x, index, callback) {
  6256. iteratee(x, function (err, v) {
  6257. truthValues[index] = !!v;
  6258. callback(err);
  6259. });
  6260. }, function (err) {
  6261. if (err) return callback(err);
  6262. var results = [];
  6263. for (var i = 0; i < arr.length; i++) {
  6264. if (truthValues[i]) results.push(arr[i]);
  6265. }
  6266. callback(null, results);
  6267. });
  6268. }
  6269. function filterGeneric(eachfn, coll, iteratee, callback) {
  6270. var results = [];
  6271. eachfn(coll, function (x, index, callback) {
  6272. iteratee(x, function (err, v) {
  6273. if (err) {
  6274. callback(err);
  6275. } else {
  6276. if (v) {
  6277. results.push({index: index, value: x});
  6278. }
  6279. callback();
  6280. }
  6281. });
  6282. }, function (err) {
  6283. if (err) {
  6284. callback(err);
  6285. } else {
  6286. callback(null, arrayMap(results.sort(function (a, b) {
  6287. return a.index - b.index;
  6288. }), baseProperty('value')));
  6289. }
  6290. });
  6291. }
  6292. function _filter(eachfn, coll, iteratee, callback) {
  6293. var filter = isArrayLike(coll) ? filterArray : filterGeneric;
  6294. filter(eachfn, coll, wrapAsync(iteratee), callback || noop);
  6295. }
  6296. /**
  6297. * Returns a new array of all the values in `coll` which pass an async truth
  6298. * test. This operation is performed in parallel, but the results array will be
  6299. * in the same order as the original.
  6300. *
  6301. * @name filter
  6302. * @static
  6303. * @memberOf module:Collections
  6304. * @method
  6305. * @alias select
  6306. * @category Collection
  6307. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6308. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  6309. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  6310. * with a boolean argument once it has completed. Invoked with (item, callback).
  6311. * @param {Function} [callback] - A callback which is called after all the
  6312. * `iteratee` functions have finished. Invoked with (err, results).
  6313. * @example
  6314. *
  6315. * async.filter(['file1','file2','file3'], function(filePath, callback) {
  6316. * fs.access(filePath, function(err) {
  6317. * callback(null, !err)
  6318. * });
  6319. * }, function(err, results) {
  6320. * // results now equals an array of the existing files
  6321. * });
  6322. */
  6323. var filter = doParallel(_filter);
  6324. /**
  6325. * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
  6326. * time.
  6327. *
  6328. * @name filterLimit
  6329. * @static
  6330. * @memberOf module:Collections
  6331. * @method
  6332. * @see [async.filter]{@link module:Collections.filter}
  6333. * @alias selectLimit
  6334. * @category Collection
  6335. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6336. * @param {number} limit - The maximum number of async operations at a time.
  6337. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  6338. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  6339. * with a boolean argument once it has completed. Invoked with (item, callback).
  6340. * @param {Function} [callback] - A callback which is called after all the
  6341. * `iteratee` functions have finished. Invoked with (err, results).
  6342. */
  6343. var filterLimit = doParallelLimit(_filter);
  6344. /**
  6345. * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
  6346. *
  6347. * @name filterSeries
  6348. * @static
  6349. * @memberOf module:Collections
  6350. * @method
  6351. * @see [async.filter]{@link module:Collections.filter}
  6352. * @alias selectSeries
  6353. * @category Collection
  6354. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6355. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  6356. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  6357. * with a boolean argument once it has completed. Invoked with (item, callback).
  6358. * @param {Function} [callback] - A callback which is called after all the
  6359. * `iteratee` functions have finished. Invoked with (err, results)
  6360. */
  6361. var filterSeries = doLimit(filterLimit, 1);
  6362. /**
  6363. * Calls the asynchronous function `fn` with a callback parameter that allows it
  6364. * to call itself again, in series, indefinitely.
  6365. * If an error is passed to the callback then `errback` is called with the
  6366. * error, and execution stops, otherwise it will never be called.
  6367. *
  6368. * @name forever
  6369. * @static
  6370. * @memberOf module:ControlFlow
  6371. * @method
  6372. * @category Control Flow
  6373. * @param {AsyncFunction} fn - an async function to call repeatedly.
  6374. * Invoked with (next).
  6375. * @param {Function} [errback] - when `fn` passes an error to it's callback,
  6376. * this function will be called, and execution stops. Invoked with (err).
  6377. * @example
  6378. *
  6379. * async.forever(
  6380. * function(next) {
  6381. * // next is suitable for passing to things that need a callback(err [, whatever]);
  6382. * // it will result in this function being called again.
  6383. * },
  6384. * function(err) {
  6385. * // if next is called with a value in its first parameter, it will appear
  6386. * // in here as 'err', and execution will stop.
  6387. * }
  6388. * );
  6389. */
  6390. function forever(fn, errback) {
  6391. var done = onlyOnce(errback || noop);
  6392. var task = wrapAsync(ensureAsync(fn));
  6393. function next(err) {
  6394. if (err) return done(err);
  6395. task(next);
  6396. }
  6397. next();
  6398. }
  6399. /**
  6400. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
  6401. *
  6402. * @name groupByLimit
  6403. * @static
  6404. * @memberOf module:Collections
  6405. * @method
  6406. * @see [async.groupBy]{@link module:Collections.groupBy}
  6407. * @category Collection
  6408. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6409. * @param {number} limit - The maximum number of async operations at a time.
  6410. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  6411. * `coll`.
  6412. * The iteratee should complete with a `key` to group the value under.
  6413. * Invoked with (value, callback).
  6414. * @param {Function} [callback] - A callback which is called when all `iteratee`
  6415. * functions have finished, or an error occurs. Result is an `Object` whoses
  6416. * properties are arrays of values which returned the corresponding key.
  6417. */
  6418. var groupByLimit = function(coll, limit, iteratee, callback) {
  6419. callback = callback || noop;
  6420. var _iteratee = wrapAsync(iteratee);
  6421. mapLimit(coll, limit, function(val, callback) {
  6422. _iteratee(val, function(err, key) {
  6423. if (err) return callback(err);
  6424. return callback(null, {key: key, val: val});
  6425. });
  6426. }, function(err, mapResults) {
  6427. var result = {};
  6428. // from MDN, handle object having an `hasOwnProperty` prop
  6429. var hasOwnProperty = Object.prototype.hasOwnProperty;
  6430. for (var i = 0; i < mapResults.length; i++) {
  6431. if (mapResults[i]) {
  6432. var key = mapResults[i].key;
  6433. var val = mapResults[i].val;
  6434. if (hasOwnProperty.call(result, key)) {
  6435. result[key].push(val);
  6436. } else {
  6437. result[key] = [val];
  6438. }
  6439. }
  6440. }
  6441. return callback(err, result);
  6442. });
  6443. };
  6444. /**
  6445. * Returns a new object, where each value corresponds to an array of items, from
  6446. * `coll`, that returned the corresponding key. That is, the keys of the object
  6447. * correspond to the values passed to the `iteratee` callback.
  6448. *
  6449. * Note: Since this function applies the `iteratee` to each item in parallel,
  6450. * there is no guarantee that the `iteratee` functions will complete in order.
  6451. * However, the values for each key in the `result` will be in the same order as
  6452. * the original `coll`. For Objects, the values will roughly be in the order of
  6453. * the original Objects' keys (but this can vary across JavaScript engines).
  6454. *
  6455. * @name groupBy
  6456. * @static
  6457. * @memberOf module:Collections
  6458. * @method
  6459. * @category Collection
  6460. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6461. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  6462. * `coll`.
  6463. * The iteratee should complete with a `key` to group the value under.
  6464. * Invoked with (value, callback).
  6465. * @param {Function} [callback] - A callback which is called when all `iteratee`
  6466. * functions have finished, or an error occurs. Result is an `Object` whoses
  6467. * properties are arrays of values which returned the corresponding key.
  6468. * @example
  6469. *
  6470. * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
  6471. * db.findById(userId, function(err, user) {
  6472. * if (err) return callback(err);
  6473. * return callback(null, user.age);
  6474. * });
  6475. * }, function(err, result) {
  6476. * // result is object containing the userIds grouped by age
  6477. * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
  6478. * });
  6479. */
  6480. var groupBy = doLimit(groupByLimit, Infinity);
  6481. /**
  6482. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.
  6483. *
  6484. * @name groupBySeries
  6485. * @static
  6486. * @memberOf module:Collections
  6487. * @method
  6488. * @see [async.groupBy]{@link module:Collections.groupBy}
  6489. * @category Collection
  6490. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  6491. * @param {number} limit - The maximum number of async operations at a time.
  6492. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  6493. * `coll`.
  6494. * The iteratee should complete with a `key` to group the value under.
  6495. * Invoked with (value, callback).
  6496. * @param {Function} [callback] - A callback which is called when all `iteratee`
  6497. * functions have finished, or an error occurs. Result is an `Object` whoses
  6498. * properties are arrays of values which returned the corresponding key.
  6499. */
  6500. var groupBySeries = doLimit(groupByLimit, 1);
  6501. /**
  6502. * Logs the result of an `async` function to the `console`. Only works in
  6503. * Node.js or in browsers that support `console.log` and `console.error` (such
  6504. * as FF and Chrome). If multiple arguments are returned from the async
  6505. * function, `console.log` is called on each argument in order.
  6506. *
  6507. * @name log
  6508. * @static
  6509. * @memberOf module:Utils
  6510. * @method
  6511. * @category Util
  6512. * @param {AsyncFunction} function - The function you want to eventually apply
  6513. * all arguments to.
  6514. * @param {...*} arguments... - Any number of arguments to apply to the function.
  6515. * @example
  6516. *
  6517. * // in a module
  6518. * var hello = function(name, callback) {
  6519. * setTimeout(function() {
  6520. * callback(null, 'hello ' + name);
  6521. * }, 1000);
  6522. * };
  6523. *
  6524. * // in the node repl
  6525. * node> async.log(hello, 'world');
  6526. * 'hello world'
  6527. */
  6528. var log = consoleFunc('log');
  6529. /**
  6530. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
  6531. * time.
  6532. *
  6533. * @name mapValuesLimit
  6534. * @static
  6535. * @memberOf module:Collections
  6536. * @method
  6537. * @see [async.mapValues]{@link module:Collections.mapValues}
  6538. * @category Collection
  6539. * @param {Object} obj - A collection to iterate over.
  6540. * @param {number} limit - The maximum number of async operations at a time.
  6541. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  6542. * in `coll`.
  6543. * The iteratee should complete with the transformed value as its result.
  6544. * Invoked with (value, key, callback).
  6545. * @param {Function} [callback] - A callback which is called when all `iteratee`
  6546. * functions have finished, or an error occurs. `result` is a new object consisting
  6547. * of each key from `obj`, with each transformed value on the right-hand side.
  6548. * Invoked with (err, result).
  6549. */
  6550. function mapValuesLimit(obj, limit, iteratee, callback) {
  6551. callback = once(callback || noop);
  6552. var newObj = {};
  6553. var _iteratee = wrapAsync(iteratee);
  6554. eachOfLimit(obj, limit, function(val, key, next) {
  6555. _iteratee(val, key, function (err, result) {
  6556. if (err) return next(err);
  6557. newObj[key] = result;
  6558. next();
  6559. });
  6560. }, function (err) {
  6561. callback(err, newObj);
  6562. });
  6563. }
  6564. /**
  6565. * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
  6566. *
  6567. * Produces a new Object by mapping each value of `obj` through the `iteratee`
  6568. * function. The `iteratee` is called each `value` and `key` from `obj` and a
  6569. * callback for when it has finished processing. Each of these callbacks takes
  6570. * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
  6571. * passes an error to its callback, the main `callback` (for the `mapValues`
  6572. * function) is immediately called with the error.
  6573. *
  6574. * Note, the order of the keys in the result is not guaranteed. The keys will
  6575. * be roughly in the order they complete, (but this is very engine-specific)
  6576. *
  6577. * @name mapValues
  6578. * @static
  6579. * @memberOf module:Collections
  6580. * @method
  6581. * @category Collection
  6582. * @param {Object} obj - A collection to iterate over.
  6583. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  6584. * in `coll`.
  6585. * The iteratee should complete with the transformed value as its result.
  6586. * Invoked with (value, key, callback).
  6587. * @param {Function} [callback] - A callback which is called when all `iteratee`
  6588. * functions have finished, or an error occurs. `result` is a new object consisting
  6589. * of each key from `obj`, with each transformed value on the right-hand side.
  6590. * Invoked with (err, result).
  6591. * @example
  6592. *
  6593. * async.mapValues({
  6594. * f1: 'file1',
  6595. * f2: 'file2',
  6596. * f3: 'file3'
  6597. * }, function (file, key, callback) {
  6598. * fs.stat(file, callback);
  6599. * }, function(err, result) {
  6600. * // result is now a map of stats for each file, e.g.
  6601. * // {
  6602. * // f1: [stats for file1],
  6603. * // f2: [stats for file2],
  6604. * // f3: [stats for file3]
  6605. * // }
  6606. * });
  6607. */
  6608. var mapValues = doLimit(mapValuesLimit, Infinity);
  6609. /**
  6610. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
  6611. *
  6612. * @name mapValuesSeries
  6613. * @static
  6614. * @memberOf module:Collections
  6615. * @method
  6616. * @see [async.mapValues]{@link module:Collections.mapValues}
  6617. * @category Collection
  6618. * @param {Object} obj - A collection to iterate over.
  6619. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  6620. * in `coll`.
  6621. * The iteratee should complete with the transformed value as its result.
  6622. * Invoked with (value, key, callback).
  6623. * @param {Function} [callback] - A callback which is called when all `iteratee`
  6624. * functions have finished, or an error occurs. `result` is a new object consisting
  6625. * of each key from `obj`, with each transformed value on the right-hand side.
  6626. * Invoked with (err, result).
  6627. */
  6628. var mapValuesSeries = doLimit(mapValuesLimit, 1);
  6629. function has(obj, key) {
  6630. return key in obj;
  6631. }
  6632. /**
  6633. * Caches the results of an async function. When creating a hash to store
  6634. * function results against, the callback is omitted from the hash and an
  6635. * optional hash function can be used.
  6636. *
  6637. * If no hash function is specified, the first argument is used as a hash key,
  6638. * which may work reasonably if it is a string or a data type that converts to a
  6639. * distinct string. Note that objects and arrays will not behave reasonably.
  6640. * Neither will cases where the other arguments are significant. In such cases,
  6641. * specify your own hash function.
  6642. *
  6643. * The cache of results is exposed as the `memo` property of the function
  6644. * returned by `memoize`.
  6645. *
  6646. * @name memoize
  6647. * @static
  6648. * @memberOf module:Utils
  6649. * @method
  6650. * @category Util
  6651. * @param {AsyncFunction} fn - The async function to proxy and cache results from.
  6652. * @param {Function} hasher - An optional function for generating a custom hash
  6653. * for storing results. It has all the arguments applied to it apart from the
  6654. * callback, and must be synchronous.
  6655. * @returns {AsyncFunction} a memoized version of `fn`
  6656. * @example
  6657. *
  6658. * var slow_fn = function(name, callback) {
  6659. * // do something
  6660. * callback(null, result);
  6661. * };
  6662. * var fn = async.memoize(slow_fn);
  6663. *
  6664. * // fn can now be used as if it were slow_fn
  6665. * fn('some name', function() {
  6666. * // callback
  6667. * });
  6668. */
  6669. function memoize(fn, hasher) {
  6670. var memo = Object.create(null);
  6671. var queues = Object.create(null);
  6672. hasher = hasher || identity;
  6673. var _fn = wrapAsync(fn);
  6674. var memoized = initialParams(function memoized(args, callback) {
  6675. var key = hasher.apply(null, args);
  6676. if (has(memo, key)) {
  6677. setImmediate$1(function() {
  6678. callback.apply(null, memo[key]);
  6679. });
  6680. } else if (has(queues, key)) {
  6681. queues[key].push(callback);
  6682. } else {
  6683. queues[key] = [callback];
  6684. _fn.apply(null, args.concat(function(/*args*/) {
  6685. var args = slice(arguments);
  6686. memo[key] = args;
  6687. var q = queues[key];
  6688. delete queues[key];
  6689. for (var i = 0, l = q.length; i < l; i++) {
  6690. q[i].apply(null, args);
  6691. }
  6692. }));
  6693. }
  6694. });
  6695. memoized.memo = memo;
  6696. memoized.unmemoized = fn;
  6697. return memoized;
  6698. }
  6699. /**
  6700. * Calls `callback` on a later loop around the event loop. In Node.js this just
  6701. * calls `process.nextTick`. In the browser it will use `setImmediate` if
  6702. * available, otherwise `setTimeout(callback, 0)`, which means other higher
  6703. * priority events may precede the execution of `callback`.
  6704. *
  6705. * This is used internally for browser-compatibility purposes.
  6706. *
  6707. * @name nextTick
  6708. * @static
  6709. * @memberOf module:Utils
  6710. * @method
  6711. * @see [async.setImmediate]{@link module:Utils.setImmediate}
  6712. * @category Util
  6713. * @param {Function} callback - The function to call on a later loop around
  6714. * the event loop. Invoked with (args...).
  6715. * @param {...*} args... - any number of additional arguments to pass to the
  6716. * callback on the next tick.
  6717. * @example
  6718. *
  6719. * var call_order = [];
  6720. * async.nextTick(function() {
  6721. * call_order.push('two');
  6722. * // call_order now equals ['one','two']
  6723. * });
  6724. * call_order.push('one');
  6725. *
  6726. * async.setImmediate(function (a, b, c) {
  6727. * // a, b, and c equal 1, 2, and 3
  6728. * }, 1, 2, 3);
  6729. */
  6730. var _defer$1;
  6731. if (hasNextTick) {
  6732. _defer$1 = process.nextTick;
  6733. } else if (hasSetImmediate) {
  6734. _defer$1 = setImmediate;
  6735. } else {
  6736. _defer$1 = fallback;
  6737. }
  6738. var nextTick = wrap(_defer$1);
  6739. function _parallel(eachfn, tasks, callback) {
  6740. callback = callback || noop;
  6741. var results = isArrayLike(tasks) ? [] : {};
  6742. eachfn(tasks, function (task, key, callback) {
  6743. wrapAsync(task)(function (err, result) {
  6744. if (arguments.length > 2) {
  6745. result = slice(arguments, 1);
  6746. }
  6747. results[key] = result;
  6748. callback(err);
  6749. });
  6750. }, function (err) {
  6751. callback(err, results);
  6752. });
  6753. }
  6754. /**
  6755. * Run the `tasks` collection of functions in parallel, without waiting until
  6756. * the previous function has completed. If any of the functions pass an error to
  6757. * its callback, the main `callback` is immediately called with the value of the
  6758. * error. Once the `tasks` have completed, the results are passed to the final
  6759. * `callback` as an array.
  6760. *
  6761. * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
  6762. * parallel execution of code. If your tasks do not use any timers or perform
  6763. * any I/O, they will actually be executed in series. Any synchronous setup
  6764. * sections for each task will happen one after the other. JavaScript remains
  6765. * single-threaded.
  6766. *
  6767. * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
  6768. * execution of other tasks when a task fails.
  6769. *
  6770. * It is also possible to use an object instead of an array. Each property will
  6771. * be run as a function and the results will be passed to the final `callback`
  6772. * as an object instead of an array. This can be a more readable way of handling
  6773. * results from {@link async.parallel}.
  6774. *
  6775. * @name parallel
  6776. * @static
  6777. * @memberOf module:ControlFlow
  6778. * @method
  6779. * @category Control Flow
  6780. * @param {Array|Iterable|Object} tasks - A collection of
  6781. * [async functions]{@link AsyncFunction} to run.
  6782. * Each async function can complete with any number of optional `result` values.
  6783. * @param {Function} [callback] - An optional callback to run once all the
  6784. * functions have completed successfully. This function gets a results array
  6785. * (or object) containing all the result arguments passed to the task callbacks.
  6786. * Invoked with (err, results).
  6787. *
  6788. * @example
  6789. * async.parallel([
  6790. * function(callback) {
  6791. * setTimeout(function() {
  6792. * callback(null, 'one');
  6793. * }, 200);
  6794. * },
  6795. * function(callback) {
  6796. * setTimeout(function() {
  6797. * callback(null, 'two');
  6798. * }, 100);
  6799. * }
  6800. * ],
  6801. * // optional callback
  6802. * function(err, results) {
  6803. * // the results array will equal ['one','two'] even though
  6804. * // the second function had a shorter timeout.
  6805. * });
  6806. *
  6807. * // an example using an object instead of an array
  6808. * async.parallel({
  6809. * one: function(callback) {
  6810. * setTimeout(function() {
  6811. * callback(null, 1);
  6812. * }, 200);
  6813. * },
  6814. * two: function(callback) {
  6815. * setTimeout(function() {
  6816. * callback(null, 2);
  6817. * }, 100);
  6818. * }
  6819. * }, function(err, results) {
  6820. * // results is now equals to: {one: 1, two: 2}
  6821. * });
  6822. */
  6823. function parallelLimit(tasks, callback) {
  6824. _parallel(eachOf, tasks, callback);
  6825. }
  6826. /**
  6827. * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
  6828. * time.
  6829. *
  6830. * @name parallelLimit
  6831. * @static
  6832. * @memberOf module:ControlFlow
  6833. * @method
  6834. * @see [async.parallel]{@link module:ControlFlow.parallel}
  6835. * @category Control Flow
  6836. * @param {Array|Iterable|Object} tasks - A collection of
  6837. * [async functions]{@link AsyncFunction} to run.
  6838. * Each async function can complete with any number of optional `result` values.
  6839. * @param {number} limit - The maximum number of async operations at a time.
  6840. * @param {Function} [callback] - An optional callback to run once all the
  6841. * functions have completed successfully. This function gets a results array
  6842. * (or object) containing all the result arguments passed to the task callbacks.
  6843. * Invoked with (err, results).
  6844. */
  6845. function parallelLimit$1(tasks, limit, callback) {
  6846. _parallel(_eachOfLimit(limit), tasks, callback);
  6847. }
  6848. /**
  6849. * A queue of tasks for the worker function to complete.
  6850. * @typedef {Object} QueueObject
  6851. * @memberOf module:ControlFlow
  6852. * @property {Function} length - a function returning the number of items
  6853. * waiting to be processed. Invoke with `queue.length()`.
  6854. * @property {boolean} started - a boolean indicating whether or not any
  6855. * items have been pushed and processed by the queue.
  6856. * @property {Function} running - a function returning the number of items
  6857. * currently being processed. Invoke with `queue.running()`.
  6858. * @property {Function} workersList - a function returning the array of items
  6859. * currently being processed. Invoke with `queue.workersList()`.
  6860. * @property {Function} idle - a function returning false if there are items
  6861. * waiting or being processed, or true if not. Invoke with `queue.idle()`.
  6862. * @property {number} concurrency - an integer for determining how many `worker`
  6863. * functions should be run in parallel. This property can be changed after a
  6864. * `queue` is created to alter the concurrency on-the-fly.
  6865. * @property {Function} push - add a new task to the `queue`. Calls `callback`
  6866. * once the `worker` has finished processing the task. Instead of a single task,
  6867. * a `tasks` array can be submitted. The respective callback is used for every
  6868. * task in the list. Invoke with `queue.push(task, [callback])`,
  6869. * @property {Function} unshift - add a new task to the front of the `queue`.
  6870. * Invoke with `queue.unshift(task, [callback])`.
  6871. * @property {Function} remove - remove items from the queue that match a test
  6872. * function. The test function will be passed an object with a `data` property,
  6873. * and a `priority` property, if this is a
  6874. * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
  6875. * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
  6876. * `function ({data, priority}) {}` and returns a Boolean.
  6877. * @property {Function} saturated - a callback that is called when the number of
  6878. * running workers hits the `concurrency` limit, and further tasks will be
  6879. * queued.
  6880. * @property {Function} unsaturated - a callback that is called when the number
  6881. * of running workers is less than the `concurrency` & `buffer` limits, and
  6882. * further tasks will not be queued.
  6883. * @property {number} buffer - A minimum threshold buffer in order to say that
  6884. * the `queue` is `unsaturated`.
  6885. * @property {Function} empty - a callback that is called when the last item
  6886. * from the `queue` is given to a `worker`.
  6887. * @property {Function} drain - a callback that is called when the last item
  6888. * from the `queue` has returned from the `worker`.
  6889. * @property {Function} error - a callback that is called when a task errors.
  6890. * Has the signature `function(error, task)`.
  6891. * @property {boolean} paused - a boolean for determining whether the queue is
  6892. * in a paused state.
  6893. * @property {Function} pause - a function that pauses the processing of tasks
  6894. * until `resume()` is called. Invoke with `queue.pause()`.
  6895. * @property {Function} resume - a function that resumes the processing of
  6896. * queued tasks when the queue is paused. Invoke with `queue.resume()`.
  6897. * @property {Function} kill - a function that removes the `drain` callback and
  6898. * empties remaining tasks from the queue forcing it to go idle. No more tasks
  6899. * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
  6900. */
  6901. /**
  6902. * Creates a `queue` object with the specified `concurrency`. Tasks added to the
  6903. * `queue` are processed in parallel (up to the `concurrency` limit). If all
  6904. * `worker`s are in progress, the task is queued until one becomes available.
  6905. * Once a `worker` completes a `task`, that `task`'s callback is called.
  6906. *
  6907. * @name queue
  6908. * @static
  6909. * @memberOf module:ControlFlow
  6910. * @method
  6911. * @category Control Flow
  6912. * @param {AsyncFunction} worker - An async function for processing a queued task.
  6913. * If you want to handle errors from an individual task, pass a callback to
  6914. * `q.push()`. Invoked with (task, callback).
  6915. * @param {number} [concurrency=1] - An `integer` for determining how many
  6916. * `worker` functions should be run in parallel. If omitted, the concurrency
  6917. * defaults to `1`. If the concurrency is `0`, an error is thrown.
  6918. * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can
  6919. * attached as certain properties to listen for specific events during the
  6920. * lifecycle of the queue.
  6921. * @example
  6922. *
  6923. * // create a queue object with concurrency 2
  6924. * var q = async.queue(function(task, callback) {
  6925. * console.log('hello ' + task.name);
  6926. * callback();
  6927. * }, 2);
  6928. *
  6929. * // assign a callback
  6930. * q.drain = function() {
  6931. * console.log('all items have been processed');
  6932. * };
  6933. *
  6934. * // add some items to the queue
  6935. * q.push({name: 'foo'}, function(err) {
  6936. * console.log('finished processing foo');
  6937. * });
  6938. * q.push({name: 'bar'}, function (err) {
  6939. * console.log('finished processing bar');
  6940. * });
  6941. *
  6942. * // add some items to the queue (batch-wise)
  6943. * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
  6944. * console.log('finished processing item');
  6945. * });
  6946. *
  6947. * // add some items to the front of the queue
  6948. * q.unshift({name: 'bar'}, function (err) {
  6949. * console.log('finished processing bar');
  6950. * });
  6951. */
  6952. var queue$1 = function (worker, concurrency) {
  6953. var _worker = wrapAsync(worker);
  6954. return queue(function (items, cb) {
  6955. _worker(items[0], cb);
  6956. }, concurrency, 1);
  6957. };
  6958. /**
  6959. * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
  6960. * completed in ascending priority order.
  6961. *
  6962. * @name priorityQueue
  6963. * @static
  6964. * @memberOf module:ControlFlow
  6965. * @method
  6966. * @see [async.queue]{@link module:ControlFlow.queue}
  6967. * @category Control Flow
  6968. * @param {AsyncFunction} worker - An async function for processing a queued task.
  6969. * If you want to handle errors from an individual task, pass a callback to
  6970. * `q.push()`.
  6971. * Invoked with (task, callback).
  6972. * @param {number} concurrency - An `integer` for determining how many `worker`
  6973. * functions should be run in parallel. If omitted, the concurrency defaults to
  6974. * `1`. If the concurrency is `0`, an error is thrown.
  6975. * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
  6976. * differences between `queue` and `priorityQueue` objects:
  6977. * * `push(task, priority, [callback])` - `priority` should be a number. If an
  6978. * array of `tasks` is given, all tasks will be assigned the same priority.
  6979. * * The `unshift` method was removed.
  6980. */
  6981. var priorityQueue = function(worker, concurrency) {
  6982. // Start with a normal queue
  6983. var q = queue$1(worker, concurrency);
  6984. // Override push to accept second parameter representing priority
  6985. q.push = function(data, priority, callback) {
  6986. if (callback == null) callback = noop;
  6987. if (typeof callback !== 'function') {
  6988. throw new Error('task callback must be a function');
  6989. }
  6990. q.started = true;
  6991. if (!isArray(data)) {
  6992. data = [data];
  6993. }
  6994. if (data.length === 0) {
  6995. // call drain immediately if there are no tasks
  6996. return setImmediate$1(function() {
  6997. q.drain();
  6998. });
  6999. }
  7000. priority = priority || 0;
  7001. var nextNode = q._tasks.head;
  7002. while (nextNode && priority >= nextNode.priority) {
  7003. nextNode = nextNode.next;
  7004. }
  7005. for (var i = 0, l = data.length; i < l; i++) {
  7006. var item = {
  7007. data: data[i],
  7008. priority: priority,
  7009. callback: callback
  7010. };
  7011. if (nextNode) {
  7012. q._tasks.insertBefore(nextNode, item);
  7013. } else {
  7014. q._tasks.push(item);
  7015. }
  7016. }
  7017. setImmediate$1(q.process);
  7018. };
  7019. // Remove unshift function
  7020. delete q.unshift;
  7021. return q;
  7022. };
  7023. /**
  7024. * Runs the `tasks` array of functions in parallel, without waiting until the
  7025. * previous function has completed. Once any of the `tasks` complete or pass an
  7026. * error to its callback, the main `callback` is immediately called. It's
  7027. * equivalent to `Promise.race()`.
  7028. *
  7029. * @name race
  7030. * @static
  7031. * @memberOf module:ControlFlow
  7032. * @method
  7033. * @category Control Flow
  7034. * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
  7035. * to run. Each function can complete with an optional `result` value.
  7036. * @param {Function} callback - A callback to run once any of the functions have
  7037. * completed. This function gets an error or result from the first function that
  7038. * completed. Invoked with (err, result).
  7039. * @returns undefined
  7040. * @example
  7041. *
  7042. * async.race([
  7043. * function(callback) {
  7044. * setTimeout(function() {
  7045. * callback(null, 'one');
  7046. * }, 200);
  7047. * },
  7048. * function(callback) {
  7049. * setTimeout(function() {
  7050. * callback(null, 'two');
  7051. * }, 100);
  7052. * }
  7053. * ],
  7054. * // main callback
  7055. * function(err, result) {
  7056. * // the result will be equal to 'two' as it finishes earlier
  7057. * });
  7058. */
  7059. function race(tasks, callback) {
  7060. callback = once(callback || noop);
  7061. if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
  7062. if (!tasks.length) return callback();
  7063. for (var i = 0, l = tasks.length; i < l; i++) {
  7064. wrapAsync(tasks[i])(callback);
  7065. }
  7066. }
  7067. /**
  7068. * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
  7069. *
  7070. * @name reduceRight
  7071. * @static
  7072. * @memberOf module:Collections
  7073. * @method
  7074. * @see [async.reduce]{@link module:Collections.reduce}
  7075. * @alias foldr
  7076. * @category Collection
  7077. * @param {Array} array - A collection to iterate over.
  7078. * @param {*} memo - The initial state of the reduction.
  7079. * @param {AsyncFunction} iteratee - A function applied to each item in the
  7080. * array to produce the next step in the reduction.
  7081. * The `iteratee` should complete with the next state of the reduction.
  7082. * If the iteratee complete with an error, the reduction is stopped and the
  7083. * main `callback` is immediately called with the error.
  7084. * Invoked with (memo, item, callback).
  7085. * @param {Function} [callback] - A callback which is called after all the
  7086. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  7087. * (err, result).
  7088. */
  7089. function reduceRight (array, memo, iteratee, callback) {
  7090. var reversed = slice(array).reverse();
  7091. reduce(reversed, memo, iteratee, callback);
  7092. }
  7093. /**
  7094. * Wraps the async function in another function that always completes with a
  7095. * result object, even when it errors.
  7096. *
  7097. * The result object has either the property `error` or `value`.
  7098. *
  7099. * @name reflect
  7100. * @static
  7101. * @memberOf module:Utils
  7102. * @method
  7103. * @category Util
  7104. * @param {AsyncFunction} fn - The async function you want to wrap
  7105. * @returns {Function} - A function that always passes null to it's callback as
  7106. * the error. The second argument to the callback will be an `object` with
  7107. * either an `error` or a `value` property.
  7108. * @example
  7109. *
  7110. * async.parallel([
  7111. * async.reflect(function(callback) {
  7112. * // do some stuff ...
  7113. * callback(null, 'one');
  7114. * }),
  7115. * async.reflect(function(callback) {
  7116. * // do some more stuff but error ...
  7117. * callback('bad stuff happened');
  7118. * }),
  7119. * async.reflect(function(callback) {
  7120. * // do some more stuff ...
  7121. * callback(null, 'two');
  7122. * })
  7123. * ],
  7124. * // optional callback
  7125. * function(err, results) {
  7126. * // values
  7127. * // results[0].value = 'one'
  7128. * // results[1].error = 'bad stuff happened'
  7129. * // results[2].value = 'two'
  7130. * });
  7131. */
  7132. function reflect(fn) {
  7133. var _fn = wrapAsync(fn);
  7134. return initialParams(function reflectOn(args, reflectCallback) {
  7135. args.push(function callback(error, cbArg) {
  7136. if (error) {
  7137. reflectCallback(null, { error: error });
  7138. } else {
  7139. var value;
  7140. if (arguments.length <= 2) {
  7141. value = cbArg;
  7142. } else {
  7143. value = slice(arguments, 1);
  7144. }
  7145. reflectCallback(null, { value: value });
  7146. }
  7147. });
  7148. return _fn.apply(this, args);
  7149. });
  7150. }
  7151. /**
  7152. * A helper function that wraps an array or an object of functions with `reflect`.
  7153. *
  7154. * @name reflectAll
  7155. * @static
  7156. * @memberOf module:Utils
  7157. * @method
  7158. * @see [async.reflect]{@link module:Utils.reflect}
  7159. * @category Util
  7160. * @param {Array|Object|Iterable} tasks - The collection of
  7161. * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
  7162. * @returns {Array} Returns an array of async functions, each wrapped in
  7163. * `async.reflect`
  7164. * @example
  7165. *
  7166. * let tasks = [
  7167. * function(callback) {
  7168. * setTimeout(function() {
  7169. * callback(null, 'one');
  7170. * }, 200);
  7171. * },
  7172. * function(callback) {
  7173. * // do some more stuff but error ...
  7174. * callback(new Error('bad stuff happened'));
  7175. * },
  7176. * function(callback) {
  7177. * setTimeout(function() {
  7178. * callback(null, 'two');
  7179. * }, 100);
  7180. * }
  7181. * ];
  7182. *
  7183. * async.parallel(async.reflectAll(tasks),
  7184. * // optional callback
  7185. * function(err, results) {
  7186. * // values
  7187. * // results[0].value = 'one'
  7188. * // results[1].error = Error('bad stuff happened')
  7189. * // results[2].value = 'two'
  7190. * });
  7191. *
  7192. * // an example using an object instead of an array
  7193. * let tasks = {
  7194. * one: function(callback) {
  7195. * setTimeout(function() {
  7196. * callback(null, 'one');
  7197. * }, 200);
  7198. * },
  7199. * two: function(callback) {
  7200. * callback('two');
  7201. * },
  7202. * three: function(callback) {
  7203. * setTimeout(function() {
  7204. * callback(null, 'three');
  7205. * }, 100);
  7206. * }
  7207. * };
  7208. *
  7209. * async.parallel(async.reflectAll(tasks),
  7210. * // optional callback
  7211. * function(err, results) {
  7212. * // values
  7213. * // results.one.value = 'one'
  7214. * // results.two.error = 'two'
  7215. * // results.three.value = 'three'
  7216. * });
  7217. */
  7218. function reflectAll(tasks) {
  7219. var results;
  7220. if (isArray(tasks)) {
  7221. results = arrayMap(tasks, reflect);
  7222. } else {
  7223. results = {};
  7224. baseForOwn(tasks, function(task, key) {
  7225. results[key] = reflect.call(this, task);
  7226. });
  7227. }
  7228. return results;
  7229. }
  7230. function reject$1(eachfn, arr, iteratee, callback) {
  7231. _filter(eachfn, arr, function(value, cb) {
  7232. iteratee(value, function(err, v) {
  7233. cb(err, !v);
  7234. });
  7235. }, callback);
  7236. }
  7237. /**
  7238. * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
  7239. *
  7240. * @name reject
  7241. * @static
  7242. * @memberOf module:Collections
  7243. * @method
  7244. * @see [async.filter]{@link module:Collections.filter}
  7245. * @category Collection
  7246. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  7247. * @param {Function} iteratee - An async truth test to apply to each item in
  7248. * `coll`.
  7249. * The should complete with a boolean value as its `result`.
  7250. * Invoked with (item, callback).
  7251. * @param {Function} [callback] - A callback which is called after all the
  7252. * `iteratee` functions have finished. Invoked with (err, results).
  7253. * @example
  7254. *
  7255. * async.reject(['file1','file2','file3'], function(filePath, callback) {
  7256. * fs.access(filePath, function(err) {
  7257. * callback(null, !err)
  7258. * });
  7259. * }, function(err, results) {
  7260. * // results now equals an array of missing files
  7261. * createFiles(results);
  7262. * });
  7263. */
  7264. var reject = doParallel(reject$1);
  7265. /**
  7266. * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
  7267. * time.
  7268. *
  7269. * @name rejectLimit
  7270. * @static
  7271. * @memberOf module:Collections
  7272. * @method
  7273. * @see [async.reject]{@link module:Collections.reject}
  7274. * @category Collection
  7275. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  7276. * @param {number} limit - The maximum number of async operations at a time.
  7277. * @param {Function} iteratee - An async truth test to apply to each item in
  7278. * `coll`.
  7279. * The should complete with a boolean value as its `result`.
  7280. * Invoked with (item, callback).
  7281. * @param {Function} [callback] - A callback which is called after all the
  7282. * `iteratee` functions have finished. Invoked with (err, results).
  7283. */
  7284. var rejectLimit = doParallelLimit(reject$1);
  7285. /**
  7286. * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
  7287. *
  7288. * @name rejectSeries
  7289. * @static
  7290. * @memberOf module:Collections
  7291. * @method
  7292. * @see [async.reject]{@link module:Collections.reject}
  7293. * @category Collection
  7294. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  7295. * @param {Function} iteratee - An async truth test to apply to each item in
  7296. * `coll`.
  7297. * The should complete with a boolean value as its `result`.
  7298. * Invoked with (item, callback).
  7299. * @param {Function} [callback] - A callback which is called after all the
  7300. * `iteratee` functions have finished. Invoked with (err, results).
  7301. */
  7302. var rejectSeries = doLimit(rejectLimit, 1);
  7303. /**
  7304. * Creates a function that returns `value`.
  7305. *
  7306. * @static
  7307. * @memberOf _
  7308. * @since 2.4.0
  7309. * @category Util
  7310. * @param {*} value The value to return from the new function.
  7311. * @returns {Function} Returns the new constant function.
  7312. * @example
  7313. *
  7314. * var objects = _.times(2, _.constant({ 'a': 1 }));
  7315. *
  7316. * console.log(objects);
  7317. * // => [{ 'a': 1 }, { 'a': 1 }]
  7318. *
  7319. * console.log(objects[0] === objects[1]);
  7320. * // => true
  7321. */
  7322. function constant$1(value) {
  7323. return function() {
  7324. return value;
  7325. };
  7326. }
  7327. /**
  7328. * Attempts to get a successful response from `task` no more than `times` times
  7329. * before returning an error. If the task is successful, the `callback` will be
  7330. * passed the result of the successful task. If all attempts fail, the callback
  7331. * will be passed the error and result (if any) of the final attempt.
  7332. *
  7333. * @name retry
  7334. * @static
  7335. * @memberOf module:ControlFlow
  7336. * @method
  7337. * @category Control Flow
  7338. * @see [async.retryable]{@link module:ControlFlow.retryable}
  7339. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
  7340. * object with `times` and `interval` or a number.
  7341. * * `times` - The number of attempts to make before giving up. The default
  7342. * is `5`.
  7343. * * `interval` - The time to wait between retries, in milliseconds. The
  7344. * default is `0`. The interval may also be specified as a function of the
  7345. * retry count (see example).
  7346. * * `errorFilter` - An optional synchronous function that is invoked on
  7347. * erroneous result. If it returns `true` the retry attempts will continue;
  7348. * if the function returns `false` the retry flow is aborted with the current
  7349. * attempt's error and result being returned to the final callback.
  7350. * Invoked with (err).
  7351. * * If `opts` is a number, the number specifies the number of times to retry,
  7352. * with the default interval of `0`.
  7353. * @param {AsyncFunction} task - An async function to retry.
  7354. * Invoked with (callback).
  7355. * @param {Function} [callback] - An optional callback which is called when the
  7356. * task has succeeded, or after the final failed attempt. It receives the `err`
  7357. * and `result` arguments of the last attempt at completing the `task`. Invoked
  7358. * with (err, results).
  7359. *
  7360. * @example
  7361. *
  7362. * // The `retry` function can be used as a stand-alone control flow by passing
  7363. * // a callback, as shown below:
  7364. *
  7365. * // try calling apiMethod 3 times
  7366. * async.retry(3, apiMethod, function(err, result) {
  7367. * // do something with the result
  7368. * });
  7369. *
  7370. * // try calling apiMethod 3 times, waiting 200 ms between each retry
  7371. * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
  7372. * // do something with the result
  7373. * });
  7374. *
  7375. * // try calling apiMethod 10 times with exponential backoff
  7376. * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
  7377. * async.retry({
  7378. * times: 10,
  7379. * interval: function(retryCount) {
  7380. * return 50 * Math.pow(2, retryCount);
  7381. * }
  7382. * }, apiMethod, function(err, result) {
  7383. * // do something with the result
  7384. * });
  7385. *
  7386. * // try calling apiMethod the default 5 times no delay between each retry
  7387. * async.retry(apiMethod, function(err, result) {
  7388. * // do something with the result
  7389. * });
  7390. *
  7391. * // try calling apiMethod only when error condition satisfies, all other
  7392. * // errors will abort the retry control flow and return to final callback
  7393. * async.retry({
  7394. * errorFilter: function(err) {
  7395. * return err.message === 'Temporary error'; // only retry on a specific error
  7396. * }
  7397. * }, apiMethod, function(err, result) {
  7398. * // do something with the result
  7399. * });
  7400. *
  7401. * // to retry individual methods that are not as reliable within other
  7402. * // control flow functions, use the `retryable` wrapper:
  7403. * async.auto({
  7404. * users: api.getUsers.bind(api),
  7405. * payments: async.retryable(3, api.getPayments.bind(api))
  7406. * }, function(err, results) {
  7407. * // do something with the results
  7408. * });
  7409. *
  7410. */
  7411. function retry(opts, task, callback) {
  7412. var DEFAULT_TIMES = 5;
  7413. var DEFAULT_INTERVAL = 0;
  7414. var options = {
  7415. times: DEFAULT_TIMES,
  7416. intervalFunc: constant$1(DEFAULT_INTERVAL)
  7417. };
  7418. function parseTimes(acc, t) {
  7419. if (typeof t === 'object') {
  7420. acc.times = +t.times || DEFAULT_TIMES;
  7421. acc.intervalFunc = typeof t.interval === 'function' ?
  7422. t.interval :
  7423. constant$1(+t.interval || DEFAULT_INTERVAL);
  7424. acc.errorFilter = t.errorFilter;
  7425. } else if (typeof t === 'number' || typeof t === 'string') {
  7426. acc.times = +t || DEFAULT_TIMES;
  7427. } else {
  7428. throw new Error("Invalid arguments for async.retry");
  7429. }
  7430. }
  7431. if (arguments.length < 3 && typeof opts === 'function') {
  7432. callback = task || noop;
  7433. task = opts;
  7434. } else {
  7435. parseTimes(options, opts);
  7436. callback = callback || noop;
  7437. }
  7438. if (typeof task !== 'function') {
  7439. throw new Error("Invalid arguments for async.retry");
  7440. }
  7441. var _task = wrapAsync(task);
  7442. var attempt = 1;
  7443. function retryAttempt() {
  7444. _task(function(err) {
  7445. if (err && attempt++ < options.times &&
  7446. (typeof options.errorFilter != 'function' ||
  7447. options.errorFilter(err))) {
  7448. setTimeout(retryAttempt, options.intervalFunc(attempt));
  7449. } else {
  7450. callback.apply(null, arguments);
  7451. }
  7452. });
  7453. }
  7454. retryAttempt();
  7455. }
  7456. /**
  7457. * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
  7458. * wraps a task and makes it retryable, rather than immediately calling it
  7459. * with retries.
  7460. *
  7461. * @name retryable
  7462. * @static
  7463. * @memberOf module:ControlFlow
  7464. * @method
  7465. * @see [async.retry]{@link module:ControlFlow.retry}
  7466. * @category Control Flow
  7467. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
  7468. * options, exactly the same as from `retry`
  7469. * @param {AsyncFunction} task - the asynchronous function to wrap.
  7470. * This function will be passed any arguments passed to the returned wrapper.
  7471. * Invoked with (...args, callback).
  7472. * @returns {AsyncFunction} The wrapped function, which when invoked, will
  7473. * retry on an error, based on the parameters specified in `opts`.
  7474. * This function will accept the same parameters as `task`.
  7475. * @example
  7476. *
  7477. * async.auto({
  7478. * dep1: async.retryable(3, getFromFlakyService),
  7479. * process: ["dep1", async.retryable(3, function (results, cb) {
  7480. * maybeProcessData(results.dep1, cb);
  7481. * })]
  7482. * }, callback);
  7483. */
  7484. var retryable = function (opts, task) {
  7485. if (!task) {
  7486. task = opts;
  7487. opts = null;
  7488. }
  7489. var _task = wrapAsync(task);
  7490. return initialParams(function (args, callback) {
  7491. function taskFn(cb) {
  7492. _task.apply(null, args.concat(cb));
  7493. }
  7494. if (opts) retry(opts, taskFn, callback);
  7495. else retry(taskFn, callback);
  7496. });
  7497. };
  7498. /**
  7499. * Run the functions in the `tasks` collection in series, each one running once
  7500. * the previous function has completed. If any functions in the series pass an
  7501. * error to its callback, no more functions are run, and `callback` is
  7502. * immediately called with the value of the error. Otherwise, `callback`
  7503. * receives an array of results when `tasks` have completed.
  7504. *
  7505. * It is also possible to use an object instead of an array. Each property will
  7506. * be run as a function, and the results will be passed to the final `callback`
  7507. * as an object instead of an array. This can be a more readable way of handling
  7508. * results from {@link async.series}.
  7509. *
  7510. * **Note** that while many implementations preserve the order of object
  7511. * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
  7512. * explicitly states that
  7513. *
  7514. * > The mechanics and order of enumerating the properties is not specified.
  7515. *
  7516. * So if you rely on the order in which your series of functions are executed,
  7517. * and want this to work on all platforms, consider using an array.
  7518. *
  7519. * @name series
  7520. * @static
  7521. * @memberOf module:ControlFlow
  7522. * @method
  7523. * @category Control Flow
  7524. * @param {Array|Iterable|Object} tasks - A collection containing
  7525. * [async functions]{@link AsyncFunction} to run in series.
  7526. * Each function can complete with any number of optional `result` values.
  7527. * @param {Function} [callback] - An optional callback to run once all the
  7528. * functions have completed. This function gets a results array (or object)
  7529. * containing all the result arguments passed to the `task` callbacks. Invoked
  7530. * with (err, result).
  7531. * @example
  7532. * async.series([
  7533. * function(callback) {
  7534. * // do some stuff ...
  7535. * callback(null, 'one');
  7536. * },
  7537. * function(callback) {
  7538. * // do some more stuff ...
  7539. * callback(null, 'two');
  7540. * }
  7541. * ],
  7542. * // optional callback
  7543. * function(err, results) {
  7544. * // results is now equal to ['one', 'two']
  7545. * });
  7546. *
  7547. * async.series({
  7548. * one: function(callback) {
  7549. * setTimeout(function() {
  7550. * callback(null, 1);
  7551. * }, 200);
  7552. * },
  7553. * two: function(callback){
  7554. * setTimeout(function() {
  7555. * callback(null, 2);
  7556. * }, 100);
  7557. * }
  7558. * }, function(err, results) {
  7559. * // results is now equal to: {one: 1, two: 2}
  7560. * });
  7561. */
  7562. function series(tasks, callback) {
  7563. _parallel(eachOfSeries, tasks, callback);
  7564. }
  7565. /**
  7566. * Returns `true` if at least one element in the `coll` satisfies an async test.
  7567. * If any iteratee call returns `true`, the main `callback` is immediately
  7568. * called.
  7569. *
  7570. * @name some
  7571. * @static
  7572. * @memberOf module:Collections
  7573. * @method
  7574. * @alias any
  7575. * @category Collection
  7576. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  7577. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  7578. * in the collections in parallel.
  7579. * The iteratee should complete with a boolean `result` value.
  7580. * Invoked with (item, callback).
  7581. * @param {Function} [callback] - A callback which is called as soon as any
  7582. * iteratee returns `true`, or after all the iteratee functions have finished.
  7583. * Result will be either `true` or `false` depending on the values of the async
  7584. * tests. Invoked with (err, result).
  7585. * @example
  7586. *
  7587. * async.some(['file1','file2','file3'], function(filePath, callback) {
  7588. * fs.access(filePath, function(err) {
  7589. * callback(null, !err)
  7590. * });
  7591. * }, function(err, result) {
  7592. * // if result is true then at least one of the files exists
  7593. * });
  7594. */
  7595. var some = doParallel(_createTester(Boolean, identity));
  7596. /**
  7597. * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
  7598. *
  7599. * @name someLimit
  7600. * @static
  7601. * @memberOf module:Collections
  7602. * @method
  7603. * @see [async.some]{@link module:Collections.some}
  7604. * @alias anyLimit
  7605. * @category Collection
  7606. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  7607. * @param {number} limit - The maximum number of async operations at a time.
  7608. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  7609. * in the collections in parallel.
  7610. * The iteratee should complete with a boolean `result` value.
  7611. * Invoked with (item, callback).
  7612. * @param {Function} [callback] - A callback which is called as soon as any
  7613. * iteratee returns `true`, or after all the iteratee functions have finished.
  7614. * Result will be either `true` or `false` depending on the values of the async
  7615. * tests. Invoked with (err, result).
  7616. */
  7617. var someLimit = doParallelLimit(_createTester(Boolean, identity));
  7618. /**
  7619. * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
  7620. *
  7621. * @name someSeries
  7622. * @static
  7623. * @memberOf module:Collections
  7624. * @method
  7625. * @see [async.some]{@link module:Collections.some}
  7626. * @alias anySeries
  7627. * @category Collection
  7628. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  7629. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  7630. * in the collections in series.
  7631. * The iteratee should complete with a boolean `result` value.
  7632. * Invoked with (item, callback).
  7633. * @param {Function} [callback] - A callback which is called as soon as any
  7634. * iteratee returns `true`, or after all the iteratee functions have finished.
  7635. * Result will be either `true` or `false` depending on the values of the async
  7636. * tests. Invoked with (err, result).
  7637. */
  7638. var someSeries = doLimit(someLimit, 1);
  7639. /**
  7640. * Sorts a list by the results of running each `coll` value through an async
  7641. * `iteratee`.
  7642. *
  7643. * @name sortBy
  7644. * @static
  7645. * @memberOf module:Collections
  7646. * @method
  7647. * @category Collection
  7648. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  7649. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  7650. * `coll`.
  7651. * The iteratee should complete with a value to use as the sort criteria as
  7652. * its `result`.
  7653. * Invoked with (item, callback).
  7654. * @param {Function} callback - A callback which is called after all the
  7655. * `iteratee` functions have finished, or an error occurs. Results is the items
  7656. * from the original `coll` sorted by the values returned by the `iteratee`
  7657. * calls. Invoked with (err, results).
  7658. * @example
  7659. *
  7660. * async.sortBy(['file1','file2','file3'], function(file, callback) {
  7661. * fs.stat(file, function(err, stats) {
  7662. * callback(err, stats.mtime);
  7663. * });
  7664. * }, function(err, results) {
  7665. * // results is now the original array of files sorted by
  7666. * // modified date
  7667. * });
  7668. *
  7669. * // By modifying the callback parameter the
  7670. * // sorting order can be influenced:
  7671. *
  7672. * // ascending order
  7673. * async.sortBy([1,9,3,5], function(x, callback) {
  7674. * callback(null, x);
  7675. * }, function(err,result) {
  7676. * // result callback
  7677. * });
  7678. *
  7679. * // descending order
  7680. * async.sortBy([1,9,3,5], function(x, callback) {
  7681. * callback(null, x*-1); //<- x*-1 instead of x, turns the order around
  7682. * }, function(err,result) {
  7683. * // result callback
  7684. * });
  7685. */
  7686. function sortBy (coll, iteratee, callback) {
  7687. var _iteratee = wrapAsync(iteratee);
  7688. map(coll, function (x, callback) {
  7689. _iteratee(x, function (err, criteria) {
  7690. if (err) return callback(err);
  7691. callback(null, {value: x, criteria: criteria});
  7692. });
  7693. }, function (err, results) {
  7694. if (err) return callback(err);
  7695. callback(null, arrayMap(results.sort(comparator), baseProperty('value')));
  7696. });
  7697. function comparator(left, right) {
  7698. var a = left.criteria, b = right.criteria;
  7699. return a < b ? -1 : a > b ? 1 : 0;
  7700. }
  7701. }
  7702. /**
  7703. * Sets a time limit on an asynchronous function. If the function does not call
  7704. * its callback within the specified milliseconds, it will be called with a
  7705. * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
  7706. *
  7707. * @name timeout
  7708. * @static
  7709. * @memberOf module:Utils
  7710. * @method
  7711. * @category Util
  7712. * @param {AsyncFunction} asyncFn - The async function to limit in time.
  7713. * @param {number} milliseconds - The specified time limit.
  7714. * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
  7715. * to timeout Error for more information..
  7716. * @returns {AsyncFunction} Returns a wrapped function that can be used with any
  7717. * of the control flow functions.
  7718. * Invoke this function with the same parameters as you would `asyncFunc`.
  7719. * @example
  7720. *
  7721. * function myFunction(foo, callback) {
  7722. * doAsyncTask(foo, function(err, data) {
  7723. * // handle errors
  7724. * if (err) return callback(err);
  7725. *
  7726. * // do some stuff ...
  7727. *
  7728. * // return processed data
  7729. * return callback(null, data);
  7730. * });
  7731. * }
  7732. *
  7733. * var wrapped = async.timeout(myFunction, 1000);
  7734. *
  7735. * // call `wrapped` as you would `myFunction`
  7736. * wrapped({ bar: 'bar' }, function(err, data) {
  7737. * // if `myFunction` takes < 1000 ms to execute, `err`
  7738. * // and `data` will have their expected values
  7739. *
  7740. * // else `err` will be an Error with the code 'ETIMEDOUT'
  7741. * });
  7742. */
  7743. function timeout(asyncFn, milliseconds, info) {
  7744. var fn = wrapAsync(asyncFn);
  7745. return initialParams(function (args, callback) {
  7746. var timedOut = false;
  7747. var timer;
  7748. function timeoutCallback() {
  7749. var name = asyncFn.name || 'anonymous';
  7750. var error = new Error('Callback function "' + name + '" timed out.');
  7751. error.code = 'ETIMEDOUT';
  7752. if (info) {
  7753. error.info = info;
  7754. }
  7755. timedOut = true;
  7756. callback(error);
  7757. }
  7758. args.push(function () {
  7759. if (!timedOut) {
  7760. callback.apply(null, arguments);
  7761. clearTimeout(timer);
  7762. }
  7763. });
  7764. // setup timer and call original function
  7765. timer = setTimeout(timeoutCallback, milliseconds);
  7766. fn.apply(null, args);
  7767. });
  7768. }
  7769. /* Built-in method references for those with the same name as other `lodash` methods. */
  7770. var nativeCeil = Math.ceil;
  7771. var nativeMax = Math.max;
  7772. /**
  7773. * The base implementation of `_.range` and `_.rangeRight` which doesn't
  7774. * coerce arguments.
  7775. *
  7776. * @private
  7777. * @param {number} start The start of the range.
  7778. * @param {number} end The end of the range.
  7779. * @param {number} step The value to increment or decrement by.
  7780. * @param {boolean} [fromRight] Specify iterating from right to left.
  7781. * @returns {Array} Returns the range of numbers.
  7782. */
  7783. function baseRange(start, end, step, fromRight) {
  7784. var index = -1,
  7785. length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
  7786. result = Array(length);
  7787. while (length--) {
  7788. result[fromRight ? length : ++index] = start;
  7789. start += step;
  7790. }
  7791. return result;
  7792. }
  7793. /**
  7794. * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
  7795. * time.
  7796. *
  7797. * @name timesLimit
  7798. * @static
  7799. * @memberOf module:ControlFlow
  7800. * @method
  7801. * @see [async.times]{@link module:ControlFlow.times}
  7802. * @category Control Flow
  7803. * @param {number} count - The number of times to run the function.
  7804. * @param {number} limit - The maximum number of async operations at a time.
  7805. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  7806. * Invoked with the iteration index and a callback: (n, next).
  7807. * @param {Function} callback - see [async.map]{@link module:Collections.map}.
  7808. */
  7809. function timeLimit(count, limit, iteratee, callback) {
  7810. var _iteratee = wrapAsync(iteratee);
  7811. mapLimit(baseRange(0, count, 1), limit, _iteratee, callback);
  7812. }
  7813. /**
  7814. * Calls the `iteratee` function `n` times, and accumulates results in the same
  7815. * manner you would use with [map]{@link module:Collections.map}.
  7816. *
  7817. * @name times
  7818. * @static
  7819. * @memberOf module:ControlFlow
  7820. * @method
  7821. * @see [async.map]{@link module:Collections.map}
  7822. * @category Control Flow
  7823. * @param {number} n - The number of times to run the function.
  7824. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  7825. * Invoked with the iteration index and a callback: (n, next).
  7826. * @param {Function} callback - see {@link module:Collections.map}.
  7827. * @example
  7828. *
  7829. * // Pretend this is some complicated async factory
  7830. * var createUser = function(id, callback) {
  7831. * callback(null, {
  7832. * id: 'user' + id
  7833. * });
  7834. * };
  7835. *
  7836. * // generate 5 users
  7837. * async.times(5, function(n, next) {
  7838. * createUser(n, function(err, user) {
  7839. * next(err, user);
  7840. * });
  7841. * }, function(err, users) {
  7842. * // we should now have 5 users
  7843. * });
  7844. */
  7845. var times = doLimit(timeLimit, Infinity);
  7846. /**
  7847. * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
  7848. *
  7849. * @name timesSeries
  7850. * @static
  7851. * @memberOf module:ControlFlow
  7852. * @method
  7853. * @see [async.times]{@link module:ControlFlow.times}
  7854. * @category Control Flow
  7855. * @param {number} n - The number of times to run the function.
  7856. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  7857. * Invoked with the iteration index and a callback: (n, next).
  7858. * @param {Function} callback - see {@link module:Collections.map}.
  7859. */
  7860. var timesSeries = doLimit(timeLimit, 1);
  7861. /**
  7862. * A relative of `reduce`. Takes an Object or Array, and iterates over each
  7863. * element in series, each step potentially mutating an `accumulator` value.
  7864. * The type of the accumulator defaults to the type of collection passed in.
  7865. *
  7866. * @name transform
  7867. * @static
  7868. * @memberOf module:Collections
  7869. * @method
  7870. * @category Collection
  7871. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  7872. * @param {*} [accumulator] - The initial state of the transform. If omitted,
  7873. * it will default to an empty Object or Array, depending on the type of `coll`
  7874. * @param {AsyncFunction} iteratee - A function applied to each item in the
  7875. * collection that potentially modifies the accumulator.
  7876. * Invoked with (accumulator, item, key, callback).
  7877. * @param {Function} [callback] - A callback which is called after all the
  7878. * `iteratee` functions have finished. Result is the transformed accumulator.
  7879. * Invoked with (err, result).
  7880. * @example
  7881. *
  7882. * async.transform([1,2,3], function(acc, item, index, callback) {
  7883. * // pointless async:
  7884. * process.nextTick(function() {
  7885. * acc.push(item * 2)
  7886. * callback(null)
  7887. * });
  7888. * }, function(err, result) {
  7889. * // result is now equal to [2, 4, 6]
  7890. * });
  7891. *
  7892. * @example
  7893. *
  7894. * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
  7895. * setImmediate(function () {
  7896. * obj[key] = val * 2;
  7897. * callback();
  7898. * })
  7899. * }, function (err, result) {
  7900. * // result is equal to {a: 2, b: 4, c: 6}
  7901. * })
  7902. */
  7903. function transform (coll, accumulator, iteratee, callback) {
  7904. if (arguments.length <= 3) {
  7905. callback = iteratee;
  7906. iteratee = accumulator;
  7907. accumulator = isArray(coll) ? [] : {};
  7908. }
  7909. callback = once(callback || noop);
  7910. var _iteratee = wrapAsync(iteratee);
  7911. eachOf(coll, function(v, k, cb) {
  7912. _iteratee(accumulator, v, k, cb);
  7913. }, function(err) {
  7914. callback(err, accumulator);
  7915. });
  7916. }
  7917. /**
  7918. * It runs each task in series but stops whenever any of the functions were
  7919. * successful. If one of the tasks were successful, the `callback` will be
  7920. * passed the result of the successful task. If all tasks fail, the callback
  7921. * will be passed the error and result (if any) of the final attempt.
  7922. *
  7923. * @name tryEach
  7924. * @static
  7925. * @memberOf module:ControlFlow
  7926. * @method
  7927. * @category Control Flow
  7928. * @param {Array|Iterable|Object} tasks - A collection containing functions to
  7929. * run, each function is passed a `callback(err, result)` it must call on
  7930. * completion with an error `err` (which can be `null`) and an optional `result`
  7931. * value.
  7932. * @param {Function} [callback] - An optional callback which is called when one
  7933. * of the tasks has succeeded, or all have failed. It receives the `err` and
  7934. * `result` arguments of the last attempt at completing the `task`. Invoked with
  7935. * (err, results).
  7936. * @example
  7937. * async.tryEach([
  7938. * function getDataFromFirstWebsite(callback) {
  7939. * // Try getting the data from the first website
  7940. * callback(err, data);
  7941. * },
  7942. * function getDataFromSecondWebsite(callback) {
  7943. * // First website failed,
  7944. * // Try getting the data from the backup website
  7945. * callback(err, data);
  7946. * }
  7947. * ],
  7948. * // optional callback
  7949. * function(err, results) {
  7950. * Now do something with the data.
  7951. * });
  7952. *
  7953. */
  7954. function tryEach(tasks, callback) {
  7955. var error = null;
  7956. var result;
  7957. callback = callback || noop;
  7958. eachSeries(tasks, function(task, callback) {
  7959. wrapAsync(task)(function (err, res/*, ...args*/) {
  7960. if (arguments.length > 2) {
  7961. result = slice(arguments, 1);
  7962. } else {
  7963. result = res;
  7964. }
  7965. error = err;
  7966. callback(!err);
  7967. });
  7968. }, function () {
  7969. callback(error, result);
  7970. });
  7971. }
  7972. /**
  7973. * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
  7974. * unmemoized form. Handy for testing.
  7975. *
  7976. * @name unmemoize
  7977. * @static
  7978. * @memberOf module:Utils
  7979. * @method
  7980. * @see [async.memoize]{@link module:Utils.memoize}
  7981. * @category Util
  7982. * @param {AsyncFunction} fn - the memoized function
  7983. * @returns {AsyncFunction} a function that calls the original unmemoized function
  7984. */
  7985. function unmemoize(fn) {
  7986. return function () {
  7987. return (fn.unmemoized || fn).apply(null, arguments);
  7988. };
  7989. }
  7990. /**
  7991. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  7992. * stopped, or an error occurs.
  7993. *
  7994. * @name whilst
  7995. * @static
  7996. * @memberOf module:ControlFlow
  7997. * @method
  7998. * @category Control Flow
  7999. * @param {Function} test - synchronous truth test to perform before each
  8000. * execution of `iteratee`. Invoked with ().
  8001. * @param {AsyncFunction} iteratee - An async function which is called each time
  8002. * `test` passes. Invoked with (callback).
  8003. * @param {Function} [callback] - A callback which is called after the test
  8004. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  8005. * will be passed an error and any arguments passed to the final `iteratee`'s
  8006. * callback. Invoked with (err, [results]);
  8007. * @returns undefined
  8008. * @example
  8009. *
  8010. * var count = 0;
  8011. * async.whilst(
  8012. * function() { return count < 5; },
  8013. * function(callback) {
  8014. * count++;
  8015. * setTimeout(function() {
  8016. * callback(null, count);
  8017. * }, 1000);
  8018. * },
  8019. * function (err, n) {
  8020. * // 5 seconds have passed, n = 5
  8021. * }
  8022. * );
  8023. */
  8024. function whilst(test, iteratee, callback) {
  8025. callback = onlyOnce(callback || noop);
  8026. var _iteratee = wrapAsync(iteratee);
  8027. if (!test()) return callback(null);
  8028. var next = function(err/*, ...args*/) {
  8029. if (err) return callback(err);
  8030. if (test()) return _iteratee(next);
  8031. var args = slice(arguments, 1);
  8032. callback.apply(null, [null].concat(args));
  8033. };
  8034. _iteratee(next);
  8035. }
  8036. /**
  8037. * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
  8038. * stopped, or an error occurs. `callback` will be passed an error and any
  8039. * arguments passed to the final `iteratee`'s callback.
  8040. *
  8041. * The inverse of [whilst]{@link module:ControlFlow.whilst}.
  8042. *
  8043. * @name until
  8044. * @static
  8045. * @memberOf module:ControlFlow
  8046. * @method
  8047. * @see [async.whilst]{@link module:ControlFlow.whilst}
  8048. * @category Control Flow
  8049. * @param {Function} test - synchronous truth test to perform before each
  8050. * execution of `iteratee`. Invoked with ().
  8051. * @param {AsyncFunction} iteratee - An async function which is called each time
  8052. * `test` fails. Invoked with (callback).
  8053. * @param {Function} [callback] - A callback which is called after the test
  8054. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  8055. * will be passed an error and any arguments passed to the final `iteratee`'s
  8056. * callback. Invoked with (err, [results]);
  8057. */
  8058. function until(test, iteratee, callback) {
  8059. whilst(function() {
  8060. return !test.apply(this, arguments);
  8061. }, iteratee, callback);
  8062. }
  8063. /**
  8064. * Runs the `tasks` array of functions in series, each passing their results to
  8065. * the next in the array. However, if any of the `tasks` pass an error to their
  8066. * own callback, the next function is not executed, and the main `callback` is
  8067. * immediately called with the error.
  8068. *
  8069. * @name waterfall
  8070. * @static
  8071. * @memberOf module:ControlFlow
  8072. * @method
  8073. * @category Control Flow
  8074. * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
  8075. * to run.
  8076. * Each function should complete with any number of `result` values.
  8077. * The `result` values will be passed as arguments, in order, to the next task.
  8078. * @param {Function} [callback] - An optional callback to run once all the
  8079. * functions have completed. This will be passed the results of the last task's
  8080. * callback. Invoked with (err, [results]).
  8081. * @returns undefined
  8082. * @example
  8083. *
  8084. * async.waterfall([
  8085. * function(callback) {
  8086. * callback(null, 'one', 'two');
  8087. * },
  8088. * function(arg1, arg2, callback) {
  8089. * // arg1 now equals 'one' and arg2 now equals 'two'
  8090. * callback(null, 'three');
  8091. * },
  8092. * function(arg1, callback) {
  8093. * // arg1 now equals 'three'
  8094. * callback(null, 'done');
  8095. * }
  8096. * ], function (err, result) {
  8097. * // result now equals 'done'
  8098. * });
  8099. *
  8100. * // Or, with named functions:
  8101. * async.waterfall([
  8102. * myFirstFunction,
  8103. * mySecondFunction,
  8104. * myLastFunction,
  8105. * ], function (err, result) {
  8106. * // result now equals 'done'
  8107. * });
  8108. * function myFirstFunction(callback) {
  8109. * callback(null, 'one', 'two');
  8110. * }
  8111. * function mySecondFunction(arg1, arg2, callback) {
  8112. * // arg1 now equals 'one' and arg2 now equals 'two'
  8113. * callback(null, 'three');
  8114. * }
  8115. * function myLastFunction(arg1, callback) {
  8116. * // arg1 now equals 'three'
  8117. * callback(null, 'done');
  8118. * }
  8119. */
  8120. var waterfall = function(tasks, callback) {
  8121. callback = once(callback || noop);
  8122. if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
  8123. if (!tasks.length) return callback();
  8124. var taskIndex = 0;
  8125. function nextTask(args) {
  8126. var task = wrapAsync(tasks[taskIndex++]);
  8127. args.push(onlyOnce(next));
  8128. task.apply(null, args);
  8129. }
  8130. function next(err/*, ...args*/) {
  8131. if (err || taskIndex === tasks.length) {
  8132. return callback.apply(null, arguments);
  8133. }
  8134. nextTask(slice(arguments, 1));
  8135. }
  8136. nextTask([]);
  8137. };
  8138. /**
  8139. * An "async function" in the context of Async is an asynchronous function with
  8140. * a variable number of parameters, with the final parameter being a callback.
  8141. * (`function (arg1, arg2, ..., callback) {}`)
  8142. * The final callback is of the form `callback(err, results...)`, which must be
  8143. * called once the function is completed. The callback should be called with a
  8144. * Error as its first argument to signal that an error occurred.
  8145. * Otherwise, if no error occurred, it should be called with `null` as the first
  8146. * argument, and any additional `result` arguments that may apply, to signal
  8147. * successful completion.
  8148. * The callback must be called exactly once, ideally on a later tick of the
  8149. * JavaScript event loop.
  8150. *
  8151. * This type of function is also referred to as a "Node-style async function",
  8152. * or a "continuation passing-style function" (CPS). Most of the methods of this
  8153. * library are themselves CPS/Node-style async functions, or functions that
  8154. * return CPS/Node-style async functions.
  8155. *
  8156. * Wherever we accept a Node-style async function, we also directly accept an
  8157. * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.
  8158. * In this case, the `async` function will not be passed a final callback
  8159. * argument, and any thrown error will be used as the `err` argument of the
  8160. * implicit callback, and the return value will be used as the `result` value.
  8161. * (i.e. a `rejected` of the returned Promise becomes the `err` callback
  8162. * argument, and a `resolved` value becomes the `result`.)
  8163. *
  8164. * Note, due to JavaScript limitations, we can only detect native `async`
  8165. * functions and not transpilied implementations.
  8166. * Your environment must have `async`/`await` support for this to work.
  8167. * (e.g. Node > v7.6, or a recent version of a modern browser).
  8168. * If you are using `async` functions through a transpiler (e.g. Babel), you
  8169. * must still wrap the function with [asyncify]{@link module:Utils.asyncify},
  8170. * because the `async function` will be compiled to an ordinary function that
  8171. * returns a promise.
  8172. *
  8173. * @typedef {Function} AsyncFunction
  8174. * @static
  8175. */
  8176. /**
  8177. * Async is a utility module which provides straight-forward, powerful functions
  8178. * for working with asynchronous JavaScript. Although originally designed for
  8179. * use with [Node.js](http://nodejs.org) and installable via
  8180. * `npm install --save async`, it can also be used directly in the browser.
  8181. * @module async
  8182. * @see AsyncFunction
  8183. */
  8184. /**
  8185. * A collection of `async` functions for manipulating collections, such as
  8186. * arrays and objects.
  8187. * @module Collections
  8188. */
  8189. /**
  8190. * A collection of `async` functions for controlling the flow through a script.
  8191. * @module ControlFlow
  8192. */
  8193. /**
  8194. * A collection of `async` utility functions.
  8195. * @module Utils
  8196. */
  8197. var index = {
  8198. apply: apply,
  8199. applyEach: applyEach,
  8200. applyEachSeries: applyEachSeries,
  8201. asyncify: asyncify,
  8202. auto: auto,
  8203. autoInject: autoInject,
  8204. cargo: cargo,
  8205. compose: compose,
  8206. concat: concat,
  8207. concatLimit: concatLimit,
  8208. concatSeries: concatSeries,
  8209. constant: constant,
  8210. detect: detect,
  8211. detectLimit: detectLimit,
  8212. detectSeries: detectSeries,
  8213. dir: dir,
  8214. doDuring: doDuring,
  8215. doUntil: doUntil,
  8216. doWhilst: doWhilst,
  8217. during: during,
  8218. each: eachLimit,
  8219. eachLimit: eachLimit$1,
  8220. eachOf: eachOf,
  8221. eachOfLimit: eachOfLimit,
  8222. eachOfSeries: eachOfSeries,
  8223. eachSeries: eachSeries,
  8224. ensureAsync: ensureAsync,
  8225. every: every,
  8226. everyLimit: everyLimit,
  8227. everySeries: everySeries,
  8228. filter: filter,
  8229. filterLimit: filterLimit,
  8230. filterSeries: filterSeries,
  8231. forever: forever,
  8232. groupBy: groupBy,
  8233. groupByLimit: groupByLimit,
  8234. groupBySeries: groupBySeries,
  8235. log: log,
  8236. map: map,
  8237. mapLimit: mapLimit,
  8238. mapSeries: mapSeries,
  8239. mapValues: mapValues,
  8240. mapValuesLimit: mapValuesLimit,
  8241. mapValuesSeries: mapValuesSeries,
  8242. memoize: memoize,
  8243. nextTick: nextTick,
  8244. parallel: parallelLimit,
  8245. parallelLimit: parallelLimit$1,
  8246. priorityQueue: priorityQueue,
  8247. queue: queue$1,
  8248. race: race,
  8249. reduce: reduce,
  8250. reduceRight: reduceRight,
  8251. reflect: reflect,
  8252. reflectAll: reflectAll,
  8253. reject: reject,
  8254. rejectLimit: rejectLimit,
  8255. rejectSeries: rejectSeries,
  8256. retry: retry,
  8257. retryable: retryable,
  8258. seq: seq,
  8259. series: series,
  8260. setImmediate: setImmediate$1,
  8261. some: some,
  8262. someLimit: someLimit,
  8263. someSeries: someSeries,
  8264. sortBy: sortBy,
  8265. timeout: timeout,
  8266. times: times,
  8267. timesLimit: timeLimit,
  8268. timesSeries: timesSeries,
  8269. transform: transform,
  8270. tryEach: tryEach,
  8271. unmemoize: unmemoize,
  8272. until: until,
  8273. waterfall: waterfall,
  8274. whilst: whilst,
  8275. // aliases
  8276. all: every,
  8277. allLimit: everyLimit,
  8278. allSeries: everySeries,
  8279. any: some,
  8280. anyLimit: someLimit,
  8281. anySeries: someSeries,
  8282. find: detect,
  8283. findLimit: detectLimit,
  8284. findSeries: detectSeries,
  8285. forEach: eachLimit,
  8286. forEachSeries: eachSeries,
  8287. forEachLimit: eachLimit$1,
  8288. forEachOf: eachOf,
  8289. forEachOfSeries: eachOfSeries,
  8290. forEachOfLimit: eachOfLimit,
  8291. inject: reduce,
  8292. foldl: reduce,
  8293. foldr: reduceRight,
  8294. select: filter,
  8295. selectLimit: filterLimit,
  8296. selectSeries: filterSeries,
  8297. wrapSync: asyncify
  8298. };
  8299. exports['default'] = index;
  8300. exports.apply = apply;
  8301. exports.applyEach = applyEach;
  8302. exports.applyEachSeries = applyEachSeries;
  8303. exports.asyncify = asyncify;
  8304. exports.auto = auto;
  8305. exports.autoInject = autoInject;
  8306. exports.cargo = cargo;
  8307. exports.compose = compose;
  8308. exports.concat = concat;
  8309. exports.concatLimit = concatLimit;
  8310. exports.concatSeries = concatSeries;
  8311. exports.constant = constant;
  8312. exports.detect = detect;
  8313. exports.detectLimit = detectLimit;
  8314. exports.detectSeries = detectSeries;
  8315. exports.dir = dir;
  8316. exports.doDuring = doDuring;
  8317. exports.doUntil = doUntil;
  8318. exports.doWhilst = doWhilst;
  8319. exports.during = during;
  8320. exports.each = eachLimit;
  8321. exports.eachLimit = eachLimit$1;
  8322. exports.eachOf = eachOf;
  8323. exports.eachOfLimit = eachOfLimit;
  8324. exports.eachOfSeries = eachOfSeries;
  8325. exports.eachSeries = eachSeries;
  8326. exports.ensureAsync = ensureAsync;
  8327. exports.every = every;
  8328. exports.everyLimit = everyLimit;
  8329. exports.everySeries = everySeries;
  8330. exports.filter = filter;
  8331. exports.filterLimit = filterLimit;
  8332. exports.filterSeries = filterSeries;
  8333. exports.forever = forever;
  8334. exports.groupBy = groupBy;
  8335. exports.groupByLimit = groupByLimit;
  8336. exports.groupBySeries = groupBySeries;
  8337. exports.log = log;
  8338. exports.map = map;
  8339. exports.mapLimit = mapLimit;
  8340. exports.mapSeries = mapSeries;
  8341. exports.mapValues = mapValues;
  8342. exports.mapValuesLimit = mapValuesLimit;
  8343. exports.mapValuesSeries = mapValuesSeries;
  8344. exports.memoize = memoize;
  8345. exports.nextTick = nextTick;
  8346. exports.parallel = parallelLimit;
  8347. exports.parallelLimit = parallelLimit$1;
  8348. exports.priorityQueue = priorityQueue;
  8349. exports.queue = queue$1;
  8350. exports.race = race;
  8351. exports.reduce = reduce;
  8352. exports.reduceRight = reduceRight;
  8353. exports.reflect = reflect;
  8354. exports.reflectAll = reflectAll;
  8355. exports.reject = reject;
  8356. exports.rejectLimit = rejectLimit;
  8357. exports.rejectSeries = rejectSeries;
  8358. exports.retry = retry;
  8359. exports.retryable = retryable;
  8360. exports.seq = seq;
  8361. exports.series = series;
  8362. exports.setImmediate = setImmediate$1;
  8363. exports.some = some;
  8364. exports.someLimit = someLimit;
  8365. exports.someSeries = someSeries;
  8366. exports.sortBy = sortBy;
  8367. exports.timeout = timeout;
  8368. exports.times = times;
  8369. exports.timesLimit = timeLimit;
  8370. exports.timesSeries = timesSeries;
  8371. exports.transform = transform;
  8372. exports.tryEach = tryEach;
  8373. exports.unmemoize = unmemoize;
  8374. exports.until = until;
  8375. exports.waterfall = waterfall;
  8376. exports.whilst = whilst;
  8377. exports.all = every;
  8378. exports.allLimit = everyLimit;
  8379. exports.allSeries = everySeries;
  8380. exports.any = some;
  8381. exports.anyLimit = someLimit;
  8382. exports.anySeries = someSeries;
  8383. exports.find = detect;
  8384. exports.findLimit = detectLimit;
  8385. exports.findSeries = detectSeries;
  8386. exports.forEach = eachLimit;
  8387. exports.forEachSeries = eachSeries;
  8388. exports.forEachLimit = eachLimit$1;
  8389. exports.forEachOf = eachOf;
  8390. exports.forEachOfSeries = eachOfSeries;
  8391. exports.forEachOfLimit = eachOfLimit;
  8392. exports.inject = reduce;
  8393. exports.foldl = reduce;
  8394. exports.foldr = reduceRight;
  8395. exports.select = filter;
  8396. exports.selectLimit = filterLimit;
  8397. exports.selectSeries = filterSeries;
  8398. exports.wrapSync = asyncify;
  8399. Object.defineProperty(exports, '__esModule', { value: true });
  8400. })));
  8401. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  8402. },{"_process":202,"timers":206}],20:[function(require,module,exports){
  8403. 'use strict'
  8404. var GeoJSONBounds = require('geojson-bounds')
  8405. /* global L:false */
  8406. function BoundingBox (bounds) {
  8407. var k
  8408. if (bounds === null || typeof bounds === 'undefined') {
  8409. this.minlat = -90
  8410. this.minlon = -180
  8411. this.maxlat = +90
  8412. this.maxlon = +180
  8413. return
  8414. }
  8415. // Leaflet.latLngBounds detected!
  8416. if (typeof bounds.getSouthWest === 'function') {
  8417. var sw = bounds.getSouthWest()
  8418. var ne = bounds.getNorthEast()
  8419. bounds = {
  8420. minlat: sw.lat,
  8421. minlon: sw.lng,
  8422. maxlat: ne.lat,
  8423. maxlon: ne.lng
  8424. }
  8425. }
  8426. // GeoJSON detected
  8427. if (bounds.type === 'Feature') {
  8428. var b = GeoJSONBounds.extent(bounds)
  8429. bounds = {
  8430. minlat: b[1],
  8431. minlon: b[0],
  8432. maxlat: b[3],
  8433. maxlon: b[2]
  8434. }
  8435. }
  8436. if ('bounds' in bounds) {
  8437. bounds = bounds.bounds
  8438. }
  8439. if (bounds.lat) {
  8440. this.minlat = bounds.lat
  8441. this.maxlat = bounds.lat
  8442. }
  8443. if (bounds.lon) {
  8444. this.minlon = bounds.lon
  8445. this.maxlon = bounds.lon
  8446. }
  8447. if (Array.isArray(bounds)) {
  8448. this.minlat = bounds[0]
  8449. this.maxlat = bounds[0]
  8450. this.minlon = bounds[1]
  8451. this.maxlon = bounds[1]
  8452. }
  8453. // e.g. L.latLng object
  8454. if (bounds.lng) {
  8455. this.minlon = bounds.lng
  8456. this.maxlon = bounds.lng
  8457. }
  8458. var props = ['minlon', 'minlat', 'maxlon', 'maxlat']
  8459. for (var i = 0; i < props.length; i++) {
  8460. k = props[i]
  8461. if (k in bounds) {
  8462. this[k] = bounds[k]
  8463. }
  8464. }
  8465. }
  8466. BoundingBox.prototype.intersects = function (other) {
  8467. other = new BoundingBox(other)
  8468. if (other.maxlat < this.minlat) {
  8469. return false
  8470. }
  8471. if (other.minlat > this.maxlat) {
  8472. return false
  8473. }
  8474. if (other.maxlon < this.minlon) {
  8475. return false
  8476. }
  8477. if (other.minlon > this.maxlon) {
  8478. return false
  8479. }
  8480. return true
  8481. }
  8482. BoundingBox.prototype.toTile = function () {
  8483. return new BoundingBox({
  8484. minlat: Math.floor(this.minlat * 10) / 10,
  8485. minlon: Math.floor(this.minlon * 10) / 10,
  8486. maxlat: Math.ceil(this.maxlat * 10) / 10,
  8487. maxlon: Math.ceil(this.maxlon * 10) / 10
  8488. })
  8489. }
  8490. BoundingBox.prototype.toLonLatString = function () {
  8491. return this.minlon + ',' +
  8492. this.minlat + ',' +
  8493. this.maxlon + ',' +
  8494. this.maxlat
  8495. }
  8496. BoundingBox.prototype.toBBoxString = BoundingBox.prototype.toLonLatString
  8497. BoundingBox.prototype.toLatLonString = function () {
  8498. return this.minlat + ',' +
  8499. this.minlon + ',' +
  8500. this.maxlat + ',' +
  8501. this.maxlon
  8502. }
  8503. BoundingBox.prototype.diagonalLength = function () {
  8504. var dlat = this.maxlat - this.minlat
  8505. var dlon = this.maxlon - this.minlon
  8506. return Math.sqrt(dlat * dlat + dlon * dlon)
  8507. }
  8508. BoundingBox.prototype.getCenter = function () {
  8509. var dlat = this.maxlat - this.minlat
  8510. var dlon = this.maxlon - this.minlon
  8511. return {
  8512. lat: this.minlat + dlat / 2,
  8513. lon: this.minlon + dlon / 2
  8514. }
  8515. }
  8516. BoundingBox.prototype.getNorth = function () {
  8517. return this.maxlat
  8518. }
  8519. BoundingBox.prototype.getSouth = function () {
  8520. return this.minlat
  8521. }
  8522. BoundingBox.prototype.getEast = function () {
  8523. return this.maxlon
  8524. }
  8525. BoundingBox.prototype.getWest = function () {
  8526. return this.minlon
  8527. }
  8528. BoundingBox.prototype.extend = function (other) {
  8529. other = new BoundingBox(other)
  8530. if (other.minlon < this.minlon) {
  8531. this.minlon = other.minlon
  8532. }
  8533. if (other.minlat < this.minlat) {
  8534. this.minlat = other.minlat
  8535. }
  8536. if (other.maxlon > this.maxlon) {
  8537. this.maxlon = other.maxlon
  8538. }
  8539. if (other.maxlat > this.maxlat) {
  8540. this.maxlat = other.maxlat
  8541. }
  8542. }
  8543. BoundingBox.prototype.toGeoJSON = function () {
  8544. return {
  8545. type: 'Feature',
  8546. properties: {},
  8547. geometry: {
  8548. 'type': 'Polygon',
  8549. 'coordinates': [[
  8550. [ this.minlon, this.minlat ],
  8551. [ this.maxlon, this.minlat ],
  8552. [ this.maxlon, this.maxlat ],
  8553. [ this.minlon, this.maxlat ],
  8554. [ this.minlon, this.minlat ]
  8555. ]]
  8556. }
  8557. }
  8558. }
  8559. BoundingBox.prototype.toLeaflet = function () {
  8560. return L.latLngBounds(
  8561. L.latLng(this.minlat, this.minlon),
  8562. L.latLng(this.maxlat, this.maxlon)
  8563. )
  8564. }
  8565. if (typeof module !== 'undefined' && module.exports) {
  8566. module.exports = BoundingBox
  8567. }
  8568. if (typeof window !== 'undefined') {
  8569. window.BoundingBox = BoundingBox
  8570. }
  8571. },{"geojson-bounds":43}],21:[function(require,module,exports){
  8572. },{}],22:[function(require,module,exports){
  8573. 'use strict';
  8574. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  8575. var styleElementsInsertedAtTop = [];
  8576. var insertStyleElement = function(styleElement, options) {
  8577. var head = document.head || document.getElementsByTagName('head')[0];
  8578. var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
  8579. options = options || {};
  8580. options.insertAt = options.insertAt || 'bottom';
  8581. if (options.insertAt === 'top') {
  8582. if (!lastStyleElementInsertedAtTop) {
  8583. head.insertBefore(styleElement, head.firstChild);
  8584. } else if (lastStyleElementInsertedAtTop.nextSibling) {
  8585. head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
  8586. } else {
  8587. head.appendChild(styleElement);
  8588. }
  8589. styleElementsInsertedAtTop.push(styleElement);
  8590. } else if (options.insertAt === 'bottom') {
  8591. head.appendChild(styleElement);
  8592. } else {
  8593. throw new Error('Invalid value for parameter \'insertAt\'. Must be \'top\' or \'bottom\'.');
  8594. }
  8595. };
  8596. module.exports = {
  8597. // Create a <link> tag with optional data attributes
  8598. createLink: function(href, attributes) {
  8599. var head = document.head || document.getElementsByTagName('head')[0];
  8600. var link = document.createElement('link');
  8601. link.href = href;
  8602. link.rel = 'stylesheet';
  8603. for (var key in attributes) {
  8604. if ( ! attributes.hasOwnProperty(key)) {
  8605. continue;
  8606. }
  8607. var value = attributes[key];
  8608. link.setAttribute('data-' + key, value);
  8609. }
  8610. head.appendChild(link);
  8611. },
  8612. // Create a <style> tag with optional data attributes
  8613. createStyle: function(cssText, attributes, extraOptions) {
  8614. extraOptions = extraOptions || {};
  8615. var style = document.createElement('style');
  8616. style.type = 'text/css';
  8617. for (var key in attributes) {
  8618. if ( ! attributes.hasOwnProperty(key)) {
  8619. continue;
  8620. }
  8621. var value = attributes[key];
  8622. style.setAttribute('data-' + key, value);
  8623. }
  8624. if (style.sheet) { // for jsdom and IE9+
  8625. style.innerHTML = cssText;
  8626. style.sheet.cssText = cssText;
  8627. insertStyleElement(style, { insertAt: extraOptions.insertAt });
  8628. } else if (style.styleSheet) { // for IE8 and below
  8629. insertStyleElement(style, { insertAt: extraOptions.insertAt });
  8630. style.styleSheet.cssText = cssText;
  8631. } else { // for Chrome, Firefox, and Safari
  8632. style.appendChild(document.createTextNode(cssText));
  8633. insertStyleElement(style, { insertAt: extraOptions.insertAt });
  8634. }
  8635. }
  8636. };
  8637. },{}],23:[function(require,module,exports){
  8638. arguments[4][21][0].apply(exports,arguments)
  8639. },{"dup":21}],24:[function(require,module,exports){
  8640. /*
  8641. bzip2.js - a small bzip2 decompression implementation
  8642. Copyright 2011 by antimatter15 (antimatter15@gmail.com)
  8643. Based on micro-bunzip by Rob Landley (rob@landley.net).
  8644. Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
  8645. which also acknowledges contributions by Mike Burrows, David Wheeler,
  8646. Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
  8647. Robert Sedgewick, and Jon L. Bentley.
  8648. I hereby release this code under the GNU Library General Public License
  8649. (LGPL) version 2, available at http://www.gnu.org/copyleft/lgpl.html
  8650. */
  8651. var bzip2 = {};
  8652. bzip2.array = function (bytes) {
  8653. var bit = 0,
  8654. byte = 0;
  8655. var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
  8656. return function (n) {
  8657. var result = 0;
  8658. while (n > 0) {
  8659. var left = 8 - bit;
  8660. if (n >= left) {
  8661. result <<= left;
  8662. result |= (BITMASK[left] & bytes[byte++]);
  8663. bit = 0;
  8664. n -= left;
  8665. } else {
  8666. result <<= n;
  8667. result |= ((bytes[byte] & (BITMASK[n] << (8 - n - bit))) >> (8 - n - bit));
  8668. bit += n;
  8669. n = 0;
  8670. }
  8671. }
  8672. return result
  8673. }
  8674. }
  8675. bzip2.simple = function (bits) {
  8676. var size = bzip2.header(bits);
  8677. var all, chunk, chunks = [];
  8678. var index = 0;
  8679. do {
  8680. //all += chunk;
  8681. chunk = bzip2.decompress(bits, size);
  8682. //all.set(chunk, index);
  8683. if (chunk != -1) {
  8684. chunks.push(chunk);
  8685. index += chunk.byteLength;
  8686. }
  8687. } while (chunk != -1);
  8688. all = new Uint8Array(index);
  8689. index = 0;
  8690. for (var i = 0; i < chunks.length; ++i) {
  8691. chunk = chunks[i];
  8692. all.set(chunk, index);
  8693. index += chunk.byteLength;
  8694. }
  8695. return all;
  8696. }
  8697. bzip2.header = function (bits) {
  8698. if (bits(8 * 3) != 4348520)
  8699. throw "No magic number found";
  8700. var i = bits(8) - 48;
  8701. if (i < 1 || i > 9)
  8702. throw "Not a BZIP archive";
  8703. return i;
  8704. };
  8705. //takes a function for reading the block data (starting with 0x314159265359)
  8706. //a block size (0-9) (optional, defaults to 9)
  8707. //a length at which to stop decompressing and return the output
  8708. bzip2.decompress = function (bits, size, len) {
  8709. var MAX_HUFCODE_BITS = 20;
  8710. var MAX_SYMBOLS = 258;
  8711. var SYMBOL_RUNA = 0;
  8712. var SYMBOL_RUNB = 1;
  8713. var GROUP_SIZE = 50;
  8714. var bufsize = 100000 * 9;
  8715. for (var h = '', i = 0; i < 6; i++)
  8716. h += bits(8).toString(16);
  8717. if (h == "177245385090")
  8718. return -1; //last block
  8719. if (h != "314159265359")
  8720. throw "eek not valid bzip data";
  8721. bits(32); //ignore CRC codes
  8722. if (bits(1))
  8723. throw "unsupported obsolete version";
  8724. var origPtr = bits(24);
  8725. if (origPtr > bufsize)
  8726. throw "Initial position larger than buffer size";
  8727. var t = bits(16);
  8728. var symToByte = new Uint8Array(256),
  8729. symTotal = 0;
  8730. for (i = 0; i < 16; i++) {
  8731. if (t & (1 << (15 - i))) {
  8732. var k = bits(16);
  8733. for (j = 0; j < 16; j++) {
  8734. if (k & (1 << (15 - j))) {
  8735. symToByte[symTotal++] = (16 * i) + j;
  8736. }
  8737. }
  8738. }
  8739. }
  8740. var groupCount = bits(3);
  8741. if (groupCount < 2 || groupCount > 6)
  8742. throw "another error";
  8743. var nSelectors = bits(15);
  8744. if (nSelectors == 0)
  8745. throw "meh";
  8746. var mtfSymbol = []; //TODO: possibly replace JS array with typed arrays
  8747. for (var i = 0; i < groupCount; i++)
  8748. mtfSymbol[i] = i;
  8749. var selectors = new Uint8Array(32768);
  8750. for (var i = 0; i < nSelectors; i++) {
  8751. for (var j = 0; bits(1); j++)
  8752. if (j >= groupCount)
  8753. throw "whoops another error";
  8754. var uc = mtfSymbol[j];
  8755. mtfSymbol.splice(j, 1); //this is a probably inefficient MTF transform
  8756. mtfSymbol.splice(0, 0, uc);
  8757. selectors[i] = uc;
  8758. }
  8759. var symCount = symTotal + 2;
  8760. var groups = [];
  8761. for (var j = 0; j < groupCount; j++) {
  8762. var length = new Uint8Array(MAX_SYMBOLS),
  8763. temp = new Uint8Array(MAX_HUFCODE_BITS + 1);
  8764. t = bits(5); //lengths
  8765. for (var i = 0; i < symCount; i++) {
  8766. while (true) {
  8767. if (t < 1 || t > MAX_HUFCODE_BITS)
  8768. throw "I gave up a while ago on writing error messages";
  8769. if (!bits(1))
  8770. break;
  8771. if (!bits(1))
  8772. t++;
  8773. else
  8774. t--;
  8775. }
  8776. length[i] = t;
  8777. }
  8778. var minLen, maxLen;
  8779. minLen = maxLen = length[0];
  8780. for (var i = 1; i < symCount; i++) {
  8781. if (length[i] > maxLen)
  8782. maxLen = length[i];
  8783. else if (length[i] < minLen)
  8784. minLen = length[i];
  8785. }
  8786. var hufGroup;
  8787. hufGroup = groups[j] = {};
  8788. hufGroup.permute = new Uint32Array(MAX_SYMBOLS);
  8789. hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 1);
  8790. hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
  8791. hufGroup.minLen = minLen;
  8792. hufGroup.maxLen = maxLen;
  8793. var base = hufGroup.base.subarray(1);
  8794. var limit = hufGroup.limit.subarray(1);
  8795. var pp = 0;
  8796. for (var i = minLen; i <= maxLen; i++)
  8797. for (var t = 0; t < symCount; t++)
  8798. if (length[t] == i)
  8799. hufGroup.permute[pp++] = t;
  8800. for (i = minLen; i <= maxLen; i++)
  8801. temp[i] = limit[i] = 0;
  8802. for (i = 0; i < symCount; i++)
  8803. temp[length[i]]++;
  8804. pp = t = 0;
  8805. for (i = minLen; i < maxLen; i++) {
  8806. pp += temp[i];
  8807. limit[i] = pp - 1;
  8808. pp <<= 1;
  8809. base[i + 1] = pp - (t += temp[i]);
  8810. }
  8811. limit[maxLen] = pp + temp[maxLen] - 1;
  8812. base[minLen] = 0;
  8813. }
  8814. var byteCount = new Uint32Array(256);
  8815. for (var i = 0; i < 256; i++)
  8816. mtfSymbol[i] = i;
  8817. var runPos, count, symCount, selector;
  8818. runPos = count = symCount = selector = 0;
  8819. var buf = new Uint32Array(bufsize);
  8820. while (true) {
  8821. if (!(symCount--)) {
  8822. symCount = GROUP_SIZE - 1;
  8823. if (selector >= nSelectors)
  8824. throw "meow i'm a kitty, that's an error";
  8825. hufGroup = groups[selectors[selector++]];
  8826. base = hufGroup.base.subarray(1);
  8827. limit = hufGroup.limit.subarray(1);
  8828. }
  8829. i = hufGroup.minLen;
  8830. j = bits(i);
  8831. while (true) {
  8832. if (i > hufGroup.maxLen)
  8833. throw "rawr i'm a dinosaur";
  8834. if (j <= limit[i])
  8835. break;
  8836. i++;
  8837. j = (j << 1) | bits(1);
  8838. }
  8839. j -= base[i];
  8840. if (j < 0 || j >= MAX_SYMBOLS)
  8841. throw "moo i'm a cow";
  8842. var nextSym = hufGroup.permute[j];
  8843. if (nextSym == SYMBOL_RUNA || nextSym == SYMBOL_RUNB) {
  8844. if (!runPos) {
  8845. runPos = 1;
  8846. t = 0;
  8847. }
  8848. if (nextSym == SYMBOL_RUNA)
  8849. t += runPos;
  8850. else
  8851. t += 2 * runPos;
  8852. runPos <<= 1;
  8853. continue;
  8854. }
  8855. if (runPos) {
  8856. runPos = 0;
  8857. if (count + t >= bufsize)
  8858. throw "Boom.";
  8859. uc = symToByte[mtfSymbol[0]];
  8860. byteCount[uc] += t;
  8861. while (t--)
  8862. buf[count++] = uc;
  8863. }
  8864. if (nextSym > symTotal)
  8865. break;
  8866. if (count >= bufsize)
  8867. throw "I can't think of anything. Error";
  8868. i = nextSym - 1;
  8869. uc = mtfSymbol[i];
  8870. mtfSymbol.splice(i, 1);
  8871. mtfSymbol.splice(0, 0, uc);
  8872. uc = symToByte[uc];
  8873. byteCount[uc]++;
  8874. buf[count++] = uc;
  8875. }
  8876. if (origPtr < 0 || origPtr >= count)
  8877. throw "I'm a monkey and I'm throwing something at someone, namely you";
  8878. var j = 0;
  8879. for (var i = 0; i < 256; i++) {
  8880. k = j + byteCount[i];
  8881. byteCount[i] = j;
  8882. j = k;
  8883. }
  8884. for (var i = 0; i < count; i++) {
  8885. uc = buf[i] & 0xff;
  8886. buf[byteCount[uc]] |= (i << 8);
  8887. byteCount[uc]++;
  8888. }
  8889. var pos = 0,
  8890. current = 0,
  8891. run = 0;
  8892. if (count) {
  8893. pos = buf[origPtr];
  8894. current = (pos & 0xff);
  8895. pos >>= 8;
  8896. run = -1;
  8897. }
  8898. count = count;
  8899. var output = new Uint8Array(bufsize);
  8900. var copies, previous, outbyte;
  8901. var index = 0;
  8902. if (!len)
  8903. len = Infinity;
  8904. while (count) {
  8905. count--;
  8906. previous = current;
  8907. pos = buf[pos];
  8908. current = pos & 0xff;
  8909. pos >>= 8;
  8910. if (run++ == 3) {
  8911. copies = current;
  8912. outbyte = previous;
  8913. current = -1;
  8914. } else {
  8915. copies = 1;
  8916. outbyte = current;
  8917. }
  8918. while (copies--) {
  8919. //output += (String.fromCharCode(outbyte));
  8920. output[index++] = outbyte;
  8921. //index++;
  8922. if (!--len)
  8923. return output;
  8924. }
  8925. if (current != previous)
  8926. run = 0;
  8927. }
  8928. //return output;
  8929. //return output.subarray(0,index-1);
  8930. return output.subarray(0, index);
  8931. }
  8932. module.exports = bzip2;
  8933. },{}],25:[function(require,module,exports){
  8934. 'use strict';
  8935. var assign = require('es5-ext/object/assign')
  8936. , normalizeOpts = require('es5-ext/object/normalize-options')
  8937. , isCallable = require('es5-ext/object/is-callable')
  8938. , contains = require('es5-ext/string/#/contains')
  8939. , d;
  8940. d = module.exports = function (dscr, value/*, options*/) {
  8941. var c, e, w, options, desc;
  8942. if ((arguments.length < 2) || (typeof dscr !== 'string')) {
  8943. options = value;
  8944. value = dscr;
  8945. dscr = null;
  8946. } else {
  8947. options = arguments[2];
  8948. }
  8949. if (dscr == null) {
  8950. c = w = true;
  8951. e = false;
  8952. } else {
  8953. c = contains.call(dscr, 'c');
  8954. e = contains.call(dscr, 'e');
  8955. w = contains.call(dscr, 'w');
  8956. }
  8957. desc = { value: value, configurable: c, enumerable: e, writable: w };
  8958. return !options ? desc : assign(normalizeOpts(options), desc);
  8959. };
  8960. d.gs = function (dscr, get, set/*, options*/) {
  8961. var c, e, options, desc;
  8962. if (typeof dscr !== 'string') {
  8963. options = set;
  8964. set = get;
  8965. get = dscr;
  8966. dscr = null;
  8967. } else {
  8968. options = arguments[3];
  8969. }
  8970. if (get == null) {
  8971. get = undefined;
  8972. } else if (!isCallable(get)) {
  8973. options = get;
  8974. get = set = undefined;
  8975. } else if (set == null) {
  8976. set = undefined;
  8977. } else if (!isCallable(set)) {
  8978. options = set;
  8979. set = undefined;
  8980. }
  8981. if (dscr == null) {
  8982. c = true;
  8983. e = false;
  8984. } else {
  8985. c = contains.call(dscr, 'c');
  8986. e = contains.call(dscr, 'e');
  8987. }
  8988. desc = { get: get, set: set, configurable: c, enumerable: e };
  8989. return !options ? desc : assign(normalizeOpts(options), desc);
  8990. };
  8991. },{"es5-ext/object/assign":27,"es5-ext/object/is-callable":30,"es5-ext/object/normalize-options":35,"es5-ext/string/#/contains":38}],26:[function(require,module,exports){
  8992. "use strict";
  8993. // eslint-disable-next-line no-empty-function
  8994. module.exports = function () {};
  8995. },{}],27:[function(require,module,exports){
  8996. "use strict";
  8997. module.exports = require("./is-implemented")()
  8998. ? Object.assign
  8999. : require("./shim");
  9000. },{"./is-implemented":28,"./shim":29}],28:[function(require,module,exports){
  9001. "use strict";
  9002. module.exports = function () {
  9003. var assign = Object.assign, obj;
  9004. if (typeof assign !== "function") return false;
  9005. obj = { foo: "raz" };
  9006. assign(obj, { bar: "dwa" }, { trzy: "trzy" });
  9007. return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
  9008. };
  9009. },{}],29:[function(require,module,exports){
  9010. "use strict";
  9011. var keys = require("../keys")
  9012. , value = require("../valid-value")
  9013. , max = Math.max;
  9014. module.exports = function (dest, src /*, …srcn*/) {
  9015. var error, i, length = max(arguments.length, 2), assign;
  9016. dest = Object(value(dest));
  9017. assign = function (key) {
  9018. try {
  9019. dest[key] = src[key];
  9020. } catch (e) {
  9021. if (!error) error = e;
  9022. }
  9023. };
  9024. for (i = 1; i < length; ++i) {
  9025. src = arguments[i];
  9026. keys(src).forEach(assign);
  9027. }
  9028. if (error !== undefined) throw error;
  9029. return dest;
  9030. };
  9031. },{"../keys":32,"../valid-value":37}],30:[function(require,module,exports){
  9032. // Deprecated
  9033. "use strict";
  9034. module.exports = function (obj) {
  9035. return typeof obj === "function";
  9036. };
  9037. },{}],31:[function(require,module,exports){
  9038. "use strict";
  9039. var _undefined = require("../function/noop")(); // Support ES3 engines
  9040. module.exports = function (val) {
  9041. return (val !== _undefined) && (val !== null);
  9042. };
  9043. },{"../function/noop":26}],32:[function(require,module,exports){
  9044. "use strict";
  9045. module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
  9046. },{"./is-implemented":33,"./shim":34}],33:[function(require,module,exports){
  9047. "use strict";
  9048. module.exports = function () {
  9049. try {
  9050. Object.keys("primitive");
  9051. return true;
  9052. } catch (e) {
  9053. return false;
  9054. }
  9055. };
  9056. },{}],34:[function(require,module,exports){
  9057. "use strict";
  9058. var isValue = require("../is-value");
  9059. var keys = Object.keys;
  9060. module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
  9061. },{"../is-value":31}],35:[function(require,module,exports){
  9062. "use strict";
  9063. var isValue = require("./is-value");
  9064. var forEach = Array.prototype.forEach, create = Object.create;
  9065. var process = function (src, obj) {
  9066. var key;
  9067. for (key in src) obj[key] = src[key];
  9068. };
  9069. // eslint-disable-next-line no-unused-vars
  9070. module.exports = function (opts1 /*, …options*/) {
  9071. var result = create(null);
  9072. forEach.call(arguments, function (options) {
  9073. if (!isValue(options)) return;
  9074. process(Object(options), result);
  9075. });
  9076. return result;
  9077. };
  9078. },{"./is-value":31}],36:[function(require,module,exports){
  9079. "use strict";
  9080. module.exports = function (fn) {
  9081. if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
  9082. return fn;
  9083. };
  9084. },{}],37:[function(require,module,exports){
  9085. "use strict";
  9086. var isValue = require("./is-value");
  9087. module.exports = function (value) {
  9088. if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
  9089. return value;
  9090. };
  9091. },{"./is-value":31}],38:[function(require,module,exports){
  9092. "use strict";
  9093. module.exports = require("./is-implemented")()
  9094. ? String.prototype.contains
  9095. : require("./shim");
  9096. },{"./is-implemented":39,"./shim":40}],39:[function(require,module,exports){
  9097. "use strict";
  9098. var str = "razdwatrzy";
  9099. module.exports = function () {
  9100. if (typeof str.contains !== "function") return false;
  9101. return (str.contains("dwa") === true) && (str.contains("foo") === false);
  9102. };
  9103. },{}],40:[function(require,module,exports){
  9104. "use strict";
  9105. var indexOf = String.prototype.indexOf;
  9106. module.exports = function (searchString/*, position*/) {
  9107. return indexOf.call(this, searchString, arguments[1]) > -1;
  9108. };
  9109. },{}],41:[function(require,module,exports){
  9110. 'use strict';
  9111. var d = require('d')
  9112. , callable = require('es5-ext/object/valid-callable')
  9113. , apply = Function.prototype.apply, call = Function.prototype.call
  9114. , create = Object.create, defineProperty = Object.defineProperty
  9115. , defineProperties = Object.defineProperties
  9116. , hasOwnProperty = Object.prototype.hasOwnProperty
  9117. , descriptor = { configurable: true, enumerable: false, writable: true }
  9118. , on, once, off, emit, methods, descriptors, base;
  9119. on = function (type, listener) {
  9120. var data;
  9121. callable(listener);
  9122. if (!hasOwnProperty.call(this, '__ee__')) {
  9123. data = descriptor.value = create(null);
  9124. defineProperty(this, '__ee__', descriptor);
  9125. descriptor.value = null;
  9126. } else {
  9127. data = this.__ee__;
  9128. }
  9129. if (!data[type]) data[type] = listener;
  9130. else if (typeof data[type] === 'object') data[type].push(listener);
  9131. else data[type] = [data[type], listener];
  9132. return this;
  9133. };
  9134. once = function (type, listener) {
  9135. var once, self;
  9136. callable(listener);
  9137. self = this;
  9138. on.call(this, type, once = function () {
  9139. off.call(self, type, once);
  9140. apply.call(listener, this, arguments);
  9141. });
  9142. once.__eeOnceListener__ = listener;
  9143. return this;
  9144. };
  9145. off = function (type, listener) {
  9146. var data, listeners, candidate, i;
  9147. callable(listener);
  9148. if (!hasOwnProperty.call(this, '__ee__')) return this;
  9149. data = this.__ee__;
  9150. if (!data[type]) return this;
  9151. listeners = data[type];
  9152. if (typeof listeners === 'object') {
  9153. for (i = 0; (candidate = listeners[i]); ++i) {
  9154. if ((candidate === listener) ||
  9155. (candidate.__eeOnceListener__ === listener)) {
  9156. if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
  9157. else listeners.splice(i, 1);
  9158. }
  9159. }
  9160. } else {
  9161. if ((listeners === listener) ||
  9162. (listeners.__eeOnceListener__ === listener)) {
  9163. delete data[type];
  9164. }
  9165. }
  9166. return this;
  9167. };
  9168. emit = function (type) {
  9169. var i, l, listener, listeners, args;
  9170. if (!hasOwnProperty.call(this, '__ee__')) return;
  9171. listeners = this.__ee__[type];
  9172. if (!listeners) return;
  9173. if (typeof listeners === 'object') {
  9174. l = arguments.length;
  9175. args = new Array(l - 1);
  9176. for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
  9177. listeners = listeners.slice();
  9178. for (i = 0; (listener = listeners[i]); ++i) {
  9179. apply.call(listener, this, args);
  9180. }
  9181. } else {
  9182. switch (arguments.length) {
  9183. case 1:
  9184. call.call(listeners, this);
  9185. break;
  9186. case 2:
  9187. call.call(listeners, this, arguments[1]);
  9188. break;
  9189. case 3:
  9190. call.call(listeners, this, arguments[1], arguments[2]);
  9191. break;
  9192. default:
  9193. l = arguments.length;
  9194. args = new Array(l - 1);
  9195. for (i = 1; i < l; ++i) {
  9196. args[i - 1] = arguments[i];
  9197. }
  9198. apply.call(listeners, this, args);
  9199. }
  9200. }
  9201. };
  9202. methods = {
  9203. on: on,
  9204. once: once,
  9205. off: off,
  9206. emit: emit
  9207. };
  9208. descriptors = {
  9209. on: d(on),
  9210. once: d(once),
  9211. off: d(off),
  9212. emit: d(emit)
  9213. };
  9214. base = defineProperties({}, descriptors);
  9215. module.exports = exports = function (o) {
  9216. return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
  9217. };
  9218. exports.methods = methods;
  9219. },{"d":25,"es5-ext/object/valid-callable":36}],42:[function(require,module,exports){
  9220. var wgs84 = require('wgs84');
  9221. module.exports.geometry = geometry;
  9222. module.exports.ring = ringArea;
  9223. function geometry(_) {
  9224. if (_.type === 'Polygon') return polygonArea(_.coordinates);
  9225. else if (_.type === 'MultiPolygon') {
  9226. var area = 0;
  9227. for (var i = 0; i < _.coordinates.length; i++) {
  9228. area += polygonArea(_.coordinates[i]);
  9229. }
  9230. return area;
  9231. } else {
  9232. return null;
  9233. }
  9234. }
  9235. function polygonArea(coords) {
  9236. var area = 0;
  9237. if (coords && coords.length > 0) {
  9238. area += Math.abs(ringArea(coords[0]));
  9239. for (var i = 1; i < coords.length; i++) {
  9240. area -= Math.abs(ringArea(coords[i]));
  9241. }
  9242. }
  9243. return area;
  9244. }
  9245. /**
  9246. * Calculate the approximate area of the polygon were it projected onto
  9247. * the earth. Note that this area will be positive if ring is oriented
  9248. * clockwise, otherwise it will be negative.
  9249. *
  9250. * Reference:
  9251. * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
  9252. * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
  9253. * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
  9254. *
  9255. * Returns:
  9256. * {float} The approximate signed geodesic area of the polygon in square
  9257. * meters.
  9258. */
  9259. function ringArea(coords) {
  9260. var area = 0;
  9261. if (coords.length > 2) {
  9262. var p1, p2;
  9263. for (var i = 0; i < coords.length - 1; i++) {
  9264. p1 = coords[i];
  9265. p2 = coords[i + 1];
  9266. area += rad(p2[0] - p1[0]) * (2 + Math.sin(rad(p1[1])) + Math.sin(rad(p2[1])));
  9267. }
  9268. area = area * wgs84.RADIUS * wgs84.RADIUS / 2;
  9269. }
  9270. return area;
  9271. }
  9272. function rad(_) {
  9273. return _ * Math.PI / 180;
  9274. }
  9275. },{"wgs84":209}],43:[function(require,module,exports){
  9276. (function() {
  9277. /*
  9278. Modified version of underscore.js's flatten function
  9279. https://github.com/jashkenas/underscore/blob/master/underscore.js#L501
  9280. */
  9281. function flatten(input, output) {
  9282. output = output || [];
  9283. var idx = output.length;
  9284. for (var i = 0; i < input.length; i++) {
  9285. if (Array.isArray(input[i]) && Array.isArray(input[i][0])) {
  9286. flatten(input[i], output);
  9287. idx = output.length;
  9288. } else {
  9289. output[idx++] = input[i];
  9290. }
  9291. }
  9292. return (Array.isArray(output[0])) ? output : [output];
  9293. };
  9294. function maxLat(coords) {
  9295. return Math.max.apply(null, coords.map(function(d) { return d[1]; }));
  9296. }
  9297. function maxLng(coords) {
  9298. return Math.max.apply(null, coords.map(function(d) { return d[0]; }));
  9299. }
  9300. function minLat(coords) {
  9301. return Math.min.apply(null, coords.map(function(d) { return d[1]; }));
  9302. }
  9303. function minLng(coords) {
  9304. return Math.min.apply(null, coords.map(function(d) { return d[0]; }));
  9305. }
  9306. function fetchEnvelope(coords) {
  9307. var mmc = {
  9308. "minLng": minLng(coords),
  9309. "minLat": minLat(coords),
  9310. "maxLng": maxLng(coords),
  9311. "maxLat": maxLat(coords)
  9312. }
  9313. return {
  9314. "type": "Feature",
  9315. "properties": {},
  9316. "geometry": {
  9317. "type": "Polygon",
  9318. "coordinates": [[
  9319. [mmc.minLng, mmc.minLat],
  9320. [mmc.minLng, mmc.maxLat],
  9321. [mmc.maxLng, mmc.maxLat],
  9322. [mmc.maxLng, mmc.minLat],
  9323. [mmc.minLng, mmc.minLat]
  9324. ]]
  9325. }
  9326. }
  9327. }
  9328. function fetchExtent(coords) {
  9329. return [
  9330. minLng(coords),
  9331. minLat(coords),
  9332. maxLng(coords),
  9333. maxLat(coords)
  9334. ]
  9335. }
  9336. // Adapted from http://stackoverflow.com/questions/2792443/finding-the-centroid-of-a-polygon
  9337. function fetchCentroid(vertices) {
  9338. var centroid = {
  9339. x: 0,
  9340. y: 0
  9341. }
  9342. var signedArea = 0;
  9343. var x0 = 0;
  9344. var y0 = 0;
  9345. var x1 = 0;
  9346. var y1 = 0;
  9347. var a = 0;
  9348. for (var i = 0; i < vertices.length - 1; i++) {
  9349. x0 = vertices[i][0];
  9350. y0 = vertices[i][1];
  9351. x1 = vertices[i + 1][0];
  9352. y1 = vertices[i + 1][1];
  9353. a = (x0 * y1) - (x1 * y0);
  9354. signedArea += a;
  9355. centroid.x += (x0 + x1) * a;
  9356. centroid.y += (y0 + y1) * a;
  9357. }
  9358. x0 = vertices[vertices.length - 1][0];
  9359. y0 = vertices[vertices.length - 1][1];
  9360. x1 = vertices[0][0];
  9361. y1 = vertices[0][1];
  9362. a = (x0 * y1) - (x1 * y0);
  9363. signedArea += a;
  9364. centroid.x += (x0 + x1) * a;
  9365. centroid.y += (y0 + y1) * a;
  9366. signedArea = signedArea * 0.5;
  9367. centroid.x = centroid.x / (6.0*signedArea);
  9368. centroid.y = centroid.y / (6.0*signedArea);
  9369. return [centroid.x, centroid.y];
  9370. }
  9371. function feature(obj) {
  9372. return flatten(obj.geometry.coordinates);
  9373. }
  9374. function featureCollection(f) {
  9375. return flatten(f.features.map(feature));
  9376. }
  9377. function geometryCollection(g) {
  9378. return flatten(g.geometries.map(process));
  9379. }
  9380. function process(t) {
  9381. if (!t) {
  9382. return [];
  9383. }
  9384. switch (t.type) {
  9385. case "Feature":
  9386. return feature(t);
  9387. case "GeometryCollection":
  9388. return geometryCollection(t);
  9389. case "FeatureCollection":
  9390. return featureCollection(t);
  9391. case "Point":
  9392. case "LineString":
  9393. case "Polygon":
  9394. case "MultiPoint":
  9395. case "MultiPolygon":
  9396. case "MultiLineString":
  9397. return flatten(t.coordinates);
  9398. default:
  9399. return [];
  9400. }
  9401. }
  9402. function envelope(t) {
  9403. return fetchEnvelope(process(t));
  9404. }
  9405. function extent(t) {
  9406. return fetchExtent(process(t));
  9407. }
  9408. function centroid(t) {
  9409. return fetchCentroid(process(t));
  9410. }
  9411. function xMin(t) {
  9412. return minLng(process(t));
  9413. }
  9414. function xMax(t) {
  9415. return maxLng(process(t));
  9416. }
  9417. function yMin(t) {
  9418. return minLat(process(t));
  9419. }
  9420. function yMax(t) {
  9421. return maxLat(process(t));
  9422. }
  9423. module.exports = {
  9424. "envelope": envelope,
  9425. "extent": extent,
  9426. "centroid": centroid,
  9427. "xMin": xMin,
  9428. "xMax": xMax,
  9429. "yMin": yMin,
  9430. "yMax": yMax
  9431. }
  9432. }());
  9433. },{}],44:[function(require,module,exports){
  9434. var rbush = require('rbush');
  9435. var helpers = require('@turf/helpers');
  9436. var meta = require('@turf/meta');
  9437. var turfBBox = require('@turf/bbox').default;
  9438. var featureEach = meta.featureEach;
  9439. var coordEach = meta.coordEach;
  9440. var polygon = helpers.polygon;
  9441. var featureCollection = helpers.featureCollection;
  9442. /**
  9443. * GeoJSON implementation of [RBush](https://github.com/mourner/rbush#rbush) spatial index.
  9444. *
  9445. * @name rbush
  9446. * @param {number} [maxEntries=9] defines the maximum number of entries in a tree node. 9 (used by default) is a
  9447. * reasonable choice for most applications. Higher value means faster insertion and slower search, and vice versa.
  9448. * @returns {RBush} GeoJSON RBush
  9449. * @example
  9450. * var geojsonRbush = require('geojson-rbush').default;
  9451. * var tree = geojsonRbush();
  9452. */
  9453. function geojsonRbush(maxEntries) {
  9454. var tree = rbush(maxEntries);
  9455. /**
  9456. * [insert](https://github.com/mourner/rbush#data-format)
  9457. *
  9458. * @param {Feature} feature insert single GeoJSON Feature
  9459. * @returns {RBush} GeoJSON RBush
  9460. * @example
  9461. * var poly = turf.polygon([[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]);
  9462. * tree.insert(poly)
  9463. */
  9464. tree.insert = function (feature) {
  9465. if (feature.type !== 'Feature') throw new Error('invalid feature');
  9466. feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
  9467. return rbush.prototype.insert.call(this, feature);
  9468. };
  9469. /**
  9470. * [load](https://github.com/mourner/rbush#bulk-inserting-data)
  9471. *
  9472. * @param {FeatureCollection|Array<Feature>} features load entire GeoJSON FeatureCollection
  9473. * @returns {RBush} GeoJSON RBush
  9474. * @example
  9475. * var polys = turf.polygons([
  9476. * [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]],
  9477. * [[[-93, 32], [-83, 32], [-83, 39], [-93, 39], [-93, 32]]]
  9478. * ]);
  9479. * tree.load(polys);
  9480. */
  9481. tree.load = function (features) {
  9482. var load = [];
  9483. // Load an Array of Features
  9484. if (Array.isArray(features)) {
  9485. features.forEach(function (feature) {
  9486. if (feature.type !== 'Feature') throw new Error('invalid features');
  9487. feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
  9488. load.push(feature);
  9489. });
  9490. } else {
  9491. // Load a FeatureCollection
  9492. featureEach(features, function (feature) {
  9493. if (feature.type !== 'Feature') throw new Error('invalid features');
  9494. feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
  9495. load.push(feature);
  9496. });
  9497. }
  9498. return rbush.prototype.load.call(this, load);
  9499. };
  9500. /**
  9501. * [remove](https://github.com/mourner/rbush#removing-data)
  9502. *
  9503. * @param {Feature} feature remove single GeoJSON Feature
  9504. * @param {Function} equals Pass a custom equals function to compare by value for removal.
  9505. * @returns {RBush} GeoJSON RBush
  9506. * @example
  9507. * var poly = turf.polygon([[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]);
  9508. *
  9509. * tree.remove(poly);
  9510. */
  9511. tree.remove = function (feature, equals) {
  9512. if (feature.type !== 'Feature') throw new Error('invalid feature');
  9513. feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
  9514. return rbush.prototype.remove.call(this, feature, equals);
  9515. };
  9516. /**
  9517. * [clear](https://github.com/mourner/rbush#removing-data)
  9518. *
  9519. * @returns {RBush} GeoJSON Rbush
  9520. * @example
  9521. * tree.clear()
  9522. */
  9523. tree.clear = function () {
  9524. return rbush.prototype.clear.call(this);
  9525. };
  9526. /**
  9527. * [search](https://github.com/mourner/rbush#search)
  9528. *
  9529. * @param {BBox|FeatureCollection|Feature} geojson search with GeoJSON
  9530. * @returns {FeatureCollection} all features that intersects with the given GeoJSON.
  9531. * @example
  9532. * var poly = turf.polygon([[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]);
  9533. *
  9534. * tree.search(poly);
  9535. */
  9536. tree.search = function (geojson) {
  9537. var features = rbush.prototype.search.call(this, this.toBBox(geojson));
  9538. return featureCollection(features);
  9539. };
  9540. /**
  9541. * [collides](https://github.com/mourner/rbush#collisions)
  9542. *
  9543. * @param {BBox|FeatureCollection|Feature} geojson collides with GeoJSON
  9544. * @returns {boolean} true if there are any items intersecting the given GeoJSON, otherwise false.
  9545. * @example
  9546. * var poly = turf.polygon([[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]);
  9547. *
  9548. * tree.collides(poly);
  9549. */
  9550. tree.collides = function (geojson) {
  9551. return rbush.prototype.collides.call(this, this.toBBox(geojson));
  9552. };
  9553. /**
  9554. * [all](https://github.com/mourner/rbush#search)
  9555. *
  9556. * @returns {FeatureCollection} all the features in RBush
  9557. * @example
  9558. * tree.all()
  9559. */
  9560. tree.all = function () {
  9561. var features = rbush.prototype.all.call(this);
  9562. return featureCollection(features);
  9563. };
  9564. /**
  9565. * [toJSON](https://github.com/mourner/rbush#export-and-import)
  9566. *
  9567. * @returns {any} export data as JSON object
  9568. * @example
  9569. * var exported = tree.toJSON()
  9570. */
  9571. tree.toJSON = function () {
  9572. return rbush.prototype.toJSON.call(this);
  9573. };
  9574. /**
  9575. * [fromJSON](https://github.com/mourner/rbush#export-and-import)
  9576. *
  9577. * @param {any} json import previously exported data
  9578. * @returns {RBush} GeoJSON RBush
  9579. * @example
  9580. * var exported = {
  9581. * "children": [
  9582. * {
  9583. * "type": "Feature",
  9584. * "geometry": {
  9585. * "type": "Point",
  9586. * "coordinates": [110, 50]
  9587. * },
  9588. * "properties": {},
  9589. * "bbox": [110, 50, 110, 50]
  9590. * }
  9591. * ],
  9592. * "height": 1,
  9593. * "leaf": true,
  9594. * "minX": 110,
  9595. * "minY": 50,
  9596. * "maxX": 110,
  9597. * "maxY": 50
  9598. * }
  9599. * tree.fromJSON(exported)
  9600. */
  9601. tree.fromJSON = function (json) {
  9602. return rbush.prototype.fromJSON.call(this, json);
  9603. };
  9604. /**
  9605. * Converts GeoJSON to {minX, minY, maxX, maxY} schema
  9606. *
  9607. * @private
  9608. * @param {BBox|FeatureCollection|Feature} geojson feature(s) to retrieve BBox from
  9609. * @returns {Object} converted to {minX, minY, maxX, maxY}
  9610. */
  9611. tree.toBBox = function (geojson) {
  9612. var bbox;
  9613. if (geojson.bbox) bbox = geojson.bbox;
  9614. else if (Array.isArray(geojson) && geojson.length === 4) bbox = geojson;
  9615. else if (Array.isArray(geojson) && geojson.length === 6) bbox = [geojson[0], geojson[1], geojson[3], geojson[4]];
  9616. else if (geojson.type === 'Feature') bbox = turfBBox(geojson);
  9617. else if (geojson.type === 'FeatureCollection') bbox = turfBBox(geojson);
  9618. else throw new Error('invalid geojson')
  9619. return {
  9620. minX: bbox[0],
  9621. minY: bbox[1],
  9622. maxX: bbox[2],
  9623. maxY: bbox[3]
  9624. };
  9625. };
  9626. return tree;
  9627. }
  9628. module.exports = geojsonRbush;
  9629. module.exports.default = geojsonRbush;
  9630. },{"@turf/bbox":5,"@turf/helpers":11,"@turf/meta":16,"rbush":204}],45:[function(require,module,exports){
  9631. var geojsonArea = require('geojson-area');
  9632. module.exports = rewind;
  9633. function rewind(gj, outer) {
  9634. switch ((gj && gj.type) || null) {
  9635. case 'FeatureCollection':
  9636. gj.features = gj.features.map(curryOuter(rewind, outer));
  9637. return gj;
  9638. case 'Feature':
  9639. gj.geometry = rewind(gj.geometry, outer);
  9640. return gj;
  9641. case 'Polygon':
  9642. case 'MultiPolygon':
  9643. return correct(gj, outer);
  9644. default:
  9645. return gj;
  9646. }
  9647. }
  9648. function curryOuter(a, b) {
  9649. return function(_) { return a(_, b); };
  9650. }
  9651. function correct(_, outer) {
  9652. if (_.type === 'Polygon') {
  9653. _.coordinates = correctRings(_.coordinates, outer);
  9654. } else if (_.type === 'MultiPolygon') {
  9655. _.coordinates = _.coordinates.map(curryOuter(correctRings, outer));
  9656. }
  9657. return _;
  9658. }
  9659. function correctRings(_, outer) {
  9660. outer = !!outer;
  9661. _[0] = wind(_[0], outer);
  9662. for (var i = 1; i < _.length; i++) {
  9663. _[i] = wind(_[i], !outer);
  9664. }
  9665. return _;
  9666. }
  9667. function wind(_, dir) {
  9668. return cw(_) === dir ? _ : _.reverse();
  9669. }
  9670. function cw(_) {
  9671. return geojsonArea.ring(_) >= 0;
  9672. }
  9673. },{"geojson-area":42}],46:[function(require,module,exports){
  9674. "use strict";
  9675. // Implementation originally from Twitter's Hogan.js:
  9676. // https://github.com/twitter/hogan.js/blob/master/lib/template.js#L325-L335
  9677. var rAmp = /&/g;
  9678. var rLt = /</g;
  9679. var rApos =/\'/g;
  9680. var rQuot = /\"/g;
  9681. var hChars =/[&<>\"\']/;
  9682. module.exports = function(str) {
  9683. if (str == null) {
  9684. return str;
  9685. }
  9686. if (typeof str !== "string") {
  9687. str = String(str);
  9688. }
  9689. if (hChars.test(String(str))) {
  9690. return str
  9691. .replace(rAmp,'&amp;')
  9692. .replace(rLt,'&lt;')
  9693. .replace(rApos,'&apos;')
  9694. .replace(rQuot, '&quot;');
  9695. }
  9696. else {
  9697. return str;
  9698. }
  9699. };
  9700. },{}],47:[function(require,module,exports){
  9701. var getNative = require('./_getNative'),
  9702. root = require('./_root');
  9703. /* Built-in method references that are verified to be native. */
  9704. var DataView = getNative(root, 'DataView');
  9705. module.exports = DataView;
  9706. },{"./_getNative":102,"./_root":137}],48:[function(require,module,exports){
  9707. var hashClear = require('./_hashClear'),
  9708. hashDelete = require('./_hashDelete'),
  9709. hashGet = require('./_hashGet'),
  9710. hashHas = require('./_hashHas'),
  9711. hashSet = require('./_hashSet');
  9712. /**
  9713. * Creates a hash object.
  9714. *
  9715. * @private
  9716. * @constructor
  9717. * @param {Array} [entries] The key-value pairs to cache.
  9718. */
  9719. function Hash(entries) {
  9720. var index = -1,
  9721. length = entries == null ? 0 : entries.length;
  9722. this.clear();
  9723. while (++index < length) {
  9724. var entry = entries[index];
  9725. this.set(entry[0], entry[1]);
  9726. }
  9727. }
  9728. // Add methods to `Hash`.
  9729. Hash.prototype.clear = hashClear;
  9730. Hash.prototype['delete'] = hashDelete;
  9731. Hash.prototype.get = hashGet;
  9732. Hash.prototype.has = hashHas;
  9733. Hash.prototype.set = hashSet;
  9734. module.exports = Hash;
  9735. },{"./_hashClear":108,"./_hashDelete":109,"./_hashGet":110,"./_hashHas":111,"./_hashSet":112}],49:[function(require,module,exports){
  9736. var listCacheClear = require('./_listCacheClear'),
  9737. listCacheDelete = require('./_listCacheDelete'),
  9738. listCacheGet = require('./_listCacheGet'),
  9739. listCacheHas = require('./_listCacheHas'),
  9740. listCacheSet = require('./_listCacheSet');
  9741. /**
  9742. * Creates an list cache object.
  9743. *
  9744. * @private
  9745. * @constructor
  9746. * @param {Array} [entries] The key-value pairs to cache.
  9747. */
  9748. function ListCache(entries) {
  9749. var index = -1,
  9750. length = entries == null ? 0 : entries.length;
  9751. this.clear();
  9752. while (++index < length) {
  9753. var entry = entries[index];
  9754. this.set(entry[0], entry[1]);
  9755. }
  9756. }
  9757. // Add methods to `ListCache`.
  9758. ListCache.prototype.clear = listCacheClear;
  9759. ListCache.prototype['delete'] = listCacheDelete;
  9760. ListCache.prototype.get = listCacheGet;
  9761. ListCache.prototype.has = listCacheHas;
  9762. ListCache.prototype.set = listCacheSet;
  9763. module.exports = ListCache;
  9764. },{"./_listCacheClear":119,"./_listCacheDelete":120,"./_listCacheGet":121,"./_listCacheHas":122,"./_listCacheSet":123}],50:[function(require,module,exports){
  9765. var getNative = require('./_getNative'),
  9766. root = require('./_root');
  9767. /* Built-in method references that are verified to be native. */
  9768. var Map = getNative(root, 'Map');
  9769. module.exports = Map;
  9770. },{"./_getNative":102,"./_root":137}],51:[function(require,module,exports){
  9771. var mapCacheClear = require('./_mapCacheClear'),
  9772. mapCacheDelete = require('./_mapCacheDelete'),
  9773. mapCacheGet = require('./_mapCacheGet'),
  9774. mapCacheHas = require('./_mapCacheHas'),
  9775. mapCacheSet = require('./_mapCacheSet');
  9776. /**
  9777. * Creates a map cache object to store key-value pairs.
  9778. *
  9779. * @private
  9780. * @constructor
  9781. * @param {Array} [entries] The key-value pairs to cache.
  9782. */
  9783. function MapCache(entries) {
  9784. var index = -1,
  9785. length = entries == null ? 0 : entries.length;
  9786. this.clear();
  9787. while (++index < length) {
  9788. var entry = entries[index];
  9789. this.set(entry[0], entry[1]);
  9790. }
  9791. }
  9792. // Add methods to `MapCache`.
  9793. MapCache.prototype.clear = mapCacheClear;
  9794. MapCache.prototype['delete'] = mapCacheDelete;
  9795. MapCache.prototype.get = mapCacheGet;
  9796. MapCache.prototype.has = mapCacheHas;
  9797. MapCache.prototype.set = mapCacheSet;
  9798. module.exports = MapCache;
  9799. },{"./_mapCacheClear":124,"./_mapCacheDelete":125,"./_mapCacheGet":126,"./_mapCacheHas":127,"./_mapCacheSet":128}],52:[function(require,module,exports){
  9800. var getNative = require('./_getNative'),
  9801. root = require('./_root');
  9802. /* Built-in method references that are verified to be native. */
  9803. var Promise = getNative(root, 'Promise');
  9804. module.exports = Promise;
  9805. },{"./_getNative":102,"./_root":137}],53:[function(require,module,exports){
  9806. var getNative = require('./_getNative'),
  9807. root = require('./_root');
  9808. /* Built-in method references that are verified to be native. */
  9809. var Set = getNative(root, 'Set');
  9810. module.exports = Set;
  9811. },{"./_getNative":102,"./_root":137}],54:[function(require,module,exports){
  9812. var MapCache = require('./_MapCache'),
  9813. setCacheAdd = require('./_setCacheAdd'),
  9814. setCacheHas = require('./_setCacheHas');
  9815. /**
  9816. *
  9817. * Creates an array cache object to store unique values.
  9818. *
  9819. * @private
  9820. * @constructor
  9821. * @param {Array} [values] The values to cache.
  9822. */
  9823. function SetCache(values) {
  9824. var index = -1,
  9825. length = values == null ? 0 : values.length;
  9826. this.__data__ = new MapCache;
  9827. while (++index < length) {
  9828. this.add(values[index]);
  9829. }
  9830. }
  9831. // Add methods to `SetCache`.
  9832. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
  9833. SetCache.prototype.has = setCacheHas;
  9834. module.exports = SetCache;
  9835. },{"./_MapCache":51,"./_setCacheAdd":138,"./_setCacheHas":139}],55:[function(require,module,exports){
  9836. var ListCache = require('./_ListCache'),
  9837. stackClear = require('./_stackClear'),
  9838. stackDelete = require('./_stackDelete'),
  9839. stackGet = require('./_stackGet'),
  9840. stackHas = require('./_stackHas'),
  9841. stackSet = require('./_stackSet');
  9842. /**
  9843. * Creates a stack cache object to store key-value pairs.
  9844. *
  9845. * @private
  9846. * @constructor
  9847. * @param {Array} [entries] The key-value pairs to cache.
  9848. */
  9849. function Stack(entries) {
  9850. var data = this.__data__ = new ListCache(entries);
  9851. this.size = data.size;
  9852. }
  9853. // Add methods to `Stack`.
  9854. Stack.prototype.clear = stackClear;
  9855. Stack.prototype['delete'] = stackDelete;
  9856. Stack.prototype.get = stackGet;
  9857. Stack.prototype.has = stackHas;
  9858. Stack.prototype.set = stackSet;
  9859. module.exports = Stack;
  9860. },{"./_ListCache":49,"./_stackClear":141,"./_stackDelete":142,"./_stackGet":143,"./_stackHas":144,"./_stackSet":145}],56:[function(require,module,exports){
  9861. var root = require('./_root');
  9862. /** Built-in value references. */
  9863. var Symbol = root.Symbol;
  9864. module.exports = Symbol;
  9865. },{"./_root":137}],57:[function(require,module,exports){
  9866. var root = require('./_root');
  9867. /** Built-in value references. */
  9868. var Uint8Array = root.Uint8Array;
  9869. module.exports = Uint8Array;
  9870. },{"./_root":137}],58:[function(require,module,exports){
  9871. var getNative = require('./_getNative'),
  9872. root = require('./_root');
  9873. /* Built-in method references that are verified to be native. */
  9874. var WeakMap = getNative(root, 'WeakMap');
  9875. module.exports = WeakMap;
  9876. },{"./_getNative":102,"./_root":137}],59:[function(require,module,exports){
  9877. /**
  9878. * A specialized version of `_.forEach` for arrays without support for
  9879. * iteratee shorthands.
  9880. *
  9881. * @private
  9882. * @param {Array} [array] The array to iterate over.
  9883. * @param {Function} iteratee The function invoked per iteration.
  9884. * @returns {Array} Returns `array`.
  9885. */
  9886. function arrayEach(array, iteratee) {
  9887. var index = -1,
  9888. length = array == null ? 0 : array.length;
  9889. while (++index < length) {
  9890. if (iteratee(array[index], index, array) === false) {
  9891. break;
  9892. }
  9893. }
  9894. return array;
  9895. }
  9896. module.exports = arrayEach;
  9897. },{}],60:[function(require,module,exports){
  9898. /**
  9899. * A specialized version of `_.filter` for arrays without support for
  9900. * iteratee shorthands.
  9901. *
  9902. * @private
  9903. * @param {Array} [array] The array to iterate over.
  9904. * @param {Function} predicate The function invoked per iteration.
  9905. * @returns {Array} Returns the new filtered array.
  9906. */
  9907. function arrayFilter(array, predicate) {
  9908. var index = -1,
  9909. length = array == null ? 0 : array.length,
  9910. resIndex = 0,
  9911. result = [];
  9912. while (++index < length) {
  9913. var value = array[index];
  9914. if (predicate(value, index, array)) {
  9915. result[resIndex++] = value;
  9916. }
  9917. }
  9918. return result;
  9919. }
  9920. module.exports = arrayFilter;
  9921. },{}],61:[function(require,module,exports){
  9922. var baseTimes = require('./_baseTimes'),
  9923. isArguments = require('./isArguments'),
  9924. isArray = require('./isArray'),
  9925. isBuffer = require('./isBuffer'),
  9926. isIndex = require('./_isIndex'),
  9927. isTypedArray = require('./isTypedArray');
  9928. /** Used for built-in method references. */
  9929. var objectProto = Object.prototype;
  9930. /** Used to check objects for own properties. */
  9931. var hasOwnProperty = objectProto.hasOwnProperty;
  9932. /**
  9933. * Creates an array of the enumerable property names of the array-like `value`.
  9934. *
  9935. * @private
  9936. * @param {*} value The value to query.
  9937. * @param {boolean} inherited Specify returning inherited property names.
  9938. * @returns {Array} Returns the array of property names.
  9939. */
  9940. function arrayLikeKeys(value, inherited) {
  9941. var isArr = isArray(value),
  9942. isArg = !isArr && isArguments(value),
  9943. isBuff = !isArr && !isArg && isBuffer(value),
  9944. isType = !isArr && !isArg && !isBuff && isTypedArray(value),
  9945. skipIndexes = isArr || isArg || isBuff || isType,
  9946. result = skipIndexes ? baseTimes(value.length, String) : [],
  9947. length = result.length;
  9948. for (var key in value) {
  9949. if ((inherited || hasOwnProperty.call(value, key)) &&
  9950. !(skipIndexes && (
  9951. // Safari 9 has enumerable `arguments.length` in strict mode.
  9952. key == 'length' ||
  9953. // Node.js 0.10 has enumerable non-index properties on buffers.
  9954. (isBuff && (key == 'offset' || key == 'parent')) ||
  9955. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  9956. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  9957. // Skip index properties.
  9958. isIndex(key, length)
  9959. ))) {
  9960. result.push(key);
  9961. }
  9962. }
  9963. return result;
  9964. }
  9965. module.exports = arrayLikeKeys;
  9966. },{"./_baseTimes":86,"./_isIndex":113,"./isArguments":154,"./isArray":155,"./isBuffer":157,"./isTypedArray":163}],62:[function(require,module,exports){
  9967. /**
  9968. * A specialized version of `_.map` for arrays without support for iteratee
  9969. * shorthands.
  9970. *
  9971. * @private
  9972. * @param {Array} [array] The array to iterate over.
  9973. * @param {Function} iteratee The function invoked per iteration.
  9974. * @returns {Array} Returns the new mapped array.
  9975. */
  9976. function arrayMap(array, iteratee) {
  9977. var index = -1,
  9978. length = array == null ? 0 : array.length,
  9979. result = Array(length);
  9980. while (++index < length) {
  9981. result[index] = iteratee(array[index], index, array);
  9982. }
  9983. return result;
  9984. }
  9985. module.exports = arrayMap;
  9986. },{}],63:[function(require,module,exports){
  9987. /**
  9988. * Appends the elements of `values` to `array`.
  9989. *
  9990. * @private
  9991. * @param {Array} array The array to modify.
  9992. * @param {Array} values The values to append.
  9993. * @returns {Array} Returns `array`.
  9994. */
  9995. function arrayPush(array, values) {
  9996. var index = -1,
  9997. length = values.length,
  9998. offset = array.length;
  9999. while (++index < length) {
  10000. array[offset + index] = values[index];
  10001. }
  10002. return array;
  10003. }
  10004. module.exports = arrayPush;
  10005. },{}],64:[function(require,module,exports){
  10006. /**
  10007. * A specialized version of `_.some` for arrays without support for iteratee
  10008. * shorthands.
  10009. *
  10010. * @private
  10011. * @param {Array} [array] The array to iterate over.
  10012. * @param {Function} predicate The function invoked per iteration.
  10013. * @returns {boolean} Returns `true` if any element passes the predicate check,
  10014. * else `false`.
  10015. */
  10016. function arraySome(array, predicate) {
  10017. var index = -1,
  10018. length = array == null ? 0 : array.length;
  10019. while (++index < length) {
  10020. if (predicate(array[index], index, array)) {
  10021. return true;
  10022. }
  10023. }
  10024. return false;
  10025. }
  10026. module.exports = arraySome;
  10027. },{}],65:[function(require,module,exports){
  10028. var eq = require('./eq');
  10029. /**
  10030. * Gets the index at which the `key` is found in `array` of key-value pairs.
  10031. *
  10032. * @private
  10033. * @param {Array} array The array to inspect.
  10034. * @param {*} key The key to search for.
  10035. * @returns {number} Returns the index of the matched value, else `-1`.
  10036. */
  10037. function assocIndexOf(array, key) {
  10038. var length = array.length;
  10039. while (length--) {
  10040. if (eq(array[length][0], key)) {
  10041. return length;
  10042. }
  10043. }
  10044. return -1;
  10045. }
  10046. module.exports = assocIndexOf;
  10047. },{"./eq":149}],66:[function(require,module,exports){
  10048. var baseForOwn = require('./_baseForOwn'),
  10049. createBaseEach = require('./_createBaseEach');
  10050. /**
  10051. * The base implementation of `_.forEach` without support for iteratee shorthands.
  10052. *
  10053. * @private
  10054. * @param {Array|Object} collection The collection to iterate over.
  10055. * @param {Function} iteratee The function invoked per iteration.
  10056. * @returns {Array|Object} Returns `collection`.
  10057. */
  10058. var baseEach = createBaseEach(baseForOwn);
  10059. module.exports = baseEach;
  10060. },{"./_baseForOwn":68,"./_createBaseEach":93}],67:[function(require,module,exports){
  10061. var createBaseFor = require('./_createBaseFor');
  10062. /**
  10063. * The base implementation of `baseForOwn` which iterates over `object`
  10064. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  10065. * Iteratee functions may exit iteration early by explicitly returning `false`.
  10066. *
  10067. * @private
  10068. * @param {Object} object The object to iterate over.
  10069. * @param {Function} iteratee The function invoked per iteration.
  10070. * @param {Function} keysFunc The function to get the keys of `object`.
  10071. * @returns {Object} Returns `object`.
  10072. */
  10073. var baseFor = createBaseFor();
  10074. module.exports = baseFor;
  10075. },{"./_createBaseFor":94}],68:[function(require,module,exports){
  10076. var baseFor = require('./_baseFor'),
  10077. keys = require('./keys');
  10078. /**
  10079. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  10080. *
  10081. * @private
  10082. * @param {Object} object The object to iterate over.
  10083. * @param {Function} iteratee The function invoked per iteration.
  10084. * @returns {Object} Returns `object`.
  10085. */
  10086. function baseForOwn(object, iteratee) {
  10087. return object && baseFor(object, iteratee, keys);
  10088. }
  10089. module.exports = baseForOwn;
  10090. },{"./_baseFor":67,"./keys":164}],69:[function(require,module,exports){
  10091. var castPath = require('./_castPath'),
  10092. toKey = require('./_toKey');
  10093. /**
  10094. * The base implementation of `_.get` without support for default values.
  10095. *
  10096. * @private
  10097. * @param {Object} object The object to query.
  10098. * @param {Array|string} path The path of the property to get.
  10099. * @returns {*} Returns the resolved value.
  10100. */
  10101. function baseGet(object, path) {
  10102. path = castPath(path, object);
  10103. var index = 0,
  10104. length = path.length;
  10105. while (object != null && index < length) {
  10106. object = object[toKey(path[index++])];
  10107. }
  10108. return (index && index == length) ? object : undefined;
  10109. }
  10110. module.exports = baseGet;
  10111. },{"./_castPath":91,"./_toKey":147}],70:[function(require,module,exports){
  10112. var arrayPush = require('./_arrayPush'),
  10113. isArray = require('./isArray');
  10114. /**
  10115. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  10116. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  10117. * symbols of `object`.
  10118. *
  10119. * @private
  10120. * @param {Object} object The object to query.
  10121. * @param {Function} keysFunc The function to get the keys of `object`.
  10122. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  10123. * @returns {Array} Returns the array of property names and symbols.
  10124. */
  10125. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  10126. var result = keysFunc(object);
  10127. return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
  10128. }
  10129. module.exports = baseGetAllKeys;
  10130. },{"./_arrayPush":63,"./isArray":155}],71:[function(require,module,exports){
  10131. var Symbol = require('./_Symbol'),
  10132. getRawTag = require('./_getRawTag'),
  10133. objectToString = require('./_objectToString');
  10134. /** `Object#toString` result references. */
  10135. var nullTag = '[object Null]',
  10136. undefinedTag = '[object Undefined]';
  10137. /** Built-in value references. */
  10138. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  10139. /**
  10140. * The base implementation of `getTag` without fallbacks for buggy environments.
  10141. *
  10142. * @private
  10143. * @param {*} value The value to query.
  10144. * @returns {string} Returns the `toStringTag`.
  10145. */
  10146. function baseGetTag(value) {
  10147. if (value == null) {
  10148. return value === undefined ? undefinedTag : nullTag;
  10149. }
  10150. return (symToStringTag && symToStringTag in Object(value))
  10151. ? getRawTag(value)
  10152. : objectToString(value);
  10153. }
  10154. module.exports = baseGetTag;
  10155. },{"./_Symbol":56,"./_getRawTag":103,"./_objectToString":135}],72:[function(require,module,exports){
  10156. /**
  10157. * The base implementation of `_.hasIn` without support for deep paths.
  10158. *
  10159. * @private
  10160. * @param {Object} [object] The object to query.
  10161. * @param {Array|string} key The key to check.
  10162. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  10163. */
  10164. function baseHasIn(object, key) {
  10165. return object != null && key in Object(object);
  10166. }
  10167. module.exports = baseHasIn;
  10168. },{}],73:[function(require,module,exports){
  10169. var baseGetTag = require('./_baseGetTag'),
  10170. isObjectLike = require('./isObjectLike');
  10171. /** `Object#toString` result references. */
  10172. var argsTag = '[object Arguments]';
  10173. /**
  10174. * The base implementation of `_.isArguments`.
  10175. *
  10176. * @private
  10177. * @param {*} value The value to check.
  10178. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  10179. */
  10180. function baseIsArguments(value) {
  10181. return isObjectLike(value) && baseGetTag(value) == argsTag;
  10182. }
  10183. module.exports = baseIsArguments;
  10184. },{"./_baseGetTag":71,"./isObjectLike":161}],74:[function(require,module,exports){
  10185. var baseIsEqualDeep = require('./_baseIsEqualDeep'),
  10186. isObjectLike = require('./isObjectLike');
  10187. /**
  10188. * The base implementation of `_.isEqual` which supports partial comparisons
  10189. * and tracks traversed objects.
  10190. *
  10191. * @private
  10192. * @param {*} value The value to compare.
  10193. * @param {*} other The other value to compare.
  10194. * @param {boolean} bitmask The bitmask flags.
  10195. * 1 - Unordered comparison
  10196. * 2 - Partial comparison
  10197. * @param {Function} [customizer] The function to customize comparisons.
  10198. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  10199. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  10200. */
  10201. function baseIsEqual(value, other, bitmask, customizer, stack) {
  10202. if (value === other) {
  10203. return true;
  10204. }
  10205. if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
  10206. return value !== value && other !== other;
  10207. }
  10208. return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  10209. }
  10210. module.exports = baseIsEqual;
  10211. },{"./_baseIsEqualDeep":75,"./isObjectLike":161}],75:[function(require,module,exports){
  10212. var Stack = require('./_Stack'),
  10213. equalArrays = require('./_equalArrays'),
  10214. equalByTag = require('./_equalByTag'),
  10215. equalObjects = require('./_equalObjects'),
  10216. getTag = require('./_getTag'),
  10217. isArray = require('./isArray'),
  10218. isBuffer = require('./isBuffer'),
  10219. isTypedArray = require('./isTypedArray');
  10220. /** Used to compose bitmasks for value comparisons. */
  10221. var COMPARE_PARTIAL_FLAG = 1;
  10222. /** `Object#toString` result references. */
  10223. var argsTag = '[object Arguments]',
  10224. arrayTag = '[object Array]',
  10225. objectTag = '[object Object]';
  10226. /** Used for built-in method references. */
  10227. var objectProto = Object.prototype;
  10228. /** Used to check objects for own properties. */
  10229. var hasOwnProperty = objectProto.hasOwnProperty;
  10230. /**
  10231. * A specialized version of `baseIsEqual` for arrays and objects which performs
  10232. * deep comparisons and tracks traversed objects enabling objects with circular
  10233. * references to be compared.
  10234. *
  10235. * @private
  10236. * @param {Object} object The object to compare.
  10237. * @param {Object} other The other object to compare.
  10238. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  10239. * @param {Function} customizer The function to customize comparisons.
  10240. * @param {Function} equalFunc The function to determine equivalents of values.
  10241. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  10242. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  10243. */
  10244. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  10245. var objIsArr = isArray(object),
  10246. othIsArr = isArray(other),
  10247. objTag = objIsArr ? arrayTag : getTag(object),
  10248. othTag = othIsArr ? arrayTag : getTag(other);
  10249. objTag = objTag == argsTag ? objectTag : objTag;
  10250. othTag = othTag == argsTag ? objectTag : othTag;
  10251. var objIsObj = objTag == objectTag,
  10252. othIsObj = othTag == objectTag,
  10253. isSameTag = objTag == othTag;
  10254. if (isSameTag && isBuffer(object)) {
  10255. if (!isBuffer(other)) {
  10256. return false;
  10257. }
  10258. objIsArr = true;
  10259. objIsObj = false;
  10260. }
  10261. if (isSameTag && !objIsObj) {
  10262. stack || (stack = new Stack);
  10263. return (objIsArr || isTypedArray(object))
  10264. ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
  10265. : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  10266. }
  10267. if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
  10268. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  10269. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  10270. if (objIsWrapped || othIsWrapped) {
  10271. var objUnwrapped = objIsWrapped ? object.value() : object,
  10272. othUnwrapped = othIsWrapped ? other.value() : other;
  10273. stack || (stack = new Stack);
  10274. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  10275. }
  10276. }
  10277. if (!isSameTag) {
  10278. return false;
  10279. }
  10280. stack || (stack = new Stack);
  10281. return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  10282. }
  10283. module.exports = baseIsEqualDeep;
  10284. },{"./_Stack":55,"./_equalArrays":95,"./_equalByTag":96,"./_equalObjects":97,"./_getTag":105,"./isArray":155,"./isBuffer":157,"./isTypedArray":163}],76:[function(require,module,exports){
  10285. var Stack = require('./_Stack'),
  10286. baseIsEqual = require('./_baseIsEqual');
  10287. /** Used to compose bitmasks for value comparisons. */
  10288. var COMPARE_PARTIAL_FLAG = 1,
  10289. COMPARE_UNORDERED_FLAG = 2;
  10290. /**
  10291. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  10292. *
  10293. * @private
  10294. * @param {Object} object The object to inspect.
  10295. * @param {Object} source The object of property values to match.
  10296. * @param {Array} matchData The property names, values, and compare flags to match.
  10297. * @param {Function} [customizer] The function to customize comparisons.
  10298. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  10299. */
  10300. function baseIsMatch(object, source, matchData, customizer) {
  10301. var index = matchData.length,
  10302. length = index,
  10303. noCustomizer = !customizer;
  10304. if (object == null) {
  10305. return !length;
  10306. }
  10307. object = Object(object);
  10308. while (index--) {
  10309. var data = matchData[index];
  10310. if ((noCustomizer && data[2])
  10311. ? data[1] !== object[data[0]]
  10312. : !(data[0] in object)
  10313. ) {
  10314. return false;
  10315. }
  10316. }
  10317. while (++index < length) {
  10318. data = matchData[index];
  10319. var key = data[0],
  10320. objValue = object[key],
  10321. srcValue = data[1];
  10322. if (noCustomizer && data[2]) {
  10323. if (objValue === undefined && !(key in object)) {
  10324. return false;
  10325. }
  10326. } else {
  10327. var stack = new Stack;
  10328. if (customizer) {
  10329. var result = customizer(objValue, srcValue, key, object, source, stack);
  10330. }
  10331. if (!(result === undefined
  10332. ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
  10333. : result
  10334. )) {
  10335. return false;
  10336. }
  10337. }
  10338. }
  10339. return true;
  10340. }
  10341. module.exports = baseIsMatch;
  10342. },{"./_Stack":55,"./_baseIsEqual":74}],77:[function(require,module,exports){
  10343. var isFunction = require('./isFunction'),
  10344. isMasked = require('./_isMasked'),
  10345. isObject = require('./isObject'),
  10346. toSource = require('./_toSource');
  10347. /**
  10348. * Used to match `RegExp`
  10349. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  10350. */
  10351. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  10352. /** Used to detect host constructors (Safari). */
  10353. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  10354. /** Used for built-in method references. */
  10355. var funcProto = Function.prototype,
  10356. objectProto = Object.prototype;
  10357. /** Used to resolve the decompiled source of functions. */
  10358. var funcToString = funcProto.toString;
  10359. /** Used to check objects for own properties. */
  10360. var hasOwnProperty = objectProto.hasOwnProperty;
  10361. /** Used to detect if a method is native. */
  10362. var reIsNative = RegExp('^' +
  10363. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  10364. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  10365. );
  10366. /**
  10367. * The base implementation of `_.isNative` without bad shim checks.
  10368. *
  10369. * @private
  10370. * @param {*} value The value to check.
  10371. * @returns {boolean} Returns `true` if `value` is a native function,
  10372. * else `false`.
  10373. */
  10374. function baseIsNative(value) {
  10375. if (!isObject(value) || isMasked(value)) {
  10376. return false;
  10377. }
  10378. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  10379. return pattern.test(toSource(value));
  10380. }
  10381. module.exports = baseIsNative;
  10382. },{"./_isMasked":116,"./_toSource":148,"./isFunction":158,"./isObject":160}],78:[function(require,module,exports){
  10383. var baseGetTag = require('./_baseGetTag'),
  10384. isLength = require('./isLength'),
  10385. isObjectLike = require('./isObjectLike');
  10386. /** `Object#toString` result references. */
  10387. var argsTag = '[object Arguments]',
  10388. arrayTag = '[object Array]',
  10389. boolTag = '[object Boolean]',
  10390. dateTag = '[object Date]',
  10391. errorTag = '[object Error]',
  10392. funcTag = '[object Function]',
  10393. mapTag = '[object Map]',
  10394. numberTag = '[object Number]',
  10395. objectTag = '[object Object]',
  10396. regexpTag = '[object RegExp]',
  10397. setTag = '[object Set]',
  10398. stringTag = '[object String]',
  10399. weakMapTag = '[object WeakMap]';
  10400. var arrayBufferTag = '[object ArrayBuffer]',
  10401. dataViewTag = '[object DataView]',
  10402. float32Tag = '[object Float32Array]',
  10403. float64Tag = '[object Float64Array]',
  10404. int8Tag = '[object Int8Array]',
  10405. int16Tag = '[object Int16Array]',
  10406. int32Tag = '[object Int32Array]',
  10407. uint8Tag = '[object Uint8Array]',
  10408. uint8ClampedTag = '[object Uint8ClampedArray]',
  10409. uint16Tag = '[object Uint16Array]',
  10410. uint32Tag = '[object Uint32Array]';
  10411. /** Used to identify `toStringTag` values of typed arrays. */
  10412. var typedArrayTags = {};
  10413. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  10414. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  10415. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  10416. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  10417. typedArrayTags[uint32Tag] = true;
  10418. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  10419. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  10420. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  10421. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  10422. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  10423. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  10424. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  10425. typedArrayTags[weakMapTag] = false;
  10426. /**
  10427. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  10428. *
  10429. * @private
  10430. * @param {*} value The value to check.
  10431. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  10432. */
  10433. function baseIsTypedArray(value) {
  10434. return isObjectLike(value) &&
  10435. isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
  10436. }
  10437. module.exports = baseIsTypedArray;
  10438. },{"./_baseGetTag":71,"./isLength":159,"./isObjectLike":161}],79:[function(require,module,exports){
  10439. var baseMatches = require('./_baseMatches'),
  10440. baseMatchesProperty = require('./_baseMatchesProperty'),
  10441. identity = require('./identity'),
  10442. isArray = require('./isArray'),
  10443. property = require('./property');
  10444. /**
  10445. * The base implementation of `_.iteratee`.
  10446. *
  10447. * @private
  10448. * @param {*} [value=_.identity] The value to convert to an iteratee.
  10449. * @returns {Function} Returns the iteratee.
  10450. */
  10451. function baseIteratee(value) {
  10452. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  10453. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  10454. if (typeof value == 'function') {
  10455. return value;
  10456. }
  10457. if (value == null) {
  10458. return identity;
  10459. }
  10460. if (typeof value == 'object') {
  10461. return isArray(value)
  10462. ? baseMatchesProperty(value[0], value[1])
  10463. : baseMatches(value);
  10464. }
  10465. return property(value);
  10466. }
  10467. module.exports = baseIteratee;
  10468. },{"./_baseMatches":82,"./_baseMatchesProperty":83,"./identity":153,"./isArray":155,"./property":167}],80:[function(require,module,exports){
  10469. var isPrototype = require('./_isPrototype'),
  10470. nativeKeys = require('./_nativeKeys');
  10471. /** Used for built-in method references. */
  10472. var objectProto = Object.prototype;
  10473. /** Used to check objects for own properties. */
  10474. var hasOwnProperty = objectProto.hasOwnProperty;
  10475. /**
  10476. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  10477. *
  10478. * @private
  10479. * @param {Object} object The object to query.
  10480. * @returns {Array} Returns the array of property names.
  10481. */
  10482. function baseKeys(object) {
  10483. if (!isPrototype(object)) {
  10484. return nativeKeys(object);
  10485. }
  10486. var result = [];
  10487. for (var key in Object(object)) {
  10488. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  10489. result.push(key);
  10490. }
  10491. }
  10492. return result;
  10493. }
  10494. module.exports = baseKeys;
  10495. },{"./_isPrototype":117,"./_nativeKeys":133}],81:[function(require,module,exports){
  10496. var baseEach = require('./_baseEach'),
  10497. isArrayLike = require('./isArrayLike');
  10498. /**
  10499. * The base implementation of `_.map` without support for iteratee shorthands.
  10500. *
  10501. * @private
  10502. * @param {Array|Object} collection The collection to iterate over.
  10503. * @param {Function} iteratee The function invoked per iteration.
  10504. * @returns {Array} Returns the new mapped array.
  10505. */
  10506. function baseMap(collection, iteratee) {
  10507. var index = -1,
  10508. result = isArrayLike(collection) ? Array(collection.length) : [];
  10509. baseEach(collection, function(value, key, collection) {
  10510. result[++index] = iteratee(value, key, collection);
  10511. });
  10512. return result;
  10513. }
  10514. module.exports = baseMap;
  10515. },{"./_baseEach":66,"./isArrayLike":156}],82:[function(require,module,exports){
  10516. var baseIsMatch = require('./_baseIsMatch'),
  10517. getMatchData = require('./_getMatchData'),
  10518. matchesStrictComparable = require('./_matchesStrictComparable');
  10519. /**
  10520. * The base implementation of `_.matches` which doesn't clone `source`.
  10521. *
  10522. * @private
  10523. * @param {Object} source The object of property values to match.
  10524. * @returns {Function} Returns the new spec function.
  10525. */
  10526. function baseMatches(source) {
  10527. var matchData = getMatchData(source);
  10528. if (matchData.length == 1 && matchData[0][2]) {
  10529. return matchesStrictComparable(matchData[0][0], matchData[0][1]);
  10530. }
  10531. return function(object) {
  10532. return object === source || baseIsMatch(object, source, matchData);
  10533. };
  10534. }
  10535. module.exports = baseMatches;
  10536. },{"./_baseIsMatch":76,"./_getMatchData":101,"./_matchesStrictComparable":130}],83:[function(require,module,exports){
  10537. var baseIsEqual = require('./_baseIsEqual'),
  10538. get = require('./get'),
  10539. hasIn = require('./hasIn'),
  10540. isKey = require('./_isKey'),
  10541. isStrictComparable = require('./_isStrictComparable'),
  10542. matchesStrictComparable = require('./_matchesStrictComparable'),
  10543. toKey = require('./_toKey');
  10544. /** Used to compose bitmasks for value comparisons. */
  10545. var COMPARE_PARTIAL_FLAG = 1,
  10546. COMPARE_UNORDERED_FLAG = 2;
  10547. /**
  10548. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  10549. *
  10550. * @private
  10551. * @param {string} path The path of the property to get.
  10552. * @param {*} srcValue The value to match.
  10553. * @returns {Function} Returns the new spec function.
  10554. */
  10555. function baseMatchesProperty(path, srcValue) {
  10556. if (isKey(path) && isStrictComparable(srcValue)) {
  10557. return matchesStrictComparable(toKey(path), srcValue);
  10558. }
  10559. return function(object) {
  10560. var objValue = get(object, path);
  10561. return (objValue === undefined && objValue === srcValue)
  10562. ? hasIn(object, path)
  10563. : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  10564. };
  10565. }
  10566. module.exports = baseMatchesProperty;
  10567. },{"./_baseIsEqual":74,"./_isKey":114,"./_isStrictComparable":118,"./_matchesStrictComparable":130,"./_toKey":147,"./get":151,"./hasIn":152}],84:[function(require,module,exports){
  10568. /**
  10569. * The base implementation of `_.property` without support for deep paths.
  10570. *
  10571. * @private
  10572. * @param {string} key The key of the property to get.
  10573. * @returns {Function} Returns the new accessor function.
  10574. */
  10575. function baseProperty(key) {
  10576. return function(object) {
  10577. return object == null ? undefined : object[key];
  10578. };
  10579. }
  10580. module.exports = baseProperty;
  10581. },{}],85:[function(require,module,exports){
  10582. var baseGet = require('./_baseGet');
  10583. /**
  10584. * A specialized version of `baseProperty` which supports deep paths.
  10585. *
  10586. * @private
  10587. * @param {Array|string} path The path of the property to get.
  10588. * @returns {Function} Returns the new accessor function.
  10589. */
  10590. function basePropertyDeep(path) {
  10591. return function(object) {
  10592. return baseGet(object, path);
  10593. };
  10594. }
  10595. module.exports = basePropertyDeep;
  10596. },{"./_baseGet":69}],86:[function(require,module,exports){
  10597. /**
  10598. * The base implementation of `_.times` without support for iteratee shorthands
  10599. * or max array length checks.
  10600. *
  10601. * @private
  10602. * @param {number} n The number of times to invoke `iteratee`.
  10603. * @param {Function} iteratee The function invoked per iteration.
  10604. * @returns {Array} Returns the array of results.
  10605. */
  10606. function baseTimes(n, iteratee) {
  10607. var index = -1,
  10608. result = Array(n);
  10609. while (++index < n) {
  10610. result[index] = iteratee(index);
  10611. }
  10612. return result;
  10613. }
  10614. module.exports = baseTimes;
  10615. },{}],87:[function(require,module,exports){
  10616. var Symbol = require('./_Symbol'),
  10617. arrayMap = require('./_arrayMap'),
  10618. isArray = require('./isArray'),
  10619. isSymbol = require('./isSymbol');
  10620. /** Used as references for various `Number` constants. */
  10621. var INFINITY = 1 / 0;
  10622. /** Used to convert symbols to primitives and strings. */
  10623. var symbolProto = Symbol ? Symbol.prototype : undefined,
  10624. symbolToString = symbolProto ? symbolProto.toString : undefined;
  10625. /**
  10626. * The base implementation of `_.toString` which doesn't convert nullish
  10627. * values to empty strings.
  10628. *
  10629. * @private
  10630. * @param {*} value The value to process.
  10631. * @returns {string} Returns the string.
  10632. */
  10633. function baseToString(value) {
  10634. // Exit early for strings to avoid a performance hit in some environments.
  10635. if (typeof value == 'string') {
  10636. return value;
  10637. }
  10638. if (isArray(value)) {
  10639. // Recursively convert values (susceptible to call stack limits).
  10640. return arrayMap(value, baseToString) + '';
  10641. }
  10642. if (isSymbol(value)) {
  10643. return symbolToString ? symbolToString.call(value) : '';
  10644. }
  10645. var result = (value + '');
  10646. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  10647. }
  10648. module.exports = baseToString;
  10649. },{"./_Symbol":56,"./_arrayMap":62,"./isArray":155,"./isSymbol":162}],88:[function(require,module,exports){
  10650. /**
  10651. * The base implementation of `_.unary` without support for storing metadata.
  10652. *
  10653. * @private
  10654. * @param {Function} func The function to cap arguments for.
  10655. * @returns {Function} Returns the new capped function.
  10656. */
  10657. function baseUnary(func) {
  10658. return function(value) {
  10659. return func(value);
  10660. };
  10661. }
  10662. module.exports = baseUnary;
  10663. },{}],89:[function(require,module,exports){
  10664. /**
  10665. * Checks if a `cache` value for `key` exists.
  10666. *
  10667. * @private
  10668. * @param {Object} cache The cache to query.
  10669. * @param {string} key The key of the entry to check.
  10670. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  10671. */
  10672. function cacheHas(cache, key) {
  10673. return cache.has(key);
  10674. }
  10675. module.exports = cacheHas;
  10676. },{}],90:[function(require,module,exports){
  10677. var identity = require('./identity');
  10678. /**
  10679. * Casts `value` to `identity` if it's not a function.
  10680. *
  10681. * @private
  10682. * @param {*} value The value to inspect.
  10683. * @returns {Function} Returns cast function.
  10684. */
  10685. function castFunction(value) {
  10686. return typeof value == 'function' ? value : identity;
  10687. }
  10688. module.exports = castFunction;
  10689. },{"./identity":153}],91:[function(require,module,exports){
  10690. var isArray = require('./isArray'),
  10691. isKey = require('./_isKey'),
  10692. stringToPath = require('./_stringToPath'),
  10693. toString = require('./toString');
  10694. /**
  10695. * Casts `value` to a path array if it's not one.
  10696. *
  10697. * @private
  10698. * @param {*} value The value to inspect.
  10699. * @param {Object} [object] The object to query keys on.
  10700. * @returns {Array} Returns the cast property path array.
  10701. */
  10702. function castPath(value, object) {
  10703. if (isArray(value)) {
  10704. return value;
  10705. }
  10706. return isKey(value, object) ? [value] : stringToPath(toString(value));
  10707. }
  10708. module.exports = castPath;
  10709. },{"./_isKey":114,"./_stringToPath":146,"./isArray":155,"./toString":170}],92:[function(require,module,exports){
  10710. var root = require('./_root');
  10711. /** Used to detect overreaching core-js shims. */
  10712. var coreJsData = root['__core-js_shared__'];
  10713. module.exports = coreJsData;
  10714. },{"./_root":137}],93:[function(require,module,exports){
  10715. var isArrayLike = require('./isArrayLike');
  10716. /**
  10717. * Creates a `baseEach` or `baseEachRight` function.
  10718. *
  10719. * @private
  10720. * @param {Function} eachFunc The function to iterate over a collection.
  10721. * @param {boolean} [fromRight] Specify iterating from right to left.
  10722. * @returns {Function} Returns the new base function.
  10723. */
  10724. function createBaseEach(eachFunc, fromRight) {
  10725. return function(collection, iteratee) {
  10726. if (collection == null) {
  10727. return collection;
  10728. }
  10729. if (!isArrayLike(collection)) {
  10730. return eachFunc(collection, iteratee);
  10731. }
  10732. var length = collection.length,
  10733. index = fromRight ? length : -1,
  10734. iterable = Object(collection);
  10735. while ((fromRight ? index-- : ++index < length)) {
  10736. if (iteratee(iterable[index], index, iterable) === false) {
  10737. break;
  10738. }
  10739. }
  10740. return collection;
  10741. };
  10742. }
  10743. module.exports = createBaseEach;
  10744. },{"./isArrayLike":156}],94:[function(require,module,exports){
  10745. /**
  10746. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  10747. *
  10748. * @private
  10749. * @param {boolean} [fromRight] Specify iterating from right to left.
  10750. * @returns {Function} Returns the new base function.
  10751. */
  10752. function createBaseFor(fromRight) {
  10753. return function(object, iteratee, keysFunc) {
  10754. var index = -1,
  10755. iterable = Object(object),
  10756. props = keysFunc(object),
  10757. length = props.length;
  10758. while (length--) {
  10759. var key = props[fromRight ? length : ++index];
  10760. if (iteratee(iterable[key], key, iterable) === false) {
  10761. break;
  10762. }
  10763. }
  10764. return object;
  10765. };
  10766. }
  10767. module.exports = createBaseFor;
  10768. },{}],95:[function(require,module,exports){
  10769. var SetCache = require('./_SetCache'),
  10770. arraySome = require('./_arraySome'),
  10771. cacheHas = require('./_cacheHas');
  10772. /** Used to compose bitmasks for value comparisons. */
  10773. var COMPARE_PARTIAL_FLAG = 1,
  10774. COMPARE_UNORDERED_FLAG = 2;
  10775. /**
  10776. * A specialized version of `baseIsEqualDeep` for arrays with support for
  10777. * partial deep comparisons.
  10778. *
  10779. * @private
  10780. * @param {Array} array The array to compare.
  10781. * @param {Array} other The other array to compare.
  10782. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  10783. * @param {Function} customizer The function to customize comparisons.
  10784. * @param {Function} equalFunc The function to determine equivalents of values.
  10785. * @param {Object} stack Tracks traversed `array` and `other` objects.
  10786. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  10787. */
  10788. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  10789. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  10790. arrLength = array.length,
  10791. othLength = other.length;
  10792. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  10793. return false;
  10794. }
  10795. // Assume cyclic values are equal.
  10796. var stacked = stack.get(array);
  10797. if (stacked && stack.get(other)) {
  10798. return stacked == other;
  10799. }
  10800. var index = -1,
  10801. result = true,
  10802. seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
  10803. stack.set(array, other);
  10804. stack.set(other, array);
  10805. // Ignore non-index properties.
  10806. while (++index < arrLength) {
  10807. var arrValue = array[index],
  10808. othValue = other[index];
  10809. if (customizer) {
  10810. var compared = isPartial
  10811. ? customizer(othValue, arrValue, index, other, array, stack)
  10812. : customizer(arrValue, othValue, index, array, other, stack);
  10813. }
  10814. if (compared !== undefined) {
  10815. if (compared) {
  10816. continue;
  10817. }
  10818. result = false;
  10819. break;
  10820. }
  10821. // Recursively compare arrays (susceptible to call stack limits).
  10822. if (seen) {
  10823. if (!arraySome(other, function(othValue, othIndex) {
  10824. if (!cacheHas(seen, othIndex) &&
  10825. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  10826. return seen.push(othIndex);
  10827. }
  10828. })) {
  10829. result = false;
  10830. break;
  10831. }
  10832. } else if (!(
  10833. arrValue === othValue ||
  10834. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  10835. )) {
  10836. result = false;
  10837. break;
  10838. }
  10839. }
  10840. stack['delete'](array);
  10841. stack['delete'](other);
  10842. return result;
  10843. }
  10844. module.exports = equalArrays;
  10845. },{"./_SetCache":54,"./_arraySome":64,"./_cacheHas":89}],96:[function(require,module,exports){
  10846. var Symbol = require('./_Symbol'),
  10847. Uint8Array = require('./_Uint8Array'),
  10848. eq = require('./eq'),
  10849. equalArrays = require('./_equalArrays'),
  10850. mapToArray = require('./_mapToArray'),
  10851. setToArray = require('./_setToArray');
  10852. /** Used to compose bitmasks for value comparisons. */
  10853. var COMPARE_PARTIAL_FLAG = 1,
  10854. COMPARE_UNORDERED_FLAG = 2;
  10855. /** `Object#toString` result references. */
  10856. var boolTag = '[object Boolean]',
  10857. dateTag = '[object Date]',
  10858. errorTag = '[object Error]',
  10859. mapTag = '[object Map]',
  10860. numberTag = '[object Number]',
  10861. regexpTag = '[object RegExp]',
  10862. setTag = '[object Set]',
  10863. stringTag = '[object String]',
  10864. symbolTag = '[object Symbol]';
  10865. var arrayBufferTag = '[object ArrayBuffer]',
  10866. dataViewTag = '[object DataView]';
  10867. /** Used to convert symbols to primitives and strings. */
  10868. var symbolProto = Symbol ? Symbol.prototype : undefined,
  10869. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
  10870. /**
  10871. * A specialized version of `baseIsEqualDeep` for comparing objects of
  10872. * the same `toStringTag`.
  10873. *
  10874. * **Note:** This function only supports comparing values with tags of
  10875. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  10876. *
  10877. * @private
  10878. * @param {Object} object The object to compare.
  10879. * @param {Object} other The other object to compare.
  10880. * @param {string} tag The `toStringTag` of the objects to compare.
  10881. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  10882. * @param {Function} customizer The function to customize comparisons.
  10883. * @param {Function} equalFunc The function to determine equivalents of values.
  10884. * @param {Object} stack Tracks traversed `object` and `other` objects.
  10885. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  10886. */
  10887. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  10888. switch (tag) {
  10889. case dataViewTag:
  10890. if ((object.byteLength != other.byteLength) ||
  10891. (object.byteOffset != other.byteOffset)) {
  10892. return false;
  10893. }
  10894. object = object.buffer;
  10895. other = other.buffer;
  10896. case arrayBufferTag:
  10897. if ((object.byteLength != other.byteLength) ||
  10898. !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
  10899. return false;
  10900. }
  10901. return true;
  10902. case boolTag:
  10903. case dateTag:
  10904. case numberTag:
  10905. // Coerce booleans to `1` or `0` and dates to milliseconds.
  10906. // Invalid dates are coerced to `NaN`.
  10907. return eq(+object, +other);
  10908. case errorTag:
  10909. return object.name == other.name && object.message == other.message;
  10910. case regexpTag:
  10911. case stringTag:
  10912. // Coerce regexes to strings and treat strings, primitives and objects,
  10913. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  10914. // for more details.
  10915. return object == (other + '');
  10916. case mapTag:
  10917. var convert = mapToArray;
  10918. case setTag:
  10919. var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
  10920. convert || (convert = setToArray);
  10921. if (object.size != other.size && !isPartial) {
  10922. return false;
  10923. }
  10924. // Assume cyclic values are equal.
  10925. var stacked = stack.get(object);
  10926. if (stacked) {
  10927. return stacked == other;
  10928. }
  10929. bitmask |= COMPARE_UNORDERED_FLAG;
  10930. // Recursively compare objects (susceptible to call stack limits).
  10931. stack.set(object, other);
  10932. var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  10933. stack['delete'](object);
  10934. return result;
  10935. case symbolTag:
  10936. if (symbolValueOf) {
  10937. return symbolValueOf.call(object) == symbolValueOf.call(other);
  10938. }
  10939. }
  10940. return false;
  10941. }
  10942. module.exports = equalByTag;
  10943. },{"./_Symbol":56,"./_Uint8Array":57,"./_equalArrays":95,"./_mapToArray":129,"./_setToArray":140,"./eq":149}],97:[function(require,module,exports){
  10944. var getAllKeys = require('./_getAllKeys');
  10945. /** Used to compose bitmasks for value comparisons. */
  10946. var COMPARE_PARTIAL_FLAG = 1;
  10947. /** Used for built-in method references. */
  10948. var objectProto = Object.prototype;
  10949. /** Used to check objects for own properties. */
  10950. var hasOwnProperty = objectProto.hasOwnProperty;
  10951. /**
  10952. * A specialized version of `baseIsEqualDeep` for objects with support for
  10953. * partial deep comparisons.
  10954. *
  10955. * @private
  10956. * @param {Object} object The object to compare.
  10957. * @param {Object} other The other object to compare.
  10958. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  10959. * @param {Function} customizer The function to customize comparisons.
  10960. * @param {Function} equalFunc The function to determine equivalents of values.
  10961. * @param {Object} stack Tracks traversed `object` and `other` objects.
  10962. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  10963. */
  10964. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  10965. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  10966. objProps = getAllKeys(object),
  10967. objLength = objProps.length,
  10968. othProps = getAllKeys(other),
  10969. othLength = othProps.length;
  10970. if (objLength != othLength && !isPartial) {
  10971. return false;
  10972. }
  10973. var index = objLength;
  10974. while (index--) {
  10975. var key = objProps[index];
  10976. if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
  10977. return false;
  10978. }
  10979. }
  10980. // Assume cyclic values are equal.
  10981. var stacked = stack.get(object);
  10982. if (stacked && stack.get(other)) {
  10983. return stacked == other;
  10984. }
  10985. var result = true;
  10986. stack.set(object, other);
  10987. stack.set(other, object);
  10988. var skipCtor = isPartial;
  10989. while (++index < objLength) {
  10990. key = objProps[index];
  10991. var objValue = object[key],
  10992. othValue = other[key];
  10993. if (customizer) {
  10994. var compared = isPartial
  10995. ? customizer(othValue, objValue, key, other, object, stack)
  10996. : customizer(objValue, othValue, key, object, other, stack);
  10997. }
  10998. // Recursively compare objects (susceptible to call stack limits).
  10999. if (!(compared === undefined
  11000. ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
  11001. : compared
  11002. )) {
  11003. result = false;
  11004. break;
  11005. }
  11006. skipCtor || (skipCtor = key == 'constructor');
  11007. }
  11008. if (result && !skipCtor) {
  11009. var objCtor = object.constructor,
  11010. othCtor = other.constructor;
  11011. // Non `Object` object instances with different constructors are not equal.
  11012. if (objCtor != othCtor &&
  11013. ('constructor' in object && 'constructor' in other) &&
  11014. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  11015. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  11016. result = false;
  11017. }
  11018. }
  11019. stack['delete'](object);
  11020. stack['delete'](other);
  11021. return result;
  11022. }
  11023. module.exports = equalObjects;
  11024. },{"./_getAllKeys":99}],98:[function(require,module,exports){
  11025. (function (global){
  11026. /** Detect free variable `global` from Node.js. */
  11027. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  11028. module.exports = freeGlobal;
  11029. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11030. },{}],99:[function(require,module,exports){
  11031. var baseGetAllKeys = require('./_baseGetAllKeys'),
  11032. getSymbols = require('./_getSymbols'),
  11033. keys = require('./keys');
  11034. /**
  11035. * Creates an array of own enumerable property names and symbols of `object`.
  11036. *
  11037. * @private
  11038. * @param {Object} object The object to query.
  11039. * @returns {Array} Returns the array of property names and symbols.
  11040. */
  11041. function getAllKeys(object) {
  11042. return baseGetAllKeys(object, keys, getSymbols);
  11043. }
  11044. module.exports = getAllKeys;
  11045. },{"./_baseGetAllKeys":70,"./_getSymbols":104,"./keys":164}],100:[function(require,module,exports){
  11046. var isKeyable = require('./_isKeyable');
  11047. /**
  11048. * Gets the data for `map`.
  11049. *
  11050. * @private
  11051. * @param {Object} map The map to query.
  11052. * @param {string} key The reference key.
  11053. * @returns {*} Returns the map data.
  11054. */
  11055. function getMapData(map, key) {
  11056. var data = map.__data__;
  11057. return isKeyable(key)
  11058. ? data[typeof key == 'string' ? 'string' : 'hash']
  11059. : data.map;
  11060. }
  11061. module.exports = getMapData;
  11062. },{"./_isKeyable":115}],101:[function(require,module,exports){
  11063. var isStrictComparable = require('./_isStrictComparable'),
  11064. keys = require('./keys');
  11065. /**
  11066. * Gets the property names, values, and compare flags of `object`.
  11067. *
  11068. * @private
  11069. * @param {Object} object The object to query.
  11070. * @returns {Array} Returns the match data of `object`.
  11071. */
  11072. function getMatchData(object) {
  11073. var result = keys(object),
  11074. length = result.length;
  11075. while (length--) {
  11076. var key = result[length],
  11077. value = object[key];
  11078. result[length] = [key, value, isStrictComparable(value)];
  11079. }
  11080. return result;
  11081. }
  11082. module.exports = getMatchData;
  11083. },{"./_isStrictComparable":118,"./keys":164}],102:[function(require,module,exports){
  11084. var baseIsNative = require('./_baseIsNative'),
  11085. getValue = require('./_getValue');
  11086. /**
  11087. * Gets the native function at `key` of `object`.
  11088. *
  11089. * @private
  11090. * @param {Object} object The object to query.
  11091. * @param {string} key The key of the method to get.
  11092. * @returns {*} Returns the function if it's native, else `undefined`.
  11093. */
  11094. function getNative(object, key) {
  11095. var value = getValue(object, key);
  11096. return baseIsNative(value) ? value : undefined;
  11097. }
  11098. module.exports = getNative;
  11099. },{"./_baseIsNative":77,"./_getValue":106}],103:[function(require,module,exports){
  11100. var Symbol = require('./_Symbol');
  11101. /** Used for built-in method references. */
  11102. var objectProto = Object.prototype;
  11103. /** Used to check objects for own properties. */
  11104. var hasOwnProperty = objectProto.hasOwnProperty;
  11105. /**
  11106. * Used to resolve the
  11107. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11108. * of values.
  11109. */
  11110. var nativeObjectToString = objectProto.toString;
  11111. /** Built-in value references. */
  11112. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  11113. /**
  11114. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  11115. *
  11116. * @private
  11117. * @param {*} value The value to query.
  11118. * @returns {string} Returns the raw `toStringTag`.
  11119. */
  11120. function getRawTag(value) {
  11121. var isOwn = hasOwnProperty.call(value, symToStringTag),
  11122. tag = value[symToStringTag];
  11123. try {
  11124. value[symToStringTag] = undefined;
  11125. var unmasked = true;
  11126. } catch (e) {}
  11127. var result = nativeObjectToString.call(value);
  11128. if (unmasked) {
  11129. if (isOwn) {
  11130. value[symToStringTag] = tag;
  11131. } else {
  11132. delete value[symToStringTag];
  11133. }
  11134. }
  11135. return result;
  11136. }
  11137. module.exports = getRawTag;
  11138. },{"./_Symbol":56}],104:[function(require,module,exports){
  11139. var arrayFilter = require('./_arrayFilter'),
  11140. stubArray = require('./stubArray');
  11141. /** Used for built-in method references. */
  11142. var objectProto = Object.prototype;
  11143. /** Built-in value references. */
  11144. var propertyIsEnumerable = objectProto.propertyIsEnumerable;
  11145. /* Built-in method references for those with the same name as other `lodash` methods. */
  11146. var nativeGetSymbols = Object.getOwnPropertySymbols;
  11147. /**
  11148. * Creates an array of the own enumerable symbols of `object`.
  11149. *
  11150. * @private
  11151. * @param {Object} object The object to query.
  11152. * @returns {Array} Returns the array of symbols.
  11153. */
  11154. var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
  11155. if (object == null) {
  11156. return [];
  11157. }
  11158. object = Object(object);
  11159. return arrayFilter(nativeGetSymbols(object), function(symbol) {
  11160. return propertyIsEnumerable.call(object, symbol);
  11161. });
  11162. };
  11163. module.exports = getSymbols;
  11164. },{"./_arrayFilter":60,"./stubArray":168}],105:[function(require,module,exports){
  11165. var DataView = require('./_DataView'),
  11166. Map = require('./_Map'),
  11167. Promise = require('./_Promise'),
  11168. Set = require('./_Set'),
  11169. WeakMap = require('./_WeakMap'),
  11170. baseGetTag = require('./_baseGetTag'),
  11171. toSource = require('./_toSource');
  11172. /** `Object#toString` result references. */
  11173. var mapTag = '[object Map]',
  11174. objectTag = '[object Object]',
  11175. promiseTag = '[object Promise]',
  11176. setTag = '[object Set]',
  11177. weakMapTag = '[object WeakMap]';
  11178. var dataViewTag = '[object DataView]';
  11179. /** Used to detect maps, sets, and weakmaps. */
  11180. var dataViewCtorString = toSource(DataView),
  11181. mapCtorString = toSource(Map),
  11182. promiseCtorString = toSource(Promise),
  11183. setCtorString = toSource(Set),
  11184. weakMapCtorString = toSource(WeakMap);
  11185. /**
  11186. * Gets the `toStringTag` of `value`.
  11187. *
  11188. * @private
  11189. * @param {*} value The value to query.
  11190. * @returns {string} Returns the `toStringTag`.
  11191. */
  11192. var getTag = baseGetTag;
  11193. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  11194. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
  11195. (Map && getTag(new Map) != mapTag) ||
  11196. (Promise && getTag(Promise.resolve()) != promiseTag) ||
  11197. (Set && getTag(new Set) != setTag) ||
  11198. (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  11199. getTag = function(value) {
  11200. var result = baseGetTag(value),
  11201. Ctor = result == objectTag ? value.constructor : undefined,
  11202. ctorString = Ctor ? toSource(Ctor) : '';
  11203. if (ctorString) {
  11204. switch (ctorString) {
  11205. case dataViewCtorString: return dataViewTag;
  11206. case mapCtorString: return mapTag;
  11207. case promiseCtorString: return promiseTag;
  11208. case setCtorString: return setTag;
  11209. case weakMapCtorString: return weakMapTag;
  11210. }
  11211. }
  11212. return result;
  11213. };
  11214. }
  11215. module.exports = getTag;
  11216. },{"./_DataView":47,"./_Map":50,"./_Promise":52,"./_Set":53,"./_WeakMap":58,"./_baseGetTag":71,"./_toSource":148}],106:[function(require,module,exports){
  11217. /**
  11218. * Gets the value at `key` of `object`.
  11219. *
  11220. * @private
  11221. * @param {Object} [object] The object to query.
  11222. * @param {string} key The key of the property to get.
  11223. * @returns {*} Returns the property value.
  11224. */
  11225. function getValue(object, key) {
  11226. return object == null ? undefined : object[key];
  11227. }
  11228. module.exports = getValue;
  11229. },{}],107:[function(require,module,exports){
  11230. var castPath = require('./_castPath'),
  11231. isArguments = require('./isArguments'),
  11232. isArray = require('./isArray'),
  11233. isIndex = require('./_isIndex'),
  11234. isLength = require('./isLength'),
  11235. toKey = require('./_toKey');
  11236. /**
  11237. * Checks if `path` exists on `object`.
  11238. *
  11239. * @private
  11240. * @param {Object} object The object to query.
  11241. * @param {Array|string} path The path to check.
  11242. * @param {Function} hasFunc The function to check properties.
  11243. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  11244. */
  11245. function hasPath(object, path, hasFunc) {
  11246. path = castPath(path, object);
  11247. var index = -1,
  11248. length = path.length,
  11249. result = false;
  11250. while (++index < length) {
  11251. var key = toKey(path[index]);
  11252. if (!(result = object != null && hasFunc(object, key))) {
  11253. break;
  11254. }
  11255. object = object[key];
  11256. }
  11257. if (result || ++index != length) {
  11258. return result;
  11259. }
  11260. length = object == null ? 0 : object.length;
  11261. return !!length && isLength(length) && isIndex(key, length) &&
  11262. (isArray(object) || isArguments(object));
  11263. }
  11264. module.exports = hasPath;
  11265. },{"./_castPath":91,"./_isIndex":113,"./_toKey":147,"./isArguments":154,"./isArray":155,"./isLength":159}],108:[function(require,module,exports){
  11266. var nativeCreate = require('./_nativeCreate');
  11267. /**
  11268. * Removes all key-value entries from the hash.
  11269. *
  11270. * @private
  11271. * @name clear
  11272. * @memberOf Hash
  11273. */
  11274. function hashClear() {
  11275. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  11276. this.size = 0;
  11277. }
  11278. module.exports = hashClear;
  11279. },{"./_nativeCreate":132}],109:[function(require,module,exports){
  11280. /**
  11281. * Removes `key` and its value from the hash.
  11282. *
  11283. * @private
  11284. * @name delete
  11285. * @memberOf Hash
  11286. * @param {Object} hash The hash to modify.
  11287. * @param {string} key The key of the value to remove.
  11288. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  11289. */
  11290. function hashDelete(key) {
  11291. var result = this.has(key) && delete this.__data__[key];
  11292. this.size -= result ? 1 : 0;
  11293. return result;
  11294. }
  11295. module.exports = hashDelete;
  11296. },{}],110:[function(require,module,exports){
  11297. var nativeCreate = require('./_nativeCreate');
  11298. /** Used to stand-in for `undefined` hash values. */
  11299. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  11300. /** Used for built-in method references. */
  11301. var objectProto = Object.prototype;
  11302. /** Used to check objects for own properties. */
  11303. var hasOwnProperty = objectProto.hasOwnProperty;
  11304. /**
  11305. * Gets the hash value for `key`.
  11306. *
  11307. * @private
  11308. * @name get
  11309. * @memberOf Hash
  11310. * @param {string} key The key of the value to get.
  11311. * @returns {*} Returns the entry value.
  11312. */
  11313. function hashGet(key) {
  11314. var data = this.__data__;
  11315. if (nativeCreate) {
  11316. var result = data[key];
  11317. return result === HASH_UNDEFINED ? undefined : result;
  11318. }
  11319. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  11320. }
  11321. module.exports = hashGet;
  11322. },{"./_nativeCreate":132}],111:[function(require,module,exports){
  11323. var nativeCreate = require('./_nativeCreate');
  11324. /** Used for built-in method references. */
  11325. var objectProto = Object.prototype;
  11326. /** Used to check objects for own properties. */
  11327. var hasOwnProperty = objectProto.hasOwnProperty;
  11328. /**
  11329. * Checks if a hash value for `key` exists.
  11330. *
  11331. * @private
  11332. * @name has
  11333. * @memberOf Hash
  11334. * @param {string} key The key of the entry to check.
  11335. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  11336. */
  11337. function hashHas(key) {
  11338. var data = this.__data__;
  11339. return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
  11340. }
  11341. module.exports = hashHas;
  11342. },{"./_nativeCreate":132}],112:[function(require,module,exports){
  11343. var nativeCreate = require('./_nativeCreate');
  11344. /** Used to stand-in for `undefined` hash values. */
  11345. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  11346. /**
  11347. * Sets the hash `key` to `value`.
  11348. *
  11349. * @private
  11350. * @name set
  11351. * @memberOf Hash
  11352. * @param {string} key The key of the value to set.
  11353. * @param {*} value The value to set.
  11354. * @returns {Object} Returns the hash instance.
  11355. */
  11356. function hashSet(key, value) {
  11357. var data = this.__data__;
  11358. this.size += this.has(key) ? 0 : 1;
  11359. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  11360. return this;
  11361. }
  11362. module.exports = hashSet;
  11363. },{"./_nativeCreate":132}],113:[function(require,module,exports){
  11364. /** Used as references for various `Number` constants. */
  11365. var MAX_SAFE_INTEGER = 9007199254740991;
  11366. /** Used to detect unsigned integer values. */
  11367. var reIsUint = /^(?:0|[1-9]\d*)$/;
  11368. /**
  11369. * Checks if `value` is a valid array-like index.
  11370. *
  11371. * @private
  11372. * @param {*} value The value to check.
  11373. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  11374. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  11375. */
  11376. function isIndex(value, length) {
  11377. var type = typeof value;
  11378. length = length == null ? MAX_SAFE_INTEGER : length;
  11379. return !!length &&
  11380. (type == 'number' ||
  11381. (type != 'symbol' && reIsUint.test(value))) &&
  11382. (value > -1 && value % 1 == 0 && value < length);
  11383. }
  11384. module.exports = isIndex;
  11385. },{}],114:[function(require,module,exports){
  11386. var isArray = require('./isArray'),
  11387. isSymbol = require('./isSymbol');
  11388. /** Used to match property names within property paths. */
  11389. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  11390. reIsPlainProp = /^\w*$/;
  11391. /**
  11392. * Checks if `value` is a property name and not a property path.
  11393. *
  11394. * @private
  11395. * @param {*} value The value to check.
  11396. * @param {Object} [object] The object to query keys on.
  11397. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  11398. */
  11399. function isKey(value, object) {
  11400. if (isArray(value)) {
  11401. return false;
  11402. }
  11403. var type = typeof value;
  11404. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  11405. value == null || isSymbol(value)) {
  11406. return true;
  11407. }
  11408. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  11409. (object != null && value in Object(object));
  11410. }
  11411. module.exports = isKey;
  11412. },{"./isArray":155,"./isSymbol":162}],115:[function(require,module,exports){
  11413. /**
  11414. * Checks if `value` is suitable for use as unique object key.
  11415. *
  11416. * @private
  11417. * @param {*} value The value to check.
  11418. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  11419. */
  11420. function isKeyable(value) {
  11421. var type = typeof value;
  11422. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  11423. ? (value !== '__proto__')
  11424. : (value === null);
  11425. }
  11426. module.exports = isKeyable;
  11427. },{}],116:[function(require,module,exports){
  11428. var coreJsData = require('./_coreJsData');
  11429. /** Used to detect methods masquerading as native. */
  11430. var maskSrcKey = (function() {
  11431. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  11432. return uid ? ('Symbol(src)_1.' + uid) : '';
  11433. }());
  11434. /**
  11435. * Checks if `func` has its source masked.
  11436. *
  11437. * @private
  11438. * @param {Function} func The function to check.
  11439. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  11440. */
  11441. function isMasked(func) {
  11442. return !!maskSrcKey && (maskSrcKey in func);
  11443. }
  11444. module.exports = isMasked;
  11445. },{"./_coreJsData":92}],117:[function(require,module,exports){
  11446. /** Used for built-in method references. */
  11447. var objectProto = Object.prototype;
  11448. /**
  11449. * Checks if `value` is likely a prototype object.
  11450. *
  11451. * @private
  11452. * @param {*} value The value to check.
  11453. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  11454. */
  11455. function isPrototype(value) {
  11456. var Ctor = value && value.constructor,
  11457. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
  11458. return value === proto;
  11459. }
  11460. module.exports = isPrototype;
  11461. },{}],118:[function(require,module,exports){
  11462. var isObject = require('./isObject');
  11463. /**
  11464. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  11465. *
  11466. * @private
  11467. * @param {*} value The value to check.
  11468. * @returns {boolean} Returns `true` if `value` if suitable for strict
  11469. * equality comparisons, else `false`.
  11470. */
  11471. function isStrictComparable(value) {
  11472. return value === value && !isObject(value);
  11473. }
  11474. module.exports = isStrictComparable;
  11475. },{"./isObject":160}],119:[function(require,module,exports){
  11476. /**
  11477. * Removes all key-value entries from the list cache.
  11478. *
  11479. * @private
  11480. * @name clear
  11481. * @memberOf ListCache
  11482. */
  11483. function listCacheClear() {
  11484. this.__data__ = [];
  11485. this.size = 0;
  11486. }
  11487. module.exports = listCacheClear;
  11488. },{}],120:[function(require,module,exports){
  11489. var assocIndexOf = require('./_assocIndexOf');
  11490. /** Used for built-in method references. */
  11491. var arrayProto = Array.prototype;
  11492. /** Built-in value references. */
  11493. var splice = arrayProto.splice;
  11494. /**
  11495. * Removes `key` and its value from the list cache.
  11496. *
  11497. * @private
  11498. * @name delete
  11499. * @memberOf ListCache
  11500. * @param {string} key The key of the value to remove.
  11501. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  11502. */
  11503. function listCacheDelete(key) {
  11504. var data = this.__data__,
  11505. index = assocIndexOf(data, key);
  11506. if (index < 0) {
  11507. return false;
  11508. }
  11509. var lastIndex = data.length - 1;
  11510. if (index == lastIndex) {
  11511. data.pop();
  11512. } else {
  11513. splice.call(data, index, 1);
  11514. }
  11515. --this.size;
  11516. return true;
  11517. }
  11518. module.exports = listCacheDelete;
  11519. },{"./_assocIndexOf":65}],121:[function(require,module,exports){
  11520. var assocIndexOf = require('./_assocIndexOf');
  11521. /**
  11522. * Gets the list cache value for `key`.
  11523. *
  11524. * @private
  11525. * @name get
  11526. * @memberOf ListCache
  11527. * @param {string} key The key of the value to get.
  11528. * @returns {*} Returns the entry value.
  11529. */
  11530. function listCacheGet(key) {
  11531. var data = this.__data__,
  11532. index = assocIndexOf(data, key);
  11533. return index < 0 ? undefined : data[index][1];
  11534. }
  11535. module.exports = listCacheGet;
  11536. },{"./_assocIndexOf":65}],122:[function(require,module,exports){
  11537. var assocIndexOf = require('./_assocIndexOf');
  11538. /**
  11539. * Checks if a list cache value for `key` exists.
  11540. *
  11541. * @private
  11542. * @name has
  11543. * @memberOf ListCache
  11544. * @param {string} key The key of the entry to check.
  11545. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  11546. */
  11547. function listCacheHas(key) {
  11548. return assocIndexOf(this.__data__, key) > -1;
  11549. }
  11550. module.exports = listCacheHas;
  11551. },{"./_assocIndexOf":65}],123:[function(require,module,exports){
  11552. var assocIndexOf = require('./_assocIndexOf');
  11553. /**
  11554. * Sets the list cache `key` to `value`.
  11555. *
  11556. * @private
  11557. * @name set
  11558. * @memberOf ListCache
  11559. * @param {string} key The key of the value to set.
  11560. * @param {*} value The value to set.
  11561. * @returns {Object} Returns the list cache instance.
  11562. */
  11563. function listCacheSet(key, value) {
  11564. var data = this.__data__,
  11565. index = assocIndexOf(data, key);
  11566. if (index < 0) {
  11567. ++this.size;
  11568. data.push([key, value]);
  11569. } else {
  11570. data[index][1] = value;
  11571. }
  11572. return this;
  11573. }
  11574. module.exports = listCacheSet;
  11575. },{"./_assocIndexOf":65}],124:[function(require,module,exports){
  11576. var Hash = require('./_Hash'),
  11577. ListCache = require('./_ListCache'),
  11578. Map = require('./_Map');
  11579. /**
  11580. * Removes all key-value entries from the map.
  11581. *
  11582. * @private
  11583. * @name clear
  11584. * @memberOf MapCache
  11585. */
  11586. function mapCacheClear() {
  11587. this.size = 0;
  11588. this.__data__ = {
  11589. 'hash': new Hash,
  11590. 'map': new (Map || ListCache),
  11591. 'string': new Hash
  11592. };
  11593. }
  11594. module.exports = mapCacheClear;
  11595. },{"./_Hash":48,"./_ListCache":49,"./_Map":50}],125:[function(require,module,exports){
  11596. var getMapData = require('./_getMapData');
  11597. /**
  11598. * Removes `key` and its value from the map.
  11599. *
  11600. * @private
  11601. * @name delete
  11602. * @memberOf MapCache
  11603. * @param {string} key The key of the value to remove.
  11604. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  11605. */
  11606. function mapCacheDelete(key) {
  11607. var result = getMapData(this, key)['delete'](key);
  11608. this.size -= result ? 1 : 0;
  11609. return result;
  11610. }
  11611. module.exports = mapCacheDelete;
  11612. },{"./_getMapData":100}],126:[function(require,module,exports){
  11613. var getMapData = require('./_getMapData');
  11614. /**
  11615. * Gets the map value for `key`.
  11616. *
  11617. * @private
  11618. * @name get
  11619. * @memberOf MapCache
  11620. * @param {string} key The key of the value to get.
  11621. * @returns {*} Returns the entry value.
  11622. */
  11623. function mapCacheGet(key) {
  11624. return getMapData(this, key).get(key);
  11625. }
  11626. module.exports = mapCacheGet;
  11627. },{"./_getMapData":100}],127:[function(require,module,exports){
  11628. var getMapData = require('./_getMapData');
  11629. /**
  11630. * Checks if a map value for `key` exists.
  11631. *
  11632. * @private
  11633. * @name has
  11634. * @memberOf MapCache
  11635. * @param {string} key The key of the entry to check.
  11636. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  11637. */
  11638. function mapCacheHas(key) {
  11639. return getMapData(this, key).has(key);
  11640. }
  11641. module.exports = mapCacheHas;
  11642. },{"./_getMapData":100}],128:[function(require,module,exports){
  11643. var getMapData = require('./_getMapData');
  11644. /**
  11645. * Sets the map `key` to `value`.
  11646. *
  11647. * @private
  11648. * @name set
  11649. * @memberOf MapCache
  11650. * @param {string} key The key of the value to set.
  11651. * @param {*} value The value to set.
  11652. * @returns {Object} Returns the map cache instance.
  11653. */
  11654. function mapCacheSet(key, value) {
  11655. var data = getMapData(this, key),
  11656. size = data.size;
  11657. data.set(key, value);
  11658. this.size += data.size == size ? 0 : 1;
  11659. return this;
  11660. }
  11661. module.exports = mapCacheSet;
  11662. },{"./_getMapData":100}],129:[function(require,module,exports){
  11663. /**
  11664. * Converts `map` to its key-value pairs.
  11665. *
  11666. * @private
  11667. * @param {Object} map The map to convert.
  11668. * @returns {Array} Returns the key-value pairs.
  11669. */
  11670. function mapToArray(map) {
  11671. var index = -1,
  11672. result = Array(map.size);
  11673. map.forEach(function(value, key) {
  11674. result[++index] = [key, value];
  11675. });
  11676. return result;
  11677. }
  11678. module.exports = mapToArray;
  11679. },{}],130:[function(require,module,exports){
  11680. /**
  11681. * A specialized version of `matchesProperty` for source values suitable
  11682. * for strict equality comparisons, i.e. `===`.
  11683. *
  11684. * @private
  11685. * @param {string} key The key of the property to get.
  11686. * @param {*} srcValue The value to match.
  11687. * @returns {Function} Returns the new spec function.
  11688. */
  11689. function matchesStrictComparable(key, srcValue) {
  11690. return function(object) {
  11691. if (object == null) {
  11692. return false;
  11693. }
  11694. return object[key] === srcValue &&
  11695. (srcValue !== undefined || (key in Object(object)));
  11696. };
  11697. }
  11698. module.exports = matchesStrictComparable;
  11699. },{}],131:[function(require,module,exports){
  11700. var memoize = require('./memoize');
  11701. /** Used as the maximum memoize cache size. */
  11702. var MAX_MEMOIZE_SIZE = 500;
  11703. /**
  11704. * A specialized version of `_.memoize` which clears the memoized function's
  11705. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  11706. *
  11707. * @private
  11708. * @param {Function} func The function to have its output memoized.
  11709. * @returns {Function} Returns the new memoized function.
  11710. */
  11711. function memoizeCapped(func) {
  11712. var result = memoize(func, function(key) {
  11713. if (cache.size === MAX_MEMOIZE_SIZE) {
  11714. cache.clear();
  11715. }
  11716. return key;
  11717. });
  11718. var cache = result.cache;
  11719. return result;
  11720. }
  11721. module.exports = memoizeCapped;
  11722. },{"./memoize":166}],132:[function(require,module,exports){
  11723. var getNative = require('./_getNative');
  11724. /* Built-in method references that are verified to be native. */
  11725. var nativeCreate = getNative(Object, 'create');
  11726. module.exports = nativeCreate;
  11727. },{"./_getNative":102}],133:[function(require,module,exports){
  11728. var overArg = require('./_overArg');
  11729. /* Built-in method references for those with the same name as other `lodash` methods. */
  11730. var nativeKeys = overArg(Object.keys, Object);
  11731. module.exports = nativeKeys;
  11732. },{"./_overArg":136}],134:[function(require,module,exports){
  11733. var freeGlobal = require('./_freeGlobal');
  11734. /** Detect free variable `exports`. */
  11735. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  11736. /** Detect free variable `module`. */
  11737. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  11738. /** Detect the popular CommonJS extension `module.exports`. */
  11739. var moduleExports = freeModule && freeModule.exports === freeExports;
  11740. /** Detect free variable `process` from Node.js. */
  11741. var freeProcess = moduleExports && freeGlobal.process;
  11742. /** Used to access faster Node.js helpers. */
  11743. var nodeUtil = (function() {
  11744. try {
  11745. // Use `util.types` for Node.js 10+.
  11746. var types = freeModule && freeModule.require && freeModule.require('util').types;
  11747. if (types) {
  11748. return types;
  11749. }
  11750. // Legacy `process.binding('util')` for Node.js < 10.
  11751. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  11752. } catch (e) {}
  11753. }());
  11754. module.exports = nodeUtil;
  11755. },{"./_freeGlobal":98}],135:[function(require,module,exports){
  11756. /** Used for built-in method references. */
  11757. var objectProto = Object.prototype;
  11758. /**
  11759. * Used to resolve the
  11760. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11761. * of values.
  11762. */
  11763. var nativeObjectToString = objectProto.toString;
  11764. /**
  11765. * Converts `value` to a string using `Object.prototype.toString`.
  11766. *
  11767. * @private
  11768. * @param {*} value The value to convert.
  11769. * @returns {string} Returns the converted string.
  11770. */
  11771. function objectToString(value) {
  11772. return nativeObjectToString.call(value);
  11773. }
  11774. module.exports = objectToString;
  11775. },{}],136:[function(require,module,exports){
  11776. /**
  11777. * Creates a unary function that invokes `func` with its argument transformed.
  11778. *
  11779. * @private
  11780. * @param {Function} func The function to wrap.
  11781. * @param {Function} transform The argument transform.
  11782. * @returns {Function} Returns the new function.
  11783. */
  11784. function overArg(func, transform) {
  11785. return function(arg) {
  11786. return func(transform(arg));
  11787. };
  11788. }
  11789. module.exports = overArg;
  11790. },{}],137:[function(require,module,exports){
  11791. var freeGlobal = require('./_freeGlobal');
  11792. /** Detect free variable `self`. */
  11793. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11794. /** Used as a reference to the global object. */
  11795. var root = freeGlobal || freeSelf || Function('return this')();
  11796. module.exports = root;
  11797. },{"./_freeGlobal":98}],138:[function(require,module,exports){
  11798. /** Used to stand-in for `undefined` hash values. */
  11799. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  11800. /**
  11801. * Adds `value` to the array cache.
  11802. *
  11803. * @private
  11804. * @name add
  11805. * @memberOf SetCache
  11806. * @alias push
  11807. * @param {*} value The value to cache.
  11808. * @returns {Object} Returns the cache instance.
  11809. */
  11810. function setCacheAdd(value) {
  11811. this.__data__.set(value, HASH_UNDEFINED);
  11812. return this;
  11813. }
  11814. module.exports = setCacheAdd;
  11815. },{}],139:[function(require,module,exports){
  11816. /**
  11817. * Checks if `value` is in the array cache.
  11818. *
  11819. * @private
  11820. * @name has
  11821. * @memberOf SetCache
  11822. * @param {*} value The value to search for.
  11823. * @returns {number} Returns `true` if `value` is found, else `false`.
  11824. */
  11825. function setCacheHas(value) {
  11826. return this.__data__.has(value);
  11827. }
  11828. module.exports = setCacheHas;
  11829. },{}],140:[function(require,module,exports){
  11830. /**
  11831. * Converts `set` to an array of its values.
  11832. *
  11833. * @private
  11834. * @param {Object} set The set to convert.
  11835. * @returns {Array} Returns the values.
  11836. */
  11837. function setToArray(set) {
  11838. var index = -1,
  11839. result = Array(set.size);
  11840. set.forEach(function(value) {
  11841. result[++index] = value;
  11842. });
  11843. return result;
  11844. }
  11845. module.exports = setToArray;
  11846. },{}],141:[function(require,module,exports){
  11847. var ListCache = require('./_ListCache');
  11848. /**
  11849. * Removes all key-value entries from the stack.
  11850. *
  11851. * @private
  11852. * @name clear
  11853. * @memberOf Stack
  11854. */
  11855. function stackClear() {
  11856. this.__data__ = new ListCache;
  11857. this.size = 0;
  11858. }
  11859. module.exports = stackClear;
  11860. },{"./_ListCache":49}],142:[function(require,module,exports){
  11861. /**
  11862. * Removes `key` and its value from the stack.
  11863. *
  11864. * @private
  11865. * @name delete
  11866. * @memberOf Stack
  11867. * @param {string} key The key of the value to remove.
  11868. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  11869. */
  11870. function stackDelete(key) {
  11871. var data = this.__data__,
  11872. result = data['delete'](key);
  11873. this.size = data.size;
  11874. return result;
  11875. }
  11876. module.exports = stackDelete;
  11877. },{}],143:[function(require,module,exports){
  11878. /**
  11879. * Gets the stack value for `key`.
  11880. *
  11881. * @private
  11882. * @name get
  11883. * @memberOf Stack
  11884. * @param {string} key The key of the value to get.
  11885. * @returns {*} Returns the entry value.
  11886. */
  11887. function stackGet(key) {
  11888. return this.__data__.get(key);
  11889. }
  11890. module.exports = stackGet;
  11891. },{}],144:[function(require,module,exports){
  11892. /**
  11893. * Checks if a stack value for `key` exists.
  11894. *
  11895. * @private
  11896. * @name has
  11897. * @memberOf Stack
  11898. * @param {string} key The key of the entry to check.
  11899. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  11900. */
  11901. function stackHas(key) {
  11902. return this.__data__.has(key);
  11903. }
  11904. module.exports = stackHas;
  11905. },{}],145:[function(require,module,exports){
  11906. var ListCache = require('./_ListCache'),
  11907. Map = require('./_Map'),
  11908. MapCache = require('./_MapCache');
  11909. /** Used as the size to enable large array optimizations. */
  11910. var LARGE_ARRAY_SIZE = 200;
  11911. /**
  11912. * Sets the stack `key` to `value`.
  11913. *
  11914. * @private
  11915. * @name set
  11916. * @memberOf Stack
  11917. * @param {string} key The key of the value to set.
  11918. * @param {*} value The value to set.
  11919. * @returns {Object} Returns the stack cache instance.
  11920. */
  11921. function stackSet(key, value) {
  11922. var data = this.__data__;
  11923. if (data instanceof ListCache) {
  11924. var pairs = data.__data__;
  11925. if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  11926. pairs.push([key, value]);
  11927. this.size = ++data.size;
  11928. return this;
  11929. }
  11930. data = this.__data__ = new MapCache(pairs);
  11931. }
  11932. data.set(key, value);
  11933. this.size = data.size;
  11934. return this;
  11935. }
  11936. module.exports = stackSet;
  11937. },{"./_ListCache":49,"./_Map":50,"./_MapCache":51}],146:[function(require,module,exports){
  11938. var memoizeCapped = require('./_memoizeCapped');
  11939. /** Used to match property names within property paths. */
  11940. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  11941. /** Used to match backslashes in property paths. */
  11942. var reEscapeChar = /\\(\\)?/g;
  11943. /**
  11944. * Converts `string` to a property path array.
  11945. *
  11946. * @private
  11947. * @param {string} string The string to convert.
  11948. * @returns {Array} Returns the property path array.
  11949. */
  11950. var stringToPath = memoizeCapped(function(string) {
  11951. var result = [];
  11952. if (string.charCodeAt(0) === 46 /* . */) {
  11953. result.push('');
  11954. }
  11955. string.replace(rePropName, function(match, number, quote, subString) {
  11956. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  11957. });
  11958. return result;
  11959. });
  11960. module.exports = stringToPath;
  11961. },{"./_memoizeCapped":131}],147:[function(require,module,exports){
  11962. var isSymbol = require('./isSymbol');
  11963. /** Used as references for various `Number` constants. */
  11964. var INFINITY = 1 / 0;
  11965. /**
  11966. * Converts `value` to a string key if it's not a string or symbol.
  11967. *
  11968. * @private
  11969. * @param {*} value The value to inspect.
  11970. * @returns {string|symbol} Returns the key.
  11971. */
  11972. function toKey(value) {
  11973. if (typeof value == 'string' || isSymbol(value)) {
  11974. return value;
  11975. }
  11976. var result = (value + '');
  11977. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  11978. }
  11979. module.exports = toKey;
  11980. },{"./isSymbol":162}],148:[function(require,module,exports){
  11981. /** Used for built-in method references. */
  11982. var funcProto = Function.prototype;
  11983. /** Used to resolve the decompiled source of functions. */
  11984. var funcToString = funcProto.toString;
  11985. /**
  11986. * Converts `func` to its source code.
  11987. *
  11988. * @private
  11989. * @param {Function} func The function to convert.
  11990. * @returns {string} Returns the source code.
  11991. */
  11992. function toSource(func) {
  11993. if (func != null) {
  11994. try {
  11995. return funcToString.call(func);
  11996. } catch (e) {}
  11997. try {
  11998. return (func + '');
  11999. } catch (e) {}
  12000. }
  12001. return '';
  12002. }
  12003. module.exports = toSource;
  12004. },{}],149:[function(require,module,exports){
  12005. /**
  12006. * Performs a
  12007. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  12008. * comparison between two values to determine if they are equivalent.
  12009. *
  12010. * @static
  12011. * @memberOf _
  12012. * @since 4.0.0
  12013. * @category Lang
  12014. * @param {*} value The value to compare.
  12015. * @param {*} other The other value to compare.
  12016. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  12017. * @example
  12018. *
  12019. * var object = { 'a': 1 };
  12020. * var other = { 'a': 1 };
  12021. *
  12022. * _.eq(object, object);
  12023. * // => true
  12024. *
  12025. * _.eq(object, other);
  12026. * // => false
  12027. *
  12028. * _.eq('a', 'a');
  12029. * // => true
  12030. *
  12031. * _.eq('a', Object('a'));
  12032. * // => false
  12033. *
  12034. * _.eq(NaN, NaN);
  12035. * // => true
  12036. */
  12037. function eq(value, other) {
  12038. return value === other || (value !== value && other !== other);
  12039. }
  12040. module.exports = eq;
  12041. },{}],150:[function(require,module,exports){
  12042. var arrayEach = require('./_arrayEach'),
  12043. baseEach = require('./_baseEach'),
  12044. castFunction = require('./_castFunction'),
  12045. isArray = require('./isArray');
  12046. /**
  12047. * Iterates over elements of `collection` and invokes `iteratee` for each element.
  12048. * The iteratee is invoked with three arguments: (value, index|key, collection).
  12049. * Iteratee functions may exit iteration early by explicitly returning `false`.
  12050. *
  12051. * **Note:** As with other "Collections" methods, objects with a "length"
  12052. * property are iterated like arrays. To avoid this behavior use `_.forIn`
  12053. * or `_.forOwn` for object iteration.
  12054. *
  12055. * @static
  12056. * @memberOf _
  12057. * @since 0.1.0
  12058. * @alias each
  12059. * @category Collection
  12060. * @param {Array|Object} collection The collection to iterate over.
  12061. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  12062. * @returns {Array|Object} Returns `collection`.
  12063. * @see _.forEachRight
  12064. * @example
  12065. *
  12066. * _.forEach([1, 2], function(value) {
  12067. * console.log(value);
  12068. * });
  12069. * // => Logs `1` then `2`.
  12070. *
  12071. * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  12072. * console.log(key);
  12073. * });
  12074. * // => Logs 'a' then 'b' (iteration order is not guaranteed).
  12075. */
  12076. function forEach(collection, iteratee) {
  12077. var func = isArray(collection) ? arrayEach : baseEach;
  12078. return func(collection, castFunction(iteratee));
  12079. }
  12080. module.exports = forEach;
  12081. },{"./_arrayEach":59,"./_baseEach":66,"./_castFunction":90,"./isArray":155}],151:[function(require,module,exports){
  12082. var baseGet = require('./_baseGet');
  12083. /**
  12084. * Gets the value at `path` of `object`. If the resolved value is
  12085. * `undefined`, the `defaultValue` is returned in its place.
  12086. *
  12087. * @static
  12088. * @memberOf _
  12089. * @since 3.7.0
  12090. * @category Object
  12091. * @param {Object} object The object to query.
  12092. * @param {Array|string} path The path of the property to get.
  12093. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  12094. * @returns {*} Returns the resolved value.
  12095. * @example
  12096. *
  12097. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  12098. *
  12099. * _.get(object, 'a[0].b.c');
  12100. * // => 3
  12101. *
  12102. * _.get(object, ['a', '0', 'b', 'c']);
  12103. * // => 3
  12104. *
  12105. * _.get(object, 'a.b.c', 'default');
  12106. * // => 'default'
  12107. */
  12108. function get(object, path, defaultValue) {
  12109. var result = object == null ? undefined : baseGet(object, path);
  12110. return result === undefined ? defaultValue : result;
  12111. }
  12112. module.exports = get;
  12113. },{"./_baseGet":69}],152:[function(require,module,exports){
  12114. var baseHasIn = require('./_baseHasIn'),
  12115. hasPath = require('./_hasPath');
  12116. /**
  12117. * Checks if `path` is a direct or inherited property of `object`.
  12118. *
  12119. * @static
  12120. * @memberOf _
  12121. * @since 4.0.0
  12122. * @category Object
  12123. * @param {Object} object The object to query.
  12124. * @param {Array|string} path The path to check.
  12125. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  12126. * @example
  12127. *
  12128. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  12129. *
  12130. * _.hasIn(object, 'a');
  12131. * // => true
  12132. *
  12133. * _.hasIn(object, 'a.b');
  12134. * // => true
  12135. *
  12136. * _.hasIn(object, ['a', 'b']);
  12137. * // => true
  12138. *
  12139. * _.hasIn(object, 'b');
  12140. * // => false
  12141. */
  12142. function hasIn(object, path) {
  12143. return object != null && hasPath(object, path, baseHasIn);
  12144. }
  12145. module.exports = hasIn;
  12146. },{"./_baseHasIn":72,"./_hasPath":107}],153:[function(require,module,exports){
  12147. /**
  12148. * This method returns the first argument it receives.
  12149. *
  12150. * @static
  12151. * @since 0.1.0
  12152. * @memberOf _
  12153. * @category Util
  12154. * @param {*} value Any value.
  12155. * @returns {*} Returns `value`.
  12156. * @example
  12157. *
  12158. * var object = { 'a': 1 };
  12159. *
  12160. * console.log(_.identity(object) === object);
  12161. * // => true
  12162. */
  12163. function identity(value) {
  12164. return value;
  12165. }
  12166. module.exports = identity;
  12167. },{}],154:[function(require,module,exports){
  12168. var baseIsArguments = require('./_baseIsArguments'),
  12169. isObjectLike = require('./isObjectLike');
  12170. /** Used for built-in method references. */
  12171. var objectProto = Object.prototype;
  12172. /** Used to check objects for own properties. */
  12173. var hasOwnProperty = objectProto.hasOwnProperty;
  12174. /** Built-in value references. */
  12175. var propertyIsEnumerable = objectProto.propertyIsEnumerable;
  12176. /**
  12177. * Checks if `value` is likely an `arguments` object.
  12178. *
  12179. * @static
  12180. * @memberOf _
  12181. * @since 0.1.0
  12182. * @category Lang
  12183. * @param {*} value The value to check.
  12184. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  12185. * else `false`.
  12186. * @example
  12187. *
  12188. * _.isArguments(function() { return arguments; }());
  12189. * // => true
  12190. *
  12191. * _.isArguments([1, 2, 3]);
  12192. * // => false
  12193. */
  12194. var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  12195. return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
  12196. !propertyIsEnumerable.call(value, 'callee');
  12197. };
  12198. module.exports = isArguments;
  12199. },{"./_baseIsArguments":73,"./isObjectLike":161}],155:[function(require,module,exports){
  12200. /**
  12201. * Checks if `value` is classified as an `Array` object.
  12202. *
  12203. * @static
  12204. * @memberOf _
  12205. * @since 0.1.0
  12206. * @category Lang
  12207. * @param {*} value The value to check.
  12208. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  12209. * @example
  12210. *
  12211. * _.isArray([1, 2, 3]);
  12212. * // => true
  12213. *
  12214. * _.isArray(document.body.children);
  12215. * // => false
  12216. *
  12217. * _.isArray('abc');
  12218. * // => false
  12219. *
  12220. * _.isArray(_.noop);
  12221. * // => false
  12222. */
  12223. var isArray = Array.isArray;
  12224. module.exports = isArray;
  12225. },{}],156:[function(require,module,exports){
  12226. var isFunction = require('./isFunction'),
  12227. isLength = require('./isLength');
  12228. /**
  12229. * Checks if `value` is array-like. A value is considered array-like if it's
  12230. * not a function and has a `value.length` that's an integer greater than or
  12231. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  12232. *
  12233. * @static
  12234. * @memberOf _
  12235. * @since 4.0.0
  12236. * @category Lang
  12237. * @param {*} value The value to check.
  12238. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  12239. * @example
  12240. *
  12241. * _.isArrayLike([1, 2, 3]);
  12242. * // => true
  12243. *
  12244. * _.isArrayLike(document.body.children);
  12245. * // => true
  12246. *
  12247. * _.isArrayLike('abc');
  12248. * // => true
  12249. *
  12250. * _.isArrayLike(_.noop);
  12251. * // => false
  12252. */
  12253. function isArrayLike(value) {
  12254. return value != null && isLength(value.length) && !isFunction(value);
  12255. }
  12256. module.exports = isArrayLike;
  12257. },{"./isFunction":158,"./isLength":159}],157:[function(require,module,exports){
  12258. var root = require('./_root'),
  12259. stubFalse = require('./stubFalse');
  12260. /** Detect free variable `exports`. */
  12261. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  12262. /** Detect free variable `module`. */
  12263. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  12264. /** Detect the popular CommonJS extension `module.exports`. */
  12265. var moduleExports = freeModule && freeModule.exports === freeExports;
  12266. /** Built-in value references. */
  12267. var Buffer = moduleExports ? root.Buffer : undefined;
  12268. /* Built-in method references for those with the same name as other `lodash` methods. */
  12269. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  12270. /**
  12271. * Checks if `value` is a buffer.
  12272. *
  12273. * @static
  12274. * @memberOf _
  12275. * @since 4.3.0
  12276. * @category Lang
  12277. * @param {*} value The value to check.
  12278. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  12279. * @example
  12280. *
  12281. * _.isBuffer(new Buffer(2));
  12282. * // => true
  12283. *
  12284. * _.isBuffer(new Uint8Array(2));
  12285. * // => false
  12286. */
  12287. var isBuffer = nativeIsBuffer || stubFalse;
  12288. module.exports = isBuffer;
  12289. },{"./_root":137,"./stubFalse":169}],158:[function(require,module,exports){
  12290. var baseGetTag = require('./_baseGetTag'),
  12291. isObject = require('./isObject');
  12292. /** `Object#toString` result references. */
  12293. var asyncTag = '[object AsyncFunction]',
  12294. funcTag = '[object Function]',
  12295. genTag = '[object GeneratorFunction]',
  12296. proxyTag = '[object Proxy]';
  12297. /**
  12298. * Checks if `value` is classified as a `Function` object.
  12299. *
  12300. * @static
  12301. * @memberOf _
  12302. * @since 0.1.0
  12303. * @category Lang
  12304. * @param {*} value The value to check.
  12305. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  12306. * @example
  12307. *
  12308. * _.isFunction(_);
  12309. * // => true
  12310. *
  12311. * _.isFunction(/abc/);
  12312. * // => false
  12313. */
  12314. function isFunction(value) {
  12315. if (!isObject(value)) {
  12316. return false;
  12317. }
  12318. // The use of `Object#toString` avoids issues with the `typeof` operator
  12319. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  12320. var tag = baseGetTag(value);
  12321. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  12322. }
  12323. module.exports = isFunction;
  12324. },{"./_baseGetTag":71,"./isObject":160}],159:[function(require,module,exports){
  12325. /** Used as references for various `Number` constants. */
  12326. var MAX_SAFE_INTEGER = 9007199254740991;
  12327. /**
  12328. * Checks if `value` is a valid array-like length.
  12329. *
  12330. * **Note:** This method is loosely based on
  12331. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  12332. *
  12333. * @static
  12334. * @memberOf _
  12335. * @since 4.0.0
  12336. * @category Lang
  12337. * @param {*} value The value to check.
  12338. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  12339. * @example
  12340. *
  12341. * _.isLength(3);
  12342. * // => true
  12343. *
  12344. * _.isLength(Number.MIN_VALUE);
  12345. * // => false
  12346. *
  12347. * _.isLength(Infinity);
  12348. * // => false
  12349. *
  12350. * _.isLength('3');
  12351. * // => false
  12352. */
  12353. function isLength(value) {
  12354. return typeof value == 'number' &&
  12355. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  12356. }
  12357. module.exports = isLength;
  12358. },{}],160:[function(require,module,exports){
  12359. /**
  12360. * Checks if `value` is the
  12361. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  12362. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  12363. *
  12364. * @static
  12365. * @memberOf _
  12366. * @since 0.1.0
  12367. * @category Lang
  12368. * @param {*} value The value to check.
  12369. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  12370. * @example
  12371. *
  12372. * _.isObject({});
  12373. * // => true
  12374. *
  12375. * _.isObject([1, 2, 3]);
  12376. * // => true
  12377. *
  12378. * _.isObject(_.noop);
  12379. * // => true
  12380. *
  12381. * _.isObject(null);
  12382. * // => false
  12383. */
  12384. function isObject(value) {
  12385. var type = typeof value;
  12386. return value != null && (type == 'object' || type == 'function');
  12387. }
  12388. module.exports = isObject;
  12389. },{}],161:[function(require,module,exports){
  12390. /**
  12391. * Checks if `value` is object-like. A value is object-like if it's not `null`
  12392. * and has a `typeof` result of "object".
  12393. *
  12394. * @static
  12395. * @memberOf _
  12396. * @since 4.0.0
  12397. * @category Lang
  12398. * @param {*} value The value to check.
  12399. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  12400. * @example
  12401. *
  12402. * _.isObjectLike({});
  12403. * // => true
  12404. *
  12405. * _.isObjectLike([1, 2, 3]);
  12406. * // => true
  12407. *
  12408. * _.isObjectLike(_.noop);
  12409. * // => false
  12410. *
  12411. * _.isObjectLike(null);
  12412. * // => false
  12413. */
  12414. function isObjectLike(value) {
  12415. return value != null && typeof value == 'object';
  12416. }
  12417. module.exports = isObjectLike;
  12418. },{}],162:[function(require,module,exports){
  12419. var baseGetTag = require('./_baseGetTag'),
  12420. isObjectLike = require('./isObjectLike');
  12421. /** `Object#toString` result references. */
  12422. var symbolTag = '[object Symbol]';
  12423. /**
  12424. * Checks if `value` is classified as a `Symbol` primitive or object.
  12425. *
  12426. * @static
  12427. * @memberOf _
  12428. * @since 4.0.0
  12429. * @category Lang
  12430. * @param {*} value The value to check.
  12431. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  12432. * @example
  12433. *
  12434. * _.isSymbol(Symbol.iterator);
  12435. * // => true
  12436. *
  12437. * _.isSymbol('abc');
  12438. * // => false
  12439. */
  12440. function isSymbol(value) {
  12441. return typeof value == 'symbol' ||
  12442. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  12443. }
  12444. module.exports = isSymbol;
  12445. },{"./_baseGetTag":71,"./isObjectLike":161}],163:[function(require,module,exports){
  12446. var baseIsTypedArray = require('./_baseIsTypedArray'),
  12447. baseUnary = require('./_baseUnary'),
  12448. nodeUtil = require('./_nodeUtil');
  12449. /* Node.js helper references. */
  12450. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  12451. /**
  12452. * Checks if `value` is classified as a typed array.
  12453. *
  12454. * @static
  12455. * @memberOf _
  12456. * @since 3.0.0
  12457. * @category Lang
  12458. * @param {*} value The value to check.
  12459. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  12460. * @example
  12461. *
  12462. * _.isTypedArray(new Uint8Array);
  12463. * // => true
  12464. *
  12465. * _.isTypedArray([]);
  12466. * // => false
  12467. */
  12468. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  12469. module.exports = isTypedArray;
  12470. },{"./_baseIsTypedArray":78,"./_baseUnary":88,"./_nodeUtil":134}],164:[function(require,module,exports){
  12471. var arrayLikeKeys = require('./_arrayLikeKeys'),
  12472. baseKeys = require('./_baseKeys'),
  12473. isArrayLike = require('./isArrayLike');
  12474. /**
  12475. * Creates an array of the own enumerable property names of `object`.
  12476. *
  12477. * **Note:** Non-object values are coerced to objects. See the
  12478. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  12479. * for more details.
  12480. *
  12481. * @static
  12482. * @since 0.1.0
  12483. * @memberOf _
  12484. * @category Object
  12485. * @param {Object} object The object to query.
  12486. * @returns {Array} Returns the array of property names.
  12487. * @example
  12488. *
  12489. * function Foo() {
  12490. * this.a = 1;
  12491. * this.b = 2;
  12492. * }
  12493. *
  12494. * Foo.prototype.c = 3;
  12495. *
  12496. * _.keys(new Foo);
  12497. * // => ['a', 'b'] (iteration order is not guaranteed)
  12498. *
  12499. * _.keys('hi');
  12500. * // => ['0', '1']
  12501. */
  12502. function keys(object) {
  12503. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  12504. }
  12505. module.exports = keys;
  12506. },{"./_arrayLikeKeys":61,"./_baseKeys":80,"./isArrayLike":156}],165:[function(require,module,exports){
  12507. var arrayMap = require('./_arrayMap'),
  12508. baseIteratee = require('./_baseIteratee'),
  12509. baseMap = require('./_baseMap'),
  12510. isArray = require('./isArray');
  12511. /**
  12512. * Creates an array of values by running each element in `collection` thru
  12513. * `iteratee`. The iteratee is invoked with three arguments:
  12514. * (value, index|key, collection).
  12515. *
  12516. * Many lodash methods are guarded to work as iteratees for methods like
  12517. * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
  12518. *
  12519. * The guarded methods are:
  12520. * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
  12521. * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
  12522. * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
  12523. * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
  12524. *
  12525. * @static
  12526. * @memberOf _
  12527. * @since 0.1.0
  12528. * @category Collection
  12529. * @param {Array|Object} collection The collection to iterate over.
  12530. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  12531. * @returns {Array} Returns the new mapped array.
  12532. * @example
  12533. *
  12534. * function square(n) {
  12535. * return n * n;
  12536. * }
  12537. *
  12538. * _.map([4, 8], square);
  12539. * // => [16, 64]
  12540. *
  12541. * _.map({ 'a': 4, 'b': 8 }, square);
  12542. * // => [16, 64] (iteration order is not guaranteed)
  12543. *
  12544. * var users = [
  12545. * { 'user': 'barney' },
  12546. * { 'user': 'fred' }
  12547. * ];
  12548. *
  12549. * // The `_.property` iteratee shorthand.
  12550. * _.map(users, 'user');
  12551. * // => ['barney', 'fred']
  12552. */
  12553. function map(collection, iteratee) {
  12554. var func = isArray(collection) ? arrayMap : baseMap;
  12555. return func(collection, baseIteratee(iteratee, 3));
  12556. }
  12557. module.exports = map;
  12558. },{"./_arrayMap":62,"./_baseIteratee":79,"./_baseMap":81,"./isArray":155}],166:[function(require,module,exports){
  12559. var MapCache = require('./_MapCache');
  12560. /** Error message constants. */
  12561. var FUNC_ERROR_TEXT = 'Expected a function';
  12562. /**
  12563. * Creates a function that memoizes the result of `func`. If `resolver` is
  12564. * provided, it determines the cache key for storing the result based on the
  12565. * arguments provided to the memoized function. By default, the first argument
  12566. * provided to the memoized function is used as the map cache key. The `func`
  12567. * is invoked with the `this` binding of the memoized function.
  12568. *
  12569. * **Note:** The cache is exposed as the `cache` property on the memoized
  12570. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  12571. * constructor with one whose instances implement the
  12572. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  12573. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  12574. *
  12575. * @static
  12576. * @memberOf _
  12577. * @since 0.1.0
  12578. * @category Function
  12579. * @param {Function} func The function to have its output memoized.
  12580. * @param {Function} [resolver] The function to resolve the cache key.
  12581. * @returns {Function} Returns the new memoized function.
  12582. * @example
  12583. *
  12584. * var object = { 'a': 1, 'b': 2 };
  12585. * var other = { 'c': 3, 'd': 4 };
  12586. *
  12587. * var values = _.memoize(_.values);
  12588. * values(object);
  12589. * // => [1, 2]
  12590. *
  12591. * values(other);
  12592. * // => [3, 4]
  12593. *
  12594. * object.a = 2;
  12595. * values(object);
  12596. * // => [1, 2]
  12597. *
  12598. * // Modify the result cache.
  12599. * values.cache.set(object, ['a', 'b']);
  12600. * values(object);
  12601. * // => ['a', 'b']
  12602. *
  12603. * // Replace `_.memoize.Cache`.
  12604. * _.memoize.Cache = WeakMap;
  12605. */
  12606. function memoize(func, resolver) {
  12607. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  12608. throw new TypeError(FUNC_ERROR_TEXT);
  12609. }
  12610. var memoized = function() {
  12611. var args = arguments,
  12612. key = resolver ? resolver.apply(this, args) : args[0],
  12613. cache = memoized.cache;
  12614. if (cache.has(key)) {
  12615. return cache.get(key);
  12616. }
  12617. var result = func.apply(this, args);
  12618. memoized.cache = cache.set(key, result) || cache;
  12619. return result;
  12620. };
  12621. memoized.cache = new (memoize.Cache || MapCache);
  12622. return memoized;
  12623. }
  12624. // Expose `MapCache`.
  12625. memoize.Cache = MapCache;
  12626. module.exports = memoize;
  12627. },{"./_MapCache":51}],167:[function(require,module,exports){
  12628. var baseProperty = require('./_baseProperty'),
  12629. basePropertyDeep = require('./_basePropertyDeep'),
  12630. isKey = require('./_isKey'),
  12631. toKey = require('./_toKey');
  12632. /**
  12633. * Creates a function that returns the value at `path` of a given object.
  12634. *
  12635. * @static
  12636. * @memberOf _
  12637. * @since 2.4.0
  12638. * @category Util
  12639. * @param {Array|string} path The path of the property to get.
  12640. * @returns {Function} Returns the new accessor function.
  12641. * @example
  12642. *
  12643. * var objects = [
  12644. * { 'a': { 'b': 2 } },
  12645. * { 'a': { 'b': 1 } }
  12646. * ];
  12647. *
  12648. * _.map(objects, _.property('a.b'));
  12649. * // => [2, 1]
  12650. *
  12651. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  12652. * // => [1, 2]
  12653. */
  12654. function property(path) {
  12655. return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
  12656. }
  12657. module.exports = property;
  12658. },{"./_baseProperty":84,"./_basePropertyDeep":85,"./_isKey":114,"./_toKey":147}],168:[function(require,module,exports){
  12659. /**
  12660. * This method returns a new empty array.
  12661. *
  12662. * @static
  12663. * @memberOf _
  12664. * @since 4.13.0
  12665. * @category Util
  12666. * @returns {Array} Returns the new empty array.
  12667. * @example
  12668. *
  12669. * var arrays = _.times(2, _.stubArray);
  12670. *
  12671. * console.log(arrays);
  12672. * // => [[], []]
  12673. *
  12674. * console.log(arrays[0] === arrays[1]);
  12675. * // => false
  12676. */
  12677. function stubArray() {
  12678. return [];
  12679. }
  12680. module.exports = stubArray;
  12681. },{}],169:[function(require,module,exports){
  12682. /**
  12683. * This method returns `false`.
  12684. *
  12685. * @static
  12686. * @memberOf _
  12687. * @since 4.13.0
  12688. * @category Util
  12689. * @returns {boolean} Returns `false`.
  12690. * @example
  12691. *
  12692. * _.times(2, _.stubFalse);
  12693. * // => [false, false]
  12694. */
  12695. function stubFalse() {
  12696. return false;
  12697. }
  12698. module.exports = stubFalse;
  12699. },{}],170:[function(require,module,exports){
  12700. var baseToString = require('./_baseToString');
  12701. /**
  12702. * Converts `value` to a string. An empty string is returned for `null`
  12703. * and `undefined` values. The sign of `-0` is preserved.
  12704. *
  12705. * @static
  12706. * @memberOf _
  12707. * @since 4.0.0
  12708. * @category Lang
  12709. * @param {*} value The value to convert.
  12710. * @returns {string} Returns the converted string.
  12711. * @example
  12712. *
  12713. * _.toString(null);
  12714. * // => ''
  12715. *
  12716. * _.toString(-0);
  12717. * // => '-0'
  12718. *
  12719. * _.toString([1, 2, 3]);
  12720. * // => '1,2,3'
  12721. */
  12722. function toString(value) {
  12723. return value == null ? '' : baseToString(value);
  12724. }
  12725. module.exports = toString;
  12726. },{"./_baseToString":87}],171:[function(require,module,exports){
  12727. /*
  12728. Loki IndexedDb Adapter (need to include this script to use it)
  12729. Console Usage can be used for management/diagnostic, here are a few examples :
  12730. adapter.getDatabaseList(); // with no callback passed, this method will log results to console
  12731. adapter.saveDatabase('UserDatabase', JSON.stringify(myDb));
  12732. adapter.loadDatabase('UserDatabase'); // will log the serialized db to console
  12733. adapter.deleteDatabase('UserDatabase');
  12734. */
  12735. (function (root, factory) {
  12736. if (typeof define === 'function' && define.amd) {
  12737. // AMD
  12738. define([], factory);
  12739. } else if (typeof exports === 'object') {
  12740. // Node, CommonJS-like
  12741. module.exports = factory();
  12742. } else {
  12743. // Browser globals (root is window)
  12744. root.LokiIndexedAdapter = factory();
  12745. }
  12746. }(this, function () {
  12747. return (function() {
  12748. /**
  12749. * Loki persistence adapter class for indexedDb.
  12750. * This class fulfills abstract adapter interface which can be applied to other storage methods.
  12751. * Utilizes the included LokiCatalog app/key/value database for actual database persistence.
  12752. * Indexeddb is highly async, but this adapter has been made 'console-friendly' as well.
  12753. * Anywhere a callback is omitted, it should return results (if applicable) to console.
  12754. * IndexedDb storage is provided per-domain, so we implement app/key/value database to
  12755. * allow separate contexts for separate apps within a domain.
  12756. *
  12757. * @example
  12758. * var idbAdapter = new LokiIndexedAdapter('finance');
  12759. *
  12760. * @constructor LokiIndexedAdapter
  12761. *
  12762. * @param {string} appname - (Optional) Application name context can be used to distinguish subdomains, 'loki' by default
  12763. * @param {object=} options Configuration options for the adapter
  12764. * @param {boolean} options.closeAfterSave Whether the indexedDB database should be closed after saving.
  12765. */
  12766. function LokiIndexedAdapter(appname, options)
  12767. {
  12768. this.app = 'loki';
  12769. this.options = options || {};
  12770. if (typeof (appname) !== 'undefined')
  12771. {
  12772. this.app = appname;
  12773. }
  12774. // keep reference to catalog class for base AKV operations
  12775. this.catalog = null;
  12776. if (!this.checkAvailability()) {
  12777. throw new Error('indexedDB does not seem to be supported for your environment');
  12778. }
  12779. }
  12780. /**
  12781. * Used for closing the indexeddb database.
  12782. */
  12783. LokiIndexedAdapter.prototype.closeDatabase = function ()
  12784. {
  12785. if (this.catalog && this.catalog.db) {
  12786. this.catalog.db.close();
  12787. this.catalog.db = null;
  12788. }
  12789. };
  12790. /**
  12791. * Used to check if adapter is available
  12792. *
  12793. * @returns {boolean} true if indexeddb is available, false if not.
  12794. * @memberof LokiIndexedAdapter
  12795. */
  12796. LokiIndexedAdapter.prototype.checkAvailability = function()
  12797. {
  12798. if (typeof indexedDB !== 'undefined' && indexedDB) return true;
  12799. return false;
  12800. };
  12801. /**
  12802. * Retrieves a serialized db string from the catalog.
  12803. *
  12804. * @example
  12805. * // LOAD
  12806. * var idbAdapter = new LokiIndexedAdapter('finance');
  12807. * var db = new loki('test', { adapter: idbAdapter });
  12808. * db.loadDatabase(function(result) {
  12809. * console.log('done');
  12810. * });
  12811. *
  12812. * @param {string} dbname - the name of the database to retrieve.
  12813. * @param {function} callback - callback should accept string param containing serialized db string.
  12814. * @memberof LokiIndexedAdapter
  12815. */
  12816. LokiIndexedAdapter.prototype.loadDatabase = function(dbname, callback)
  12817. {
  12818. var appName = this.app;
  12819. var adapter = this;
  12820. // lazy open/create db reference so dont -need- callback in constructor
  12821. if (this.catalog === null || this.catalog.db === null) {
  12822. this.catalog = new LokiCatalog(function(cat) {
  12823. adapter.catalog = cat;
  12824. adapter.loadDatabase(dbname, callback);
  12825. });
  12826. return;
  12827. }
  12828. // lookup up db string in AKV db
  12829. this.catalog.getAppKey(appName, dbname, function(result) {
  12830. if (typeof (callback) === 'function') {
  12831. if (result.id === 0) {
  12832. callback(null);
  12833. return;
  12834. }
  12835. callback(result.val);
  12836. }
  12837. else {
  12838. // support console use of api
  12839. console.log(result.val);
  12840. }
  12841. });
  12842. };
  12843. // alias
  12844. LokiIndexedAdapter.prototype.loadKey = LokiIndexedAdapter.prototype.loadDatabase;
  12845. /**
  12846. * Saves a serialized db to the catalog.
  12847. *
  12848. * @example
  12849. * // SAVE : will save App/Key/Val as 'finance'/'test'/{serializedDb}
  12850. * var idbAdapter = new LokiIndexedAdapter('finance');
  12851. * var db = new loki('test', { adapter: idbAdapter });
  12852. * var coll = db.addCollection('testColl');
  12853. * coll.insert({test: 'val'});
  12854. * db.saveDatabase(); // could pass callback if needed for async complete
  12855. *
  12856. * @param {string} dbname - the name to give the serialized database within the catalog.
  12857. * @param {string} dbstring - the serialized db string to save.
  12858. * @param {function} callback - (Optional) callback passed obj.success with true or false
  12859. * @memberof LokiIndexedAdapter
  12860. */
  12861. LokiIndexedAdapter.prototype.saveDatabase = function(dbname, dbstring, callback)
  12862. {
  12863. var appName = this.app;
  12864. var adapter = this;
  12865. function saveCallback(result) {
  12866. if (result && result.success === true) {
  12867. callback(null);
  12868. }
  12869. else {
  12870. callback(new Error("Error saving database"));
  12871. }
  12872. if (adapter.options.closeAfterSave) {
  12873. adapter.closeDatabase();
  12874. }
  12875. }
  12876. // lazy open/create db reference so dont -need- callback in constructor
  12877. if (this.catalog === null || this.catalog.db === null) {
  12878. this.catalog = new LokiCatalog(function(cat) {
  12879. adapter.saveDatabase(dbname, dbstring, saveCallback);
  12880. });
  12881. return;
  12882. }
  12883. // set (add/update) entry to AKV database
  12884. this.catalog.setAppKey(appName, dbname, dbstring, saveCallback);
  12885. };
  12886. // alias
  12887. LokiIndexedAdapter.prototype.saveKey = LokiIndexedAdapter.prototype.saveDatabase;
  12888. /**
  12889. * Deletes a serialized db from the catalog.
  12890. *
  12891. * @example
  12892. * // DELETE DATABASE
  12893. * // delete 'finance'/'test' value from catalog
  12894. * idbAdapter.deleteDatabase('test', function {
  12895. * // database deleted
  12896. * });
  12897. *
  12898. * @param {string} dbname - the name of the database to delete from the catalog.
  12899. * @param {function=} callback - (Optional) executed on database delete
  12900. * @memberof LokiIndexedAdapter
  12901. */
  12902. LokiIndexedAdapter.prototype.deleteDatabase = function(dbname, callback)
  12903. {
  12904. var appName = this.app;
  12905. var adapter = this;
  12906. // lazy open/create db reference and pass callback ahead
  12907. if (this.catalog === null || this.catalog.db === null) {
  12908. this.catalog = new LokiCatalog(function(cat) {
  12909. adapter.catalog = cat;
  12910. adapter.deleteDatabase(dbname, callback);
  12911. });
  12912. return;
  12913. }
  12914. // catalog was already initialized, so just lookup object and delete by id
  12915. this.catalog.getAppKey(appName, dbname, function(result) {
  12916. var id = result.id;
  12917. if (id !== 0) {
  12918. adapter.catalog.deleteAppKey(id, callback);
  12919. } else if (typeof (callback) === 'function') {
  12920. callback({ success: true });
  12921. }
  12922. });
  12923. };
  12924. // alias
  12925. LokiIndexedAdapter.prototype.deleteKey = LokiIndexedAdapter.prototype.deleteDatabase;
  12926. /**
  12927. * Removes all database partitions and pages with the base filename passed in.
  12928. * This utility method does not (yet) guarantee async deletions will be completed before returning
  12929. *
  12930. * @param {string} dbname - the base filename which container, partitions, or pages are derived
  12931. * @memberof LokiIndexedAdapter
  12932. */
  12933. LokiIndexedAdapter.prototype.deleteDatabasePartitions = function(dbname) {
  12934. var self=this;
  12935. this.getDatabaseList(function(result) {
  12936. result.forEach(function(str) {
  12937. if (str.startsWith(dbname)) {
  12938. self.deleteDatabase(str);
  12939. }
  12940. });
  12941. });
  12942. };
  12943. /**
  12944. * Retrieves object array of catalog entries for current app.
  12945. *
  12946. * @example
  12947. * idbAdapter.getDatabaseList(function(result) {
  12948. * // result is array of string names for that appcontext ('finance')
  12949. * result.forEach(function(str) {
  12950. * console.log(str);
  12951. * });
  12952. * });
  12953. *
  12954. * @param {function} callback - should accept array of database names in the catalog for current app.
  12955. * @memberof LokiIndexedAdapter
  12956. */
  12957. LokiIndexedAdapter.prototype.getDatabaseList = function(callback)
  12958. {
  12959. var appName = this.app;
  12960. var adapter = this;
  12961. // lazy open/create db reference so dont -need- callback in constructor
  12962. if (this.catalog === null || this.catalog.db === null) {
  12963. this.catalog = new LokiCatalog(function(cat) {
  12964. adapter.catalog = cat;
  12965. adapter.getDatabaseList(callback);
  12966. });
  12967. return;
  12968. }
  12969. // catalog already initialized
  12970. // get all keys for current appName, and transpose results so just string array
  12971. this.catalog.getAppKeys(appName, function(results) {
  12972. var names = [];
  12973. for(var idx = 0; idx < results.length; idx++) {
  12974. names.push(results[idx].key);
  12975. }
  12976. if (typeof (callback) === 'function') {
  12977. callback(names);
  12978. }
  12979. else {
  12980. names.forEach(function(obj) {
  12981. console.log(obj);
  12982. });
  12983. }
  12984. });
  12985. };
  12986. // alias
  12987. LokiIndexedAdapter.prototype.getKeyList = LokiIndexedAdapter.prototype.getDatabaseList;
  12988. /**
  12989. * Allows retrieval of list of all keys in catalog along with size
  12990. *
  12991. * @param {function} callback - (Optional) callback to accept result array.
  12992. * @memberof LokiIndexedAdapter
  12993. */
  12994. LokiIndexedAdapter.prototype.getCatalogSummary = function(callback)
  12995. {
  12996. var appName = this.app;
  12997. var adapter = this;
  12998. // lazy open/create db reference
  12999. if (this.catalog === null || this.catalog.db === null) {
  13000. this.catalog = new LokiCatalog(function(cat) {
  13001. adapter.catalog = cat;
  13002. adapter.getCatalogSummary(callback);
  13003. });
  13004. return;
  13005. }
  13006. // catalog already initialized
  13007. // get all keys for current appName, and transpose results so just string array
  13008. this.catalog.getAllKeys(function(results) {
  13009. var entries = [];
  13010. var obj,
  13011. size,
  13012. oapp,
  13013. okey,
  13014. oval;
  13015. for(var idx = 0; idx < results.length; idx++) {
  13016. obj = results[idx];
  13017. oapp = obj.app || '';
  13018. okey = obj.key || '';
  13019. oval = obj.val || '';
  13020. // app and key are composited into an appkey column so we will mult by 2
  13021. size = oapp.length * 2 + okey.length * 2 + oval.length + 1;
  13022. entries.push({ "app": obj.app, "key": obj.key, "size": size });
  13023. }
  13024. if (typeof (callback) === 'function') {
  13025. callback(entries);
  13026. }
  13027. else {
  13028. entries.forEach(function(obj) {
  13029. console.log(obj);
  13030. });
  13031. }
  13032. });
  13033. };
  13034. /**
  13035. * LokiCatalog - underlying App/Key/Value catalog persistence
  13036. * This non-interface class implements the actual persistence.
  13037. * Used by the IndexedAdapter class.
  13038. */
  13039. function LokiCatalog(callback)
  13040. {
  13041. this.db = null;
  13042. this.initializeLokiCatalog(callback);
  13043. }
  13044. LokiCatalog.prototype.initializeLokiCatalog = function(callback) {
  13045. var openRequest = indexedDB.open('LokiCatalog', 1);
  13046. var cat = this;
  13047. // If database doesn't exist yet or its version is lower than our version specified above (2nd param in line above)
  13048. openRequest.onupgradeneeded = function(e) {
  13049. var thisDB = e.target.result;
  13050. if (thisDB.objectStoreNames.contains('LokiAKV')) {
  13051. thisDB.deleteObjectStore('LokiAKV');
  13052. }
  13053. if(!thisDB.objectStoreNames.contains('LokiAKV')) {
  13054. var objectStore = thisDB.createObjectStore('LokiAKV', { keyPath: 'id', autoIncrement:true });
  13055. objectStore.createIndex('app', 'app', {unique:false});
  13056. objectStore.createIndex('key', 'key', {unique:false});
  13057. // hack to simulate composite key since overhead is low (main size should be in val field)
  13058. // user (me) required to duplicate the app and key into comma delimited appkey field off object
  13059. // This will allow retrieving single record with that composite key as well as
  13060. // still supporting opening cursors on app or key alone
  13061. objectStore.createIndex('appkey', 'appkey', {unique:true});
  13062. }
  13063. };
  13064. openRequest.onsuccess = function(e) {
  13065. cat.db = e.target.result;
  13066. if (typeof (callback) === 'function') callback(cat);
  13067. };
  13068. openRequest.onerror = function(e) {
  13069. throw e;
  13070. };
  13071. };
  13072. LokiCatalog.prototype.getAppKey = function(app, key, callback) {
  13073. var transaction = this.db.transaction(['LokiAKV'], 'readonly');
  13074. var store = transaction.objectStore('LokiAKV');
  13075. var index = store.index('appkey');
  13076. var appkey = app + "," + key;
  13077. var request = index.get(appkey);
  13078. request.onsuccess = (function(usercallback) {
  13079. return function(e) {
  13080. var lres = e.target.result;
  13081. if (lres === null || typeof(lres) === 'undefined') {
  13082. lres = {
  13083. id: 0,
  13084. success: false
  13085. };
  13086. }
  13087. if (typeof(usercallback) === 'function') {
  13088. usercallback(lres);
  13089. }
  13090. else {
  13091. console.log(lres);
  13092. }
  13093. };
  13094. })(callback);
  13095. request.onerror = (function(usercallback) {
  13096. return function(e) {
  13097. if (typeof(usercallback) === 'function') {
  13098. usercallback({ id: 0, success: false });
  13099. }
  13100. else {
  13101. throw e;
  13102. }
  13103. };
  13104. })(callback);
  13105. };
  13106. LokiCatalog.prototype.getAppKeyById = function (id, callback, data) {
  13107. var transaction = this.db.transaction(['LokiAKV'], 'readonly');
  13108. var store = transaction.objectStore('LokiAKV');
  13109. var request = store.get(id);
  13110. request.onsuccess = (function(data, usercallback){
  13111. return function(e) {
  13112. if (typeof(usercallback) === 'function') {
  13113. usercallback(e.target.result, data);
  13114. }
  13115. else {
  13116. console.log(e.target.result);
  13117. }
  13118. };
  13119. })(data, callback);
  13120. };
  13121. LokiCatalog.prototype.setAppKey = function (app, key, val, callback) {
  13122. var transaction = this.db.transaction(['LokiAKV'], 'readwrite');
  13123. var store = transaction.objectStore('LokiAKV');
  13124. var index = store.index('appkey');
  13125. var appkey = app + "," + key;
  13126. var request = index.get(appkey);
  13127. // first try to retrieve an existing object by that key
  13128. // need to do this because to update an object you need to have id in object, otherwise it will append id with new autocounter and clash the unique index appkey
  13129. request.onsuccess = function(e) {
  13130. var res = e.target.result;
  13131. if (res === null || res === undefined) {
  13132. res = {
  13133. app:app,
  13134. key:key,
  13135. appkey: app + ',' + key,
  13136. val:val
  13137. };
  13138. }
  13139. else {
  13140. res.val = val;
  13141. }
  13142. var requestPut = store.put(res);
  13143. requestPut.onerror = (function(usercallback) {
  13144. return function(e) {
  13145. if (typeof(usercallback) === 'function') {
  13146. usercallback({ success: false });
  13147. }
  13148. else {
  13149. console.error('LokiCatalog.setAppKey (set) onerror');
  13150. console.error(request.error);
  13151. }
  13152. };
  13153. })(callback);
  13154. requestPut.onsuccess = (function(usercallback) {
  13155. return function(e) {
  13156. if (typeof(usercallback) === 'function') {
  13157. usercallback({ success: true });
  13158. }
  13159. };
  13160. })(callback);
  13161. };
  13162. request.onerror = (function(usercallback) {
  13163. return function(e) {
  13164. if (typeof(usercallback) === 'function') {
  13165. usercallback({ success: false });
  13166. }
  13167. else {
  13168. console.error('LokiCatalog.setAppKey (get) onerror');
  13169. console.error(request.error);
  13170. }
  13171. };
  13172. })(callback);
  13173. };
  13174. LokiCatalog.prototype.deleteAppKey = function (id, callback) {
  13175. var transaction = this.db.transaction(['LokiAKV'], 'readwrite');
  13176. var store = transaction.objectStore('LokiAKV');
  13177. var request = store.delete(id);
  13178. request.onsuccess = (function(usercallback) {
  13179. return function(evt) {
  13180. if (typeof(usercallback) === 'function') usercallback({ success: true });
  13181. };
  13182. })(callback);
  13183. request.onerror = (function(usercallback) {
  13184. return function(evt) {
  13185. if (typeof(usercallback) === 'function') {
  13186. usercallback({ success: false });
  13187. }
  13188. else {
  13189. console.error('LokiCatalog.deleteAppKey raised onerror');
  13190. console.error(request.error);
  13191. }
  13192. };
  13193. })(callback);
  13194. };
  13195. LokiCatalog.prototype.getAppKeys = function(app, callback) {
  13196. var transaction = this.db.transaction(['LokiAKV'], 'readonly');
  13197. var store = transaction.objectStore('LokiAKV');
  13198. var index = store.index('app');
  13199. // We want cursor to all values matching our (single) app param
  13200. var singleKeyRange = IDBKeyRange.only(app);
  13201. // To use one of the key ranges, pass it in as the first argument of openCursor()/openKeyCursor()
  13202. var cursor = index.openCursor(singleKeyRange);
  13203. // cursor internally, pushing results into this.data[] and return
  13204. // this.data[] when done (similar to service)
  13205. var localdata = [];
  13206. cursor.onsuccess = (function(data, callback) {
  13207. return function(e) {
  13208. var cursor = e.target.result;
  13209. if (cursor) {
  13210. var currObject = cursor.value;
  13211. data.push(currObject);
  13212. cursor.continue();
  13213. }
  13214. else {
  13215. if (typeof(callback) === 'function') {
  13216. callback(data);
  13217. }
  13218. else {
  13219. console.log(data);
  13220. }
  13221. }
  13222. };
  13223. })(localdata, callback);
  13224. cursor.onerror = (function(usercallback) {
  13225. return function(e) {
  13226. if (typeof(usercallback) === 'function') {
  13227. usercallback(null);
  13228. }
  13229. else {
  13230. console.error('LokiCatalog.getAppKeys raised onerror');
  13231. console.error(e);
  13232. }
  13233. };
  13234. })(callback);
  13235. };
  13236. // Hide 'cursoring' and return array of { id: id, key: key }
  13237. LokiCatalog.prototype.getAllKeys = function (callback) {
  13238. var transaction = this.db.transaction(['LokiAKV'], 'readonly');
  13239. var store = transaction.objectStore('LokiAKV');
  13240. var cursor = store.openCursor();
  13241. var localdata = [];
  13242. cursor.onsuccess = (function(data, callback) {
  13243. return function(e) {
  13244. var cursor = e.target.result;
  13245. if (cursor) {
  13246. var currObject = cursor.value;
  13247. data.push(currObject);
  13248. cursor.continue();
  13249. }
  13250. else {
  13251. if (typeof(callback) === 'function') {
  13252. callback(data);
  13253. }
  13254. else {
  13255. console.log(data);
  13256. }
  13257. }
  13258. };
  13259. })(localdata, callback);
  13260. cursor.onerror = (function(usercallback) {
  13261. return function(e) {
  13262. if (typeof(usercallback) === 'function') usercallback(null);
  13263. };
  13264. })(callback);
  13265. };
  13266. return LokiIndexedAdapter;
  13267. }());
  13268. }));
  13269. },{}],172:[function(require,module,exports){
  13270. (function (process,global){
  13271. /**
  13272. * LokiJS
  13273. * @author Joe Minichino <joe.minichino@gmail.com>
  13274. *
  13275. * A lightweight document oriented javascript database
  13276. */
  13277. (function (root, factory) {
  13278. if (typeof define === 'function' && define.amd) {
  13279. // AMD
  13280. define([], factory);
  13281. } else if (typeof exports === 'object') {
  13282. // CommonJS
  13283. module.exports = factory();
  13284. } else {
  13285. // Browser globals
  13286. root.loki = factory();
  13287. }
  13288. }(this, function () {
  13289. return (function () {
  13290. 'use strict';
  13291. var hasOwnProperty = Object.prototype.hasOwnProperty;
  13292. var Utils = {
  13293. copyProperties: function (src, dest) {
  13294. var prop;
  13295. for (prop in src) {
  13296. dest[prop] = src[prop];
  13297. }
  13298. },
  13299. // used to recursively scan hierarchical transform step object for param substitution
  13300. resolveTransformObject: function (subObj, params, depth) {
  13301. var prop,
  13302. pname;
  13303. if (typeof depth !== 'number') {
  13304. depth = 0;
  13305. }
  13306. if (++depth >= 10) return subObj;
  13307. for (prop in subObj) {
  13308. if (typeof subObj[prop] === 'string' && subObj[prop].indexOf("[%lktxp]") === 0) {
  13309. pname = subObj[prop].substring(8);
  13310. if (params.hasOwnProperty(pname)) {
  13311. subObj[prop] = params[pname];
  13312. }
  13313. } else if (typeof subObj[prop] === "object") {
  13314. subObj[prop] = Utils.resolveTransformObject(subObj[prop], params, depth);
  13315. }
  13316. }
  13317. return subObj;
  13318. },
  13319. // top level utility to resolve an entire (single) transform (array of steps) for parameter substitution
  13320. resolveTransformParams: function (transform, params) {
  13321. var idx,
  13322. clonedStep,
  13323. resolvedTransform = [];
  13324. if (typeof params === 'undefined') return transform;
  13325. // iterate all steps in the transform array
  13326. for (idx = 0; idx < transform.length; idx++) {
  13327. // clone transform so our scan/replace can operate directly on cloned transform
  13328. clonedStep = clone(transform[idx], "shallow-recurse-objects");
  13329. resolvedTransform.push(Utils.resolveTransformObject(clonedStep, params));
  13330. }
  13331. return resolvedTransform;
  13332. },
  13333. // By default (if usingDotNotation is false), looks up path in
  13334. // object via `object[path]`
  13335. //
  13336. // If `usingDotNotation` is true, then the path is assumed to
  13337. // represent a nested path. It can be in the form of an array of
  13338. // field names, or a period delimited string. The function will
  13339. // look up the value of object[path[0]], and then call
  13340. // result[path[1]] on the result, etc etc.
  13341. //
  13342. // If `usingDotNotation` is true, this function still supports
  13343. // non nested fields.
  13344. //
  13345. // `usingDotNotation` is a performance optimization. The caller
  13346. // may know that a path is *not* nested. In which case, this
  13347. // function avoids a costly string.split('.')
  13348. //
  13349. // examples:
  13350. // getIn({a: 1}, "a") => 1
  13351. // getIn({a: 1}, "a", true) => 1
  13352. // getIn({a: {b: 1}}, ["a", "b"], true) => 1
  13353. // getIn({a: {b: 1}}, "a.b", true) => 1
  13354. getIn: function (object, path, usingDotNotation) {
  13355. if (object == null) {
  13356. return undefined;
  13357. }
  13358. if (!usingDotNotation) {
  13359. return object[path];
  13360. }
  13361. if (typeof(path) === "string") {
  13362. path = path.split(".");
  13363. }
  13364. if (!Array.isArray(path)) {
  13365. throw new Error("path must be a string or array. Found " + typeof(path));
  13366. }
  13367. var index = 0,
  13368. length = path.length;
  13369. while (object != null && index < length) {
  13370. object = object[path[index++]];
  13371. }
  13372. return (index && index == length) ? object : undefined;
  13373. }
  13374. };
  13375. // wrapping in object to expose to default export for potential user override.
  13376. // warning: overriding these methods will override behavior for all loki db instances in memory.
  13377. // warning: if you use binary indices these comparators should be the same for all inserts/updates/removes.
  13378. var Comparators = {
  13379. aeq: aeqHelper,
  13380. lt: ltHelper,
  13381. gt: gtHelper
  13382. };
  13383. /** Helper function for determining 'loki' abstract equality which is a little more abstract than ==
  13384. * aeqHelper(5, '5') === true
  13385. * aeqHelper(5.0, '5') === true
  13386. * aeqHelper(new Date("1/1/2011"), new Date("1/1/2011")) === true
  13387. * aeqHelper({a:1}, {z:4}) === true (all objects sorted equally)
  13388. * aeqHelper([1, 2, 3], [1, 3]) === false
  13389. * aeqHelper([1, 2, 3], [1, 2, 3]) === true
  13390. * aeqHelper(undefined, null) === true
  13391. */
  13392. function aeqHelper(prop1, prop2) {
  13393. var cv1, cv2, t1, t2;
  13394. if (prop1 === prop2) return true;
  13395. // 'falsy' and Boolean handling
  13396. if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
  13397. // dates and NaN conditions (typed dates before serialization)
  13398. switch (prop1) {
  13399. case undefined: t1 = 1; break;
  13400. case null: t1 = 1; break;
  13401. case false: t1 = 3; break;
  13402. case true: t1 = 4; break;
  13403. case "": t1 = 5; break;
  13404. default: t1 = (prop1 === prop1)?9:0; break;
  13405. }
  13406. switch (prop2) {
  13407. case undefined: t2 = 1; break;
  13408. case null: t2 = 1; break;
  13409. case false: t2 = 3; break;
  13410. case true: t2 = 4; break;
  13411. case "": t2 = 5; break;
  13412. default: t2 = (prop2 === prop2)?9:0; break;
  13413. }
  13414. // one or both is edge case
  13415. if (t1 !== 9 || t2 !== 9) {
  13416. return (t1===t2);
  13417. }
  13418. }
  13419. // Handle 'Number-like' comparisons
  13420. cv1 = Number(prop1);
  13421. cv2 = Number(prop2);
  13422. // if one or both are 'number-like'...
  13423. if (cv1 === cv1 || cv2 === cv2) {
  13424. return (cv1 === cv2);
  13425. }
  13426. // not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare
  13427. cv1 = prop1.toString();
  13428. cv2 = prop2.toString();
  13429. return (cv1 == cv2);
  13430. }
  13431. /** Helper function for determining 'less-than' conditions for ops, sorting, and binary indices.
  13432. * In the future we might want $lt and $gt ops to use their own functionality/helper.
  13433. * Since binary indices on a property might need to index [12, NaN, new Date(), Infinity], we
  13434. * need this function (as well as gtHelper) to always ensure one value is LT, GT, or EQ to another.
  13435. */
  13436. function ltHelper(prop1, prop2, equal) {
  13437. var cv1, cv2, t1, t2;
  13438. // if one of the params is falsy or strictly true or not equal to itself
  13439. // 0, 0.0, "", NaN, null, undefined, not defined, false, true
  13440. if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
  13441. switch (prop1) {
  13442. case undefined: t1 = 1; break;
  13443. case null: t1 = 1; break;
  13444. case false: t1 = 3; break;
  13445. case true: t1 = 4; break;
  13446. case "": t1 = 5; break;
  13447. // if strict equal probably 0 so sort higher, otherwise probably NaN so sort lower than even null
  13448. default: t1 = (prop1 === prop1)?9:0; break;
  13449. }
  13450. switch (prop2) {
  13451. case undefined: t2 = 1; break;
  13452. case null: t2 = 1; break;
  13453. case false: t2 = 3; break;
  13454. case true: t2 = 4; break;
  13455. case "": t2 = 5; break;
  13456. default: t2 = (prop2 === prop2)?9:0; break;
  13457. }
  13458. // one or both is edge case
  13459. if (t1 !== 9 || t2 !== 9) {
  13460. return (t1===t2)?equal:(t1<t2);
  13461. }
  13462. }
  13463. // if both are numbers (string encoded or not), compare as numbers
  13464. cv1 = Number(prop1);
  13465. cv2 = Number(prop2);
  13466. if (cv1 === cv1 && cv2 === cv2) {
  13467. if (cv1 < cv2) return true;
  13468. if (cv1 > cv2) return false;
  13469. return equal;
  13470. }
  13471. if (cv1 === cv1 && cv2 !== cv2) {
  13472. return true;
  13473. }
  13474. if (cv2 === cv2 && cv1 !== cv1) {
  13475. return false;
  13476. }
  13477. if (prop1 < prop2) return true;
  13478. if (prop1 > prop2) return false;
  13479. if (prop1 == prop2) return equal;
  13480. // not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare
  13481. cv1 = prop1.toString();
  13482. cv2 = prop2.toString();
  13483. if (cv1 < cv2) {
  13484. return true;
  13485. }
  13486. if (cv1 == cv2) {
  13487. return equal;
  13488. }
  13489. return false;
  13490. }
  13491. function gtHelper(prop1, prop2, equal) {
  13492. var cv1, cv2, t1, t2;
  13493. // 'falsy' and Boolean handling
  13494. if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
  13495. switch (prop1) {
  13496. case undefined: t1 = 1; break;
  13497. case null: t1 = 1; break;
  13498. case false: t1 = 3; break;
  13499. case true: t1 = 4; break;
  13500. case "": t1 = 5; break;
  13501. // NaN 0
  13502. default: t1 = (prop1 === prop1)?9:0; break;
  13503. }
  13504. switch (prop2) {
  13505. case undefined: t2 = 1; break;
  13506. case null: t2 = 1; break;
  13507. case false: t2 = 3; break;
  13508. case true: t2 = 4; break;
  13509. case "": t2 = 5; break;
  13510. default: t2 = (prop2 === prop2)?9:0; break;
  13511. }
  13512. // one or both is edge case
  13513. if (t1 !== 9 || t2 !== 9) {
  13514. return (t1===t2)?equal:(t1>t2);
  13515. }
  13516. }
  13517. // if both are numbers (string encoded or not), compare as numbers
  13518. cv1 = Number(prop1);
  13519. cv2 = Number(prop2);
  13520. if (cv1 === cv1 && cv2 === cv2) {
  13521. if (cv1 > cv2) return true;
  13522. if (cv1 < cv2) return false;
  13523. return equal;
  13524. }
  13525. if (cv1 === cv1 && cv2 !== cv2) {
  13526. return false;
  13527. }
  13528. if (cv2 === cv2 && cv1 !== cv1) {
  13529. return true;
  13530. }
  13531. if (prop1 > prop2) return true;
  13532. if (prop1 < prop2) return false;
  13533. if (prop1 == prop2) return equal;
  13534. // not strict equal nor less than nor gt so must be dates or mixed types
  13535. // convert to string and use that to compare
  13536. cv1 = prop1.toString();
  13537. cv2 = prop2.toString();
  13538. if (cv1 > cv2) {
  13539. return true;
  13540. }
  13541. if (cv1 == cv2) {
  13542. return equal;
  13543. }
  13544. return false;
  13545. }
  13546. function sortHelper(prop1, prop2, desc) {
  13547. if (Comparators.aeq(prop1, prop2)) return 0;
  13548. if (Comparators.lt(prop1, prop2, false)) {
  13549. return (desc) ? (1) : (-1);
  13550. }
  13551. if (Comparators.gt(prop1, prop2, false)) {
  13552. return (desc) ? (-1) : (1);
  13553. }
  13554. // not lt, not gt so implied equality-- date compatible
  13555. return 0;
  13556. }
  13557. /**
  13558. * compoundeval() - helper function for compoundsort(), performing individual object comparisons
  13559. *
  13560. * @param {array} properties - array of property names, in order, by which to evaluate sort order
  13561. * @param {object} obj1 - first object to compare
  13562. * @param {object} obj2 - second object to compare
  13563. * @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first
  13564. */
  13565. function compoundeval(properties, obj1, obj2) {
  13566. var res = 0;
  13567. var prop, field, val1, val2, arr, path;
  13568. for (var i = 0, len = properties.length; i < len; i++) {
  13569. prop = properties[i];
  13570. field = prop[0];
  13571. if (~field.indexOf('.')) {
  13572. arr = field.split('.');
  13573. val1 = Utils.getIn(obj1, arr, true);
  13574. val2 = Utils.getIn(obj2, arr, true);
  13575. } else {
  13576. val1 = obj1[field];
  13577. val2 = obj2[field];
  13578. }
  13579. res = sortHelper(val1, val2, prop[1]);
  13580. if (res !== 0) {
  13581. return res;
  13582. }
  13583. }
  13584. return 0;
  13585. }
  13586. /**
  13587. * dotSubScan - helper function used for dot notation queries.
  13588. *
  13589. * @param {object} root - object to traverse
  13590. * @param {array} paths - array of properties to drill into
  13591. * @param {function} fun - evaluation function to test with
  13592. * @param {any} value - comparative value to also pass to (compare) fun
  13593. * @param {number} poffset - index of the item in 'paths' to start the sub-scan from
  13594. */
  13595. function dotSubScan(root, paths, fun, value, poffset) {
  13596. var pathOffset = poffset || 0;
  13597. var path = paths[pathOffset];
  13598. var valueFound = false;
  13599. var element;
  13600. if (typeof root === 'object' && path in root) {
  13601. element = root[path];
  13602. }
  13603. if (pathOffset + 1 >= paths.length) {
  13604. // if we have already expanded out the dot notation,
  13605. // then just evaluate the test function and value on the element
  13606. valueFound = fun(element, value);
  13607. } else if (Array.isArray(element)) {
  13608. for (var index = 0, len = element.length; index < len; index += 1) {
  13609. valueFound = dotSubScan(element[index], paths, fun, value, pathOffset + 1);
  13610. if (valueFound === true) {
  13611. break;
  13612. }
  13613. }
  13614. } else {
  13615. valueFound = dotSubScan(element, paths, fun, value, pathOffset + 1);
  13616. }
  13617. return valueFound;
  13618. }
  13619. function containsCheckFn(a) {
  13620. if (typeof a === 'string' || Array.isArray(a)) {
  13621. return function (b) {
  13622. return a.indexOf(b) !== -1;
  13623. };
  13624. } else if (typeof a === 'object' && a !== null) {
  13625. return function (b) {
  13626. return hasOwnProperty.call(a, b);
  13627. };
  13628. }
  13629. return null;
  13630. }
  13631. function doQueryOp(val, op) {
  13632. for (var p in op) {
  13633. if (hasOwnProperty.call(op, p)) {
  13634. return LokiOps[p](val, op[p]);
  13635. }
  13636. }
  13637. return false;
  13638. }
  13639. var LokiOps = {
  13640. // comparison operators
  13641. // a is the value in the collection
  13642. // b is the query value
  13643. $eq: function (a, b) {
  13644. return a === b;
  13645. },
  13646. // abstract/loose equality
  13647. $aeq: function (a, b) {
  13648. return a == b;
  13649. },
  13650. $ne: function (a, b) {
  13651. // ecma 5 safe test for NaN
  13652. if (b !== b) {
  13653. // ecma 5 test value is not NaN
  13654. return (a === a);
  13655. }
  13656. return a !== b;
  13657. },
  13658. // date equality / loki abstract equality test
  13659. $dteq: function (a, b) {
  13660. return Comparators.aeq(a, b);
  13661. },
  13662. // loki comparisons: return identical unindexed results as indexed comparisons
  13663. $gt: function (a, b) {
  13664. return Comparators.gt(a, b, false);
  13665. },
  13666. $gte: function (a, b) {
  13667. return Comparators.gt(a, b, true);
  13668. },
  13669. $lt: function (a, b) {
  13670. return Comparators.lt(a, b, false);
  13671. },
  13672. $lte: function (a, b) {
  13673. return Comparators.lt(a, b, true);
  13674. },
  13675. // lightweight javascript comparisons
  13676. $jgt: function (a, b) {
  13677. return a > b;
  13678. },
  13679. $jgte: function (a, b) {
  13680. return a >= b;
  13681. },
  13682. $jlt: function (a, b) {
  13683. return a < b;
  13684. },
  13685. $jlte: function (a, b) {
  13686. return a <= b;
  13687. },
  13688. // ex : coll.find({'orderCount': {$between: [10, 50]}});
  13689. $between: function (a, vals) {
  13690. if (a === undefined || a === null) return false;
  13691. return (Comparators.gt(a, vals[0], true) && Comparators.lt(a, vals[1], true));
  13692. },
  13693. $jbetween: function (a, vals) {
  13694. if (a === undefined || a === null) return false;
  13695. return (a >= vals[0] && a <= vals[1]);
  13696. },
  13697. $in: function (a, b) {
  13698. return b.indexOf(a) !== -1;
  13699. },
  13700. $nin: function (a, b) {
  13701. return b.indexOf(a) === -1;
  13702. },
  13703. $keyin: function (a, b) {
  13704. return a in b;
  13705. },
  13706. $nkeyin: function (a, b) {
  13707. return !(a in b);
  13708. },
  13709. $definedin: function (a, b) {
  13710. return b[a] !== undefined;
  13711. },
  13712. $undefinedin: function (a, b) {
  13713. return b[a] === undefined;
  13714. },
  13715. $regex: function (a, b) {
  13716. return b.test(a);
  13717. },
  13718. $containsString: function (a, b) {
  13719. return (typeof a === 'string') && (a.indexOf(b) !== -1);
  13720. },
  13721. $containsNone: function (a, b) {
  13722. return !LokiOps.$containsAny(a, b);
  13723. },
  13724. $containsAny: function (a, b) {
  13725. var checkFn = containsCheckFn(a);
  13726. if (checkFn !== null) {
  13727. return (Array.isArray(b)) ? (b.some(checkFn)) : (checkFn(b));
  13728. }
  13729. return false;
  13730. },
  13731. $contains: function (a, b) {
  13732. var checkFn = containsCheckFn(a);
  13733. if (checkFn !== null) {
  13734. return (Array.isArray(b)) ? (b.every(checkFn)) : (checkFn(b));
  13735. }
  13736. return false;
  13737. },
  13738. $type: function (a, b) {
  13739. var type = typeof a;
  13740. if (type === 'object') {
  13741. if (Array.isArray(a)) {
  13742. type = 'array';
  13743. } else if (a instanceof Date) {
  13744. type = 'date';
  13745. }
  13746. }
  13747. return (typeof b !== 'object') ? (type === b) : doQueryOp(type, b);
  13748. },
  13749. $finite: function(a, b) {
  13750. return (b === isFinite(a));
  13751. },
  13752. $size: function (a, b) {
  13753. if (Array.isArray(a)) {
  13754. return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b);
  13755. }
  13756. return false;
  13757. },
  13758. $len: function (a, b) {
  13759. if (typeof a === 'string') {
  13760. return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b);
  13761. }
  13762. return false;
  13763. },
  13764. $where: function (a, b) {
  13765. return b(a) === true;
  13766. },
  13767. // field-level logical operators
  13768. // a is the value in the collection
  13769. // b is the nested query operation (for '$not')
  13770. // or an array of nested query operations (for '$and' and '$or')
  13771. $not: function (a, b) {
  13772. return !doQueryOp(a, b);
  13773. },
  13774. $and: function (a, b) {
  13775. for (var idx = 0, len = b.length; idx < len; idx += 1) {
  13776. if (!doQueryOp(a, b[idx])) {
  13777. return false;
  13778. }
  13779. }
  13780. return true;
  13781. },
  13782. $or: function (a, b) {
  13783. for (var idx = 0, len = b.length; idx < len; idx += 1) {
  13784. if (doQueryOp(a, b[idx])) {
  13785. return true;
  13786. }
  13787. }
  13788. return false;
  13789. },
  13790. $exists: function (a, b) {
  13791. if (b) {
  13792. return a !== undefined;
  13793. } else {
  13794. return a === undefined;
  13795. }
  13796. }
  13797. };
  13798. // if an op is registered in this object, our 'calculateRange' can use it with our binary indices.
  13799. // if the op is registered to a function, we will run that function/op as a 2nd pass filter on results.
  13800. // those 2nd pass filter functions should be similar to LokiOps functions, accepting 2 vals to compare.
  13801. var indexedOps = {
  13802. $eq: LokiOps.$eq,
  13803. $aeq: true,
  13804. $dteq: true,
  13805. $gt: true,
  13806. $gte: true,
  13807. $lt: true,
  13808. $lte: true,
  13809. $in: true,
  13810. $between: true
  13811. };
  13812. function clone(data, method) {
  13813. if (data === null || data === undefined) {
  13814. return null;
  13815. }
  13816. var cloneMethod = method || 'parse-stringify',
  13817. cloned;
  13818. switch (cloneMethod) {
  13819. case "parse-stringify":
  13820. cloned = JSON.parse(JSON.stringify(data));
  13821. break;
  13822. case "jquery-extend-deep":
  13823. cloned = jQuery.extend(true, {}, data);
  13824. break;
  13825. case "shallow":
  13826. // more compatible method for older browsers
  13827. cloned = Object.create(data.constructor.prototype);
  13828. Object.keys(data).map(function (i) {
  13829. cloned[i] = data[i];
  13830. });
  13831. break;
  13832. case "shallow-assign":
  13833. // should be supported by newer environments/browsers
  13834. cloned = Object.create(data.constructor.prototype);
  13835. Object.assign(cloned, data);
  13836. break;
  13837. case "shallow-recurse-objects":
  13838. // shallow clone top level properties
  13839. cloned = clone(data, "shallow");
  13840. var keys = Object.keys(data);
  13841. // for each of the top level properties which are object literals, recursively shallow copy
  13842. keys.forEach(function(key) {
  13843. if (typeof data[key] === "object" && data[key].constructor.name === "Object") {
  13844. cloned[key] = clone(data[key], "shallow-recurse-objects");
  13845. }else if(Array.isArray(data[key])){
  13846. cloned[key] = cloneObjectArray(data[key], "shallow-recurse-objects");
  13847. }
  13848. });
  13849. break;
  13850. default:
  13851. break;
  13852. }
  13853. return cloned;
  13854. }
  13855. function cloneObjectArray(objarray, method) {
  13856. if (method == "parse-stringify") {
  13857. return clone(objarray, method);
  13858. }
  13859. var result = [];
  13860. for (var i = 0, len = objarray.length; i < len; i++) {
  13861. result[i] = clone(objarray[i], method);
  13862. }
  13863. return result;
  13864. }
  13865. function localStorageAvailable() {
  13866. try {
  13867. return (window && window.localStorage !== undefined && window.localStorage !== null);
  13868. } catch (e) {
  13869. return false;
  13870. }
  13871. }
  13872. /**
  13873. * LokiEventEmitter is a minimalist version of EventEmitter. It enables any
  13874. * constructor that inherits EventEmitter to emit events and trigger
  13875. * listeners that have been added to the event through the on(event, callback) method
  13876. *
  13877. * @constructor LokiEventEmitter
  13878. */
  13879. function LokiEventEmitter() {}
  13880. /**
  13881. * @prop {hashmap} events - a hashmap, with each property being an array of callbacks
  13882. * @memberof LokiEventEmitter
  13883. */
  13884. LokiEventEmitter.prototype.events = {};
  13885. /**
  13886. * @prop {boolean} asyncListeners - boolean determines whether or not the callbacks associated with each event
  13887. * should happen in an async fashion or not
  13888. * Default is false, which means events are synchronous
  13889. * @memberof LokiEventEmitter
  13890. */
  13891. LokiEventEmitter.prototype.asyncListeners = false;
  13892. /**
  13893. * on(eventName, listener) - adds a listener to the queue of callbacks associated to an event
  13894. * @param {string|string[]} eventName - the name(s) of the event(s) to listen to
  13895. * @param {function} listener - callback function of listener to attach
  13896. * @returns {int} the index of the callback in the array of listeners for a particular event
  13897. * @memberof LokiEventEmitter
  13898. */
  13899. LokiEventEmitter.prototype.on = function (eventName, listener) {
  13900. var event;
  13901. var self = this;
  13902. if (Array.isArray(eventName)) {
  13903. eventName.forEach(function(currentEventName) {
  13904. self.on(currentEventName, listener);
  13905. });
  13906. return listener;
  13907. }
  13908. event = this.events[eventName];
  13909. if (!event) {
  13910. event = this.events[eventName] = [];
  13911. }
  13912. event.push(listener);
  13913. return listener;
  13914. };
  13915. /**
  13916. * emit(eventName, data) - emits a particular event
  13917. * with the option of passing optional parameters which are going to be processed by the callback
  13918. * provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters)
  13919. * @param {string} eventName - the name of the event
  13920. * @param {object=} data - optional object passed with the event
  13921. * @memberof LokiEventEmitter
  13922. */
  13923. LokiEventEmitter.prototype.emit = function (eventName) {
  13924. var self = this;
  13925. var selfArgs = Array.prototype.slice.call(arguments, 1);
  13926. if (eventName && this.events[eventName]) {
  13927. this.events[eventName].forEach(function (listener) {
  13928. if (self.asyncListeners) {
  13929. setTimeout(function () {
  13930. listener.apply(self, selfArgs);
  13931. }, 1);
  13932. } else {
  13933. listener.apply(self, selfArgs);
  13934. }
  13935. });
  13936. } else {
  13937. throw new Error('No event ' + eventName + ' defined');
  13938. }
  13939. };
  13940. /**
  13941. * Alias of LokiEventEmitter.prototype.on
  13942. * addListener(eventName, listener) - adds a listener to the queue of callbacks associated to an event
  13943. * @param {string|string[]} eventName - the name(s) of the event(s) to listen to
  13944. * @param {function} listener - callback function of listener to attach
  13945. * @returns {int} the index of the callback in the array of listeners for a particular event
  13946. * @memberof LokiEventEmitter
  13947. */
  13948. LokiEventEmitter.prototype.addListener = LokiEventEmitter.prototype.on;
  13949. /**
  13950. * removeListener() - removes the listener at position 'index' from the event 'eventName'
  13951. * @param {string|string[]} eventName - the name(s) of the event(s) which the listener is attached to
  13952. * @param {function} listener - the listener callback function to remove from emitter
  13953. * @memberof LokiEventEmitter
  13954. */
  13955. LokiEventEmitter.prototype.removeListener = function (eventName, listener) {
  13956. var self = this;
  13957. if (Array.isArray(eventName)) {
  13958. eventName.forEach(function(currentEventName) {
  13959. self.removeListener(currentEventName, listener);
  13960. });
  13961. return;
  13962. }
  13963. if (this.events[eventName]) {
  13964. var listeners = this.events[eventName];
  13965. listeners.splice(listeners.indexOf(listener), 1);
  13966. }
  13967. };
  13968. /**
  13969. * Loki: The main database class
  13970. * @constructor Loki
  13971. * @implements LokiEventEmitter
  13972. * @param {string} filename - name of the file to be saved to
  13973. * @param {object=} options - (Optional) config options object
  13974. * @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA'
  13975. * @param {boolean} [options.verbose=false] - enable console output
  13976. * @param {boolean} [options.autosave=false] - enables autosave
  13977. * @param {int} [options.autosaveInterval=5000] - time interval (in milliseconds) between saves (if dirty)
  13978. * @param {boolean} [options.autoload=false] - enables autoload on loki instantiation
  13979. * @param {function} options.autoloadCallback - user callback called after database load
  13980. * @param {adapter} options.adapter - an instance of a loki persistence adapter
  13981. * @param {string} [options.serializationMethod='normal'] - ['normal', 'pretty', 'destructured']
  13982. * @param {string} options.destructureDelimiter - string delimiter used for destructured serialization
  13983. * @param {boolean} [options.throttledSaves=true] - debounces multiple calls to to saveDatabase reducing number of disk I/O operations
  13984. and guaranteeing proper serialization of the calls.
  13985. */
  13986. function Loki(filename, options) {
  13987. this.filename = filename || 'loki.db';
  13988. this.collections = [];
  13989. // persist version of code which created the database to the database.
  13990. // could use for upgrade scenarios
  13991. this.databaseVersion = 1.5;
  13992. this.engineVersion = 1.5;
  13993. // autosave support (disabled by default)
  13994. // pass autosave: true, autosaveInterval: 6000 in options to set 6 second autosave
  13995. this.autosave = false;
  13996. this.autosaveInterval = 5000;
  13997. this.autosaveHandle = null;
  13998. this.throttledSaves = true;
  13999. this.options = {};
  14000. // currently keeping persistenceMethod and persistenceAdapter as loki level properties that
  14001. // will not or cannot be deserialized. You are required to configure persistence every time
  14002. // you instantiate a loki object (or use default environment detection) in order to load the database anyways.
  14003. // persistenceMethod could be 'fs', 'localStorage', or 'adapter'
  14004. // this is optional option param, otherwise environment detection will be used
  14005. // if user passes their own adapter we will force this method to 'adapter' later, so no need to pass method option.
  14006. this.persistenceMethod = null;
  14007. // retain reference to optional (non-serializable) persistenceAdapter 'instance'
  14008. this.persistenceAdapter = null;
  14009. // flags used to throttle saves
  14010. this.throttledSavePending = false;
  14011. this.throttledCallbacks = [];
  14012. // enable console output if verbose flag is set (disabled by default)
  14013. this.verbose = options && options.hasOwnProperty('verbose') ? options.verbose : false;
  14014. this.events = {
  14015. 'init': [],
  14016. 'loaded': [],
  14017. 'flushChanges': [],
  14018. 'close': [],
  14019. 'changes': [],
  14020. 'warning': []
  14021. };
  14022. var getENV = function () {
  14023. if (typeof global !== 'undefined' && (global.android || global.NSObject)) {
  14024. // If no adapter assume nativescript which needs adapter to be passed manually
  14025. return 'NATIVESCRIPT'; //nativescript
  14026. }
  14027. if (typeof window === 'undefined') {
  14028. return 'NODEJS';
  14029. }
  14030. if (typeof global !== 'undefined' && global.window && typeof process !== 'undefined') {
  14031. return 'NODEJS'; //node-webkit
  14032. }
  14033. if (typeof document !== 'undefined') {
  14034. if (document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1) {
  14035. return 'CORDOVA';
  14036. }
  14037. return 'BROWSER';
  14038. }
  14039. return 'CORDOVA';
  14040. };
  14041. // refactored environment detection due to invalid detection for browser environments.
  14042. // if they do not specify an options.env we want to detect env rather than default to nodejs.
  14043. // currently keeping two properties for similar thing (options.env and options.persistenceMethod)
  14044. // might want to review whether we can consolidate.
  14045. if (options && options.hasOwnProperty('env')) {
  14046. this.ENV = options.env;
  14047. } else {
  14048. this.ENV = getENV();
  14049. }
  14050. // not sure if this is necessary now that i have refactored the line above
  14051. if (this.ENV === 'undefined') {
  14052. this.ENV = 'NODEJS';
  14053. }
  14054. this.configureOptions(options, true);
  14055. this.on('init', this.clearChanges);
  14056. }
  14057. // db class is an EventEmitter
  14058. Loki.prototype = new LokiEventEmitter();
  14059. Loki.prototype.constructor = Loki;
  14060. // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter.
  14061. // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference.
  14062. Loki.prototype.getIndexedAdapter = function () {
  14063. var adapter;
  14064. if (typeof require === 'function') {
  14065. adapter = require("./loki-indexed-adapter.js");
  14066. }
  14067. return adapter;
  14068. };
  14069. /**
  14070. * Allows reconfiguring database options
  14071. *
  14072. * @param {object} options - configuration options to apply to loki db object
  14073. * @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA'
  14074. * @param {boolean} options.verbose - enable console output (default is 'false')
  14075. * @param {boolean} options.autosave - enables autosave
  14076. * @param {int} options.autosaveInterval - time interval (in milliseconds) between saves (if dirty)
  14077. * @param {boolean} options.autoload - enables autoload on loki instantiation
  14078. * @param {function} options.autoloadCallback - user callback called after database load
  14079. * @param {adapter} options.adapter - an instance of a loki persistence adapter
  14080. * @param {string} options.serializationMethod - ['normal', 'pretty', 'destructured']
  14081. * @param {string} options.destructureDelimiter - string delimiter used for destructured serialization
  14082. * @param {boolean} initialConfig - (internal) true is passed when loki ctor is invoking
  14083. * @memberof Loki
  14084. */
  14085. Loki.prototype.configureOptions = function (options, initialConfig) {
  14086. var defaultPersistence = {
  14087. 'NODEJS': 'fs',
  14088. 'BROWSER': 'localStorage',
  14089. 'CORDOVA': 'localStorage',
  14090. 'MEMORY': 'memory'
  14091. },
  14092. persistenceMethods = {
  14093. 'fs': LokiFsAdapter,
  14094. 'localStorage': LokiLocalStorageAdapter,
  14095. 'memory': LokiMemoryAdapter
  14096. };
  14097. this.options = {};
  14098. this.persistenceMethod = null;
  14099. // retain reference to optional persistence adapter 'instance'
  14100. // currently keeping outside options because it can't be serialized
  14101. this.persistenceAdapter = null;
  14102. // process the options
  14103. if (typeof (options) !== 'undefined') {
  14104. this.options = options;
  14105. if (this.options.hasOwnProperty('persistenceMethod')) {
  14106. // check if the specified persistence method is known
  14107. if (typeof (persistenceMethods[options.persistenceMethod]) == 'function') {
  14108. this.persistenceMethod = options.persistenceMethod;
  14109. this.persistenceAdapter = new persistenceMethods[options.persistenceMethod]();
  14110. }
  14111. // should be throw an error here, or just fall back to defaults ??
  14112. }
  14113. // if user passes adapter, set persistence mode to adapter and retain persistence adapter instance
  14114. if (this.options.hasOwnProperty('adapter')) {
  14115. this.persistenceMethod = 'adapter';
  14116. this.persistenceAdapter = options.adapter;
  14117. this.options.adapter = null;
  14118. }
  14119. // if they want to load database on loki instantiation, now is a good time to load... after adapter set and before possible autosave initiation
  14120. if (options.autoload && initialConfig) {
  14121. // for autoload, let the constructor complete before firing callback
  14122. var self = this;
  14123. setTimeout(function () {
  14124. self.loadDatabase(options, options.autoloadCallback);
  14125. }, 1);
  14126. }
  14127. if (this.options.hasOwnProperty('autosaveInterval')) {
  14128. this.autosaveDisable();
  14129. this.autosaveInterval = parseInt(this.options.autosaveInterval, 10);
  14130. }
  14131. if (this.options.hasOwnProperty('autosave') && this.options.autosave) {
  14132. this.autosaveDisable();
  14133. this.autosave = true;
  14134. if (this.options.hasOwnProperty('autosaveCallback')) {
  14135. this.autosaveEnable(options, options.autosaveCallback);
  14136. } else {
  14137. this.autosaveEnable();
  14138. }
  14139. }
  14140. if (this.options.hasOwnProperty('throttledSaves')) {
  14141. this.throttledSaves = this.options.throttledSaves;
  14142. }
  14143. } // end of options processing
  14144. // ensure defaults exists for options which were not set
  14145. if (!this.options.hasOwnProperty('serializationMethod')) {
  14146. this.options.serializationMethod = 'normal';
  14147. }
  14148. // ensure passed or default option exists
  14149. if (!this.options.hasOwnProperty('destructureDelimiter')) {
  14150. this.options.destructureDelimiter = '$<\n';
  14151. }
  14152. // if by now there is no adapter specified by user nor derived from persistenceMethod: use sensible defaults
  14153. if (this.persistenceAdapter === null) {
  14154. this.persistenceMethod = defaultPersistence[this.ENV];
  14155. if (this.persistenceMethod) {
  14156. this.persistenceAdapter = new persistenceMethods[this.persistenceMethod]();
  14157. }
  14158. }
  14159. };
  14160. /**
  14161. * Copies 'this' database into a new Loki instance. Object references are shared to make lightweight.
  14162. *
  14163. * @param {object} options - apply or override collection level settings
  14164. * @param {bool} options.removeNonSerializable - nulls properties not safe for serialization.
  14165. * @memberof Loki
  14166. */
  14167. Loki.prototype.copy = function(options) {
  14168. // in case running in an environment without accurate environment detection, pass 'NA'
  14169. var databaseCopy = new Loki(this.filename, { env: "NA" });
  14170. var clen, idx;
  14171. options = options || {};
  14172. // currently inverting and letting loadJSONObject do most of the work
  14173. databaseCopy.loadJSONObject(this, { retainDirtyFlags: true });
  14174. // since our JSON serializeReplacer is not invoked for reference database adapters, this will let us mimic
  14175. if(options.hasOwnProperty("removeNonSerializable") && options.removeNonSerializable === true) {
  14176. databaseCopy.autosaveHandle = null;
  14177. databaseCopy.persistenceAdapter = null;
  14178. clen = databaseCopy.collections.length;
  14179. for (idx=0; idx<clen; idx++) {
  14180. databaseCopy.collections[idx].constraints = null;
  14181. databaseCopy.collections[idx].ttl = null;
  14182. }
  14183. }
  14184. return databaseCopy;
  14185. };
  14186. /**
  14187. * Adds a collection to the database.
  14188. * @param {string} name - name of collection to add
  14189. * @param {object=} options - (optional) options to configure collection with.
  14190. * @param {array=} [options.unique=[]] - array of property names to define unique constraints for
  14191. * @param {array=} [options.exact=[]] - array of property names to define exact constraints for
  14192. * @param {array=} [options.indices=[]] - array property names to define binary indexes for
  14193. * @param {boolean} [options.asyncListeners=false] - whether listeners are called asynchronously
  14194. * @param {boolean} [options.disableMeta=false] - set to true to disable meta property on documents
  14195. * @param {boolean} [options.disableChangesApi=true] - set to false to enable Changes Api
  14196. * @param {boolean} [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning)
  14197. * @param {boolean} [options.autoupdate=false] - use Object.observe to update objects automatically
  14198. * @param {boolean} [options.clone=false] - specify whether inserts and queries clone to/from user
  14199. * @param {string} [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow, 'shallow-assign'
  14200. * @param {int=} options.ttl - age of document (in ms.) before document is considered aged/stale.
  14201. * @param {int=} options.ttlInterval - time interval for clearing out 'aged' documents; not set by default.
  14202. * @returns {Collection} a reference to the collection which was just added
  14203. * @memberof Loki
  14204. */
  14205. Loki.prototype.addCollection = function (name, options) {
  14206. var i,
  14207. len = this.collections.length;
  14208. if (options && options.disableMeta === true) {
  14209. if (options.disableChangesApi === false) {
  14210. throw new Error("disableMeta option cannot be passed as true when disableChangesApi is passed as false");
  14211. }
  14212. if (options.disableDeltaChangesApi === false) {
  14213. throw new Error("disableMeta option cannot be passed as true when disableDeltaChangesApi is passed as false");
  14214. }
  14215. if (typeof options.ttl === "number" && options.ttl > 0) {
  14216. throw new Error("disableMeta option cannot be passed as true when ttl is enabled");
  14217. }
  14218. }
  14219. for (i = 0; i < len; i += 1) {
  14220. if (this.collections[i].name === name) {
  14221. return this.collections[i];
  14222. }
  14223. }
  14224. var collection = new Collection(name, options);
  14225. this.collections.push(collection);
  14226. if (this.verbose)
  14227. collection.console = console;
  14228. return collection;
  14229. };
  14230. Loki.prototype.loadCollection = function (collection) {
  14231. if (!collection.name) {
  14232. throw new Error('Collection must have a name property to be loaded');
  14233. }
  14234. this.collections.push(collection);
  14235. };
  14236. /**
  14237. * Retrieves reference to a collection by name.
  14238. * @param {string} collectionName - name of collection to look up
  14239. * @returns {Collection} Reference to collection in database by that name, or null if not found
  14240. * @memberof Loki
  14241. */
  14242. Loki.prototype.getCollection = function (collectionName) {
  14243. var i,
  14244. len = this.collections.length;
  14245. for (i = 0; i < len; i += 1) {
  14246. if (this.collections[i].name === collectionName) {
  14247. return this.collections[i];
  14248. }
  14249. }
  14250. // no such collection
  14251. this.emit('warning', 'collection ' + collectionName + ' not found');
  14252. return null;
  14253. };
  14254. /**
  14255. * Renames an existing loki collection
  14256. * @param {string} oldName - name of collection to rename
  14257. * @param {string} newName - new name of collection
  14258. * @returns {Collection} reference to the newly renamed collection
  14259. * @memberof Loki
  14260. */
  14261. Loki.prototype.renameCollection = function (oldName, newName) {
  14262. var c = this.getCollection(oldName);
  14263. if (c) {
  14264. c.name = newName;
  14265. }
  14266. return c;
  14267. };
  14268. /**
  14269. * Returns a list of collections in the database.
  14270. * @returns {object[]} array of objects containing 'name', 'type', and 'count' properties.
  14271. * @memberof Loki
  14272. */
  14273. Loki.prototype.listCollections = function () {
  14274. var i = this.collections.length,
  14275. colls = [];
  14276. while (i--) {
  14277. colls.push({
  14278. name: this.collections[i].name,
  14279. type: this.collections[i].objType,
  14280. count: this.collections[i].data.length
  14281. });
  14282. }
  14283. return colls;
  14284. };
  14285. /**
  14286. * Removes a collection from the database.
  14287. * @param {string} collectionName - name of collection to remove
  14288. * @memberof Loki
  14289. */
  14290. Loki.prototype.removeCollection = function (collectionName) {
  14291. var i,
  14292. len = this.collections.length;
  14293. for (i = 0; i < len; i += 1) {
  14294. if (this.collections[i].name === collectionName) {
  14295. var tmpcol = new Collection(collectionName, {});
  14296. var curcol = this.collections[i];
  14297. for (var prop in curcol) {
  14298. if (curcol.hasOwnProperty(prop) && tmpcol.hasOwnProperty(prop)) {
  14299. curcol[prop] = tmpcol[prop];
  14300. }
  14301. }
  14302. this.collections.splice(i, 1);
  14303. return;
  14304. }
  14305. }
  14306. };
  14307. Loki.prototype.getName = function () {
  14308. return this.name;
  14309. };
  14310. /**
  14311. * serializeReplacer - used to prevent certain properties from being serialized
  14312. *
  14313. */
  14314. Loki.prototype.serializeReplacer = function (key, value) {
  14315. switch (key) {
  14316. case 'autosaveHandle':
  14317. case 'persistenceAdapter':
  14318. case 'constraints':
  14319. case 'ttl':
  14320. return null;
  14321. case 'throttledSavePending':
  14322. case 'throttledCallbacks':
  14323. return undefined;
  14324. default:
  14325. return value;
  14326. }
  14327. };
  14328. /**
  14329. * Serialize database to a string which can be loaded via {@link Loki#loadJSON}
  14330. *
  14331. * @returns {string} Stringified representation of the loki database.
  14332. * @memberof Loki
  14333. */
  14334. Loki.prototype.serialize = function (options) {
  14335. options = options || {};
  14336. if (!options.hasOwnProperty("serializationMethod")) {
  14337. options.serializationMethod = this.options.serializationMethod;
  14338. }
  14339. switch(options.serializationMethod) {
  14340. case "normal": return JSON.stringify(this, this.serializeReplacer);
  14341. case "pretty": return JSON.stringify(this, this.serializeReplacer, 2);
  14342. case "destructured": return this.serializeDestructured(); // use default options
  14343. default: return JSON.stringify(this, this.serializeReplacer);
  14344. }
  14345. };
  14346. // alias of serialize
  14347. Loki.prototype.toJson = Loki.prototype.serialize;
  14348. /**
  14349. * Database level destructured JSON serialization routine to allow alternate serialization methods.
  14350. * Internally, Loki supports destructuring via loki "serializationMethod' option and
  14351. * the optional LokiPartitioningAdapter class. It is also available if you wish to do
  14352. * your own structured persistence or data exchange.
  14353. *
  14354. * @param {object=} options - output format options for use externally to loki
  14355. * @param {bool=} options.partitioned - (default: false) whether db and each collection are separate
  14356. * @param {int=} options.partition - can be used to only output an individual collection or db (-1)
  14357. * @param {bool=} options.delimited - (default: true) whether subitems are delimited or subarrays
  14358. * @param {string=} options.delimiter - override default delimiter
  14359. *
  14360. * @returns {string|array} A custom, restructured aggregation of independent serializations.
  14361. * @memberof Loki
  14362. */
  14363. Loki.prototype.serializeDestructured = function(options) {
  14364. var idx, sidx, result, resultlen;
  14365. var reconstruct = [];
  14366. var dbcopy;
  14367. options = options || {};
  14368. if (!options.hasOwnProperty("partitioned")) {
  14369. options.partitioned = false;
  14370. }
  14371. if (!options.hasOwnProperty("delimited")) {
  14372. options.delimited = true;
  14373. }
  14374. if (!options.hasOwnProperty("delimiter")) {
  14375. options.delimiter = this.options.destructureDelimiter;
  14376. }
  14377. // 'partitioned' along with 'partition' of 0 or greater is a request for single collection serialization
  14378. if (options.partitioned === true && options.hasOwnProperty("partition") && options.partition >= 0) {
  14379. return this.serializeCollection({
  14380. delimited: options.delimited,
  14381. delimiter: options.delimiter,
  14382. collectionIndex: options.partition
  14383. });
  14384. }
  14385. // not just an individual collection, so we will need to serialize db container via shallow copy
  14386. dbcopy = new Loki(this.filename);
  14387. dbcopy.loadJSONObject(this);
  14388. for(idx=0; idx < dbcopy.collections.length; idx++) {
  14389. dbcopy.collections[idx].data = [];
  14390. }
  14391. // if we -only- wanted the db container portion, return it now
  14392. if (options.partitioned === true && options.partition === -1) {
  14393. // since we are deconstructing, override serializationMethod to normal for here
  14394. return dbcopy.serialize({
  14395. serializationMethod: "normal"
  14396. });
  14397. }
  14398. // at this point we must be deconstructing the entire database
  14399. // start by pushing db serialization into first array element
  14400. reconstruct.push(dbcopy.serialize({
  14401. serializationMethod: "normal"
  14402. }));
  14403. dbcopy = null;
  14404. // push collection data into subsequent elements
  14405. for(idx=0; idx < this.collections.length; idx++) {
  14406. result = this.serializeCollection({
  14407. delimited: options.delimited,
  14408. delimiter: options.delimiter,
  14409. collectionIndex: idx
  14410. });
  14411. // NDA : Non-Delimited Array : one iterable concatenated array with empty string collection partitions
  14412. if (options.partitioned === false && options.delimited === false) {
  14413. if (!Array.isArray(result)) {
  14414. throw new Error("a nondelimited, non partitioned collection serialization did not return an expected array");
  14415. }
  14416. // Array.concat would probably duplicate memory overhead for copying strings.
  14417. // Instead copy each individually, and clear old value after each copy.
  14418. // Hopefully this will allow g.c. to reduce memory pressure, if needed.
  14419. resultlen = result.length;
  14420. for (sidx=0; sidx < resultlen; sidx++) {
  14421. reconstruct.push(result[sidx]);
  14422. result[sidx] = null;
  14423. }
  14424. reconstruct.push("");
  14425. }
  14426. else {
  14427. reconstruct.push(result);
  14428. }
  14429. }
  14430. // Reconstruct / present results according to four combinations : D, DA, NDA, NDAA
  14431. if (options.partitioned) {
  14432. // DA : Delimited Array of strings [0] db [1] collection [n] collection { partitioned: true, delimited: true }
  14433. // useful for simple future adaptations of existing persistence adapters to save collections separately
  14434. if (options.delimited) {
  14435. return reconstruct;
  14436. }
  14437. // NDAA : Non-Delimited Array with subArrays. db at [0] and collection subarrays at [n] { partitioned: true, delimited : false }
  14438. // This format might be the most versatile for 'rolling your own' partitioned sync or save.
  14439. // Memory overhead can be reduced by specifying a specific partition, but at this code path they did not, so its all.
  14440. else {
  14441. return reconstruct;
  14442. }
  14443. }
  14444. else {
  14445. // D : one big Delimited string { partitioned: false, delimited : true }
  14446. // This is the method Loki will use internally if 'destructured'.
  14447. // Little memory overhead improvements but does not require multiple asynchronous adapter call scheduling
  14448. if (options.delimited) {
  14449. // indicate no more collections
  14450. reconstruct.push("");
  14451. return reconstruct.join(options.delimiter);
  14452. }
  14453. // NDA : Non-Delimited Array : one iterable array with empty string collection partitions { partitioned: false, delimited: false }
  14454. // This format might be best candidate for custom synchronous syncs or saves
  14455. else {
  14456. // indicate no more collections
  14457. reconstruct.push("");
  14458. return reconstruct;
  14459. }
  14460. }
  14461. reconstruct.push("");
  14462. return reconstruct.join(delim);
  14463. };
  14464. /**
  14465. * Collection level utility method to serialize a collection in a 'destructured' format
  14466. *
  14467. * @param {object=} options - used to determine output of method
  14468. * @param {int} options.delimited - whether to return single delimited string or an array
  14469. * @param {string} options.delimiter - (optional) if delimited, this is delimiter to use
  14470. * @param {int} options.collectionIndex - specify which collection to serialize data for
  14471. *
  14472. * @returns {string|array} A custom, restructured aggregation of independent serializations for a single collection.
  14473. * @memberof Loki
  14474. */
  14475. Loki.prototype.serializeCollection = function(options) {
  14476. var doccount,
  14477. docidx,
  14478. resultlines = [];
  14479. options = options || {};
  14480. if (!options.hasOwnProperty("delimited")) {
  14481. options.delimited = true;
  14482. }
  14483. if (!options.hasOwnProperty("collectionIndex")) {
  14484. throw new Error("serializeCollection called without 'collectionIndex' option");
  14485. }
  14486. doccount = this.collections[options.collectionIndex].data.length;
  14487. resultlines = [];
  14488. for(docidx=0; docidx<doccount; docidx++) {
  14489. resultlines.push(JSON.stringify(this.collections[options.collectionIndex].data[docidx]));
  14490. }
  14491. // D and DA
  14492. if (options.delimited) {
  14493. // indicate no more documents in collection (via empty delimited string)
  14494. resultlines.push("");
  14495. return resultlines.join(options.delimiter);
  14496. }
  14497. else {
  14498. // NDAA and NDA
  14499. return resultlines;
  14500. }
  14501. };
  14502. /**
  14503. * Database level destructured JSON deserialization routine to minimize memory overhead.
  14504. * Internally, Loki supports destructuring via loki "serializationMethod' option and
  14505. * the optional LokiPartitioningAdapter class. It is also available if you wish to do
  14506. * your own structured persistence or data exchange.
  14507. *
  14508. * @param {string|array} destructuredSource - destructured json or array to deserialize from
  14509. * @param {object=} options - source format options
  14510. * @param {bool=} [options.partitioned=false] - whether db and each collection are separate
  14511. * @param {int=} options.partition - can be used to deserialize only a single partition
  14512. * @param {bool=} [options.delimited=true] - whether subitems are delimited or subarrays
  14513. * @param {string=} options.delimiter - override default delimiter
  14514. *
  14515. * @returns {object|array} An object representation of the deserialized database, not yet applied to 'this' db or document array
  14516. * @memberof Loki
  14517. */
  14518. Loki.prototype.deserializeDestructured = function(destructuredSource, options) {
  14519. var workarray=[];
  14520. var len, cdb;
  14521. var idx, collIndex=0, collCount, lineIndex=1, done=false;
  14522. var currLine, currObject;
  14523. options = options || {};
  14524. if (!options.hasOwnProperty("partitioned")) {
  14525. options.partitioned = false;
  14526. }
  14527. if (!options.hasOwnProperty("delimited")) {
  14528. options.delimited = true;
  14529. }
  14530. if (!options.hasOwnProperty("delimiter")) {
  14531. options.delimiter = this.options.destructureDelimiter;
  14532. }
  14533. // Partitioned
  14534. // DA : Delimited Array of strings [0] db [1] collection [n] collection { partitioned: true, delimited: true }
  14535. // NDAA : Non-Delimited Array with subArrays. db at [0] and collection subarrays at [n] { partitioned: true, delimited : false }
  14536. // -or- single partition
  14537. if (options.partitioned) {
  14538. // handle single partition
  14539. if (options.hasOwnProperty('partition')) {
  14540. // db only
  14541. if (options.partition === -1) {
  14542. cdb = JSON.parse(destructuredSource[0]);
  14543. return cdb;
  14544. }
  14545. // single collection, return doc array
  14546. return this.deserializeCollection(destructuredSource[options.partition+1], options);
  14547. }
  14548. // Otherwise we are restoring an entire partitioned db
  14549. cdb = JSON.parse(destructuredSource[0]);
  14550. collCount = cdb.collections.length;
  14551. for(collIndex=0; collIndex<collCount; collIndex++) {
  14552. // attach each collection docarray to container collection data, add 1 to collection array index since db is at 0
  14553. cdb.collections[collIndex].data = this.deserializeCollection(destructuredSource[collIndex+1], options);
  14554. }
  14555. return cdb;
  14556. }
  14557. // Non-Partitioned
  14558. // D : one big Delimited string { partitioned: false, delimited : true }
  14559. // NDA : Non-Delimited Array : one iterable array with empty string collection partitions { partitioned: false, delimited: false }
  14560. // D
  14561. if (options.delimited) {
  14562. workarray = destructuredSource.split(options.delimiter);
  14563. destructuredSource = null; // lower memory pressure
  14564. len = workarray.length;
  14565. if (len === 0) {
  14566. return null;
  14567. }
  14568. }
  14569. // NDA
  14570. else {
  14571. workarray = destructuredSource;
  14572. }
  14573. // first line is database and collection shells
  14574. cdb = JSON.parse(workarray[0]);
  14575. collCount = cdb.collections.length;
  14576. workarray[0] = null;
  14577. while (!done) {
  14578. currLine = workarray[lineIndex];
  14579. // empty string indicates either end of collection or end of file
  14580. if (workarray[lineIndex] === "") {
  14581. // if no more collections to load into, we are done
  14582. if (++collIndex > collCount) {
  14583. done = true;
  14584. }
  14585. }
  14586. else {
  14587. currObject = JSON.parse(workarray[lineIndex]);
  14588. cdb.collections[collIndex].data.push(currObject);
  14589. }
  14590. // lower memory pressure and advance iterator
  14591. workarray[lineIndex++] = null;
  14592. }
  14593. return cdb;
  14594. };
  14595. /**
  14596. * Collection level utility function to deserializes a destructured collection.
  14597. *
  14598. * @param {string|array} destructuredSource - destructured representation of collection to inflate
  14599. * @param {object=} options - used to describe format of destructuredSource input
  14600. * @param {int=} [options.delimited=false] - whether source is delimited string or an array
  14601. * @param {string=} options.delimiter - if delimited, this is delimiter to use (if other than default)
  14602. *
  14603. * @returns {array} an array of documents to attach to collection.data.
  14604. * @memberof Loki
  14605. */
  14606. Loki.prototype.deserializeCollection = function(destructuredSource, options) {
  14607. var workarray=[];
  14608. var idx, len;
  14609. options = options || {};
  14610. if (!options.hasOwnProperty("partitioned")) {
  14611. options.partitioned = false;
  14612. }
  14613. if (!options.hasOwnProperty("delimited")) {
  14614. options.delimited = true;
  14615. }
  14616. if (!options.hasOwnProperty("delimiter")) {
  14617. options.delimiter = this.options.destructureDelimiter;
  14618. }
  14619. if (options.delimited) {
  14620. workarray = destructuredSource.split(options.delimiter);
  14621. workarray.pop();
  14622. }
  14623. else {
  14624. workarray = destructuredSource;
  14625. }
  14626. len = workarray.length;
  14627. for (idx=0; idx < len; idx++) {
  14628. workarray[idx] = JSON.parse(workarray[idx]);
  14629. }
  14630. return workarray;
  14631. };
  14632. /**
  14633. * Inflates a loki database from a serialized JSON string
  14634. *
  14635. * @param {string} serializedDb - a serialized loki database string
  14636. * @param {object=} options - apply or override collection level settings
  14637. * @param {bool} options.retainDirtyFlags - whether collection dirty flags will be preserved
  14638. * @memberof Loki
  14639. */
  14640. Loki.prototype.loadJSON = function (serializedDb, options) {
  14641. var dbObject;
  14642. if (serializedDb.length === 0) {
  14643. dbObject = {};
  14644. } else {
  14645. // using option defined in instantiated db not what was in serialized db
  14646. switch (this.options.serializationMethod) {
  14647. case "normal":
  14648. case "pretty": dbObject = JSON.parse(serializedDb); break;
  14649. case "destructured": dbObject = this.deserializeDestructured(serializedDb); break;
  14650. default: dbObject = JSON.parse(serializedDb); break;
  14651. }
  14652. }
  14653. this.loadJSONObject(dbObject, options);
  14654. };
  14655. /**
  14656. * Inflates a loki database from a JS object
  14657. *
  14658. * @param {object} dbObject - a serialized loki database string
  14659. * @param {object=} options - apply or override collection level settings
  14660. * @param {bool} options.retainDirtyFlags - whether collection dirty flags will be preserved
  14661. * @memberof Loki
  14662. */
  14663. Loki.prototype.loadJSONObject = function (dbObject, options) {
  14664. var i = 0,
  14665. len = dbObject.collections ? dbObject.collections.length : 0,
  14666. coll,
  14667. copyColl,
  14668. clen,
  14669. j,
  14670. loader,
  14671. collObj;
  14672. this.name = dbObject.name;
  14673. // restore save throttled boolean only if not defined in options
  14674. if (dbObject.hasOwnProperty('throttledSaves') && options && !options.hasOwnProperty('throttledSaves')) {
  14675. this.throttledSaves = dbObject.throttledSaves;
  14676. }
  14677. this.collections = [];
  14678. function makeLoader(coll) {
  14679. var collOptions = options[coll.name];
  14680. var inflater;
  14681. if(collOptions.proto) {
  14682. inflater = collOptions.inflate || Utils.copyProperties;
  14683. return function(data) {
  14684. var collObj = new(collOptions.proto)();
  14685. inflater(data, collObj);
  14686. return collObj;
  14687. };
  14688. }
  14689. return collOptions.inflate;
  14690. }
  14691. for (i; i < len; i += 1) {
  14692. coll = dbObject.collections[i];
  14693. copyColl = this.addCollection(coll.name, { disableChangesApi: coll.disableChangesApi, disableDeltaChangesApi: coll.disableDeltaChangesApi, disableMeta: coll.disableMeta });
  14694. copyColl.adaptiveBinaryIndices = coll.hasOwnProperty('adaptiveBinaryIndices')?(coll.adaptiveBinaryIndices === true): false;
  14695. copyColl.transactional = coll.transactional;
  14696. copyColl.asyncListeners = coll.asyncListeners;
  14697. copyColl.cloneObjects = coll.cloneObjects;
  14698. copyColl.cloneMethod = coll.cloneMethod || "parse-stringify";
  14699. copyColl.autoupdate = coll.autoupdate;
  14700. copyColl.changes = coll.changes;
  14701. if (options && options.retainDirtyFlags === true) {
  14702. copyColl.dirty = coll.dirty;
  14703. }
  14704. else {
  14705. copyColl.dirty = false;
  14706. }
  14707. // load each element individually
  14708. clen = coll.data.length;
  14709. j = 0;
  14710. if (options && options.hasOwnProperty(coll.name)) {
  14711. loader = makeLoader(coll);
  14712. for (j; j < clen; j++) {
  14713. collObj = loader(coll.data[j]);
  14714. copyColl.data[j] = collObj;
  14715. copyColl.addAutoUpdateObserver(collObj);
  14716. }
  14717. } else {
  14718. for (j; j < clen; j++) {
  14719. copyColl.data[j] = coll.data[j];
  14720. copyColl.addAutoUpdateObserver(copyColl.data[j]);
  14721. }
  14722. }
  14723. copyColl.maxId = (typeof coll.maxId === 'undefined') ? 0 : coll.maxId;
  14724. copyColl.idIndex = coll.idIndex;
  14725. if (typeof (coll.binaryIndices) !== 'undefined') {
  14726. copyColl.binaryIndices = coll.binaryIndices;
  14727. }
  14728. if (typeof coll.transforms !== 'undefined') {
  14729. copyColl.transforms = coll.transforms;
  14730. }
  14731. copyColl.ensureId();
  14732. // regenerate unique indexes
  14733. copyColl.uniqueNames = [];
  14734. if (coll.hasOwnProperty("uniqueNames")) {
  14735. copyColl.uniqueNames = coll.uniqueNames;
  14736. for (j = 0; j < copyColl.uniqueNames.length; j++) {
  14737. copyColl.ensureUniqueIndex(copyColl.uniqueNames[j]);
  14738. }
  14739. }
  14740. // in case they are loading a database created before we added dynamic views, handle undefined
  14741. if (typeof (coll.DynamicViews) === 'undefined') continue;
  14742. // reinflate DynamicViews and attached Resultsets
  14743. for (var idx = 0; idx < coll.DynamicViews.length; idx++) {
  14744. var colldv = coll.DynamicViews[idx];
  14745. var dv = copyColl.addDynamicView(colldv.name, colldv.options);
  14746. dv.resultdata = colldv.resultdata;
  14747. dv.resultsdirty = colldv.resultsdirty;
  14748. dv.filterPipeline = colldv.filterPipeline;
  14749. dv.sortCriteria = colldv.sortCriteria;
  14750. dv.sortFunction = null;
  14751. dv.sortDirty = colldv.sortDirty;
  14752. dv.resultset.filteredrows = colldv.resultset.filteredrows;
  14753. dv.resultset.filterInitialized = colldv.resultset.filterInitialized;
  14754. dv.rematerialize({
  14755. removeWhereFilters: true
  14756. });
  14757. }
  14758. // Upgrade Logic for binary index refactoring at version 1.5
  14759. if (dbObject.databaseVersion < 1.5) {
  14760. // rebuild all indices
  14761. copyColl.ensureAllIndexes(true);
  14762. copyColl.dirty = true;
  14763. }
  14764. }
  14765. };
  14766. /**
  14767. * Emits the close event. In autosave scenarios, if the database is dirty, this will save and disable timer.
  14768. * Does not actually destroy the db.
  14769. *
  14770. * @param {function=} callback - (Optional) if supplied will be registered with close event before emitting.
  14771. * @memberof Loki
  14772. */
  14773. Loki.prototype.close = function (callback) {
  14774. // for autosave scenarios, we will let close perform final save (if dirty)
  14775. // For web use, you might call from window.onbeforeunload to shutdown database, saving pending changes
  14776. if (this.autosave) {
  14777. this.autosaveDisable();
  14778. if (this.autosaveDirty()) {
  14779. this.saveDatabase(callback);
  14780. callback = undefined;
  14781. }
  14782. }
  14783. if (callback) {
  14784. this.on('close', callback);
  14785. }
  14786. this.emit('close');
  14787. };
  14788. /**-------------------------+
  14789. | Changes API |
  14790. +--------------------------*/
  14791. /**
  14792. * The Changes API enables the tracking the changes occurred in the collections since the beginning of the session,
  14793. * so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db)
  14794. */
  14795. /**
  14796. * (Changes API) : takes all the changes stored in each
  14797. * collection and creates a single array for the entire database. If an array of names
  14798. * of collections is passed then only the included collections will be tracked.
  14799. *
  14800. * @param {array=} optional array of collection names. No arg means all collections are processed.
  14801. * @returns {array} array of changes
  14802. * @see private method createChange() in Collection
  14803. * @memberof Loki
  14804. */
  14805. Loki.prototype.generateChangesNotification = function (arrayOfCollectionNames) {
  14806. function getCollName(coll) {
  14807. return coll.name;
  14808. }
  14809. var changes = [],
  14810. selectedCollections = arrayOfCollectionNames || this.collections.map(getCollName);
  14811. this.collections.forEach(function (coll) {
  14812. if (selectedCollections.indexOf(getCollName(coll)) !== -1) {
  14813. changes = changes.concat(coll.getChanges());
  14814. }
  14815. });
  14816. return changes;
  14817. };
  14818. /**
  14819. * (Changes API) - stringify changes for network transmission
  14820. * @returns {string} string representation of the changes
  14821. * @memberof Loki
  14822. */
  14823. Loki.prototype.serializeChanges = function (collectionNamesArray) {
  14824. return JSON.stringify(this.generateChangesNotification(collectionNamesArray));
  14825. };
  14826. /**
  14827. * (Changes API) : clears all the changes in all collections.
  14828. * @memberof Loki
  14829. */
  14830. Loki.prototype.clearChanges = function () {
  14831. this.collections.forEach(function (coll) {
  14832. if (coll.flushChanges) {
  14833. coll.flushChanges();
  14834. }
  14835. });
  14836. };
  14837. /*------------------+
  14838. | PERSISTENCE |
  14839. -------------------*/
  14840. /** there are two build in persistence adapters for internal use
  14841. * fs for use in Nodejs type environments
  14842. * localStorage for use in browser environment
  14843. * defined as helper classes here so its easy and clean to use
  14844. */
  14845. /**
  14846. * In in-memory persistence adapter for an in-memory database.
  14847. * This simple 'key/value' adapter is intended for unit testing and diagnostics.
  14848. *
  14849. * @param {object=} options - memory adapter options
  14850. * @param {boolean} [options.asyncResponses=false] - whether callbacks are invoked asynchronously
  14851. * @param {int} [options.asyncTimeout=50] - timeout in ms to queue callbacks
  14852. * @constructor LokiMemoryAdapter
  14853. */
  14854. function LokiMemoryAdapter(options) {
  14855. this.hashStore = {};
  14856. this.options = options || {};
  14857. if (!this.options.hasOwnProperty('asyncResponses')) {
  14858. this.options.asyncResponses = false;
  14859. }
  14860. if (!this.options.hasOwnProperty('asyncTimeout')) {
  14861. this.options.asyncTimeout = 50; // 50 ms default
  14862. }
  14863. }
  14864. /**
  14865. * Loads a serialized database from its in-memory store.
  14866. * (Loki persistence adapter interface function)
  14867. *
  14868. * @param {string} dbname - name of the database (filename/keyname)
  14869. * @param {function} callback - adapter callback to return load result to caller
  14870. * @memberof LokiMemoryAdapter
  14871. */
  14872. LokiMemoryAdapter.prototype.loadDatabase = function (dbname, callback) {
  14873. var self=this;
  14874. if (this.options.asyncResponses) {
  14875. setTimeout(function() {
  14876. if (self.hashStore.hasOwnProperty(dbname)) {
  14877. callback(self.hashStore[dbname].value);
  14878. }
  14879. else {
  14880. // database doesn't exist, return falsy
  14881. callback (null);
  14882. }
  14883. }, this.options.asyncTimeout);
  14884. }
  14885. else {
  14886. if (this.hashStore.hasOwnProperty(dbname)) {
  14887. // database doesn't exist, return falsy
  14888. callback(this.hashStore[dbname].value);
  14889. }
  14890. else {
  14891. callback (null);
  14892. }
  14893. }
  14894. };
  14895. /**
  14896. * Saves a serialized database to its in-memory store.
  14897. * (Loki persistence adapter interface function)
  14898. *
  14899. * @param {string} dbname - name of the database (filename/keyname)
  14900. * @param {function} callback - adapter callback to return load result to caller
  14901. * @memberof LokiMemoryAdapter
  14902. */
  14903. LokiMemoryAdapter.prototype.saveDatabase = function (dbname, dbstring, callback) {
  14904. var self=this;
  14905. var saveCount;
  14906. if (this.options.asyncResponses) {
  14907. setTimeout(function() {
  14908. saveCount = (self.hashStore.hasOwnProperty(dbname)?self.hashStore[dbname].savecount:0);
  14909. self.hashStore[dbname] = {
  14910. savecount: saveCount+1,
  14911. lastsave: new Date(),
  14912. value: dbstring
  14913. };
  14914. callback();
  14915. }, this.options.asyncTimeout);
  14916. }
  14917. else {
  14918. saveCount = (this.hashStore.hasOwnProperty(dbname)?this.hashStore[dbname].savecount:0);
  14919. this.hashStore[dbname] = {
  14920. savecount: saveCount+1,
  14921. lastsave: new Date(),
  14922. value: dbstring
  14923. };
  14924. callback();
  14925. }
  14926. };
  14927. /**
  14928. * Deletes a database from its in-memory store.
  14929. *
  14930. * @param {string} dbname - name of the database (filename/keyname)
  14931. * @param {function} callback - function to call when done
  14932. * @memberof LokiMemoryAdapter
  14933. */
  14934. LokiMemoryAdapter.prototype.deleteDatabase = function(dbname, callback) {
  14935. if (this.hashStore.hasOwnProperty(dbname)) {
  14936. delete this.hashStore[dbname];
  14937. }
  14938. if (typeof callback === "function") {
  14939. callback();
  14940. }
  14941. };
  14942. /**
  14943. * An adapter for adapters. Converts a non reference mode adapter into a reference mode adapter
  14944. * which can perform destructuring and partioning. Each collection will be stored in its own key/save and
  14945. * only dirty collections will be saved. If you turn on paging with default page size of 25megs and save
  14946. * a 75 meg collection it should use up roughly 3 save slots (key/value pairs sent to inner adapter).
  14947. * A dirty collection that spans three pages will save all three pages again
  14948. * Paging mode was added mainly because Chrome has issues saving 'too large' of a string within a
  14949. * single indexeddb row. If a single document update causes the collection to be flagged as dirty, all
  14950. * of that collection's pages will be written on next save.
  14951. *
  14952. * @param {object} adapter - reference to a 'non-reference' mode loki adapter instance.
  14953. * @param {object=} options - configuration options for partitioning and paging
  14954. * @param {bool} options.paging - (default: false) set to true to enable paging collection data.
  14955. * @param {int} options.pageSize - (default : 25MB) you can use this to limit size of strings passed to inner adapter.
  14956. * @param {string} options.delimiter - allows you to override the default delimeter
  14957. * @constructor LokiPartitioningAdapter
  14958. */
  14959. function LokiPartitioningAdapter(adapter, options) {
  14960. this.mode = "reference";
  14961. this.adapter = null;
  14962. this.options = options || {};
  14963. this.dbref = null;
  14964. this.dbname = "";
  14965. this.pageIterator = {};
  14966. // verify user passed an appropriate adapter
  14967. if (adapter) {
  14968. if (adapter.mode === "reference") {
  14969. throw new Error("LokiPartitioningAdapter cannot be instantiated with a reference mode adapter");
  14970. }
  14971. else {
  14972. this.adapter = adapter;
  14973. }
  14974. }
  14975. else {
  14976. throw new Error("LokiPartitioningAdapter requires a (non-reference mode) adapter on construction");
  14977. }
  14978. // set collection paging defaults
  14979. if (!this.options.hasOwnProperty("paging")) {
  14980. this.options.paging = false;
  14981. }
  14982. // default to page size of 25 megs (can be up to your largest serialized object size larger than this)
  14983. if (!this.options.hasOwnProperty("pageSize")) {
  14984. this.options.pageSize = 25*1024*1024;
  14985. }
  14986. if (!this.options.hasOwnProperty("delimiter")) {
  14987. this.options.delimiter = '$<\n';
  14988. }
  14989. }
  14990. /**
  14991. * Loads a database which was partitioned into several key/value saves.
  14992. * (Loki persistence adapter interface function)
  14993. *
  14994. * @param {string} dbname - name of the database (filename/keyname)
  14995. * @param {function} callback - adapter callback to return load result to caller
  14996. * @memberof LokiPartitioningAdapter
  14997. */
  14998. LokiPartitioningAdapter.prototype.loadDatabase = function (dbname, callback) {
  14999. var self=this;
  15000. this.dbname = dbname;
  15001. this.dbref = new Loki(dbname);
  15002. // load the db container (without data)
  15003. this.adapter.loadDatabase(dbname, function(result) {
  15004. // empty database condition is for inner adapter return null/undefined/falsy
  15005. if (!result) {
  15006. // partition 0 not found so new database, no need to try to load other partitions.
  15007. // return same falsy result to loadDatabase to signify no database exists (yet)
  15008. callback(result);
  15009. return;
  15010. }
  15011. if (typeof result !== "string") {
  15012. callback(new Error("LokiPartitioningAdapter received an unexpected response from inner adapter loadDatabase()"));
  15013. }
  15014. // I will want to use loki destructuring helper methods so i will inflate into typed instance
  15015. var db = JSON.parse(result);
  15016. self.dbref.loadJSONObject(db);
  15017. db = null;
  15018. var clen = self.dbref.collections.length;
  15019. if (self.dbref.collections.length === 0) {
  15020. callback(self.dbref);
  15021. return;
  15022. }
  15023. self.pageIterator = {
  15024. collection: 0,
  15025. pageIndex: 0
  15026. };
  15027. self.loadNextPartition(0, function() {
  15028. callback(self.dbref);
  15029. });
  15030. });
  15031. };
  15032. /**
  15033. * Used to sequentially load each collection partition, one at a time.
  15034. *
  15035. * @param {int} partition - ordinal collection position to load next
  15036. * @param {function} callback - adapter callback to return load result to caller
  15037. */
  15038. LokiPartitioningAdapter.prototype.loadNextPartition = function(partition, callback) {
  15039. var keyname = this.dbname + "." + partition;
  15040. var self=this;
  15041. if (this.options.paging === true) {
  15042. this.pageIterator.pageIndex = 0;
  15043. this.loadNextPage(callback);
  15044. return;
  15045. }
  15046. this.adapter.loadDatabase(keyname, function(result) {
  15047. var data = self.dbref.deserializeCollection(result, { delimited: true, collectionIndex: partition });
  15048. self.dbref.collections[partition].data = data;
  15049. if (++partition < self.dbref.collections.length) {
  15050. self.loadNextPartition(partition, callback);
  15051. }
  15052. else {
  15053. callback();
  15054. }
  15055. });
  15056. };
  15057. /**
  15058. * Used to sequentially load the next page of collection partition, one at a time.
  15059. *
  15060. * @param {function} callback - adapter callback to return load result to caller
  15061. */
  15062. LokiPartitioningAdapter.prototype.loadNextPage = function(callback) {
  15063. // calculate name for next saved page in sequence
  15064. var keyname = this.dbname + "." + this.pageIterator.collection + "." + this.pageIterator.pageIndex;
  15065. var self=this;
  15066. // load whatever page is next in sequence
  15067. this.adapter.loadDatabase(keyname, function(result) {
  15068. var data = result.split(self.options.delimiter);
  15069. result = ""; // free up memory now that we have split it into array
  15070. var dlen = data.length;
  15071. var idx;
  15072. // detect if last page by presence of final empty string element and remove it if so
  15073. var isLastPage = (data[dlen-1] === "");
  15074. if (isLastPage) {
  15075. data.pop();
  15076. dlen = data.length;
  15077. // empty collections are just a delimiter meaning two blank items
  15078. if (data[dlen-1] === "" && dlen === 1) {
  15079. data.pop();
  15080. dlen = data.length;
  15081. }
  15082. }
  15083. // convert stringified array elements to object instances and push to collection data
  15084. for(idx=0; idx < dlen; idx++) {
  15085. self.dbref.collections[self.pageIterator.collection].data.push(JSON.parse(data[idx]));
  15086. data[idx] = null;
  15087. }
  15088. data = [];
  15089. // if last page, we are done with this partition
  15090. if (isLastPage) {
  15091. // if there are more partitions, kick off next partition load
  15092. if (++self.pageIterator.collection < self.dbref.collections.length) {
  15093. self.loadNextPartition(self.pageIterator.collection, callback);
  15094. }
  15095. else {
  15096. callback();
  15097. }
  15098. }
  15099. else {
  15100. self.pageIterator.pageIndex++;
  15101. self.loadNextPage(callback);
  15102. }
  15103. });
  15104. };
  15105. /**
  15106. * Saves a database by partioning into separate key/value saves.
  15107. * (Loki 'reference mode' persistence adapter interface function)
  15108. *
  15109. * @param {string} dbname - name of the database (filename/keyname)
  15110. * @param {object} dbref - reference to database which we will partition and save.
  15111. * @param {function} callback - adapter callback to return load result to caller
  15112. *
  15113. * @memberof LokiPartitioningAdapter
  15114. */
  15115. LokiPartitioningAdapter.prototype.exportDatabase = function(dbname, dbref, callback) {
  15116. var self=this;
  15117. var idx, clen = dbref.collections.length;
  15118. this.dbref = dbref;
  15119. this.dbname = dbname;
  15120. // queue up dirty partitions to be saved
  15121. this.dirtyPartitions = [-1];
  15122. for(idx=0; idx<clen; idx++) {
  15123. if (dbref.collections[idx].dirty) {
  15124. this.dirtyPartitions.push(idx);
  15125. }
  15126. }
  15127. this.saveNextPartition(function(err) {
  15128. callback(err);
  15129. });
  15130. };
  15131. /**
  15132. * Helper method used internally to save each dirty collection, one at a time.
  15133. *
  15134. * @param {function} callback - adapter callback to return load result to caller
  15135. */
  15136. LokiPartitioningAdapter.prototype.saveNextPartition = function(callback) {
  15137. var self=this;
  15138. var partition = this.dirtyPartitions.shift();
  15139. var keyname = this.dbname + ((partition===-1)?"":("." + partition));
  15140. // if we are doing paging and this is collection partition
  15141. if (this.options.paging && partition !== -1) {
  15142. this.pageIterator = {
  15143. collection: partition,
  15144. docIndex: 0,
  15145. pageIndex: 0
  15146. };
  15147. // since saveNextPage recursively calls itself until done, our callback means this whole paged partition is finished
  15148. this.saveNextPage(function(err) {
  15149. if (self.dirtyPartitions.length === 0) {
  15150. callback(err);
  15151. }
  15152. else {
  15153. self.saveNextPartition(callback);
  15154. }
  15155. });
  15156. return;
  15157. }
  15158. // otherwise this is 'non-paged' partioning...
  15159. var result = this.dbref.serializeDestructured({
  15160. partitioned : true,
  15161. delimited: true,
  15162. partition: partition
  15163. });
  15164. this.adapter.saveDatabase(keyname, result, function(err) {
  15165. if (err) {
  15166. callback(err);
  15167. return;
  15168. }
  15169. if (self.dirtyPartitions.length === 0) {
  15170. callback(null);
  15171. }
  15172. else {
  15173. self.saveNextPartition(callback);
  15174. }
  15175. });
  15176. };
  15177. /**
  15178. * Helper method used internally to generate and save the next page of the current (dirty) partition.
  15179. *
  15180. * @param {function} callback - adapter callback to return load result to caller
  15181. */
  15182. LokiPartitioningAdapter.prototype.saveNextPage = function(callback) {
  15183. var self=this;
  15184. var coll = this.dbref.collections[this.pageIterator.collection];
  15185. var keyname = this.dbname + "." + this.pageIterator.collection + "." + this.pageIterator.pageIndex;
  15186. var pageLen=0,
  15187. cdlen = coll.data.length,
  15188. delimlen = this.options.delimiter.length;
  15189. var serializedObject = "",
  15190. pageBuilder = "";
  15191. var doneWithPartition=false,
  15192. doneWithPage=false;
  15193. var pageSaveCallback = function(err) {
  15194. pageBuilder = "";
  15195. if (err) {
  15196. callback(err);
  15197. }
  15198. // update meta properties then continue process by invoking callback
  15199. if (doneWithPartition) {
  15200. callback(null);
  15201. }
  15202. else {
  15203. self.pageIterator.pageIndex++;
  15204. self.saveNextPage(callback);
  15205. }
  15206. };
  15207. if (coll.data.length === 0) {
  15208. doneWithPartition = true;
  15209. }
  15210. while (true) {
  15211. if (!doneWithPartition) {
  15212. // serialize object
  15213. serializedObject = JSON.stringify(coll.data[this.pageIterator.docIndex]);
  15214. pageBuilder += serializedObject;
  15215. pageLen += serializedObject.length;
  15216. // if no more documents in collection to add, we are done with partition
  15217. if (++this.pageIterator.docIndex >= cdlen) doneWithPartition = true;
  15218. }
  15219. // if our current page is bigger than defined pageSize, we are done with page
  15220. if (pageLen >= this.options.pageSize) doneWithPage = true;
  15221. // if not done with current page, need delimiter before next item
  15222. // if done with partition we also want a delmiter to indicate 'end of pages' final empty row
  15223. if (!doneWithPage || doneWithPartition) {
  15224. pageBuilder += this.options.delimiter;
  15225. pageLen += delimlen;
  15226. }
  15227. // if we are done with page save it and pass off to next recursive call or callback
  15228. if (doneWithPartition || doneWithPage) {
  15229. this.adapter.saveDatabase(keyname, pageBuilder, pageSaveCallback);
  15230. return;
  15231. }
  15232. }
  15233. };
  15234. /**
  15235. * A loki persistence adapter which persists using node fs module
  15236. * @constructor LokiFsAdapter
  15237. */
  15238. function LokiFsAdapter() {
  15239. try {
  15240. this.fs = require('fs');
  15241. }catch(e) {
  15242. this.fs = null;
  15243. }
  15244. }
  15245. /**
  15246. * loadDatabase() - Load data from file, will throw an error if the file does not exist
  15247. * @param {string} dbname - the filename of the database to load
  15248. * @param {function} callback - the callback to handle the result
  15249. * @memberof LokiFsAdapter
  15250. */
  15251. LokiFsAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) {
  15252. var self = this;
  15253. this.fs.stat(dbname, function (err, stats) {
  15254. if (!err && stats.isFile()) {
  15255. self.fs.readFile(dbname, {
  15256. encoding: 'utf8'
  15257. }, function readFileCallback(err, data) {
  15258. if (err) {
  15259. callback(new Error(err));
  15260. } else {
  15261. callback(data);
  15262. }
  15263. });
  15264. }
  15265. else {
  15266. callback(null);
  15267. }
  15268. });
  15269. };
  15270. /**
  15271. * saveDatabase() - save data to file, will throw an error if the file can't be saved
  15272. * might want to expand this to avoid dataloss on partial save
  15273. * @param {string} dbname - the filename of the database to load
  15274. * @param {function} callback - the callback to handle the result
  15275. * @memberof LokiFsAdapter
  15276. */
  15277. LokiFsAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) {
  15278. var self = this;
  15279. var tmpdbname = dbname + '~';
  15280. this.fs.writeFile(tmpdbname, dbstring, function writeFileCallback(err) {
  15281. if (err) {
  15282. callback(new Error(err));
  15283. } else {
  15284. self.fs.rename(tmpdbname,dbname,callback);
  15285. }
  15286. });
  15287. };
  15288. /**
  15289. * deleteDatabase() - delete the database file, will throw an error if the
  15290. * file can't be deleted
  15291. * @param {string} dbname - the filename of the database to delete
  15292. * @param {function} callback - the callback to handle the result
  15293. * @memberof LokiFsAdapter
  15294. */
  15295. LokiFsAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) {
  15296. this.fs.unlink(dbname, function deleteDatabaseCallback(err) {
  15297. if (err) {
  15298. callback(new Error(err));
  15299. } else {
  15300. callback();
  15301. }
  15302. });
  15303. };
  15304. /**
  15305. * A loki persistence adapter which persists to web browser's local storage object
  15306. * @constructor LokiLocalStorageAdapter
  15307. */
  15308. function LokiLocalStorageAdapter() {}
  15309. /**
  15310. * loadDatabase() - Load data from localstorage
  15311. * @param {string} dbname - the name of the database to load
  15312. * @param {function} callback - the callback to handle the result
  15313. * @memberof LokiLocalStorageAdapter
  15314. */
  15315. LokiLocalStorageAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) {
  15316. if (localStorageAvailable()) {
  15317. callback(localStorage.getItem(dbname));
  15318. } else {
  15319. callback(new Error('localStorage is not available'));
  15320. }
  15321. };
  15322. /**
  15323. * saveDatabase() - save data to localstorage, will throw an error if the file can't be saved
  15324. * might want to expand this to avoid dataloss on partial save
  15325. * @param {string} dbname - the filename of the database to load
  15326. * @param {function} callback - the callback to handle the result
  15327. * @memberof LokiLocalStorageAdapter
  15328. */
  15329. LokiLocalStorageAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) {
  15330. if (localStorageAvailable()) {
  15331. localStorage.setItem(dbname, dbstring);
  15332. callback(null);
  15333. } else {
  15334. callback(new Error('localStorage is not available'));
  15335. }
  15336. };
  15337. /**
  15338. * deleteDatabase() - delete the database from localstorage, will throw an error if it
  15339. * can't be deleted
  15340. * @param {string} dbname - the filename of the database to delete
  15341. * @param {function} callback - the callback to handle the result
  15342. * @memberof LokiLocalStorageAdapter
  15343. */
  15344. LokiLocalStorageAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) {
  15345. if (localStorageAvailable()) {
  15346. localStorage.removeItem(dbname);
  15347. callback(null);
  15348. } else {
  15349. callback(new Error('localStorage is not available'));
  15350. }
  15351. };
  15352. /**
  15353. * Wait for throttledSaves to complete and invoke your callback when drained or duration is met.
  15354. *
  15355. * @param {function} callback - callback to fire when save queue is drained, it is passed a sucess parameter value
  15356. * @param {object=} options - configuration options
  15357. * @param {boolean} options.recursiveWait - (default: true) if after queue is drained, another save was kicked off, wait for it
  15358. * @param {bool} options.recursiveWaitLimit - (default: false) limit our recursive waiting to a duration
  15359. * @param {int} options.recursiveWaitLimitDelay - (default: 2000) cutoff in ms to stop recursively re-draining
  15360. * @memberof Loki
  15361. */
  15362. Loki.prototype.throttledSaveDrain = function(callback, options) {
  15363. var self = this;
  15364. var now = (new Date()).getTime();
  15365. if (!this.throttledSaves) {
  15366. callback(true);
  15367. }
  15368. options = options || {};
  15369. if (!options.hasOwnProperty('recursiveWait')) {
  15370. options.recursiveWait = true;
  15371. }
  15372. if (!options.hasOwnProperty('recursiveWaitLimit')) {
  15373. options.recursiveWaitLimit = false;
  15374. }
  15375. if (!options.hasOwnProperty('recursiveWaitLimitDuration')) {
  15376. options.recursiveWaitLimitDuration = 2000;
  15377. }
  15378. if (!options.hasOwnProperty('started')) {
  15379. options.started = (new Date()).getTime();
  15380. }
  15381. // if save is pending
  15382. if (this.throttledSaves && this.throttledSavePending) {
  15383. // if we want to wait until we are in a state where there are no pending saves at all
  15384. if (options.recursiveWait) {
  15385. // queue the following meta callback for when it completes
  15386. this.throttledCallbacks.push(function() {
  15387. // if there is now another save pending...
  15388. if (self.throttledSavePending) {
  15389. // if we wish to wait only so long and we have exceeded limit of our waiting, callback with false success value
  15390. if (options.recursiveWaitLimit && (now - options.started > options.recursiveWaitLimitDuration)) {
  15391. callback(false);
  15392. return;
  15393. }
  15394. // it must be ok to wait on next queue drain
  15395. self.throttledSaveDrain(callback, options);
  15396. return;
  15397. }
  15398. // no pending saves so callback with true success
  15399. else {
  15400. callback(true);
  15401. return;
  15402. }
  15403. });
  15404. }
  15405. // just notify when current queue is depleted
  15406. else {
  15407. this.throttledCallbacks.push(callback);
  15408. return;
  15409. }
  15410. }
  15411. // no save pending, just callback
  15412. else {
  15413. callback(true);
  15414. }
  15415. };
  15416. /**
  15417. * Internal load logic, decoupled from throttling/contention logic
  15418. *
  15419. * @param {object} options - not currently used (remove or allow overrides?)
  15420. * @param {function=} callback - (Optional) user supplied async callback / error handler
  15421. */
  15422. Loki.prototype.loadDatabaseInternal = function (options, callback) {
  15423. var cFun = callback || function (err, data) {
  15424. if (err) {
  15425. throw err;
  15426. }
  15427. },
  15428. self = this;
  15429. // the persistenceAdapter should be present if all is ok, but check to be sure.
  15430. if (this.persistenceAdapter !== null) {
  15431. this.persistenceAdapter.loadDatabase(this.filename, function loadDatabaseCallback(dbString) {
  15432. if (typeof (dbString) === 'string') {
  15433. var parseSuccess = false;
  15434. try {
  15435. self.loadJSON(dbString, options || {});
  15436. parseSuccess = true;
  15437. } catch (err) {
  15438. cFun(err);
  15439. }
  15440. if (parseSuccess) {
  15441. cFun(null);
  15442. self.emit('loaded', 'database ' + self.filename + ' loaded');
  15443. }
  15444. } else {
  15445. // falsy result means new database
  15446. if (!dbString) {
  15447. cFun(null);
  15448. self.emit('loaded', 'empty database ' + self.filename + ' loaded');
  15449. return;
  15450. }
  15451. // instanceof error means load faulted
  15452. if (dbString instanceof Error) {
  15453. cFun(dbString);
  15454. return;
  15455. }
  15456. // if adapter has returned an js object (other than null or error) attempt to load from JSON object
  15457. if (typeof (dbString) === "object") {
  15458. self.loadJSONObject(dbString, options || {});
  15459. cFun(null); // return null on success
  15460. self.emit('loaded', 'database ' + self.filename + ' loaded');
  15461. return;
  15462. }
  15463. cFun("unexpected adapter response : " + dbString);
  15464. }
  15465. });
  15466. } else {
  15467. cFun(new Error('persistenceAdapter not configured'));
  15468. }
  15469. };
  15470. /**
  15471. * Handles manually loading from file system, local storage, or adapter (such as indexeddb)
  15472. * This method utilizes loki configuration options (if provided) to determine which
  15473. * persistence method to use, or environment detection (if configuration was not provided).
  15474. * To avoid contention with any throttledSaves, we will drain the save queue first.
  15475. *
  15476. * If you are configured with autosave, you do not need to call this method yourself.
  15477. *
  15478. * @param {object} options - if throttling saves and loads, this controls how we drain save queue before loading
  15479. * @param {boolean} options.recursiveWait - (default: true) wait recursively until no saves are queued
  15480. * @param {bool} options.recursiveWaitLimit - (default: false) limit our recursive waiting to a duration
  15481. * @param {int} options.recursiveWaitLimitDelay - (default: 2000) cutoff in ms to stop recursively re-draining
  15482. * @param {function=} callback - (Optional) user supplied async callback / error handler
  15483. * @memberof Loki
  15484. * @example
  15485. * db.loadDatabase({}, function(err) {
  15486. * if (err) {
  15487. * console.log("error : " + err);
  15488. * }
  15489. * else {
  15490. * console.log("database loaded.");
  15491. * }
  15492. * });
  15493. */
  15494. Loki.prototype.loadDatabase = function (options, callback) {
  15495. var self=this;
  15496. // if throttling disabled, just call internal
  15497. if (!this.throttledSaves) {
  15498. this.loadDatabaseInternal(options, callback);
  15499. return;
  15500. }
  15501. // try to drain any pending saves in the queue to lock it for loading
  15502. this.throttledSaveDrain(function(success) {
  15503. if (success) {
  15504. // pause/throttle saving until loading is done
  15505. self.throttledSavePending = true;
  15506. self.loadDatabaseInternal(options, function(err) {
  15507. // now that we are finished loading, if no saves were throttled, disable flag
  15508. if (self.throttledCallbacks.length === 0) {
  15509. self.throttledSavePending = false;
  15510. }
  15511. // if saves requests came in while loading, kick off new save to kick off resume saves
  15512. else {
  15513. self.saveDatabase();
  15514. }
  15515. if (typeof callback === 'function') {
  15516. callback(err);
  15517. }
  15518. });
  15519. return;
  15520. }
  15521. else {
  15522. if (typeof callback === 'function') {
  15523. callback(new Error("Unable to pause save throttling long enough to read database"));
  15524. }
  15525. }
  15526. }, options);
  15527. };
  15528. /**
  15529. * Internal save logic, decoupled from save throttling logic
  15530. */
  15531. Loki.prototype.saveDatabaseInternal = function (callback) {
  15532. var cFun = callback || function (err) {
  15533. if (err) {
  15534. throw err;
  15535. }
  15536. return;
  15537. },
  15538. self = this;
  15539. // the persistenceAdapter should be present if all is ok, but check to be sure.
  15540. if (this.persistenceAdapter !== null) {
  15541. // check if the adapter is requesting (and supports) a 'reference' mode export
  15542. if (this.persistenceAdapter.mode === "reference" && typeof this.persistenceAdapter.exportDatabase === "function") {
  15543. // filename may seem redundant but loadDatabase will need to expect this same filename
  15544. this.persistenceAdapter.exportDatabase(this.filename, this.copy({removeNonSerializable:true}), function exportDatabaseCallback(err) {
  15545. self.autosaveClearFlags();
  15546. cFun(err);
  15547. });
  15548. }
  15549. // otherwise just pass the serialized database to adapter
  15550. else {
  15551. // persistenceAdapter might be asynchronous, so we must clear `dirty` immediately
  15552. // or autosave won't work if an update occurs between here and the callback
  15553. self.autosaveClearFlags();
  15554. this.persistenceAdapter.saveDatabase(this.filename, self.serialize(), function saveDatabasecallback(err) {
  15555. cFun(err);
  15556. });
  15557. }
  15558. } else {
  15559. cFun(new Error('persistenceAdapter not configured'));
  15560. }
  15561. };
  15562. /**
  15563. * Handles manually saving to file system, local storage, or adapter (such as indexeddb)
  15564. * This method utilizes loki configuration options (if provided) to determine which
  15565. * persistence method to use, or environment detection (if configuration was not provided).
  15566. *
  15567. * If you are configured with autosave, you do not need to call this method yourself.
  15568. *
  15569. * @param {function=} callback - (Optional) user supplied async callback / error handler
  15570. * @memberof Loki
  15571. * @example
  15572. * db.saveDatabase(function(err) {
  15573. * if (err) {
  15574. * console.log("error : " + err);
  15575. * }
  15576. * else {
  15577. * console.log("database saved.");
  15578. * }
  15579. * });
  15580. */
  15581. Loki.prototype.saveDatabase = function (callback) {
  15582. if (!this.throttledSaves) {
  15583. this.saveDatabaseInternal(callback);
  15584. return;
  15585. }
  15586. if (this.throttledSavePending) {
  15587. this.throttledCallbacks.push(callback);
  15588. return;
  15589. }
  15590. var localCallbacks = this.throttledCallbacks;
  15591. this.throttledCallbacks = [];
  15592. localCallbacks.unshift(callback);
  15593. this.throttledSavePending = true;
  15594. var self = this;
  15595. this.saveDatabaseInternal(function(err) {
  15596. self.throttledSavePending = false;
  15597. localCallbacks.forEach(function(pcb) {
  15598. if (typeof pcb === 'function') {
  15599. // Queue the callbacks so we first finish this method execution
  15600. setTimeout(function() {
  15601. pcb(err);
  15602. }, 1);
  15603. }
  15604. });
  15605. // since this is called async, future requests may have come in, if so.. kick off next save
  15606. if (self.throttledCallbacks.length > 0) {
  15607. self.saveDatabase();
  15608. }
  15609. });
  15610. };
  15611. // alias
  15612. Loki.prototype.save = Loki.prototype.saveDatabase;
  15613. /**
  15614. * Handles deleting a database from file system, local
  15615. * storage, or adapter (indexeddb)
  15616. * This method utilizes loki configuration options (if provided) to determine which
  15617. * persistence method to use, or environment detection (if configuration was not provided).
  15618. *
  15619. * @param {function=} callback - (Optional) user supplied async callback / error handler
  15620. * @memberof Loki
  15621. */
  15622. Loki.prototype.deleteDatabase = function (options, callback) {
  15623. var cFun = callback || function (err, data) {
  15624. if (err) {
  15625. throw err;
  15626. }
  15627. };
  15628. // we aren't even using options, so we will support syntax where
  15629. // callback is passed as first and only argument
  15630. if (typeof options === 'function' && !callback) {
  15631. cFun = options;
  15632. }
  15633. // the persistenceAdapter should be present if all is ok, but check to be sure.
  15634. if (this.persistenceAdapter !== null) {
  15635. this.persistenceAdapter.deleteDatabase(this.filename, function deleteDatabaseCallback(err) {
  15636. cFun(err);
  15637. });
  15638. } else {
  15639. cFun(new Error('persistenceAdapter not configured'));
  15640. }
  15641. };
  15642. /**
  15643. * autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database
  15644. *
  15645. * @returns {boolean} - true if database has changed since last autosave, false if not.
  15646. */
  15647. Loki.prototype.autosaveDirty = function () {
  15648. for (var idx = 0; idx < this.collections.length; idx++) {
  15649. if (this.collections[idx].dirty) {
  15650. return true;
  15651. }
  15652. }
  15653. return false;
  15654. };
  15655. /**
  15656. * autosaveClearFlags - resets dirty flags on all collections.
  15657. * Called from saveDatabase() after db is saved.
  15658. *
  15659. */
  15660. Loki.prototype.autosaveClearFlags = function () {
  15661. for (var idx = 0; idx < this.collections.length; idx++) {
  15662. this.collections[idx].dirty = false;
  15663. }
  15664. };
  15665. /**
  15666. * autosaveEnable - begin a javascript interval to periodically save the database.
  15667. *
  15668. * @param {object} options - not currently used (remove or allow overrides?)
  15669. * @param {function=} callback - (Optional) user supplied async callback
  15670. */
  15671. Loki.prototype.autosaveEnable = function (options, callback) {
  15672. this.autosave = true;
  15673. var delay = 5000,
  15674. self = this;
  15675. if (typeof (this.autosaveInterval) !== 'undefined' && this.autosaveInterval !== null) {
  15676. delay = this.autosaveInterval;
  15677. }
  15678. this.autosaveHandle = setInterval(function autosaveHandleInterval() {
  15679. // use of dirty flag will need to be hierarchical since mods are done at collection level with no visibility of 'db'
  15680. // so next step will be to implement collection level dirty flags set on insert/update/remove
  15681. // along with loki level isdirty() function which iterates all collections to see if any are dirty
  15682. if (self.autosaveDirty()) {
  15683. self.saveDatabase(callback);
  15684. }
  15685. }, delay);
  15686. };
  15687. /**
  15688. * autosaveDisable - stop the autosave interval timer.
  15689. *
  15690. */
  15691. Loki.prototype.autosaveDisable = function () {
  15692. if (typeof (this.autosaveHandle) !== 'undefined' && this.autosaveHandle !== null) {
  15693. clearInterval(this.autosaveHandle);
  15694. this.autosaveHandle = null;
  15695. }
  15696. };
  15697. /**
  15698. * Resultset class allowing chainable queries. Intended to be instanced internally.
  15699. * Collection.find(), Collection.where(), and Collection.chain() instantiate this.
  15700. *
  15701. * @example
  15702. * mycollection.chain()
  15703. * .find({ 'doors' : 4 })
  15704. * .where(function(obj) { return obj.name === 'Toyota' })
  15705. * .data();
  15706. *
  15707. * @constructor Resultset
  15708. * @param {Collection} collection - The collection which this Resultset will query against.
  15709. */
  15710. function Resultset(collection, options) {
  15711. options = options || {};
  15712. // retain reference to collection we are querying against
  15713. this.collection = collection;
  15714. this.filteredrows = [];
  15715. this.filterInitialized = false;
  15716. return this;
  15717. }
  15718. /**
  15719. * reset() - Reset the resultset to its initial state.
  15720. *
  15721. * @returns {Resultset} Reference to this resultset, for future chain operations.
  15722. */
  15723. Resultset.prototype.reset = function () {
  15724. if (this.filteredrows.length > 0) {
  15725. this.filteredrows = [];
  15726. }
  15727. this.filterInitialized = false;
  15728. return this;
  15729. };
  15730. /**
  15731. * toJSON() - Override of toJSON to avoid circular references
  15732. *
  15733. */
  15734. Resultset.prototype.toJSON = function () {
  15735. var copy = this.copy();
  15736. copy.collection = null;
  15737. return copy;
  15738. };
  15739. /**
  15740. * Allows you to limit the number of documents passed to next chain operation.
  15741. * A resultset copy() is made to avoid altering original resultset.
  15742. *
  15743. * @param {int} qty - The number of documents to return.
  15744. * @returns {Resultset} Returns a copy of the resultset, limited by qty, for subsequent chain ops.
  15745. * @memberof Resultset
  15746. * // find the two oldest users
  15747. * var result = users.chain().simplesort("age", true).limit(2).data();
  15748. */
  15749. Resultset.prototype.limit = function (qty) {
  15750. // if this has no filters applied, we need to populate filteredrows first
  15751. if (!this.filterInitialized && this.filteredrows.length === 0) {
  15752. this.filteredrows = this.collection.prepareFullDocIndex();
  15753. }
  15754. var rscopy = new Resultset(this.collection);
  15755. rscopy.filteredrows = this.filteredrows.slice(0, qty);
  15756. rscopy.filterInitialized = true;
  15757. return rscopy;
  15758. };
  15759. /**
  15760. * Used for skipping 'pos' number of documents in the resultset.
  15761. *
  15762. * @param {int} pos - Number of documents to skip; all preceding documents are filtered out.
  15763. * @returns {Resultset} Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops.
  15764. * @memberof Resultset
  15765. * // find everyone but the two oldest users
  15766. * var result = users.chain().simplesort("age", true).offset(2).data();
  15767. */
  15768. Resultset.prototype.offset = function (pos) {
  15769. // if this has no filters applied, we need to populate filteredrows first
  15770. if (!this.filterInitialized && this.filteredrows.length === 0) {
  15771. this.filteredrows = this.collection.prepareFullDocIndex();
  15772. }
  15773. var rscopy = new Resultset(this.collection);
  15774. rscopy.filteredrows = this.filteredrows.slice(pos);
  15775. rscopy.filterInitialized = true;
  15776. return rscopy;
  15777. };
  15778. /**
  15779. * copy() - To support reuse of resultset in branched query situations.
  15780. *
  15781. * @returns {Resultset} Returns a copy of the resultset (set) but the underlying document references will be the same.
  15782. * @memberof Resultset
  15783. */
  15784. Resultset.prototype.copy = function () {
  15785. var result = new Resultset(this.collection);
  15786. if (this.filteredrows.length > 0) {
  15787. result.filteredrows = this.filteredrows.slice();
  15788. }
  15789. result.filterInitialized = this.filterInitialized;
  15790. return result;
  15791. };
  15792. /**
  15793. * Alias of copy()
  15794. * @memberof Resultset
  15795. */
  15796. Resultset.prototype.branch = Resultset.prototype.copy;
  15797. /**
  15798. * transform() - executes a named collection transform or raw array of transform steps against the resultset.
  15799. *
  15800. * @param transform {(string|array)} - name of collection transform or raw transform array
  15801. * @param parameters {object=} - (Optional) object property hash of parameters, if the transform requires them.
  15802. * @returns {Resultset} either (this) resultset or a clone of of this resultset (depending on steps)
  15803. * @memberof Resultset
  15804. * @example
  15805. * users.addTransform('CountryFilter', [
  15806. * {
  15807. * type: 'find',
  15808. * value: {
  15809. * 'country': { $eq: '[%lktxp]Country' }
  15810. * }
  15811. * },
  15812. * {
  15813. * type: 'simplesort',
  15814. * property: 'age',
  15815. * options: { desc: false}
  15816. * }
  15817. * ]);
  15818. * var results = users.chain().transform("CountryFilter", { Country: 'fr' }).data();
  15819. */
  15820. Resultset.prototype.transform = function (transform, parameters) {
  15821. var idx,
  15822. step,
  15823. rs = this;
  15824. // if transform is name, then do lookup first
  15825. if (typeof transform === 'string') {
  15826. if (this.collection.transforms.hasOwnProperty(transform)) {
  15827. transform = this.collection.transforms[transform];
  15828. }
  15829. }
  15830. // either they passed in raw transform array or we looked it up, so process
  15831. if (typeof transform !== 'object' || !Array.isArray(transform)) {
  15832. throw new Error("Invalid transform");
  15833. }
  15834. if (typeof parameters !== 'undefined') {
  15835. transform = Utils.resolveTransformParams(transform, parameters);
  15836. }
  15837. for (idx = 0; idx < transform.length; idx++) {
  15838. step = transform[idx];
  15839. switch (step.type) {
  15840. case "find":
  15841. rs.find(step.value);
  15842. break;
  15843. case "where":
  15844. rs.where(step.value);
  15845. break;
  15846. case "simplesort":
  15847. rs.simplesort(step.property, step.desc || step.options);
  15848. break;
  15849. case "compoundsort":
  15850. rs.compoundsort(step.value);
  15851. break;
  15852. case "sort":
  15853. rs.sort(step.value);
  15854. break;
  15855. case "limit":
  15856. rs = rs.limit(step.value);
  15857. break; // limit makes copy so update reference
  15858. case "offset":
  15859. rs = rs.offset(step.value);
  15860. break; // offset makes copy so update reference
  15861. case "map":
  15862. rs = rs.map(step.value, step.dataOptions);
  15863. break;
  15864. case "eqJoin":
  15865. rs = rs.eqJoin(step.joinData, step.leftJoinKey, step.rightJoinKey, step.mapFun, step.dataOptions);
  15866. break;
  15867. // following cases break chain by returning array data so make any of these last in transform steps
  15868. case "mapReduce":
  15869. rs = rs.mapReduce(step.mapFunction, step.reduceFunction);
  15870. break;
  15871. // following cases update documents in current filtered resultset (use carefully)
  15872. case "update":
  15873. rs.update(step.value);
  15874. break;
  15875. case "remove":
  15876. rs.remove();
  15877. break;
  15878. default:
  15879. break;
  15880. }
  15881. }
  15882. return rs;
  15883. };
  15884. /**
  15885. * User supplied compare function is provided two documents to compare. (chainable)
  15886. * @example
  15887. * rslt.sort(function(obj1, obj2) {
  15888. * if (obj1.name === obj2.name) return 0;
  15889. * if (obj1.name > obj2.name) return 1;
  15890. * if (obj1.name < obj2.name) return -1;
  15891. * });
  15892. *
  15893. * @param {function} comparefun - A javascript compare function used for sorting.
  15894. * @returns {Resultset} Reference to this resultset, sorted, for future chain operations.
  15895. * @memberof Resultset
  15896. */
  15897. Resultset.prototype.sort = function (comparefun) {
  15898. // if this has no filters applied, just we need to populate filteredrows first
  15899. if (!this.filterInitialized && this.filteredrows.length === 0) {
  15900. this.filteredrows = this.collection.prepareFullDocIndex();
  15901. }
  15902. var wrappedComparer =
  15903. (function (userComparer, data) {
  15904. return function (a, b) {
  15905. return userComparer(data[a], data[b]);
  15906. };
  15907. })(comparefun, this.collection.data);
  15908. this.filteredrows.sort(wrappedComparer);
  15909. return this;
  15910. };
  15911. /**
  15912. * Simpler, loose evaluation for user to sort based on a property name. (chainable).
  15913. * Sorting based on the same lt/gt helper functions used for binary indices.
  15914. *
  15915. * @param {string} propname - name of property to sort by.
  15916. * @param {object|bool=} options - boolean to specify if isdescending, or options object
  15917. * @param {boolean} [options.desc=false] - whether to sort descending
  15918. * @param {boolean} [options.disableIndexIntersect=false] - whether we should explicity not use array intersection.
  15919. * @param {boolean} [options.forceIndexIntersect=false] - force array intersection (if binary index exists).
  15920. * @param {boolean} [options.useJavascriptSorting=false] - whether results are sorted via basic javascript sort.
  15921. * @returns {Resultset} Reference to this resultset, sorted, for future chain operations.
  15922. * @memberof Resultset
  15923. * @example
  15924. * var results = users.chain().simplesort('age').data();
  15925. */
  15926. Resultset.prototype.simplesort = function (propname, options) {
  15927. var eff,
  15928. targetEff = 10,
  15929. dc = this.collection.data.length,
  15930. frl = this.filteredrows.length,
  15931. hasBinaryIndex = this.collection.binaryIndices.hasOwnProperty(propname);
  15932. if (typeof (options) === 'undefined' || options === false) {
  15933. options = { desc: false };
  15934. }
  15935. if (options === true) {
  15936. options = { desc: true };
  15937. }
  15938. // if nothing in filtered rows array...
  15939. if (frl === 0) {
  15940. // if the filter is initialized to be empty resultset, do nothing
  15941. if (this.filterInitialized) {
  15942. return this;
  15943. }
  15944. // otherwise no filters applied implies all documents, so we need to populate filteredrows first
  15945. // if we have a binary index, we can just use that instead of sorting (again)
  15946. if (this.collection.binaryIndices.hasOwnProperty(propname)) {
  15947. // make sure index is up-to-date
  15948. this.collection.ensureIndex(propname);
  15949. // copy index values into filteredrows
  15950. this.filteredrows = this.collection.binaryIndices[propname].values.slice(0);
  15951. if (options.desc) {
  15952. this.filteredrows.reverse();
  15953. }
  15954. // we are done, return this (resultset) for further chain ops
  15955. return this;
  15956. }
  15957. // otherwise initialize array for sort below
  15958. else {
  15959. // build full document index (to be sorted subsequently)
  15960. this.filteredrows = this.collection.prepareFullDocIndex();
  15961. }
  15962. }
  15963. // otherwise we had results to begin with, see if we qualify for index intercept optimization
  15964. else {
  15965. // If already filtered, but we want to leverage binary index on sort.
  15966. // This will use custom array intection algorithm.
  15967. if (!options.disableIndexIntersect && hasBinaryIndex) {
  15968. // calculate filter efficiency
  15969. eff = dc/frl;
  15970. // when javascript sort fallback is enabled, you generally need more than ~17% of total docs in resultset
  15971. // before array intersect is determined to be the faster algorithm, otherwise leave at 10% for loki sort.
  15972. if (options.useJavascriptSorting) {
  15973. targetEff = 6;
  15974. }
  15975. // anything more than ratio of 10:1 (total documents/current results) should use old sort code path
  15976. // So we will only use array intersection if you have more than 10% of total docs in your current resultset.
  15977. if (eff <= targetEff || options.forceIndexIntersect) {
  15978. var idx, fr=this.filteredrows;
  15979. var io = {};
  15980. // set up hashobject for simple 'inclusion test' with existing (filtered) results
  15981. for(idx=0; idx<frl; idx++) {
  15982. io[fr[idx]] = true;
  15983. }
  15984. // grab full sorted binary index array
  15985. var pv = this.collection.binaryIndices[propname].values;
  15986. // filter by existing results
  15987. this.filteredrows = pv.filter(function(n) { return io[n]; });
  15988. if (options.desc) {
  15989. this.filteredrows.reverse();
  15990. }
  15991. return this;
  15992. }
  15993. }
  15994. }
  15995. // at this point, we will not be able to leverage binary index so we will have to do an array sort
  15996. // if we have opted to use simplified javascript comparison function...
  15997. if (options.useJavascriptSorting) {
  15998. return this.sort(function(obj1, obj2) {
  15999. if (obj1[propname] === obj2[propname]) return 0;
  16000. if (obj1[propname] > obj2[propname]) return 1;
  16001. if (obj1[propname] < obj2[propname]) return -1;
  16002. });
  16003. }
  16004. // otherwise use loki sort which will return same results if column is indexed or not
  16005. var wrappedComparer =
  16006. (function (prop, desc, data) {
  16007. var val1, val2, arr;
  16008. return function (a, b) {
  16009. if (~prop.indexOf('.')) {
  16010. arr = prop.split('.');
  16011. val1 = Utils.getIn(data[a], arr, true);
  16012. val2 = Utils.getIn(data[b], arr, true);
  16013. } else {
  16014. val1 = data[a][prop];
  16015. val2 = data[b][prop];
  16016. }
  16017. return sortHelper(val1, val2, desc);
  16018. };
  16019. })(propname, options.desc, this.collection.data);
  16020. this.filteredrows.sort(wrappedComparer);
  16021. return this;
  16022. };
  16023. /**
  16024. * Allows sorting a resultset based on multiple columns.
  16025. * @example
  16026. * // to sort by age and then name (both ascending)
  16027. * rs.compoundsort(['age', 'name']);
  16028. * // to sort by age (ascending) and then by name (descending)
  16029. * rs.compoundsort(['age', ['name', true]]);
  16030. *
  16031. * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order
  16032. * @returns {Resultset} Reference to this resultset, sorted, for future chain operations.
  16033. * @memberof Resultset
  16034. */
  16035. Resultset.prototype.compoundsort = function (properties) {
  16036. if (properties.length === 0) {
  16037. throw new Error("Invalid call to compoundsort, need at least one property");
  16038. }
  16039. var prop;
  16040. if (properties.length === 1) {
  16041. prop = properties[0];
  16042. if (Array.isArray(prop)) {
  16043. return this.simplesort(prop[0], prop[1]);
  16044. }
  16045. return this.simplesort(prop, false);
  16046. }
  16047. // unify the structure of 'properties' to avoid checking it repeatedly while sorting
  16048. for (var i = 0, len = properties.length; i < len; i += 1) {
  16049. prop = properties[i];
  16050. if (!Array.isArray(prop)) {
  16051. properties[i] = [prop, false];
  16052. }
  16053. }
  16054. // if this has no filters applied, just we need to populate filteredrows first
  16055. if (!this.filterInitialized && this.filteredrows.length === 0) {
  16056. this.filteredrows = this.collection.prepareFullDocIndex();
  16057. }
  16058. var wrappedComparer =
  16059. (function (props, data) {
  16060. return function (a, b) {
  16061. return compoundeval(props, data[a], data[b]);
  16062. };
  16063. })(properties, this.collection.data);
  16064. this.filteredrows.sort(wrappedComparer);
  16065. return this;
  16066. };
  16067. /**
  16068. * findOr() - oversee the operation of OR'ed query expressions.
  16069. * OR'ed expression evaluation runs each expression individually against the full collection,
  16070. * and finally does a set OR on each expression's results.
  16071. * Each evaluation can utilize a binary index to prevent multiple linear array scans.
  16072. *
  16073. * @param {array} expressionArray - array of expressions
  16074. * @returns {Resultset} this resultset for further chain ops.
  16075. */
  16076. Resultset.prototype.findOr = function (expressionArray) {
  16077. var fr = null,
  16078. fri = 0,
  16079. frlen = 0,
  16080. docset = [],
  16081. idxset = [],
  16082. idx = 0,
  16083. origCount = this.count();
  16084. // If filter is already initialized, then we query against only those items already in filter.
  16085. // This means no index utilization for fields, so hopefully its filtered to a smallish filteredrows.
  16086. for (var ei = 0, elen = expressionArray.length; ei < elen; ei++) {
  16087. // we need to branch existing query to run each filter separately and combine results
  16088. fr = this.branch().find(expressionArray[ei]).filteredrows;
  16089. frlen = fr.length;
  16090. // if the find operation did not reduce the initial set, then the initial set is the actual result
  16091. if (frlen === origCount) {
  16092. return this;
  16093. }
  16094. // add any document 'hits'
  16095. for (fri = 0; fri < frlen; fri++) {
  16096. idx = fr[fri];
  16097. if (idxset[idx] === undefined) {
  16098. idxset[idx] = true;
  16099. docset.push(idx);
  16100. }
  16101. }
  16102. }
  16103. this.filteredrows = docset;
  16104. this.filterInitialized = true;
  16105. return this;
  16106. };
  16107. Resultset.prototype.$or = Resultset.prototype.findOr;
  16108. // precompile recursively
  16109. function precompileQuery (operator, value) {
  16110. // for regex ops, precompile
  16111. if (operator === '$regex') {
  16112. if (Array.isArray(value)) {
  16113. value = new RegExp(value[0], value[1]);
  16114. } else if (!(value instanceof RegExp)) {
  16115. value = new RegExp(value);
  16116. }
  16117. }
  16118. else if (typeof value === 'object') {
  16119. for (var key in value) {
  16120. if (key === '$regex' || typeof value[key] === 'object') {
  16121. value[key] = precompileQuery(key, value[key]);
  16122. }
  16123. }
  16124. }
  16125. return value;
  16126. }
  16127. /**
  16128. * findAnd() - oversee the operation of AND'ed query expressions.
  16129. * AND'ed expression evaluation runs each expression progressively against the full collection,
  16130. * internally utilizing existing chained resultset functionality.
  16131. * Only the first filter can utilize a binary index.
  16132. *
  16133. * @param {array} expressionArray - array of expressions
  16134. * @returns {Resultset} this resultset for further chain ops.
  16135. */
  16136. Resultset.prototype.findAnd = function (expressionArray) {
  16137. // we have already implementing method chaining in this (our Resultset class)
  16138. // so lets just progressively apply user supplied and filters
  16139. for (var i = 0, len = expressionArray.length; i < len; i++) {
  16140. if (this.count() === 0) {
  16141. return this;
  16142. }
  16143. this.find(expressionArray[i]);
  16144. }
  16145. return this;
  16146. };
  16147. Resultset.prototype.$and = Resultset.prototype.findAnd;
  16148. /**
  16149. * Used for querying via a mongo-style query object.
  16150. *
  16151. * @param {object} query - A mongo-style query object used for filtering current results.
  16152. * @param {boolean=} firstOnly - (Optional) Used by collection.findOne()
  16153. * @returns {Resultset} this resultset for further chain ops.
  16154. * @memberof Resultset
  16155. * @example
  16156. * var over30 = users.chain().find({ age: { $gte: 30 } }).data();
  16157. */
  16158. Resultset.prototype.find = function (query, firstOnly) {
  16159. if (this.collection.data.length === 0) {
  16160. this.filteredrows = [];
  16161. this.filterInitialized = true;
  16162. return this;
  16163. }
  16164. var queryObject = query || 'getAll',
  16165. p,
  16166. property,
  16167. queryObjectOp,
  16168. obj,
  16169. operator,
  16170. value,
  16171. key,
  16172. searchByIndex = false,
  16173. result = [],
  16174. filters = [],
  16175. index = null;
  16176. // flag if this was invoked via findOne()
  16177. firstOnly = firstOnly || false;
  16178. if (typeof queryObject === 'object') {
  16179. for (p in queryObject) {
  16180. obj = {};
  16181. obj[p] = queryObject[p];
  16182. filters.push(obj);
  16183. if (hasOwnProperty.call(queryObject, p)) {
  16184. property = p;
  16185. queryObjectOp = queryObject[p];
  16186. }
  16187. }
  16188. // if more than one expression in single query object,
  16189. // convert implicit $and to explicit $and
  16190. if (filters.length > 1) {
  16191. return this.find({ '$and': filters }, firstOnly);
  16192. }
  16193. }
  16194. // apply no filters if they want all
  16195. if (!property || queryObject === 'getAll') {
  16196. if (firstOnly) {
  16197. this.filteredrows = (this.collection.data.length > 0)?[0]: [];
  16198. this.filterInitialized = true;
  16199. }
  16200. return this;
  16201. }
  16202. // injecting $and and $or expression tree evaluation here.
  16203. if (property === '$and' || property === '$or') {
  16204. this[property](queryObjectOp);
  16205. // for chained find with firstonly,
  16206. if (firstOnly && this.filteredrows.length > 1) {
  16207. this.filteredrows = this.filteredrows.slice(0, 1);
  16208. }
  16209. return this;
  16210. }
  16211. // see if query object is in shorthand mode (assuming eq operator)
  16212. if (queryObjectOp === null || (typeof queryObjectOp !== 'object' || queryObjectOp instanceof Date)) {
  16213. operator = '$eq';
  16214. value = queryObjectOp;
  16215. } else if (typeof queryObjectOp === 'object') {
  16216. for (key in queryObjectOp) {
  16217. if (hasOwnProperty.call(queryObjectOp, key)) {
  16218. operator = key;
  16219. value = queryObjectOp[key];
  16220. break;
  16221. }
  16222. }
  16223. } else {
  16224. throw new Error('Do not know what you want to do.');
  16225. }
  16226. if (operator === '$regex' || typeof value === 'object') {
  16227. value = precompileQuery(operator, value);
  16228. }
  16229. // if user is deep querying the object such as find('name.first': 'odin')
  16230. var usingDotNotation = (property.indexOf('.') !== -1);
  16231. // if an index exists for the property being queried against, use it
  16232. // for now only enabling where it is the first filter applied and prop is indexed
  16233. var doIndexCheck = !this.filterInitialized;
  16234. if (doIndexCheck && this.collection.binaryIndices[property] && indexedOps[operator]) {
  16235. // this is where our lazy index rebuilding will take place
  16236. // basically we will leave all indexes dirty until we need them
  16237. // so here we will rebuild only the index tied to this property
  16238. // ensureIndex() will only rebuild if flagged as dirty since we are not passing force=true param
  16239. if (this.collection.adaptiveBinaryIndices !== true) {
  16240. this.collection.ensureIndex(property);
  16241. }
  16242. searchByIndex = true;
  16243. index = this.collection.binaryIndices[property];
  16244. }
  16245. // the comparison function
  16246. var fun = LokiOps[operator];
  16247. // "shortcut" for collection data
  16248. var t = this.collection.data;
  16249. // filter data length
  16250. var i = 0,
  16251. len = 0;
  16252. // Query executed differently depending on :
  16253. // - whether the property being queried has an index defined
  16254. // - if chained, we handle first pass differently for initial filteredrows[] population
  16255. //
  16256. // For performance reasons, each case has its own if block to minimize in-loop calculations
  16257. var filter, rowIdx = 0;
  16258. // If the filteredrows[] is already initialized, use it
  16259. if (this.filterInitialized) {
  16260. filter = this.filteredrows;
  16261. len = filter.length;
  16262. // currently supporting dot notation for non-indexed conditions only
  16263. if (usingDotNotation) {
  16264. property = property.split('.');
  16265. for(i=0; i<len; i++) {
  16266. rowIdx = filter[i];
  16267. if (dotSubScan(t[rowIdx], property, fun, value)) {
  16268. result.push(rowIdx);
  16269. }
  16270. }
  16271. } else {
  16272. for(i=0; i<len; i++) {
  16273. rowIdx = filter[i];
  16274. if (fun(t[rowIdx][property], value)) {
  16275. result.push(rowIdx);
  16276. }
  16277. }
  16278. }
  16279. }
  16280. // first chained query so work against data[] but put results in filteredrows
  16281. else {
  16282. // if not searching by index
  16283. if (!searchByIndex) {
  16284. len = t.length;
  16285. if (usingDotNotation) {
  16286. property = property.split('.');
  16287. for(i=0; i<len; i++) {
  16288. if (dotSubScan(t[i], property, fun, value)) {
  16289. result.push(i);
  16290. if (firstOnly) {
  16291. this.filteredrows = result;
  16292. this.filterInitialized = true;
  16293. return this;
  16294. }
  16295. }
  16296. }
  16297. } else {
  16298. for(i=0; i<len; i++) {
  16299. if (fun(t[i][property], value)) {
  16300. result.push(i);
  16301. if (firstOnly) {
  16302. this.filteredrows = result;
  16303. this.filterInitialized = true;
  16304. return this;
  16305. }
  16306. }
  16307. }
  16308. }
  16309. } else {
  16310. // search by index
  16311. var segm = this.collection.calculateRange(operator, property, value);
  16312. if (operator !== '$in') {
  16313. for (i = segm[0]; i <= segm[1]; i++) {
  16314. if (indexedOps[operator] !== true) {
  16315. // must be a function, implying 2nd phase filtering of results from calculateRange
  16316. if (indexedOps[operator](Utils.getIn(t[index.values[i]], property, usingDotNotation), value)) {
  16317. result.push(index.values[i]);
  16318. if (firstOnly) {
  16319. this.filteredrows = result;
  16320. this.filterInitialized = true;
  16321. return this;
  16322. }
  16323. }
  16324. }
  16325. else {
  16326. result.push(index.values[i]);
  16327. if (firstOnly) {
  16328. this.filteredrows = result;
  16329. this.filterInitialized = true;
  16330. return this;
  16331. }
  16332. }
  16333. }
  16334. } else {
  16335. for (i = 0, len = segm.length; i < len; i++) {
  16336. result.push(index.values[segm[i]]);
  16337. if (firstOnly) {
  16338. this.filteredrows = result;
  16339. this.filterInitialized = true;
  16340. return this;
  16341. }
  16342. }
  16343. }
  16344. }
  16345. }
  16346. this.filteredrows = result;
  16347. this.filterInitialized = true; // next time work against filteredrows[]
  16348. return this;
  16349. };
  16350. /**
  16351. * where() - Used for filtering via a javascript filter function.
  16352. *
  16353. * @param {function} fun - A javascript function used for filtering current results by.
  16354. * @returns {Resultset} this resultset for further chain ops.
  16355. * @memberof Resultset
  16356. * @example
  16357. * var over30 = users.chain().where(function(obj) { return obj.age >= 30; }.data();
  16358. */
  16359. Resultset.prototype.where = function (fun) {
  16360. var viewFunction,
  16361. result = [];
  16362. if ('function' === typeof fun) {
  16363. viewFunction = fun;
  16364. } else {
  16365. throw new TypeError('Argument is not a stored view or a function');
  16366. }
  16367. try {
  16368. // If the filteredrows[] is already initialized, use it
  16369. if (this.filterInitialized) {
  16370. var j = this.filteredrows.length;
  16371. while (j--) {
  16372. if (viewFunction(this.collection.data[this.filteredrows[j]]) === true) {
  16373. result.push(this.filteredrows[j]);
  16374. }
  16375. }
  16376. this.filteredrows = result;
  16377. return this;
  16378. }
  16379. // otherwise this is initial chained op, work against data, push into filteredrows[]
  16380. else {
  16381. var k = this.collection.data.length;
  16382. while (k--) {
  16383. if (viewFunction(this.collection.data[k]) === true) {
  16384. result.push(k);
  16385. }
  16386. }
  16387. this.filteredrows = result;
  16388. this.filterInitialized = true;
  16389. return this;
  16390. }
  16391. } catch (err) {
  16392. throw err;
  16393. }
  16394. };
  16395. /**
  16396. * count() - returns the number of documents in the resultset.
  16397. *
  16398. * @returns {number} The number of documents in the resultset.
  16399. * @memberof Resultset
  16400. * @example
  16401. * var over30Count = users.chain().find({ age: { $gte: 30 } }).count();
  16402. */
  16403. Resultset.prototype.count = function () {
  16404. if (this.filterInitialized) {
  16405. return this.filteredrows.length;
  16406. }
  16407. return this.collection.count();
  16408. };
  16409. /**
  16410. * Terminates the chain and returns array of filtered documents
  16411. *
  16412. * @param {object=} options - allows specifying 'forceClones' and 'forceCloneMethod' options.
  16413. * @param {boolean} options.forceClones - Allows forcing the return of cloned objects even when
  16414. * the collection is not configured for clone object.
  16415. * @param {string} options.forceCloneMethod - Allows overriding the default or collection specified cloning method.
  16416. * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'
  16417. * @param {bool} options.removeMeta - Will force clones and strip $loki and meta properties from documents
  16418. *
  16419. * @returns {array} Array of documents in the resultset
  16420. * @memberof Resultset
  16421. * @example
  16422. * var resutls = users.chain().find({ age: 34 }).data();
  16423. */
  16424. Resultset.prototype.data = function (options) {
  16425. var result = [],
  16426. data = this.collection.data,
  16427. obj,
  16428. len,
  16429. i,
  16430. method;
  16431. options = options || {};
  16432. // if user opts to strip meta, then force clones and use 'shallow' if 'force' options are not present
  16433. if (options.removeMeta && !options.forceClones) {
  16434. options.forceClones = true;
  16435. options.forceCloneMethod = options.forceCloneMethod || 'shallow';
  16436. }
  16437. // if collection has delta changes active, then force clones and use 'parse-stringify' for effective change tracking of nested objects
  16438. if (!this.collection.disableDeltaChangesApi) {
  16439. options.forceClones = true;
  16440. options.forceCloneMethod = 'parse-stringify';
  16441. }
  16442. // if this has no filters applied, just return collection.data
  16443. if (!this.filterInitialized) {
  16444. if (this.filteredrows.length === 0) {
  16445. // determine whether we need to clone objects or not
  16446. if (this.collection.cloneObjects || options.forceClones) {
  16447. len = data.length;
  16448. method = options.forceCloneMethod || this.collection.cloneMethod;
  16449. for (i = 0; i < len; i++) {
  16450. obj = clone(data[i], method);
  16451. if (options.removeMeta) {
  16452. delete obj.$loki;
  16453. delete obj.meta;
  16454. }
  16455. result.push(obj);
  16456. }
  16457. return result;
  16458. }
  16459. // otherwise we are not cloning so return sliced array with same object references
  16460. else {
  16461. return data.slice();
  16462. }
  16463. } else {
  16464. // filteredrows must have been set manually, so use it
  16465. this.filterInitialized = true;
  16466. }
  16467. }
  16468. var fr = this.filteredrows;
  16469. len = fr.length;
  16470. if (this.collection.cloneObjects || options.forceClones) {
  16471. method = options.forceCloneMethod || this.collection.cloneMethod;
  16472. for (i = 0; i < len; i++) {
  16473. obj = clone(data[fr[i]], method);
  16474. if (options.removeMeta) {
  16475. delete obj.$loki;
  16476. delete obj.meta;
  16477. }
  16478. result.push(obj);
  16479. }
  16480. } else {
  16481. for (i = 0; i < len; i++) {
  16482. result.push(data[fr[i]]);
  16483. }
  16484. }
  16485. return result;
  16486. };
  16487. /**
  16488. * Used to run an update operation on all documents currently in the resultset.
  16489. *
  16490. * @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object.
  16491. * @returns {Resultset} this resultset for further chain ops.
  16492. * @memberof Resultset
  16493. * @example
  16494. * users.chain().find({ country: 'de' }).update(function(user) {
  16495. * user.phoneFormat = "+49 AAAA BBBBBB";
  16496. * });
  16497. */
  16498. Resultset.prototype.update = function (updateFunction) {
  16499. if (typeof (updateFunction) !== "function") {
  16500. throw new TypeError('Argument is not a function');
  16501. }
  16502. // if this has no filters applied, we need to populate filteredrows first
  16503. if (!this.filterInitialized && this.filteredrows.length === 0) {
  16504. this.filteredrows = this.collection.prepareFullDocIndex();
  16505. }
  16506. var obj, len = this.filteredrows.length,
  16507. rcd = this.collection.data;
  16508. // pass in each document object currently in resultset to user supplied updateFunction
  16509. for (var idx = 0; idx < len; idx++) {
  16510. // if we have cloning option specified or are doing differential delta changes, clone object first
  16511. if (this.collection.cloneObjects || !this.collection.disableDeltaChangesApi) {
  16512. obj = clone(rcd[this.filteredrows[idx]], this.collection.cloneMethod);
  16513. updateFunction(obj);
  16514. this.collection.update(obj);
  16515. }
  16516. else {
  16517. // no need to clone, so just perform update on collection data object instance
  16518. updateFunction(rcd[this.filteredrows[idx]]);
  16519. this.collection.update(rcd[this.filteredrows[idx]]);
  16520. }
  16521. }
  16522. return this;
  16523. };
  16524. /**
  16525. * Removes all document objects which are currently in resultset from collection (as well as resultset)
  16526. *
  16527. * @returns {Resultset} this (empty) resultset for further chain ops.
  16528. * @memberof Resultset
  16529. * @example
  16530. * // remove users inactive since 1/1/2001
  16531. * users.chain().find({ lastActive: { $lte: new Date("1/1/2001").getTime() } }).remove();
  16532. */
  16533. Resultset.prototype.remove = function () {
  16534. // if this has no filters applied, we need to populate filteredrows first
  16535. if (!this.filterInitialized && this.filteredrows.length === 0) {
  16536. this.filteredrows = this.collection.prepareFullDocIndex();
  16537. }
  16538. this.collection.removeBatchByPositions(this.filteredrows);
  16539. this.filteredrows = [];
  16540. return this;
  16541. };
  16542. /**
  16543. * data transformation via user supplied functions
  16544. *
  16545. * @param {function} mapFunction - this function accepts a single document for you to transform and return
  16546. * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value
  16547. * @returns {value} The output of your reduceFunction
  16548. * @memberof Resultset
  16549. * @example
  16550. * var db = new loki("order.db");
  16551. * var orders = db.addCollection("orders");
  16552. * orders.insert([{ qty: 4, unitCost: 100.00 }, { qty: 10, unitCost: 999.99 }, { qty: 2, unitCost: 49.99 }]);
  16553. *
  16554. * function mapfun (obj) { return obj.qty*obj.unitCost };
  16555. * function reducefun(array) {
  16556. * var grandTotal=0;
  16557. * array.forEach(function(orderTotal) { grandTotal += orderTotal; });
  16558. * return grandTotal;
  16559. * }
  16560. * var grandOrderTotal = orders.chain().mapReduce(mapfun, reducefun);
  16561. * console.log(grandOrderTotal);
  16562. */
  16563. Resultset.prototype.mapReduce = function (mapFunction, reduceFunction) {
  16564. try {
  16565. return reduceFunction(this.data().map(mapFunction));
  16566. } catch (err) {
  16567. throw err;
  16568. }
  16569. };
  16570. /**
  16571. * eqJoin() - Left joining two sets of data. Join keys can be defined or calculated properties
  16572. * eqJoin expects the right join key values to be unique. Otherwise left data will be joined on the last joinData object with that key
  16573. * @param {Array|Resultset|Collection} joinData - Data array to join to.
  16574. * @param {(string|function)} leftJoinKey - Property name in this result set to join on or a function to produce a value to join on
  16575. * @param {(string|function)} rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on
  16576. * @param {function=} mapFun - (Optional) A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject}
  16577. * @param {object=} dataOptions - options to data() before input to your map function
  16578. * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun
  16579. * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object
  16580. * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method.
  16581. * @returns {Resultset} A resultset with data in the format [{left: leftObj, right: rightObj}]
  16582. * @memberof Resultset
  16583. * @example
  16584. * var db = new loki('sandbox.db');
  16585. *
  16586. * var products = db.addCollection('products');
  16587. * var orders = db.addCollection('orders');
  16588. *
  16589. * products.insert({ productId: "100234", name: "flywheel energy storage", unitCost: 19999.99 });
  16590. * products.insert({ productId: "140491", name: "300F super capacitor", unitCost: 129.99 });
  16591. * products.insert({ productId: "271941", name: "fuel cell", unitCost: 3999.99 });
  16592. * products.insert({ productId: "174592", name: "390V 3AH lithium bank", unitCost: 4999.99 });
  16593. *
  16594. * orders.insert({ orderDate : new Date("12/1/2017").getTime(), prodId: "174592", qty: 2, customerId: 2 });
  16595. * orders.insert({ orderDate : new Date("4/15/2016").getTime(), prodId: "271941", qty: 1, customerId: 1 });
  16596. * orders.insert({ orderDate : new Date("3/12/2017").getTime(), prodId: "140491", qty: 4, customerId: 4 });
  16597. * orders.insert({ orderDate : new Date("7/31/2017").getTime(), prodId: "100234", qty: 7, customerId: 3 });
  16598. * orders.insert({ orderDate : new Date("8/3/2016").getTime(), prodId: "174592", qty: 3, customerId: 5 });
  16599. *
  16600. * var mapfun = function(left, right) {
  16601. * return {
  16602. * orderId: left.$loki,
  16603. * orderDate: new Date(left.orderDate) + '',
  16604. * customerId: left.customerId,
  16605. * qty: left.qty,
  16606. * productId: left.prodId,
  16607. * prodName: right.name,
  16608. * prodCost: right.unitCost,
  16609. * orderTotal: +((right.unitCost * left.qty).toFixed(2))
  16610. * };
  16611. * };
  16612. *
  16613. * // join orders with relevant product info via eqJoin
  16614. * var orderSummary = orders.chain().eqJoin(products, "prodId", "productId", mapfun).data();
  16615. *
  16616. * console.log(orderSummary);
  16617. */
  16618. Resultset.prototype.eqJoin = function (joinData, leftJoinKey, rightJoinKey, mapFun, dataOptions) {
  16619. var leftData = [],
  16620. leftDataLength,
  16621. rightData = [],
  16622. rightDataLength,
  16623. key,
  16624. result = [],
  16625. leftKeyisFunction = typeof leftJoinKey === 'function',
  16626. rightKeyisFunction = typeof rightJoinKey === 'function',
  16627. joinMap = {};
  16628. //get the left data
  16629. leftData = this.data(dataOptions);
  16630. leftDataLength = leftData.length;
  16631. //get the right data
  16632. if (joinData instanceof Collection) {
  16633. rightData = joinData.chain().data(dataOptions);
  16634. } else if (joinData instanceof Resultset) {
  16635. rightData = joinData.data(dataOptions);
  16636. } else if (Array.isArray(joinData)) {
  16637. rightData = joinData;
  16638. } else {
  16639. throw new TypeError('joinData needs to be an array or result set');
  16640. }
  16641. rightDataLength = rightData.length;
  16642. //construct a lookup table
  16643. for (var i = 0; i < rightDataLength; i++) {
  16644. key = rightKeyisFunction ? rightJoinKey(rightData[i]) : rightData[i][rightJoinKey];
  16645. joinMap[key] = rightData[i];
  16646. }
  16647. if (!mapFun) {
  16648. mapFun = function (left, right) {
  16649. return {
  16650. left: left,
  16651. right: right
  16652. };
  16653. };
  16654. }
  16655. //Run map function over each object in the resultset
  16656. for (var j = 0; j < leftDataLength; j++) {
  16657. key = leftKeyisFunction ? leftJoinKey(leftData[j]) : leftData[j][leftJoinKey];
  16658. result.push(mapFun(leftData[j], joinMap[key] || {}));
  16659. }
  16660. //return return a new resultset with no filters
  16661. this.collection = new Collection('joinData');
  16662. this.collection.insert(result);
  16663. this.filteredrows = [];
  16664. this.filterInitialized = false;
  16665. return this;
  16666. };
  16667. /**
  16668. * Applies a map function into a new collection for further chaining.
  16669. * @param {function} mapFun - javascript map function
  16670. * @param {object=} dataOptions - options to data() before input to your map function
  16671. * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun
  16672. * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object
  16673. * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method.
  16674. * @memberof Resultset
  16675. * @example
  16676. * var orders.chain().find({ productId: 32 }).map(function(obj) {
  16677. * return {
  16678. * orderId: $loki,
  16679. * productId: productId,
  16680. * quantity: qty
  16681. * };
  16682. * });
  16683. */
  16684. Resultset.prototype.map = function (mapFun, dataOptions) {
  16685. var data = this.data(dataOptions).map(mapFun);
  16686. //return return a new resultset with no filters
  16687. this.collection = new Collection('mappedData');
  16688. this.collection.insert(data);
  16689. this.filteredrows = [];
  16690. this.filterInitialized = false;
  16691. return this;
  16692. };
  16693. /**
  16694. * DynamicView class is a versatile 'live' view class which can have filters and sorts applied.
  16695. * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it
  16696. * whenever documents are add/updated/removed so it can remain up-to-date. (chainable)
  16697. *
  16698. * @example
  16699. * var mydv = mycollection.addDynamicView('test'); // default is non-persistent
  16700. * mydv.applyFind({ 'doors' : 4 });
  16701. * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; });
  16702. * var results = mydv.data();
  16703. *
  16704. * @constructor DynamicView
  16705. * @implements LokiEventEmitter
  16706. * @param {Collection} collection - A reference to the collection to work against
  16707. * @param {string} name - The name of this dynamic view
  16708. * @param {object=} options - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options.
  16709. * @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata'
  16710. * @param {string} [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates)
  16711. * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here)
  16712. * @see {@link Collection#addDynamicView} to construct instances of DynamicView
  16713. */
  16714. function DynamicView(collection, name, options) {
  16715. this.collection = collection;
  16716. this.name = name;
  16717. this.rebuildPending = false;
  16718. this.options = options || {};
  16719. if (!this.options.hasOwnProperty('persistent')) {
  16720. this.options.persistent = false;
  16721. }
  16722. // 'persistentSortPriority':
  16723. // 'passive' will defer the sort phase until they call data(). (most efficient overall)
  16724. // 'active' will sort async whenever next idle. (prioritizes read speeds)
  16725. if (!this.options.hasOwnProperty('sortPriority')) {
  16726. this.options.sortPriority = 'passive';
  16727. }
  16728. if (!this.options.hasOwnProperty('minRebuildInterval')) {
  16729. this.options.minRebuildInterval = 1;
  16730. }
  16731. this.resultset = new Resultset(collection);
  16732. this.resultdata = [];
  16733. this.resultsdirty = false;
  16734. this.cachedresultset = null;
  16735. // keep ordered filter pipeline
  16736. this.filterPipeline = [];
  16737. // sorting member variables
  16738. // we only support one active search, applied using applySort() or applySimpleSort()
  16739. this.sortFunction = null;
  16740. this.sortCriteria = null;
  16741. this.sortCriteriaSimple = null;
  16742. this.sortDirty = false;
  16743. // for now just have 1 event for when we finally rebuilt lazy view
  16744. // once we refactor transactions, i will tie in certain transactional events
  16745. this.events = {
  16746. 'rebuild': []
  16747. };
  16748. }
  16749. DynamicView.prototype = new LokiEventEmitter();
  16750. /**
  16751. * rematerialize() - internally used immediately after deserialization (loading)
  16752. * This will clear out and reapply filterPipeline ops, recreating the view.
  16753. * Since where filters do not persist correctly, this method allows
  16754. * restoring the view to state where user can re-apply those where filters.
  16755. *
  16756. * @param {Object=} options - (Optional) allows specification of 'removeWhereFilters' option
  16757. * @returns {DynamicView} This dynamic view for further chained ops.
  16758. * @memberof DynamicView
  16759. * @fires DynamicView.rebuild
  16760. */
  16761. DynamicView.prototype.rematerialize = function (options) {
  16762. var fpl,
  16763. fpi,
  16764. idx;
  16765. options = options || {};
  16766. this.resultdata = [];
  16767. this.resultsdirty = true;
  16768. this.resultset = new Resultset(this.collection);
  16769. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  16770. this.sortDirty = true;
  16771. }
  16772. if (options.hasOwnProperty('removeWhereFilters')) {
  16773. // for each view see if it had any where filters applied... since they don't
  16774. // serialize those functions lets remove those invalid filters
  16775. fpl = this.filterPipeline.length;
  16776. fpi = fpl;
  16777. while (fpi--) {
  16778. if (this.filterPipeline[fpi].type === 'where') {
  16779. if (fpi !== this.filterPipeline.length - 1) {
  16780. this.filterPipeline[fpi] = this.filterPipeline[this.filterPipeline.length - 1];
  16781. }
  16782. this.filterPipeline.length--;
  16783. }
  16784. }
  16785. }
  16786. // back up old filter pipeline, clear filter pipeline, and reapply pipeline ops
  16787. var ofp = this.filterPipeline;
  16788. this.filterPipeline = [];
  16789. // now re-apply 'find' filterPipeline ops
  16790. fpl = ofp.length;
  16791. for (idx = 0; idx < fpl; idx++) {
  16792. this.applyFind(ofp[idx].val);
  16793. }
  16794. // during creation of unit tests, i will remove this forced refresh and leave lazy
  16795. this.data();
  16796. // emit rebuild event in case user wants to be notified
  16797. this.emit('rebuild', this);
  16798. return this;
  16799. };
  16800. /**
  16801. * branchResultset() - Makes a copy of the internal resultset for branched queries.
  16802. * Unlike this dynamic view, the branched resultset will not be 'live' updated,
  16803. * so your branched query should be immediately resolved and not held for future evaluation.
  16804. *
  16805. * @param {(string|array=)} transform - Optional name of collection transform, or an array of transform steps
  16806. * @param {object=} parameters - optional parameters (if optional transform requires them)
  16807. * @returns {Resultset} A copy of the internal resultset for branched queries.
  16808. * @memberof DynamicView
  16809. * @example
  16810. * var db = new loki('test');
  16811. * var coll = db.addCollection('mydocs');
  16812. * var dv = coll.addDynamicView('myview');
  16813. * var tx = [
  16814. * {
  16815. * type: 'offset',
  16816. * value: '[%lktxp]pageStart'
  16817. * },
  16818. * {
  16819. * type: 'limit',
  16820. * value: '[%lktxp]pageSize'
  16821. * }
  16822. * ];
  16823. * coll.addTransform('viewPaging', tx);
  16824. *
  16825. * // add some records
  16826. *
  16827. * var results = dv.branchResultset('viewPaging', { pageStart: 10, pageSize: 10 }).data();
  16828. */
  16829. DynamicView.prototype.branchResultset = function (transform, parameters) {
  16830. var rs = this.resultset.branch();
  16831. if (typeof transform === 'undefined') {
  16832. return rs;
  16833. }
  16834. return rs.transform(transform, parameters);
  16835. };
  16836. /**
  16837. * toJSON() - Override of toJSON to avoid circular references
  16838. *
  16839. */
  16840. DynamicView.prototype.toJSON = function () {
  16841. var copy = new DynamicView(this.collection, this.name, this.options);
  16842. copy.resultset = this.resultset;
  16843. copy.resultdata = []; // let's not save data (copy) to minimize size
  16844. copy.resultsdirty = true;
  16845. copy.filterPipeline = this.filterPipeline;
  16846. copy.sortFunction = this.sortFunction;
  16847. copy.sortCriteria = this.sortCriteria;
  16848. copy.sortCriteriaSimple = this.sortCriteriaSimple || null;
  16849. copy.sortDirty = this.sortDirty;
  16850. // avoid circular reference, reapply in db.loadJSON()
  16851. copy.collection = null;
  16852. return copy;
  16853. };
  16854. /**
  16855. * removeFilters() - Used to clear pipeline and reset dynamic view to initial state.
  16856. * Existing options should be retained.
  16857. * @param {object=} options - configure removeFilter behavior
  16858. * @param {boolean=} options.queueSortPhase - (default: false) if true we will async rebuild view (maybe set default to true in future?)
  16859. * @memberof DynamicView
  16860. */
  16861. DynamicView.prototype.removeFilters = function (options) {
  16862. options = options || {};
  16863. this.rebuildPending = false;
  16864. this.resultset.reset();
  16865. this.resultdata = [];
  16866. this.resultsdirty = true;
  16867. this.cachedresultset = null;
  16868. // keep ordered filter pipeline
  16869. this.filterPipeline = [];
  16870. // sorting member variables
  16871. // we only support one active search, applied using applySort() or applySimpleSort()
  16872. this.sortFunction = null;
  16873. this.sortCriteria = null;
  16874. this.sortCriteriaSimple = null;
  16875. this.sortDirty = false;
  16876. if (options.queueSortPhase === true) {
  16877. this.queueSortPhase();
  16878. }
  16879. };
  16880. /**
  16881. * applySort() - Used to apply a sort to the dynamic view
  16882. * @example
  16883. * dv.applySort(function(obj1, obj2) {
  16884. * if (obj1.name === obj2.name) return 0;
  16885. * if (obj1.name > obj2.name) return 1;
  16886. * if (obj1.name < obj2.name) return -1;
  16887. * });
  16888. *
  16889. * @param {function} comparefun - a javascript compare function used for sorting
  16890. * @returns {DynamicView} this DynamicView object, for further chain ops.
  16891. * @memberof DynamicView
  16892. */
  16893. DynamicView.prototype.applySort = function (comparefun) {
  16894. this.sortFunction = comparefun;
  16895. this.sortCriteria = null;
  16896. this.sortCriteriaSimple = null;
  16897. this.queueSortPhase();
  16898. return this;
  16899. };
  16900. /**
  16901. * applySimpleSort() - Used to specify a property used for view translation.
  16902. * @example
  16903. * dv.applySimpleSort("name");
  16904. *
  16905. * @param {string} propname - Name of property by which to sort.
  16906. * @param {object|boolean=} options - boolean for sort descending or options object
  16907. * @param {boolean} [options.desc=false] - whether we should sort descending.
  16908. * @param {boolean} [options.disableIndexIntersect=false] - whether we should explicity not use array intersection.
  16909. * @param {boolean} [options.forceIndexIntersect=false] - force array intersection (if binary index exists).
  16910. * @param {boolean} [options.useJavascriptSorting=false] - whether results are sorted via basic javascript sort.
  16911. * @returns {DynamicView} this DynamicView object, for further chain ops.
  16912. * @memberof DynamicView
  16913. */
  16914. DynamicView.prototype.applySimpleSort = function (propname, options) {
  16915. this.sortCriteriaSimple = { propname: propname, options: options || false };
  16916. this.sortCriteria = null;
  16917. this.sortFunction = null;
  16918. this.queueSortPhase();
  16919. return this;
  16920. };
  16921. /**
  16922. * applySortCriteria() - Allows sorting a resultset based on multiple columns.
  16923. * @example
  16924. * // to sort by age and then name (both ascending)
  16925. * dv.applySortCriteria(['age', 'name']);
  16926. * // to sort by age (ascending) and then by name (descending)
  16927. * dv.applySortCriteria(['age', ['name', true]);
  16928. * // to sort by age (descending) and then by name (descending)
  16929. * dv.applySortCriteria(['age', true], ['name', true]);
  16930. *
  16931. * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order
  16932. * @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations.
  16933. * @memberof DynamicView
  16934. */
  16935. DynamicView.prototype.applySortCriteria = function (criteria) {
  16936. this.sortCriteria = criteria;
  16937. this.sortCriteriaSimple = null;
  16938. this.sortFunction = null;
  16939. this.queueSortPhase();
  16940. return this;
  16941. };
  16942. /**
  16943. * startTransaction() - marks the beginning of a transaction.
  16944. *
  16945. * @returns {DynamicView} this DynamicView object, for further chain ops.
  16946. */
  16947. DynamicView.prototype.startTransaction = function () {
  16948. this.cachedresultset = this.resultset.copy();
  16949. return this;
  16950. };
  16951. /**
  16952. * commit() - commits a transaction.
  16953. *
  16954. * @returns {DynamicView} this DynamicView object, for further chain ops.
  16955. */
  16956. DynamicView.prototype.commit = function () {
  16957. this.cachedresultset = null;
  16958. return this;
  16959. };
  16960. /**
  16961. * rollback() - rolls back a transaction.
  16962. *
  16963. * @returns {DynamicView} this DynamicView object, for further chain ops.
  16964. */
  16965. DynamicView.prototype.rollback = function () {
  16966. this.resultset = this.cachedresultset;
  16967. if (this.options.persistent) {
  16968. // for now just rebuild the persistent dynamic view data in this worst case scenario
  16969. // (a persistent view utilizing transactions which get rolled back), we already know the filter so not too bad.
  16970. this.resultdata = this.resultset.data();
  16971. this.emit('rebuild', this);
  16972. }
  16973. return this;
  16974. };
  16975. /**
  16976. * Implementation detail.
  16977. * _indexOfFilterWithId() - Find the index of a filter in the pipeline, by that filter's ID.
  16978. *
  16979. * @param {(string|number)} uid - The unique ID of the filter.
  16980. * @returns {number}: index of the referenced filter in the pipeline; -1 if not found.
  16981. */
  16982. DynamicView.prototype._indexOfFilterWithId = function (uid) {
  16983. if (typeof uid === 'string' || typeof uid === 'number') {
  16984. for (var idx = 0, len = this.filterPipeline.length; idx < len; idx += 1) {
  16985. if (uid === this.filterPipeline[idx].uid) {
  16986. return idx;
  16987. }
  16988. }
  16989. }
  16990. return -1;
  16991. };
  16992. /**
  16993. * Implementation detail.
  16994. * _addFilter() - Add the filter object to the end of view's filter pipeline and apply the filter to the resultset.
  16995. *
  16996. * @param {object} filter - The filter object. Refer to applyFilter() for extra details.
  16997. */
  16998. DynamicView.prototype._addFilter = function (filter) {
  16999. this.filterPipeline.push(filter);
  17000. this.resultset[filter.type](filter.val);
  17001. };
  17002. /**
  17003. * reapplyFilters() - Reapply all the filters in the current pipeline.
  17004. *
  17005. * @returns {DynamicView} this DynamicView object, for further chain ops.
  17006. */
  17007. DynamicView.prototype.reapplyFilters = function () {
  17008. this.resultset.reset();
  17009. this.cachedresultset = null;
  17010. if (this.options.persistent) {
  17011. this.resultdata = [];
  17012. this.resultsdirty = true;
  17013. }
  17014. var filters = this.filterPipeline;
  17015. this.filterPipeline = [];
  17016. for (var idx = 0, len = filters.length; idx < len; idx += 1) {
  17017. this._addFilter(filters[idx]);
  17018. }
  17019. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  17020. this.queueSortPhase();
  17021. } else {
  17022. this.queueRebuildEvent();
  17023. }
  17024. return this;
  17025. };
  17026. /**
  17027. * applyFilter() - Adds or updates a filter in the DynamicView filter pipeline
  17028. *
  17029. * @param {object} filter - A filter object to add to the pipeline.
  17030. * The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id }
  17031. * @returns {DynamicView} this DynamicView object, for further chain ops.
  17032. * @memberof DynamicView
  17033. */
  17034. DynamicView.prototype.applyFilter = function (filter) {
  17035. var idx = this._indexOfFilterWithId(filter.uid);
  17036. if (idx >= 0) {
  17037. this.filterPipeline[idx] = filter;
  17038. return this.reapplyFilters();
  17039. }
  17040. this.cachedresultset = null;
  17041. if (this.options.persistent) {
  17042. this.resultdata = [];
  17043. this.resultsdirty = true;
  17044. }
  17045. this._addFilter(filter);
  17046. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  17047. this.queueSortPhase();
  17048. } else {
  17049. this.queueRebuildEvent();
  17050. }
  17051. return this;
  17052. };
  17053. /**
  17054. * applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline
  17055. *
  17056. * @param {object} query - A mongo-style query object to apply to pipeline
  17057. * @param {(string|number)=} uid - Optional: The unique ID of this filter, to reference it in the future.
  17058. * @returns {DynamicView} this DynamicView object, for further chain ops.
  17059. * @memberof DynamicView
  17060. */
  17061. DynamicView.prototype.applyFind = function (query, uid) {
  17062. this.applyFilter({
  17063. type: 'find',
  17064. val: query,
  17065. uid: uid
  17066. });
  17067. return this;
  17068. };
  17069. /**
  17070. * applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline
  17071. *
  17072. * @param {function} fun - A javascript filter function to apply to pipeline
  17073. * @param {(string|number)=} uid - Optional: The unique ID of this filter, to reference it in the future.
  17074. * @returns {DynamicView} this DynamicView object, for further chain ops.
  17075. * @memberof DynamicView
  17076. */
  17077. DynamicView.prototype.applyWhere = function (fun, uid) {
  17078. this.applyFilter({
  17079. type: 'where',
  17080. val: fun,
  17081. uid: uid
  17082. });
  17083. return this;
  17084. };
  17085. /**
  17086. * removeFilter() - Remove the specified filter from the DynamicView filter pipeline
  17087. *
  17088. * @param {(string|number)} uid - The unique ID of the filter to be removed.
  17089. * @returns {DynamicView} this DynamicView object, for further chain ops.
  17090. * @memberof DynamicView
  17091. */
  17092. DynamicView.prototype.removeFilter = function (uid) {
  17093. var idx = this._indexOfFilterWithId(uid);
  17094. if (idx < 0) {
  17095. throw new Error("Dynamic view does not contain a filter with ID: " + uid);
  17096. }
  17097. this.filterPipeline.splice(idx, 1);
  17098. this.reapplyFilters();
  17099. return this;
  17100. };
  17101. /**
  17102. * count() - returns the number of documents representing the current DynamicView contents.
  17103. *
  17104. * @returns {number} The number of documents representing the current DynamicView contents.
  17105. * @memberof DynamicView
  17106. */
  17107. DynamicView.prototype.count = function () {
  17108. // in order to be accurate we will pay the minimum cost (and not alter dv state management)
  17109. // recurring resultset data resolutions should know internally its already up to date.
  17110. // for persistent data this will not update resultdata nor fire rebuild event.
  17111. if (this.resultsdirty) {
  17112. this.resultdata = this.resultset.data();
  17113. }
  17114. return this.resultset.count();
  17115. };
  17116. /**
  17117. * data() - resolves and pending filtering and sorting, then returns document array as result.
  17118. *
  17119. * @param {object=} options - optional parameters to pass to resultset.data() if non-persistent
  17120. * @param {boolean} options.forceClones - Allows forcing the return of cloned objects even when
  17121. * the collection is not configured for clone object.
  17122. * @param {string} options.forceCloneMethod - Allows overriding the default or collection specified cloning method.
  17123. * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'
  17124. * @param {bool} options.removeMeta - Will force clones and strip $loki and meta properties from documents
  17125. * @returns {array} An array of documents representing the current DynamicView contents.
  17126. * @memberof DynamicView
  17127. */
  17128. DynamicView.prototype.data = function (options) {
  17129. // using final sort phase as 'catch all' for a few use cases which require full rebuild
  17130. if (this.sortDirty || this.resultsdirty) {
  17131. this.performSortPhase({
  17132. suppressRebuildEvent: true
  17133. });
  17134. }
  17135. return (this.options.persistent) ? (this.resultdata) : (this.resultset.data(options));
  17136. };
  17137. /**
  17138. * queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events.
  17139. * This event will throttle and queue a single rebuild event when batches of updates affect the view.
  17140. */
  17141. DynamicView.prototype.queueRebuildEvent = function () {
  17142. if (this.rebuildPending) {
  17143. return;
  17144. }
  17145. this.rebuildPending = true;
  17146. var self = this;
  17147. setTimeout(function () {
  17148. if (self.rebuildPending) {
  17149. self.rebuildPending = false;
  17150. self.emit('rebuild', self);
  17151. }
  17152. }, this.options.minRebuildInterval);
  17153. };
  17154. /**
  17155. * queueSortPhase : If the view is sorted we will throttle sorting to either :
  17156. * (1) passive - when the user calls data(), or
  17157. * (2) active - once they stop updating and yield js thread control
  17158. */
  17159. DynamicView.prototype.queueSortPhase = function () {
  17160. // already queued? exit without queuing again
  17161. if (this.sortDirty) {
  17162. return;
  17163. }
  17164. this.sortDirty = true;
  17165. var self = this;
  17166. if (this.options.sortPriority === "active") {
  17167. // active sorting... once they are done and yield js thread, run async performSortPhase()
  17168. setTimeout(function () {
  17169. self.performSortPhase();
  17170. }, this.options.minRebuildInterval);
  17171. } else {
  17172. // must be passive sorting... since not calling performSortPhase (until data call), lets use queueRebuildEvent to
  17173. // potentially notify user that data has changed.
  17174. this.queueRebuildEvent();
  17175. }
  17176. };
  17177. /**
  17178. * performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed)
  17179. *
  17180. */
  17181. DynamicView.prototype.performSortPhase = function (options) {
  17182. // async call to this may have been pre-empted by synchronous call to data before async could fire
  17183. if (!this.sortDirty && !this.resultsdirty) {
  17184. return;
  17185. }
  17186. options = options || {};
  17187. if (this.sortDirty) {
  17188. if (this.sortFunction) {
  17189. this.resultset.sort(this.sortFunction);
  17190. } else if (this.sortCriteria) {
  17191. this.resultset.compoundsort(this.sortCriteria);
  17192. } else if (this.sortCriteriaSimple) {
  17193. this.resultset.simplesort(this.sortCriteriaSimple.propname, this.sortCriteriaSimple.options);
  17194. }
  17195. this.sortDirty = false;
  17196. }
  17197. if (this.options.persistent) {
  17198. // persistent view, rebuild local resultdata array
  17199. this.resultdata = this.resultset.data();
  17200. this.resultsdirty = false;
  17201. }
  17202. if (!options.suppressRebuildEvent) {
  17203. this.emit('rebuild', this);
  17204. }
  17205. };
  17206. /**
  17207. * evaluateDocument() - internal method for (re)evaluating document inclusion.
  17208. * Called by : collection.insert() and collection.update().
  17209. *
  17210. * @param {int} objIndex - index of document to (re)run through filter pipeline.
  17211. * @param {bool} isNew - true if the document was just added to the collection.
  17212. */
  17213. DynamicView.prototype.evaluateDocument = function (objIndex, isNew) {
  17214. // if no filter applied yet, the result 'set' should remain 'everything'
  17215. if (!this.resultset.filterInitialized) {
  17216. if (this.options.persistent) {
  17217. this.resultdata = this.resultset.data();
  17218. }
  17219. // need to re-sort to sort new document
  17220. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  17221. this.queueSortPhase();
  17222. } else {
  17223. this.queueRebuildEvent();
  17224. }
  17225. return;
  17226. }
  17227. var ofr = this.resultset.filteredrows;
  17228. var oldPos = (isNew) ? (-1) : (ofr.indexOf(+objIndex));
  17229. var oldlen = ofr.length;
  17230. // creating a 1-element resultset to run filter chain ops on to see if that doc passes filters;
  17231. // mostly efficient algorithm, slight stack overhead price (this function is called on inserts and updates)
  17232. var evalResultset = new Resultset(this.collection);
  17233. evalResultset.filteredrows = [objIndex];
  17234. evalResultset.filterInitialized = true;
  17235. var filter;
  17236. for (var idx = 0, len = this.filterPipeline.length; idx < len; idx++) {
  17237. filter = this.filterPipeline[idx];
  17238. evalResultset[filter.type](filter.val);
  17239. }
  17240. // not a true position, but -1 if not pass our filter(s), 0 if passed filter(s)
  17241. var newPos = (evalResultset.filteredrows.length === 0) ? -1 : 0;
  17242. // wasn't in old, shouldn't be now... do nothing
  17243. if (oldPos === -1 && newPos === -1) return;
  17244. // wasn't in resultset, should be now... add
  17245. if (oldPos === -1 && newPos !== -1) {
  17246. ofr.push(objIndex);
  17247. if (this.options.persistent) {
  17248. this.resultdata.push(this.collection.data[objIndex]);
  17249. }
  17250. // need to re-sort to sort new document
  17251. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  17252. this.queueSortPhase();
  17253. } else {
  17254. this.queueRebuildEvent();
  17255. }
  17256. return;
  17257. }
  17258. // was in resultset, shouldn't be now... delete
  17259. if (oldPos !== -1 && newPos === -1) {
  17260. if (oldPos < oldlen - 1) {
  17261. ofr.splice(oldPos, 1);
  17262. if (this.options.persistent) {
  17263. this.resultdata.splice(oldPos, 1);
  17264. }
  17265. } else {
  17266. ofr.length = oldlen - 1;
  17267. if (this.options.persistent) {
  17268. this.resultdata.length = oldlen - 1;
  17269. }
  17270. }
  17271. // in case changes to data altered a sort column
  17272. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  17273. this.queueSortPhase();
  17274. } else {
  17275. this.queueRebuildEvent();
  17276. }
  17277. return;
  17278. }
  17279. // was in resultset, should still be now... (update persistent only?)
  17280. if (oldPos !== -1 && newPos !== -1) {
  17281. if (this.options.persistent) {
  17282. // in case document changed, replace persistent view data with the latest collection.data document
  17283. this.resultdata[oldPos] = this.collection.data[objIndex];
  17284. }
  17285. // in case changes to data altered a sort column
  17286. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  17287. this.queueSortPhase();
  17288. } else {
  17289. this.queueRebuildEvent();
  17290. }
  17291. return;
  17292. }
  17293. };
  17294. /**
  17295. * removeDocument() - internal function called on collection.delete()
  17296. * @param {number|number[]} objIndex - index of document to (re)run through filter pipeline.
  17297. */
  17298. DynamicView.prototype.removeDocument = function (objIndex) {
  17299. var idx, rmidx, rmlen, rxo = {}, fxo = {};
  17300. var adjels = [];
  17301. var drs = this.resultset;
  17302. var fr = this.resultset.filteredrows;
  17303. var frlen = fr.length;
  17304. // if no filter applied yet, the result 'set' should remain 'everything'
  17305. if (!this.resultset.filterInitialized) {
  17306. if (this.options.persistent) {
  17307. this.resultdata = this.resultset.data();
  17308. }
  17309. // in case changes to data altered a sort column
  17310. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  17311. this.queueSortPhase();
  17312. } else {
  17313. this.queueRebuildEvent();
  17314. }
  17315. return;
  17316. }
  17317. // if passed single index, wrap in array
  17318. if (!Array.isArray(objIndex)) {
  17319. objIndex = [objIndex];
  17320. }
  17321. rmlen = objIndex.length;
  17322. // create intersection object of data indices to remove
  17323. for(rmidx=0;rmidx<rmlen; rmidx++) {
  17324. rxo[objIndex[rmidx]] = true;
  17325. }
  17326. // pivot remove data indices into remove filteredrows indices and dump in hashobject
  17327. for (idx=0; idx<frlen; idx++) {
  17328. if (rxo[fr[idx]]) fxo[idx] = true;
  17329. }
  17330. // if any of the removed items were in our filteredrows...
  17331. if (Object.keys(fxo).length > 0) {
  17332. // remove them from filtered rows
  17333. this.resultset.filteredrows = this.resultset.filteredrows.filter(function(di, idx) { return !fxo[idx]; });
  17334. // if persistent...
  17335. if (this.options.persistent) {
  17336. // remove from resultdata
  17337. this.resultdata = this.resultdata.filter(function(obj, idx) { return !fxo[idx]; });
  17338. }
  17339. // and queue sorts
  17340. if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
  17341. this.queueSortPhase();
  17342. } else {
  17343. this.queueRebuildEvent();
  17344. }
  17345. }
  17346. // to remove holes, we need to 'shift down' indices, this filter function finds number of positions to shift
  17347. var filt = function(idx) { return function(di) { return di < drs.filteredrows[idx]; }; };
  17348. frlen = drs.filteredrows.length;
  17349. for (idx = 0; idx < frlen; idx++) {
  17350. // grab subset of removed elements where data index is less than current filtered row data index;
  17351. // use this to determine how many positions iterated remaining data index needs to be 'shifted down'
  17352. adjels = objIndex.filter(filt(idx));
  17353. drs.filteredrows[idx] -= adjels.length;
  17354. }
  17355. };
  17356. /**
  17357. * mapReduce() - data transformation via user supplied functions
  17358. *
  17359. * @param {function} mapFunction - this function accepts a single document for you to transform and return
  17360. * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value
  17361. * @returns The output of your reduceFunction
  17362. * @memberof DynamicView
  17363. */
  17364. DynamicView.prototype.mapReduce = function (mapFunction, reduceFunction) {
  17365. try {
  17366. return reduceFunction(this.data().map(mapFunction));
  17367. } catch (err) {
  17368. throw err;
  17369. }
  17370. };
  17371. /**
  17372. * Collection class that handles documents of same type
  17373. * @constructor Collection
  17374. * @implements LokiEventEmitter
  17375. * @param {string} name - collection name
  17376. * @param {(array|object)=} options - (optional) array of property names to be indicized OR a configuration object
  17377. * @param {array=} [options.unique=[]] - array of property names to define unique constraints for
  17378. * @param {array=} [options.exact=[]] - array of property names to define exact constraints for
  17379. * @param {array=} [options.indices=[]] - array property names to define binary indexes for
  17380. * @param {boolean} [options.adaptiveBinaryIndices=true] - collection indices will be actively rebuilt rather than lazily
  17381. * @param {boolean} [options.asyncListeners=false] - whether listeners are invoked asynchronously
  17382. * @param {boolean} [options.disableMeta=false] - set to true to disable meta property on documents
  17383. * @param {boolean} [options.disableChangesApi=true] - set to false to enable Changes API
  17384. * @param {boolean} [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning)
  17385. * @param {boolean} [options.autoupdate=false] - use Object.observe to update objects automatically
  17386. * @param {boolean} [options.clone=false] - specify whether inserts and queries clone to/from user
  17387. * @param {boolean} [options.serializableIndices=true[]] - converts date values on binary indexed properties to epoch time
  17388. * @param {string} [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'
  17389. * @param {int=} options.ttl - age of document (in ms.) before document is considered aged/stale.
  17390. * @param {int=} options.ttlInterval - time interval for clearing out 'aged' documents; not set by default.
  17391. * @see {@link Loki#addCollection} for normal creation of collections
  17392. */
  17393. function Collection(name, options) {
  17394. // the name of the collection
  17395. this.name = name;
  17396. // the data held by the collection
  17397. this.data = [];
  17398. this.idIndex = []; // index of id
  17399. this.binaryIndices = {}; // user defined indexes
  17400. this.constraints = {
  17401. unique: {},
  17402. exact: {}
  17403. };
  17404. // unique contraints contain duplicate object references, so they are not persisted.
  17405. // we will keep track of properties which have unique contraint applied here, and regenerate on load
  17406. this.uniqueNames = [];
  17407. // transforms will be used to store frequently used query chains as a series of steps
  17408. // which itself can be stored along with the database.
  17409. this.transforms = {};
  17410. // the object type of the collection
  17411. this.objType = name;
  17412. // in autosave scenarios we will use collection level dirty flags to determine whether save is needed.
  17413. // currently, if any collection is dirty we will autosave the whole database if autosave is configured.
  17414. // defaulting to true since this is called from addCollection and adding a collection should trigger save
  17415. this.dirty = true;
  17416. // private holders for cached data
  17417. this.cachedIndex = null;
  17418. this.cachedBinaryIndex = null;
  17419. this.cachedData = null;
  17420. var self = this;
  17421. /* OPTIONS */
  17422. options = options || {};
  17423. // exact match and unique constraints
  17424. if (options.hasOwnProperty('unique')) {
  17425. if (!Array.isArray(options.unique)) {
  17426. options.unique = [options.unique];
  17427. }
  17428. options.unique.forEach(function (prop) {
  17429. self.uniqueNames.push(prop); // used to regenerate on subsequent database loads
  17430. self.constraints.unique[prop] = new UniqueIndex(prop);
  17431. });
  17432. }
  17433. if (options.hasOwnProperty('exact')) {
  17434. options.exact.forEach(function (prop) {
  17435. self.constraints.exact[prop] = new ExactIndex(prop);
  17436. });
  17437. }
  17438. // if set to true we will optimally keep indices 'fresh' during insert/update/remove ops (never dirty/never needs rebuild)
  17439. // if you frequently intersperse insert/update/remove ops between find ops this will likely be significantly faster option.
  17440. this.adaptiveBinaryIndices = options.hasOwnProperty('adaptiveBinaryIndices') ? options.adaptiveBinaryIndices : true;
  17441. // is collection transactional
  17442. this.transactional = options.hasOwnProperty('transactional') ? options.transactional : false;
  17443. // options to clone objects when inserting them
  17444. this.cloneObjects = options.hasOwnProperty('clone') ? options.clone : false;
  17445. // default clone method (if enabled) is parse-stringify
  17446. this.cloneMethod = options.hasOwnProperty('cloneMethod') ? options.cloneMethod : "parse-stringify";
  17447. // option to make event listeners async, default is sync
  17448. this.asyncListeners = options.hasOwnProperty('asyncListeners') ? options.asyncListeners : false;
  17449. // if set to true we will not maintain a meta property for a document
  17450. this.disableMeta = options.hasOwnProperty('disableMeta') ? options.disableMeta : false;
  17451. // disable track changes
  17452. this.disableChangesApi = options.hasOwnProperty('disableChangesApi') ? options.disableChangesApi : true;
  17453. // disable delta update object style on changes
  17454. this.disableDeltaChangesApi = options.hasOwnProperty('disableDeltaChangesApi') ? options.disableDeltaChangesApi : true;
  17455. if (this.disableChangesApi) { this.disableDeltaChangesApi = true; }
  17456. // option to observe objects and update them automatically, ignored if Object.observe is not supported
  17457. this.autoupdate = options.hasOwnProperty('autoupdate') ? options.autoupdate : false;
  17458. // by default, if you insert a document into a collection with binary indices, if those indexed properties contain
  17459. // a DateTime we will convert to epoch time format so that (across serializations) its value position will be the
  17460. // same 'after' serialization as it was 'before'.
  17461. this.serializableIndices = options.hasOwnProperty('serializableIndices') ? options.serializableIndices : true;
  17462. //option to activate a cleaner daemon - clears "aged" documents at set intervals.
  17463. this.ttl = {
  17464. age: null,
  17465. ttlInterval: null,
  17466. daemon: null
  17467. };
  17468. this.setTTL(options.ttl || -1, options.ttlInterval);
  17469. // currentMaxId - change manually at your own peril!
  17470. this.maxId = 0;
  17471. this.DynamicViews = [];
  17472. // events
  17473. this.events = {
  17474. 'insert': [],
  17475. 'update': [],
  17476. 'pre-insert': [],
  17477. 'pre-update': [],
  17478. 'close': [],
  17479. 'flushbuffer': [],
  17480. 'error': [],
  17481. 'delete': [],
  17482. 'warning': []
  17483. };
  17484. // changes are tracked by collection and aggregated by the db
  17485. this.changes = [];
  17486. // initialize the id index
  17487. this.ensureId();
  17488. var indices = [];
  17489. // initialize optional user-supplied indices array ['age', 'lname', 'zip']
  17490. if (options && options.indices) {
  17491. if (Object.prototype.toString.call(options.indices) === '[object Array]') {
  17492. indices = options.indices;
  17493. } else if (typeof options.indices === 'string') {
  17494. indices = [options.indices];
  17495. } else {
  17496. throw new TypeError('Indices needs to be a string or an array of strings');
  17497. }
  17498. }
  17499. for (var idx = 0; idx < indices.length; idx++) {
  17500. this.ensureIndex(indices[idx]);
  17501. }
  17502. function observerCallback(changes) {
  17503. var changedObjects = typeof Set === 'function' ? new Set() : [];
  17504. if (!changedObjects.add)
  17505. changedObjects.add = function (object) {
  17506. if (this.indexOf(object) === -1)
  17507. this.push(object);
  17508. return this;
  17509. };
  17510. changes.forEach(function (change) {
  17511. changedObjects.add(change.object);
  17512. });
  17513. changedObjects.forEach(function (object) {
  17514. if (!hasOwnProperty.call(object, '$loki'))
  17515. return self.removeAutoUpdateObserver(object);
  17516. try {
  17517. self.update(object);
  17518. } catch (err) {}
  17519. });
  17520. }
  17521. this.observerCallback = observerCallback;
  17522. //Compare changed object (which is a forced clone) with existing object and return the delta
  17523. function getChangeDelta(obj, old) {
  17524. if (old) {
  17525. return getObjectDelta(old, obj);
  17526. }
  17527. else {
  17528. return JSON.parse(JSON.stringify(obj));
  17529. }
  17530. }
  17531. this.getChangeDelta = getChangeDelta;
  17532. function getObjectDelta(oldObject, newObject) {
  17533. var propertyNames = newObject !== null && typeof newObject === 'object' ? Object.keys(newObject) : null;
  17534. if (propertyNames && propertyNames.length && ['string', 'boolean', 'number'].indexOf(typeof(newObject)) < 0) {
  17535. var delta = {};
  17536. for (var i = 0; i < propertyNames.length; i++) {
  17537. var propertyName = propertyNames[i];
  17538. if (newObject.hasOwnProperty(propertyName)) {
  17539. if (!oldObject.hasOwnProperty(propertyName) || self.uniqueNames.indexOf(propertyName) >= 0 || propertyName == '$loki' || propertyName == 'meta') {
  17540. delta[propertyName] = newObject[propertyName];
  17541. }
  17542. else {
  17543. var propertyDelta = getObjectDelta(oldObject[propertyName], newObject[propertyName]);
  17544. if (typeof propertyDelta !== "undefined" && propertyDelta != {}) {
  17545. delta[propertyName] = propertyDelta;
  17546. }
  17547. }
  17548. }
  17549. }
  17550. return Object.keys(delta).length === 0 ? undefined : delta;
  17551. }
  17552. else {
  17553. return oldObject === newObject ? undefined : newObject;
  17554. }
  17555. }
  17556. this.getObjectDelta = getObjectDelta;
  17557. // clear all the changes
  17558. function flushChanges() {
  17559. self.changes = [];
  17560. }
  17561. this.getChanges = function () {
  17562. return self.changes;
  17563. };
  17564. this.flushChanges = flushChanges;
  17565. this.setChangesApi = function (enabled) {
  17566. self.disableChangesApi = !enabled;
  17567. if (!enabled) { self.disableDeltaChangesApi = false; }
  17568. };
  17569. this.on('delete', function deleteCallback(obj) {
  17570. if (!self.disableChangesApi) {
  17571. self.createChange(self.name, 'R', obj);
  17572. }
  17573. });
  17574. this.on('warning', function (warning) {
  17575. self.console.warn(warning);
  17576. });
  17577. // for de-serialization purposes
  17578. flushChanges();
  17579. }
  17580. Collection.prototype = new LokiEventEmitter();
  17581. /*
  17582. * For ChangeAPI default to clone entire object, for delta changes create object with only differences (+ $loki and meta)
  17583. */
  17584. Collection.prototype.createChange = function(name, op, obj, old) {
  17585. this.changes.push({
  17586. name: name,
  17587. operation: op,
  17588. obj: op == 'U' && !this.disableDeltaChangesApi ? this.getChangeDelta(obj, old) : JSON.parse(JSON.stringify(obj))
  17589. });
  17590. };
  17591. Collection.prototype.insertMeta = function(obj) {
  17592. var len, idx;
  17593. if (this.disableMeta || !obj) {
  17594. return;
  17595. }
  17596. // if batch insert
  17597. if (Array.isArray(obj)) {
  17598. len = obj.length;
  17599. for(idx=0; idx<len; idx++) {
  17600. if (!obj[idx].hasOwnProperty('meta')) {
  17601. obj[idx].meta = {};
  17602. }
  17603. obj[idx].meta.created = (new Date()).getTime();
  17604. obj[idx].meta.revision = 0;
  17605. }
  17606. return;
  17607. }
  17608. // single object
  17609. if (!obj.meta) {
  17610. obj.meta = {};
  17611. }
  17612. obj.meta.created = (new Date()).getTime();
  17613. obj.meta.revision = 0;
  17614. };
  17615. Collection.prototype.updateMeta = function(obj) {
  17616. if (this.disableMeta || !obj) {
  17617. return;
  17618. }
  17619. obj.meta.updated = (new Date()).getTime();
  17620. obj.meta.revision += 1;
  17621. };
  17622. Collection.prototype.createInsertChange = function(obj) {
  17623. this.createChange(this.name, 'I', obj);
  17624. };
  17625. Collection.prototype.createUpdateChange = function(obj, old) {
  17626. this.createChange(this.name, 'U', obj, old);
  17627. };
  17628. Collection.prototype.insertMetaWithChange = function(obj) {
  17629. this.insertMeta(obj);
  17630. this.createInsertChange(obj);
  17631. };
  17632. Collection.prototype.updateMetaWithChange = function(obj, old) {
  17633. this.updateMeta(obj);
  17634. this.createUpdateChange(obj, old);
  17635. };
  17636. Collection.prototype.console = {
  17637. log: function () {},
  17638. warn: function () {},
  17639. error: function () {},
  17640. };
  17641. Collection.prototype.addAutoUpdateObserver = function (object) {
  17642. if (!this.autoupdate || typeof Object.observe !== 'function')
  17643. return;
  17644. Object.observe(object, this.observerCallback, ['add', 'update', 'delete', 'reconfigure', 'setPrototype']);
  17645. };
  17646. Collection.prototype.removeAutoUpdateObserver = function (object) {
  17647. if (!this.autoupdate || typeof Object.observe !== 'function')
  17648. return;
  17649. Object.unobserve(object, this.observerCallback);
  17650. };
  17651. /**
  17652. * Adds a named collection transform to the collection
  17653. * @param {string} name - name to associate with transform
  17654. * @param {array} transform - an array of transformation 'step' objects to save into the collection
  17655. * @memberof Collection
  17656. * @example
  17657. * users.addTransform('progeny', [
  17658. * {
  17659. * type: 'find',
  17660. * value: {
  17661. * 'age': {'$lte': 40}
  17662. * }
  17663. * }
  17664. * ]);
  17665. *
  17666. * var results = users.chain('progeny').data();
  17667. */
  17668. Collection.prototype.addTransform = function (name, transform) {
  17669. if (this.transforms.hasOwnProperty(name)) {
  17670. throw new Error("a transform by that name already exists");
  17671. }
  17672. this.transforms[name] = transform;
  17673. };
  17674. /**
  17675. * Retrieves a named transform from the collection.
  17676. * @param {string} name - name of the transform to lookup.
  17677. * @memberof Collection
  17678. */
  17679. Collection.prototype.getTransform = function (name) {
  17680. return this.transforms[name];
  17681. };
  17682. /**
  17683. * Updates a named collection transform to the collection
  17684. * @param {string} name - name to associate with transform
  17685. * @param {object} transform - a transformation object to save into collection
  17686. * @memberof Collection
  17687. */
  17688. Collection.prototype.setTransform = function (name, transform) {
  17689. this.transforms[name] = transform;
  17690. };
  17691. /**
  17692. * Removes a named collection transform from the collection
  17693. * @param {string} name - name of collection transform to remove
  17694. * @memberof Collection
  17695. */
  17696. Collection.prototype.removeTransform = function (name) {
  17697. delete this.transforms[name];
  17698. };
  17699. Collection.prototype.byExample = function (template) {
  17700. var k, obj, query;
  17701. query = [];
  17702. for (k in template) {
  17703. if (!template.hasOwnProperty(k)) continue;
  17704. query.push((
  17705. obj = {},
  17706. obj[k] = template[k],
  17707. obj
  17708. ));
  17709. }
  17710. return {
  17711. '$and': query
  17712. };
  17713. };
  17714. Collection.prototype.findObject = function (template) {
  17715. return this.findOne(this.byExample(template));
  17716. };
  17717. Collection.prototype.findObjects = function (template) {
  17718. return this.find(this.byExample(template));
  17719. };
  17720. /*----------------------------+
  17721. | TTL daemon |
  17722. +----------------------------*/
  17723. Collection.prototype.ttlDaemonFuncGen = function () {
  17724. var collection = this;
  17725. var age = this.ttl.age;
  17726. return function ttlDaemon() {
  17727. var now = Date.now();
  17728. var toRemove = collection.chain().where(function daemonFilter(member) {
  17729. var timestamp = member.meta.updated || member.meta.created;
  17730. var diff = now - timestamp;
  17731. return age < diff;
  17732. });
  17733. toRemove.remove();
  17734. };
  17735. };
  17736. /**
  17737. * Updates or applies collection TTL settings.
  17738. * @param {int} age - age (in ms) to expire document from collection
  17739. * @param {int} interval - time (in ms) to clear collection of aged documents.
  17740. * @memberof Collection
  17741. */
  17742. Collection.prototype.setTTL = function (age, interval) {
  17743. if (age < 0) {
  17744. clearInterval(this.ttl.daemon);
  17745. } else {
  17746. this.ttl.age = age;
  17747. this.ttl.ttlInterval = interval;
  17748. this.ttl.daemon = setInterval(this.ttlDaemonFuncGen(), interval);
  17749. }
  17750. };
  17751. /*----------------------------+
  17752. | INDEXING |
  17753. +----------------------------*/
  17754. /**
  17755. * create a row filter that covers all documents in the collection
  17756. */
  17757. Collection.prototype.prepareFullDocIndex = function () {
  17758. var len = this.data.length;
  17759. var indexes = new Array(len);
  17760. for (var i = 0; i < len; i += 1) {
  17761. indexes[i] = i;
  17762. }
  17763. return indexes;
  17764. };
  17765. /**
  17766. * Will allow reconfiguring certain collection options.
  17767. * @param {boolean} options.adaptiveBinaryIndices - collection indices will be actively rebuilt rather than lazily
  17768. * @memberof Collection
  17769. */
  17770. Collection.prototype.configureOptions = function (options) {
  17771. options = options || {};
  17772. if (options.hasOwnProperty('adaptiveBinaryIndices')) {
  17773. this.adaptiveBinaryIndices = options.adaptiveBinaryIndices;
  17774. // if switching to adaptive binary indices, make sure none are 'dirty'
  17775. if (this.adaptiveBinaryIndices) {
  17776. this.ensureAllIndexes();
  17777. }
  17778. }
  17779. };
  17780. /**
  17781. * Ensure binary index on a certain field
  17782. * @param {string} property - name of property to create binary index on
  17783. * @param {boolean=} force - (Optional) flag indicating whether to construct index immediately
  17784. * @memberof Collection
  17785. */
  17786. Collection.prototype.ensureIndex = function (property, force) {
  17787. // optional parameter to force rebuild whether flagged as dirty or not
  17788. if (typeof (force) === 'undefined') {
  17789. force = false;
  17790. }
  17791. if (property === null || property === undefined) {
  17792. throw new Error('Attempting to set index without an associated property');
  17793. }
  17794. if (this.binaryIndices[property] && !force) {
  17795. if (!this.binaryIndices[property].dirty) return;
  17796. }
  17797. // if the index is already defined and we are using adaptiveBinaryIndices and we are not forcing a rebuild, return.
  17798. if (this.adaptiveBinaryIndices === true && this.binaryIndices.hasOwnProperty(property) && !force) {
  17799. return;
  17800. }
  17801. var index = {
  17802. 'name': property,
  17803. 'dirty': true,
  17804. 'values': this.prepareFullDocIndex()
  17805. };
  17806. this.binaryIndices[property] = index;
  17807. var wrappedComparer =
  17808. (function (prop, data) {
  17809. var val1, val2, arr;
  17810. return function (a, b) {
  17811. if (~prop.indexOf('.')) {
  17812. arr = prop.split('.');
  17813. val1 = Utils.getIn(data[a], arr, true);
  17814. val2 = Utils.getIn(data[b], arr, true);
  17815. } else {
  17816. val1 = data[a][prop];
  17817. val2 = data[b][prop];
  17818. }
  17819. if (val1 !== val2) {
  17820. if (Comparators.lt(val1, val2, false)) return -1;
  17821. if (Comparators.gt(val1, val2, false)) return 1;
  17822. }
  17823. return 0;
  17824. };
  17825. })(property, this.data);
  17826. index.values.sort(wrappedComparer);
  17827. index.dirty = false;
  17828. this.dirty = true; // for autosave scenarios
  17829. };
  17830. /**
  17831. * Perform checks to determine validity/consistency of all binary indices
  17832. * @param {object=} options - optional configuration object
  17833. * @param {boolean} [options.randomSampling=false] - whether (faster) random sampling should be used
  17834. * @param {number} [options.randomSamplingFactor=0.10] - percentage of total rows to randomly sample
  17835. * @param {boolean} [options.repair=false] - whether to fix problems if they are encountered
  17836. * @returns {string[]} array of index names where problems were found.
  17837. * @memberof Collection
  17838. * @example
  17839. * // check all indices on a collection, returns array of invalid index names
  17840. * var result = coll.checkAllIndexes({ repair: true, randomSampling: true, randomSamplingFactor: 0.15 });
  17841. * if (result.length > 0) {
  17842. * results.forEach(function(name) {
  17843. * console.log('problem encountered with index : ' + name);
  17844. * });
  17845. * }
  17846. */
  17847. Collection.prototype.checkAllIndexes = function (options) {
  17848. var key, bIndices = this.binaryIndices;
  17849. var results = [], result;
  17850. for (key in bIndices) {
  17851. if (hasOwnProperty.call(bIndices, key)) {
  17852. result = this.checkIndex(key, options);
  17853. if (!result) {
  17854. results.push(key);
  17855. }
  17856. }
  17857. }
  17858. return results;
  17859. };
  17860. /**
  17861. * Perform checks to determine validity/consistency of a binary index
  17862. * @param {string} property - name of the binary-indexed property to check
  17863. * @param {object=} options - optional configuration object
  17864. * @param {boolean} [options.randomSampling=false] - whether (faster) random sampling should be used
  17865. * @param {number} [options.randomSamplingFactor=0.10] - percentage of total rows to randomly sample
  17866. * @param {boolean} [options.repair=false] - whether to fix problems if they are encountered
  17867. * @returns {boolean} whether the index was found to be valid (before optional correcting).
  17868. * @memberof Collection
  17869. * @example
  17870. * // full test
  17871. * var valid = coll.checkIndex('name');
  17872. * // full test with repair (if issues found)
  17873. * valid = coll.checkIndex('name', { repair: true });
  17874. * // random sampling (default is 10% of total document count)
  17875. * valid = coll.checkIndex('name', { randomSampling: true });
  17876. * // random sampling (sample 20% of total document count)
  17877. * valid = coll.checkIndex('name', { randomSampling: true, randomSamplingFactor: 0.20 });
  17878. * // random sampling (implied boolean)
  17879. * valid = coll.checkIndex('name', { randomSamplingFactor: 0.20 });
  17880. * // random sampling with repair (if issues found)
  17881. * valid = coll.checkIndex('name', { repair: true, randomSampling: true });
  17882. */
  17883. Collection.prototype.checkIndex = function (property, options) {
  17884. options = options || {};
  17885. // if 'randomSamplingFactor' specified but not 'randomSampling', assume true
  17886. if (options.randomSamplingFactor && options.randomSampling !== false) {
  17887. options.randomSampling = true;
  17888. }
  17889. options.randomSamplingFactor = options.randomSamplingFactor || 0.1;
  17890. if (options.randomSamplingFactor < 0 || options.randomSamplingFactor > 1) {
  17891. options.randomSamplingFactor = 0.1;
  17892. }
  17893. var valid=true, idx, iter, pos, len, biv;
  17894. // make sure we are passed a valid binary index name
  17895. if (!this.binaryIndices.hasOwnProperty(property)) {
  17896. throw new Error("called checkIndex on property without an index: " + property);
  17897. }
  17898. // if lazy indexing, rebuild only if flagged as dirty
  17899. if (!this.adaptiveBinaryIndices) {
  17900. this.ensureIndex(property);
  17901. }
  17902. biv = this.binaryIndices[property].values;
  17903. len = biv.length;
  17904. // if the index has an incorrect number of values
  17905. if (len !== this.data.length) {
  17906. if (options.repair) {
  17907. this.ensureIndex(property, true);
  17908. }
  17909. return false;
  17910. }
  17911. if (len === 0) {
  17912. return true;
  17913. }
  17914. var usingDotNotation = (property.indexOf('.') !== -1);
  17915. if (len === 1) {
  17916. valid = (biv[0] === 0);
  17917. }
  17918. else {
  17919. if (options.randomSampling) {
  17920. // validate first and last
  17921. if (!LokiOps.$lte(Utils.getIn(this.data[biv[0]], property, usingDotNotation),
  17922. Utils.getIn(this.data[biv[1]], property, usingDotNotation))) {
  17923. valid=false;
  17924. }
  17925. if (!LokiOps.$lte(Utils.getIn(this.data[biv[len-2]], property, usingDotNotation),
  17926. Utils.getIn(this.data[biv[len-1]], property, usingDotNotation))) {
  17927. valid=false;
  17928. }
  17929. // if first and last positions are sorted correctly with their nearest neighbor,
  17930. // continue onto random sampling phase...
  17931. if (valid) {
  17932. // # random samplings = total count * sampling factor
  17933. iter = Math.floor((len-1) * options.randomSamplingFactor);
  17934. // for each random sampling, validate that the binary index is sequenced properly
  17935. // with next higher value.
  17936. for(idx=0; idx<iter-1; idx++) {
  17937. // calculate random position
  17938. pos = Math.floor(Math.random() * (len-1));
  17939. if (!LokiOps.$lte(Utils.getIn(this.data[biv[pos]], property, usingDotNotation),
  17940. Utils.getIn(this.data[biv[pos+1]], property, usingDotNotation))) {
  17941. valid=false;
  17942. break;
  17943. }
  17944. }
  17945. }
  17946. }
  17947. else {
  17948. // validate that the binary index is sequenced properly
  17949. for(idx=0; idx<len-1; idx++) {
  17950. if (!LokiOps.$lte(Utils.getIn(this.data[biv[idx]], property, usingDotNotation),
  17951. Utils.getIn(this.data[biv[idx+1]], property, usingDotNotation))) {
  17952. valid=false;
  17953. break;
  17954. }
  17955. }
  17956. }
  17957. }
  17958. // if incorrectly sequenced and we are to fix problems, rebuild index
  17959. if (!valid && options.repair) {
  17960. this.ensureIndex(property, true);
  17961. }
  17962. return valid;
  17963. };
  17964. Collection.prototype.getBinaryIndexValues = function (property) {
  17965. var idx, idxvals = this.binaryIndices[property].values;
  17966. var result = [];
  17967. for (idx = 0; idx < idxvals.length; idx++) {
  17968. result.push(Utils.getIn(this.data[idxvals[idx]], property, true));
  17969. }
  17970. return result;
  17971. };
  17972. Collection.prototype.ensureUniqueIndex = function (field) {
  17973. var index = this.constraints.unique[field];
  17974. if (!index) {
  17975. // keep track of new unique index for regenerate after database (re)load.
  17976. if (this.uniqueNames.indexOf(field) == -1) {
  17977. this.uniqueNames.push(field);
  17978. }
  17979. }
  17980. // if index already existed, (re)loading it will likely cause collisions, rebuild always
  17981. this.constraints.unique[field] = index = new UniqueIndex(field);
  17982. this.data.forEach(function (obj) {
  17983. index.set(obj);
  17984. });
  17985. return index;
  17986. };
  17987. /**
  17988. * Ensure all binary indices
  17989. * @param {boolean} force - whether to force rebuild of existing lazy binary indices
  17990. * @memberof Collection
  17991. */
  17992. Collection.prototype.ensureAllIndexes = function (force) {
  17993. var key, bIndices = this.binaryIndices;
  17994. for (key in bIndices) {
  17995. if (hasOwnProperty.call(bIndices, key)) {
  17996. this.ensureIndex(key, force);
  17997. }
  17998. }
  17999. };
  18000. /**
  18001. * Internal method used to flag all lazy index as dirty
  18002. */
  18003. Collection.prototype.flagBinaryIndexesDirty = function () {
  18004. var key, bIndices = this.binaryIndices;
  18005. for (key in bIndices) {
  18006. if (hasOwnProperty.call(bIndices, key)) {
  18007. bIndices[key].dirty = true;
  18008. }
  18009. }
  18010. };
  18011. /**
  18012. * Internal method used to flag a lazy index as dirty
  18013. */
  18014. Collection.prototype.flagBinaryIndexDirty = function (index) {
  18015. if (this.binaryIndices[index])
  18016. this.binaryIndices[index].dirty = true;
  18017. };
  18018. /**
  18019. * Quickly determine number of documents in collection (or query)
  18020. * @param {object=} query - (optional) query object to count results of
  18021. * @returns {number} number of documents in the collection
  18022. * @memberof Collection
  18023. */
  18024. Collection.prototype.count = function (query) {
  18025. if (!query) {
  18026. return this.data.length;
  18027. }
  18028. return this.chain().find(query).filteredrows.length;
  18029. };
  18030. /**
  18031. * Rebuild idIndex
  18032. */
  18033. Collection.prototype.ensureId = function () {
  18034. var len = this.data.length,
  18035. i = 0;
  18036. this.idIndex = [];
  18037. for (i; i < len; i += 1) {
  18038. this.idIndex.push(this.data[i].$loki);
  18039. }
  18040. };
  18041. /**
  18042. * Rebuild idIndex async with callback - useful for background syncing with a remote server
  18043. */
  18044. Collection.prototype.ensureIdAsync = function (callback) {
  18045. this.async(function () {
  18046. this.ensureId();
  18047. }, callback);
  18048. };
  18049. /**
  18050. * Add a dynamic view to the collection
  18051. * @param {string} name - name of dynamic view to add
  18052. * @param {object=} options - options to configure dynamic view with
  18053. * @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata'
  18054. * @param {string} [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates)
  18055. * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here)
  18056. * @returns {DynamicView} reference to the dynamic view added
  18057. * @memberof Collection
  18058. * @example
  18059. * var pview = users.addDynamicView('progeny');
  18060. * pview.applyFind({'age': {'$lte': 40}});
  18061. * pview.applySimpleSort('name');
  18062. *
  18063. * var results = pview.data();
  18064. **/
  18065. Collection.prototype.addDynamicView = function (name, options) {
  18066. var dv = new DynamicView(this, name, options);
  18067. this.DynamicViews.push(dv);
  18068. return dv;
  18069. };
  18070. /**
  18071. * Remove a dynamic view from the collection
  18072. * @param {string} name - name of dynamic view to remove
  18073. * @memberof Collection
  18074. **/
  18075. Collection.prototype.removeDynamicView = function (name) {
  18076. this.DynamicViews =
  18077. this.DynamicViews.filter(function(dv) { return dv.name !== name; });
  18078. };
  18079. /**
  18080. * Look up dynamic view reference from within the collection
  18081. * @param {string} name - name of dynamic view to retrieve reference of
  18082. * @returns {DynamicView} A reference to the dynamic view with that name
  18083. * @memberof Collection
  18084. **/
  18085. Collection.prototype.getDynamicView = function (name) {
  18086. for (var idx = 0; idx < this.DynamicViews.length; idx++) {
  18087. if (this.DynamicViews[idx].name === name) {
  18088. return this.DynamicViews[idx];
  18089. }
  18090. }
  18091. return null;
  18092. };
  18093. /**
  18094. * Applies a 'mongo-like' find query object and passes all results to an update function.
  18095. * For filter function querying you should migrate to [updateWhere()]{@link Collection#updateWhere}.
  18096. *
  18097. * @param {object|function} filterObject - 'mongo-like' query object (or deprecated filterFunction mode)
  18098. * @param {function} updateFunction - update function to run against filtered documents
  18099. * @memberof Collection
  18100. */
  18101. Collection.prototype.findAndUpdate = function (filterObject, updateFunction) {
  18102. if (typeof (filterObject) === "function") {
  18103. this.updateWhere(filterObject, updateFunction);
  18104. }
  18105. else {
  18106. this.chain().find(filterObject).update(updateFunction);
  18107. }
  18108. };
  18109. /**
  18110. * Applies a 'mongo-like' find query object removes all documents which match that filter.
  18111. *
  18112. * @param {object} filterObject - 'mongo-like' query object
  18113. * @memberof Collection
  18114. */
  18115. Collection.prototype.findAndRemove = function(filterObject) {
  18116. this.chain().find(filterObject).remove();
  18117. };
  18118. /**
  18119. * Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc.
  18120. * @param {(object|array)} doc - the document (or array of documents) to be inserted
  18121. * @returns {(object|array)} document or documents inserted
  18122. * @memberof Collection
  18123. * @example
  18124. * users.insert({
  18125. * name: 'Odin',
  18126. * age: 50,
  18127. * address: 'Asgard'
  18128. * });
  18129. *
  18130. * // alternatively, insert array of documents
  18131. * users.insert([{ name: 'Thor', age: 35}, { name: 'Loki', age: 30}]);
  18132. */
  18133. Collection.prototype.insert = function (doc) {
  18134. if (!Array.isArray(doc)) {
  18135. return this.insertOne(doc);
  18136. }
  18137. // holder to the clone of the object inserted if collections is set to clone objects
  18138. var obj;
  18139. var results = [];
  18140. this.emit('pre-insert', doc);
  18141. for (var i = 0, len = doc.length; i < len; i++) {
  18142. obj = this.insertOne(doc[i], true);
  18143. if (!obj) {
  18144. return undefined;
  18145. }
  18146. results.push(obj);
  18147. }
  18148. // at the 'batch' level, if clone option is true then emitted docs are clones
  18149. this.emit('insert', results);
  18150. // if clone option is set, clone return values
  18151. results = this.cloneObjects ? clone(results, this.cloneMethod) : results;
  18152. return results.length === 1 ? results[0] : results;
  18153. };
  18154. /**
  18155. * Adds a single object, ensures it has meta properties, clone it if necessary, etc.
  18156. * @param {object} doc - the document to be inserted
  18157. * @param {boolean} bulkInsert - quiet pre-insert and insert event emits
  18158. * @returns {object} document or 'undefined' if there was a problem inserting it
  18159. */
  18160. Collection.prototype.insertOne = function (doc, bulkInsert) {
  18161. var err = null;
  18162. var returnObj;
  18163. if (typeof doc !== 'object') {
  18164. err = new TypeError('Document needs to be an object');
  18165. } else if (doc === null) {
  18166. err = new TypeError('Object cannot be null');
  18167. }
  18168. if (err !== null) {
  18169. this.emit('error', err);
  18170. throw err;
  18171. }
  18172. // if configured to clone, do so now... otherwise just use same obj reference
  18173. var obj = this.cloneObjects ? clone(doc, this.cloneMethod) : doc;
  18174. if (!this.disableMeta && typeof obj.meta === 'undefined') {
  18175. obj.meta = {
  18176. revision: 0,
  18177. created: 0
  18178. };
  18179. }
  18180. // both 'pre-insert' and 'insert' events are passed internal data reference even when cloning
  18181. // insert needs internal reference because that is where loki itself listens to add meta
  18182. if (!bulkInsert) {
  18183. this.emit('pre-insert', obj);
  18184. }
  18185. if (!this.add(obj)) {
  18186. return undefined;
  18187. }
  18188. // update meta and store changes if ChangesAPI is enabled
  18189. // (moved from "insert" event listener to allow internal reference to be used)
  18190. if (this.disableChangesApi) {
  18191. this.insertMeta(obj);
  18192. }
  18193. else {
  18194. this.insertMetaWithChange(obj);
  18195. }
  18196. // if cloning is enabled, emit insert event with clone of new object
  18197. returnObj = this.cloneObjects ? clone(obj, this.cloneMethod) : obj;
  18198. if (!bulkInsert) {
  18199. this.emit('insert', returnObj);
  18200. }
  18201. this.addAutoUpdateObserver(returnObj);
  18202. return returnObj;
  18203. };
  18204. /**
  18205. * Empties the collection.
  18206. * @param {object=} options - configure clear behavior
  18207. * @param {bool=} [options.removeIndices=false] - whether to remove indices in addition to data
  18208. * @memberof Collection
  18209. */
  18210. Collection.prototype.clear = function (options) {
  18211. var self = this;
  18212. options = options || {};
  18213. this.data = [];
  18214. this.idIndex = [];
  18215. this.cachedIndex = null;
  18216. this.cachedBinaryIndex = null;
  18217. this.cachedData = null;
  18218. this.maxId = 0;
  18219. this.DynamicViews = [];
  18220. this.dirty = true;
  18221. // if removing indices entirely
  18222. if (options.removeIndices === true) {
  18223. this.binaryIndices = {};
  18224. this.constraints = {
  18225. unique: {},
  18226. exact: {}
  18227. };
  18228. this.uniqueNames = [];
  18229. }
  18230. // clear indices but leave definitions in place
  18231. else {
  18232. // clear binary indices
  18233. var keys = Object.keys(this.binaryIndices);
  18234. keys.forEach(function(biname) {
  18235. self.binaryIndices[biname].dirty = false;
  18236. self.binaryIndices[biname].values = [];
  18237. });
  18238. // clear entire unique indices definition
  18239. this.constraints = {
  18240. unique: {},
  18241. exact: {}
  18242. };
  18243. // add definitions back
  18244. this.uniqueNames.forEach(function(uiname) {
  18245. self.ensureUniqueIndex(uiname);
  18246. });
  18247. }
  18248. };
  18249. /**
  18250. * Updates an object and notifies collection that the document has changed.
  18251. * @param {object} doc - document to update within the collection
  18252. * @memberof Collection
  18253. */
  18254. Collection.prototype.update = function (doc) {
  18255. var adaptiveBatchOverride, k, len;
  18256. if (Array.isArray(doc)) {
  18257. len = doc.length;
  18258. // if not cloning, disable adaptive binary indices for the duration of the batch update,
  18259. // followed by lazy rebuild and re-enabling adaptive indices after batch update.
  18260. adaptiveBatchOverride = !this.cloneObjects &&
  18261. this.adaptiveBinaryIndices && Object.keys(this.binaryIndices).length > 0;
  18262. if (adaptiveBatchOverride) {
  18263. this.adaptiveBinaryIndices = false;
  18264. }
  18265. try {
  18266. for (k=0; k < len; k += 1) {
  18267. this.update(doc[k]);
  18268. }
  18269. }
  18270. finally {
  18271. if (adaptiveBatchOverride) {
  18272. this.ensureAllIndexes();
  18273. this.adaptiveBinaryIndices = true;
  18274. }
  18275. }
  18276. return;
  18277. }
  18278. // verify object is a properly formed document
  18279. if (!hasOwnProperty.call(doc, '$loki')) {
  18280. throw new Error('Trying to update unsynced document. Please save the document first by using insert() or addMany()');
  18281. }
  18282. try {
  18283. this.startTransaction();
  18284. var arr = this.get(doc.$loki, true),
  18285. oldInternal, // ref to existing obj
  18286. newInternal, // ref to new internal obj
  18287. position,
  18288. self = this;
  18289. if (!arr) {
  18290. throw new Error('Trying to update a document not in collection.');
  18291. }
  18292. oldInternal = arr[0]; // -internal- obj ref
  18293. position = arr[1]; // position in data array
  18294. // if configured to clone, do so now... otherwise just use same obj reference
  18295. newInternal = this.cloneObjects || !this.disableDeltaChangesApi ? clone(doc, this.cloneMethod) : doc;
  18296. this.emit('pre-update', doc);
  18297. Object.keys(this.constraints.unique).forEach(function (key) {
  18298. self.constraints.unique[key].update(oldInternal, newInternal);
  18299. });
  18300. // operate the update
  18301. this.data[position] = newInternal;
  18302. if (newInternal !== doc) {
  18303. this.addAutoUpdateObserver(doc);
  18304. }
  18305. // now that we can efficiently determine the data[] position of newly added document,
  18306. // submit it for all registered DynamicViews to evaluate for inclusion/exclusion
  18307. for (var idx = 0; idx < this.DynamicViews.length; idx++) {
  18308. this.DynamicViews[idx].evaluateDocument(position, false);
  18309. }
  18310. var key;
  18311. if (this.adaptiveBinaryIndices) {
  18312. // for each binary index defined in collection, immediately update rather than flag for lazy rebuild
  18313. var bIndices = this.binaryIndices;
  18314. for (key in bIndices) {
  18315. this.adaptiveBinaryIndexUpdate(position, key);
  18316. }
  18317. }
  18318. else {
  18319. this.flagBinaryIndexesDirty();
  18320. }
  18321. this.idIndex[position] = newInternal.$loki;
  18322. //this.flagBinaryIndexesDirty();
  18323. this.commit();
  18324. this.dirty = true; // for autosave scenarios
  18325. // update meta and store changes if ChangesAPI is enabled
  18326. if (this.disableChangesApi) {
  18327. this.updateMeta(newInternal, null);
  18328. }
  18329. else {
  18330. this.updateMetaWithChange(newInternal, oldInternal);
  18331. }
  18332. var returnObj;
  18333. // if cloning is enabled, emit 'update' event and return with clone of new object
  18334. if (this.cloneObjects) {
  18335. returnObj = clone(newInternal, this.cloneMethod);
  18336. }
  18337. else {
  18338. returnObj = newInternal;
  18339. }
  18340. this.emit('update', returnObj, oldInternal);
  18341. return returnObj;
  18342. } catch (err) {
  18343. this.rollback();
  18344. this.console.error(err.message);
  18345. this.emit('error', err);
  18346. throw (err); // re-throw error so user does not think it succeeded
  18347. }
  18348. };
  18349. /**
  18350. * Add object to collection
  18351. */
  18352. Collection.prototype.add = function (obj) {
  18353. // if parameter isn't object exit with throw
  18354. if ('object' !== typeof obj) {
  18355. throw new TypeError('Object being added needs to be an object');
  18356. }
  18357. // if object you are adding already has id column it is either already in the collection
  18358. // or the object is carrying its own 'id' property. If it also has a meta property,
  18359. // then this is already in collection so throw error, otherwise rename to originalId and continue adding.
  18360. if (typeof (obj.$loki) !== 'undefined') {
  18361. throw new Error('Document is already in collection, please use update()');
  18362. }
  18363. /*
  18364. * try adding object to collection
  18365. */
  18366. try {
  18367. this.startTransaction();
  18368. this.maxId++;
  18369. if (isNaN(this.maxId)) {
  18370. this.maxId = (this.data[this.data.length - 1].$loki + 1);
  18371. }
  18372. obj.$loki = this.maxId;
  18373. if (!this.disableMeta) {
  18374. obj.meta.version = 0;
  18375. }
  18376. var key, constrUnique = this.constraints.unique;
  18377. for (key in constrUnique) {
  18378. if (hasOwnProperty.call(constrUnique, key)) {
  18379. constrUnique[key].set(obj);
  18380. }
  18381. }
  18382. // add new obj id to idIndex
  18383. this.idIndex.push(obj.$loki);
  18384. // add the object
  18385. this.data.push(obj);
  18386. var addedPos = this.data.length - 1;
  18387. // now that we can efficiently determine the data[] position of newly added document,
  18388. // submit it for all registered DynamicViews to evaluate for inclusion/exclusion
  18389. var dvlen = this.DynamicViews.length;
  18390. for (var i = 0; i < dvlen; i++) {
  18391. this.DynamicViews[i].evaluateDocument(addedPos, true);
  18392. }
  18393. if (this.adaptiveBinaryIndices) {
  18394. // for each binary index defined in collection, immediately update rather than flag for lazy rebuild
  18395. var bIndices = this.binaryIndices;
  18396. for (key in bIndices) {
  18397. this.adaptiveBinaryIndexInsert(addedPos, key);
  18398. }
  18399. }
  18400. else {
  18401. this.flagBinaryIndexesDirty();
  18402. }
  18403. this.commit();
  18404. this.dirty = true; // for autosave scenarios
  18405. return (this.cloneObjects) ? (clone(obj, this.cloneMethod)) : (obj);
  18406. } catch (err) {
  18407. this.rollback();
  18408. this.console.error(err.message);
  18409. this.emit('error', err);
  18410. throw (err); // re-throw error so user does not think it succeeded
  18411. }
  18412. };
  18413. /**
  18414. * Applies a filter function and passes all results to an update function.
  18415. *
  18416. * @param {function} filterFunction - filter function whose results will execute update
  18417. * @param {function} updateFunction - update function to run against filtered documents
  18418. * @memberof Collection
  18419. */
  18420. Collection.prototype.updateWhere = function(filterFunction, updateFunction) {
  18421. var results = this.where(filterFunction),
  18422. i = 0,
  18423. obj;
  18424. try {
  18425. for (i; i < results.length; i++) {
  18426. obj = updateFunction(results[i]);
  18427. this.update(obj);
  18428. }
  18429. } catch (err) {
  18430. this.rollback();
  18431. this.console.error(err.message);
  18432. }
  18433. };
  18434. /**
  18435. * Remove all documents matching supplied filter function.
  18436. * For 'mongo-like' querying you should migrate to [findAndRemove()]{@link Collection#findAndRemove}.
  18437. * @param {function|object} query - query object to filter on
  18438. * @memberof Collection
  18439. */
  18440. Collection.prototype.removeWhere = function (query) {
  18441. var list;
  18442. if (typeof query === 'function') {
  18443. list = this.data.filter(query);
  18444. this.remove(list);
  18445. } else {
  18446. this.chain().find(query).remove();
  18447. }
  18448. };
  18449. Collection.prototype.removeDataOnly = function () {
  18450. this.remove(this.data.slice());
  18451. };
  18452. /**
  18453. * Internal method to remove a batch of documents from the collection.
  18454. * @param {number[]} positions - data/idIndex positions to remove
  18455. */
  18456. Collection.prototype.removeBatchByPositions = function(positions) {
  18457. var len = positions.length;
  18458. var xo = {};
  18459. var dlen, didx, idx;
  18460. var bic=Object.keys(this.binaryIndices).length;
  18461. var uic=Object.keys(this.constraints.unique).length;
  18462. var adaptiveOverride = this.adaptiveBinaryIndices && Object.keys(this.binaryIndices).length > 0;
  18463. var doc, self=this;
  18464. try {
  18465. this.startTransaction();
  18466. // create hashobject for positional removal inclusion tests...
  18467. // all keys defined in this hashobject represent $loki ids of the documents to remove.
  18468. for(idx=0; idx < len; idx++) {
  18469. xo[this.idIndex[positions[idx]]] = true;
  18470. }
  18471. // if we will need to notify dynamic views and/or binary indices to update themselves...
  18472. dlen = this.DynamicViews.length;
  18473. if ((dlen > 0) || (bic > 0) || (uic > 0)) {
  18474. if (dlen > 0) {
  18475. // notify dynamic views to remove relevant documents at data positions
  18476. for (didx = 0; didx < dlen; didx++) {
  18477. // notify dv of remove (passing batch/array of positions)
  18478. this.DynamicViews[didx].removeDocument(positions);
  18479. }
  18480. }
  18481. // notify binary indices to update
  18482. if (this.adaptiveBinaryIndices && !adaptiveOverride) {
  18483. // for each binary index defined in collection, immediately update rather than flag for lazy rebuild
  18484. var key, bIndices = this.binaryIndices;
  18485. for (key in bIndices) {
  18486. this.adaptiveBinaryIndexRemove(positions, key);
  18487. }
  18488. }
  18489. else {
  18490. this.flagBinaryIndexesDirty();
  18491. }
  18492. if (uic) {
  18493. Object.keys(this.constraints.unique).forEach(function (key) {
  18494. for(idx=0; idx < len; idx++) {
  18495. doc = self.data[positions[idx]];
  18496. if (doc[key] !== null && doc[key] !== undefined) {
  18497. self.constraints.unique[key].remove(doc[key]);
  18498. }
  18499. }
  18500. });
  18501. }
  18502. }
  18503. // emit 'delete' events only of listeners are attached.
  18504. // since data not removed yet, in future we can emit single delete event with array...
  18505. // for now that might be breaking change to put in potential 1.6 or LokiDB (lokijs2) version
  18506. if (!this.disableChangesApi || this.events.delete.length > 1) {
  18507. for(idx=0; idx < len; idx++) {
  18508. this.emit('delete', this.data[positions[idx]]);
  18509. }
  18510. }
  18511. // remove from data[] :
  18512. // filter collection data for items not in inclusion hashobject
  18513. this.data = this.data.filter(function(obj) {
  18514. return !xo[obj.$loki];
  18515. });
  18516. // remove from idIndex[] :
  18517. // filter idIndex for items not in inclusion hashobject
  18518. this.idIndex = this.idIndex.filter(function(id) {
  18519. return !xo[id];
  18520. });
  18521. if (this.adaptiveBinaryIndices && adaptiveOverride) {
  18522. this.adaptiveBinaryIndices = false;
  18523. this.ensureAllIndexes(true);
  18524. this.adaptiveBinaryIndices = true;
  18525. }
  18526. this.commit();
  18527. // flag collection as dirty for autosave
  18528. this.dirty = true;
  18529. }
  18530. catch (err) {
  18531. this.rollback();
  18532. if (adaptiveOverride) {
  18533. this.adaptiveBinaryIndices = true;
  18534. }
  18535. this.console.error(err.message);
  18536. this.emit('error', err);
  18537. return null;
  18538. }
  18539. };
  18540. /**
  18541. * Internal method called by remove()
  18542. * @param {object[]|number[]} batch - array of documents or $loki ids to remove
  18543. */
  18544. Collection.prototype.removeBatch = function(batch) {
  18545. var len = batch.length,
  18546. dlen=this.data.length,
  18547. idx;
  18548. var xlt = {};
  18549. var posx = [];
  18550. // create lookup hashobject to translate $loki id to position
  18551. for (idx=0; idx < dlen; idx++) {
  18552. xlt[this.data[idx].$loki] = idx;
  18553. }
  18554. // iterate the batch
  18555. for (idx=0; idx < len; idx++) {
  18556. if (typeof(batch[idx]) === 'object') {
  18557. posx.push(xlt[batch[idx].$loki]);
  18558. }
  18559. else {
  18560. posx.push(xlt[batch[idx]]);
  18561. }
  18562. }
  18563. this.removeBatchByPositions(posx);
  18564. };
  18565. /**
  18566. * Remove a document from the collection
  18567. * @param {object} doc - document to remove from collection
  18568. * @memberof Collection
  18569. */
  18570. Collection.prototype.remove = function (doc) {
  18571. if (typeof doc === 'number') {
  18572. doc = this.get(doc);
  18573. }
  18574. if ('object' !== typeof doc) {
  18575. throw new Error('Parameter is not an object');
  18576. }
  18577. if (Array.isArray(doc)) {
  18578. this.removeBatch(doc);
  18579. return;
  18580. }
  18581. if (!hasOwnProperty.call(doc, '$loki')) {
  18582. throw new Error('Object is not a document stored in the collection');
  18583. }
  18584. try {
  18585. this.startTransaction();
  18586. var arr = this.get(doc.$loki, true),
  18587. // obj = arr[0],
  18588. position = arr[1];
  18589. var self = this;
  18590. Object.keys(this.constraints.unique).forEach(function (key) {
  18591. if (doc[key] !== null && typeof doc[key] !== 'undefined') {
  18592. self.constraints.unique[key].remove(doc[key]);
  18593. }
  18594. });
  18595. // now that we can efficiently determine the data[] position of newly added document,
  18596. // submit it for all registered DynamicViews to remove
  18597. for (var idx = 0; idx < this.DynamicViews.length; idx++) {
  18598. this.DynamicViews[idx].removeDocument(position);
  18599. }
  18600. if (this.adaptiveBinaryIndices) {
  18601. // for each binary index defined in collection, immediately update rather than flag for lazy rebuild
  18602. var key, bIndices = this.binaryIndices;
  18603. for (key in bIndices) {
  18604. this.adaptiveBinaryIndexRemove(position, key);
  18605. }
  18606. }
  18607. else {
  18608. this.flagBinaryIndexesDirty();
  18609. }
  18610. this.data.splice(position, 1);
  18611. this.removeAutoUpdateObserver(doc);
  18612. // remove id from idIndex
  18613. this.idIndex.splice(position, 1);
  18614. this.commit();
  18615. this.dirty = true; // for autosave scenarios
  18616. this.emit('delete', arr[0]);
  18617. delete doc.$loki;
  18618. delete doc.meta;
  18619. return doc;
  18620. } catch (err) {
  18621. this.rollback();
  18622. this.console.error(err.message);
  18623. this.emit('error', err);
  18624. return null;
  18625. }
  18626. };
  18627. /*---------------------+
  18628. | Finding methods |
  18629. +----------------------*/
  18630. /**
  18631. * Get by Id - faster than other methods because of the searching algorithm
  18632. * @param {int} id - $loki id of document you want to retrieve
  18633. * @param {boolean} returnPosition - if 'true' we will return [object, position]
  18634. * @returns {(object|array|null)} Object reference if document was found, null if not,
  18635. * or an array if 'returnPosition' was passed.
  18636. * @memberof Collection
  18637. */
  18638. Collection.prototype.get = function (id, returnPosition) {
  18639. var retpos = returnPosition || false,
  18640. data = this.idIndex,
  18641. max = data.length - 1,
  18642. min = 0,
  18643. mid = (min + max) >> 1;
  18644. id = typeof id === 'number' ? id : parseInt(id, 10);
  18645. if (isNaN(id)) {
  18646. throw new TypeError('Passed id is not an integer');
  18647. }
  18648. while (data[min] < data[max]) {
  18649. mid = (min + max) >> 1;
  18650. if (data[mid] < id) {
  18651. min = mid + 1;
  18652. } else {
  18653. max = mid;
  18654. }
  18655. }
  18656. if (max === min && data[min] === id) {
  18657. if (retpos) {
  18658. return [this.data[min], min];
  18659. }
  18660. return this.data[min];
  18661. }
  18662. return null;
  18663. };
  18664. /**
  18665. * Perform binary range lookup for the data[dataPosition][binaryIndexName] property value
  18666. * Since multiple documents may contain the same value (which the index is sorted on),
  18667. * we hone in on range and then linear scan range to find exact index array position.
  18668. * @param {int} dataPosition : coll.data array index/position
  18669. * @param {string} binaryIndexName : index to search for dataPosition in
  18670. */
  18671. Collection.prototype.getBinaryIndexPosition = function(dataPosition, binaryIndexName) {
  18672. var val = Utils.getIn(this.data[dataPosition], binaryIndexName, true);
  18673. var index = this.binaryIndices[binaryIndexName].values;
  18674. // i think calculateRange can probably be moved to collection
  18675. // as it doesn't seem to need resultset. need to verify
  18676. var range = this.calculateRange("$eq", binaryIndexName, val);
  18677. if (range[0] === 0 && range[1] === -1) {
  18678. // uhoh didn't find range
  18679. return null;
  18680. }
  18681. var min = range[0];
  18682. var max = range[1];
  18683. // narrow down the sub-segment of index values
  18684. // where the indexed property value exactly matches our
  18685. // value and then linear scan to find exact -index- position
  18686. for(var idx = min; idx <= max; idx++) {
  18687. if (index[idx] === dataPosition) return idx;
  18688. }
  18689. // uhoh
  18690. return null;
  18691. };
  18692. /**
  18693. * Adaptively insert a selected item to the index.
  18694. * @param {int} dataPosition : coll.data array index/position
  18695. * @param {string} binaryIndexName : index to search for dataPosition in
  18696. */
  18697. Collection.prototype.adaptiveBinaryIndexInsert = function(dataPosition, binaryIndexName) {
  18698. var usingDotNotation = (binaryIndexName.indexOf('.') !== -1);
  18699. var index = this.binaryIndices[binaryIndexName].values;
  18700. var val = Utils.getIn(this.data[dataPosition], binaryIndexName, usingDotNotation);
  18701. // If you are inserting a javascript Date value into a binary index, convert to epoch time
  18702. if (this.serializableIndices === true && val instanceof Date) {
  18703. this.data[dataPosition][binaryIndexName] = val.getTime();
  18704. val = Utils.getIn(this.data[dataPosition], binaryIndexName);
  18705. }
  18706. var idxPos = (index.length === 0)?0:this.calculateRangeStart(binaryIndexName, val, true, usingDotNotation);
  18707. // insert new data index into our binary index at the proper sorted location for relevant property calculated by idxPos.
  18708. // doing this after adjusting dataPositions so no clash with previous item at that position.
  18709. this.binaryIndices[binaryIndexName].values.splice(idxPos, 0, dataPosition);
  18710. };
  18711. /**
  18712. * Adaptively update a selected item within an index.
  18713. * @param {int} dataPosition : coll.data array index/position
  18714. * @param {string} binaryIndexName : index to search for dataPosition in
  18715. */
  18716. Collection.prototype.adaptiveBinaryIndexUpdate = function(dataPosition, binaryIndexName) {
  18717. // linear scan needed to find old position within index unless we optimize for clone scenarios later
  18718. // within (my) node 5.6.0, the following for() loop with strict compare is -much- faster than indexOf()
  18719. var idxPos,
  18720. index = this.binaryIndices[binaryIndexName].values,
  18721. len=index.length;
  18722. for(idxPos=0; idxPos < len; idxPos++) {
  18723. if (index[idxPos] === dataPosition) break;
  18724. }
  18725. //var idxPos = this.binaryIndices[binaryIndexName].values.indexOf(dataPosition);
  18726. this.binaryIndices[binaryIndexName].values.splice(idxPos, 1);
  18727. //this.adaptiveBinaryIndexRemove(dataPosition, binaryIndexName, true);
  18728. this.adaptiveBinaryIndexInsert(dataPosition, binaryIndexName);
  18729. };
  18730. /**
  18731. * Adaptively remove a selected item from the index.
  18732. * @param {number|number[]} dataPosition : coll.data array index/position
  18733. * @param {string} binaryIndexName : index to search for dataPosition in
  18734. */
  18735. Collection.prototype.adaptiveBinaryIndexRemove = function(dataPosition, binaryIndexName, removedFromIndexOnly) {
  18736. var bi = this.binaryIndices[binaryIndexName];
  18737. var len, idx, rmidx, rmlen, rxo = {};
  18738. var curr, shift, idxPos;
  18739. if (Array.isArray(dataPosition)) {
  18740. // when called from chained remove, and only one document in array,
  18741. // it will be faster to use old algorithm
  18742. rmlen = dataPosition.length;
  18743. if (rmlen === 1) {
  18744. dataPosition = dataPosition[0];
  18745. }
  18746. // we were passed an array (batch) of documents so use this 'batch optimized' algorithm
  18747. else {
  18748. for(rmidx=0;rmidx<rmlen; rmidx++) {
  18749. rxo[dataPosition[rmidx]] = true;
  18750. }
  18751. // remove document from index (with filter function)
  18752. bi.values = bi.values.filter(function(di) { return !rxo[di]; });
  18753. // if we passed this optional flag parameter, we are calling from adaptiveBinaryIndexUpdate,
  18754. // in which case data positions stay the same.
  18755. if (removedFromIndexOnly === true) {
  18756. return;
  18757. }
  18758. var sortedPositions = dataPosition.slice();
  18759. sortedPositions.sort(function (a, b) { return a-b; });
  18760. // to remove holes, we need to 'shift down' the index's data array positions
  18761. // we need to adjust array positions -1 for each index data positions greater than removed positions
  18762. len = bi.values.length;
  18763. for (idx=0; idx<len; idx++) {
  18764. curr=bi.values[idx];
  18765. shift=0;
  18766. for(rmidx=0; rmidx<rmlen && curr > sortedPositions[rmidx]; rmidx++) {
  18767. shift++;
  18768. }
  18769. bi.values[idx]-=shift;
  18770. }
  18771. // batch processed, bail out
  18772. return;
  18773. }
  18774. // not a batch so continue...
  18775. }
  18776. idxPos = this.getBinaryIndexPosition(dataPosition, binaryIndexName);
  18777. if (idxPos === null) {
  18778. // throw new Error('unable to determine binary index position');
  18779. return null;
  18780. }
  18781. // remove document from index (with splice)
  18782. bi.values.splice(idxPos, 1);
  18783. // if we passed this optional flag parameter, we are calling from adaptiveBinaryIndexUpdate,
  18784. // in which case data positions stay the same.
  18785. if (removedFromIndexOnly === true) {
  18786. return;
  18787. }
  18788. // since index stores data array positions, if we remove a document
  18789. // we need to adjust array positions -1 for all document positions greater than removed position
  18790. len = bi.values.length;
  18791. for (idx = 0; idx < len; idx++) {
  18792. if (bi.values[idx] > dataPosition) {
  18793. bi.values[idx]--;
  18794. }
  18795. }
  18796. };
  18797. /**
  18798. * Internal method used for index maintenance and indexed searching.
  18799. * Calculates the beginning of an index range for a given value.
  18800. * For index maintainance (adaptive:true), we will return a valid index position to insert to.
  18801. * For querying (adaptive:false/undefined), we will :
  18802. * return lower bound/index of range of that value (if found)
  18803. * return next lower index position if not found (hole)
  18804. * If index is empty it is assumed to be handled at higher level, so
  18805. * this method assumes there is at least 1 document in index.
  18806. *
  18807. * @param {string} prop - name of property which has binary index
  18808. * @param {any} val - value to find within index
  18809. * @param {bool?} adaptive - if true, we will return insert position
  18810. */
  18811. Collection.prototype.calculateRangeStart = function (prop, val, adaptive, usingDotNotation) {
  18812. var rcd = this.data;
  18813. var index = this.binaryIndices[prop].values;
  18814. var min = 0;
  18815. var max = index.length - 1;
  18816. var mid = 0;
  18817. if (index.length === 0) {
  18818. return -1;
  18819. }
  18820. var minVal = Utils.getIn(rcd[index[min]], prop, usingDotNotation);
  18821. var maxVal = Utils.getIn(rcd[index[max]], prop, usingDotNotation);
  18822. // hone in on start position of value
  18823. while (min < max) {
  18824. mid = (min + max) >> 1;
  18825. if (Comparators.lt(Utils.getIn(rcd[index[mid]], prop, usingDotNotation), val, false)) {
  18826. min = mid + 1;
  18827. } else {
  18828. max = mid;
  18829. }
  18830. }
  18831. var lbound = min;
  18832. // found it... return it
  18833. if (Comparators.aeq(val, Utils.getIn(rcd[index[lbound]], prop, usingDotNotation))) {
  18834. return lbound;
  18835. }
  18836. // if not in index and our value is less than the found one
  18837. if (Comparators.lt(val, Utils.getIn(rcd[index[lbound]], prop, usingDotNotation), false)) {
  18838. return adaptive?lbound:lbound-1;
  18839. }
  18840. // not in index and our value is greater than the found one
  18841. return adaptive?lbound+1:lbound;
  18842. };
  18843. /**
  18844. * Internal method used for indexed $between. Given a prop (index name), and a value
  18845. * (which may or may not yet exist) this will find the final position of that upper range value.
  18846. */
  18847. Collection.prototype.calculateRangeEnd = function (prop, val, usingDotNotation) {
  18848. var rcd = this.data;
  18849. var index = this.binaryIndices[prop].values;
  18850. var min = 0;
  18851. var max = index.length - 1;
  18852. var mid = 0;
  18853. if (index.length === 0) {
  18854. return -1;
  18855. }
  18856. var minVal = Utils.getIn(rcd[index[min]], prop, usingDotNotation);
  18857. var maxVal = Utils.getIn(rcd[index[max]], prop, usingDotNotation);
  18858. // hone in on start position of value
  18859. while (min < max) {
  18860. mid = (min + max) >> 1;
  18861. if (Comparators.lt(val, Utils.getIn(rcd[index[mid]], prop, usingDotNotation), false)) {
  18862. max = mid;
  18863. } else {
  18864. min = mid + 1;
  18865. }
  18866. }
  18867. var ubound = max;
  18868. // only eq if last element in array is our val
  18869. if (Comparators.aeq(val, Utils.getIn(rcd[index[ubound]], prop, usingDotNotation))) {
  18870. return ubound;
  18871. }
  18872. // if not in index and our value is less than the found one
  18873. if (Comparators.gt(val, Utils.getIn(rcd[index[ubound]], prop, usingDotNotation), false)) {
  18874. return ubound+1;
  18875. }
  18876. // either hole or first nonmatch
  18877. if (Comparators.aeq(val, Utils.getIn(rcd[index[ubound-1]], prop, usingDotNotation))) {
  18878. return ubound-1;
  18879. }
  18880. // hole, so ubound if nearest gt than the val we were looking for
  18881. return ubound;
  18882. };
  18883. /**
  18884. * calculateRange() - Binary Search utility method to find range/segment of values matching criteria.
  18885. * this is used for collection.find() and first find filter of resultset/dynview
  18886. * slightly different than get() binary search in that get() hones in on 1 value,
  18887. * but we have to hone in on many (range)
  18888. * @param {string} op - operation, such as $eq
  18889. * @param {string} prop - name of property to calculate range for
  18890. * @param {object} val - value to use for range calculation.
  18891. * @returns {array} [start, end] index array positions
  18892. */
  18893. Collection.prototype.calculateRange = function (op, prop, val) {
  18894. var rcd = this.data;
  18895. var index = this.binaryIndices[prop].values;
  18896. var min = 0;
  18897. var max = index.length - 1;
  18898. var mid = 0;
  18899. var lbound, lval;
  18900. var ubound, uval;
  18901. // when no documents are in collection, return empty range condition
  18902. if (rcd.length === 0) {
  18903. return [0, -1];
  18904. }
  18905. var usingDotNotation = (prop.indexOf('.') !== -1);
  18906. var minVal = Utils.getIn(rcd[index[min]], prop, usingDotNotation);
  18907. var maxVal = Utils.getIn(rcd[index[max]], prop, usingDotNotation);
  18908. // if value falls outside of our range return [0, -1] to designate no results
  18909. switch (op) {
  18910. case '$eq':
  18911. case '$aeq':
  18912. if (Comparators.lt(val, minVal, false) || Comparators.gt(val, maxVal, false)) {
  18913. return [0, -1];
  18914. }
  18915. break;
  18916. case '$dteq':
  18917. if (Comparators.lt(val, minVal, false) || Comparators.gt(val, maxVal, false)) {
  18918. return [0, -1];
  18919. }
  18920. break;
  18921. case '$gt':
  18922. // none are within range
  18923. if (Comparators.gt(val, maxVal, true)) {
  18924. return [0, -1];
  18925. }
  18926. // all are within range
  18927. if (Comparators.gt(minVal, val, false)) {
  18928. return [min, max];
  18929. }
  18930. break;
  18931. case '$gte':
  18932. // none are within range
  18933. if (Comparators.gt(val, maxVal, false)) {
  18934. return [0, -1];
  18935. }
  18936. // all are within range
  18937. if (Comparators.gt(minVal, val, true)) {
  18938. return [min, max];
  18939. }
  18940. break;
  18941. case '$lt':
  18942. // none are within range
  18943. if (Comparators.lt(val, minVal, true)) {
  18944. return [0, -1];
  18945. }
  18946. // all are within range
  18947. if (Comparators.lt(maxVal, val, false)) {
  18948. return [min, max];
  18949. }
  18950. break;
  18951. case '$lte':
  18952. // none are within range
  18953. if (Comparators.lt(val, minVal, false)) {
  18954. return [0, -1];
  18955. }
  18956. // all are within range
  18957. if (Comparators.lt(maxVal, val, true)) {
  18958. return [min, max];
  18959. }
  18960. break;
  18961. case '$between':
  18962. // none are within range (low range is greater)
  18963. if (Comparators.gt(val[0], maxVal, false)) {
  18964. return [0, -1];
  18965. }
  18966. // none are within range (high range lower)
  18967. if (Comparators.lt(val[1], minVal, false)) {
  18968. return [0, -1];
  18969. }
  18970. lbound = this.calculateRangeStart(prop, val[0], false, usingDotNotation);
  18971. ubound = this.calculateRangeEnd(prop, val[1], usingDotNotation);
  18972. if (lbound < 0) lbound++;
  18973. if (ubound > max) ubound--;
  18974. if (!Comparators.gt(Utils.getIn(rcd[index[lbound]], prop, usingDotNotation), val[0], true)) lbound++;
  18975. if (!Comparators.lt(Utils.getIn(rcd[index[ubound]], prop, usingDotNotation), val[1], true)) ubound--;
  18976. if (ubound < lbound) return [0, -1];
  18977. return ([lbound, ubound]);
  18978. case '$in':
  18979. var idxset = [],
  18980. segResult = [];
  18981. // query each value '$eq' operator and merge the seqment results.
  18982. for (var j = 0, len = val.length; j < len; j++) {
  18983. var seg = this.calculateRange('$eq', prop, val[j]);
  18984. for (var i = seg[0]; i <= seg[1]; i++) {
  18985. if (idxset[i] === undefined) {
  18986. idxset[i] = true;
  18987. segResult.push(i);
  18988. }
  18989. }
  18990. }
  18991. return segResult;
  18992. }
  18993. // determine lbound where needed
  18994. switch (op) {
  18995. case '$eq':
  18996. case '$aeq':
  18997. case '$dteq':
  18998. case '$gte':
  18999. case '$lt':
  19000. lbound = this.calculateRangeStart(prop, val, false, usingDotNotation);
  19001. lval = Utils.getIn(rcd[index[lbound]], prop, usingDotNotation);
  19002. break;
  19003. default: break;
  19004. }
  19005. // determine ubound where needed
  19006. switch (op) {
  19007. case '$eq':
  19008. case '$aeq':
  19009. case '$dteq':
  19010. case '$lte':
  19011. case '$gt':
  19012. ubound = this.calculateRangeEnd(prop, val, usingDotNotation);
  19013. uval = Utils.getIn(rcd[index[ubound]], prop, usingDotNotation);
  19014. break;
  19015. default: break;
  19016. }
  19017. switch (op) {
  19018. case '$eq':
  19019. case '$aeq':
  19020. case '$dteq':
  19021. // if hole (not found)
  19022. if (!Comparators.aeq(lval, val)) {
  19023. return [0, -1];
  19024. }
  19025. return [lbound, ubound];
  19026. case '$gt':
  19027. // if hole (not found) ub position is already greater
  19028. if (!Comparators.aeq(Utils.getIn(rcd[index[ubound]], prop, usingDotNotation), val)) {
  19029. return [ubound, max];
  19030. }
  19031. // otherwise (found) so ubound is still equal, get next
  19032. return [ubound+1, max];
  19033. case '$gte':
  19034. // if hole (not found) lb position marks left outside of range
  19035. if (!Comparators.aeq(Utils.getIn(rcd[index[lbound]], prop, usingDotNotation), val)) {
  19036. return [lbound+1, max];
  19037. }
  19038. // otherwise (found) so lb is first position where its equal
  19039. return [lbound, max];
  19040. case '$lt':
  19041. // if hole (not found) position already is less than
  19042. if (!Comparators.aeq(Utils.getIn(rcd[index[lbound]], prop, usingDotNotation), val)) {
  19043. return [min, lbound];
  19044. }
  19045. // otherwise (found) so lb marks left inside of eq range, get previous
  19046. return [min, lbound-1];
  19047. case '$lte':
  19048. // if hole (not found) ub position marks right outside so get previous
  19049. if (!Comparators.aeq(Utils.getIn(rcd[index[ubound]], prop, usingDotNotation), val)) {
  19050. return [min, ubound-1];
  19051. }
  19052. // otherwise (found) so ub is last position where its still equal
  19053. return [min, ubound];
  19054. default:
  19055. return [0, rcd.length - 1];
  19056. }
  19057. };
  19058. /**
  19059. * Retrieve doc by Unique index
  19060. * @param {string} field - name of uniquely indexed property to use when doing lookup
  19061. * @param {value} value - unique value to search for
  19062. * @returns {object} document matching the value passed
  19063. * @memberof Collection
  19064. */
  19065. Collection.prototype.by = function (field, value) {
  19066. var self;
  19067. if (value === undefined) {
  19068. self = this;
  19069. return function (value) {
  19070. return self.by(field, value);
  19071. };
  19072. }
  19073. var result = this.constraints.unique[field].get(value);
  19074. if (!this.cloneObjects) {
  19075. return result;
  19076. } else {
  19077. return clone(result, this.cloneMethod);
  19078. }
  19079. };
  19080. /**
  19081. * Find one object by index property, by property equal to value
  19082. * @param {object} query - query object used to perform search with
  19083. * @returns {(object|null)} First matching document, or null if none
  19084. * @memberof Collection
  19085. */
  19086. Collection.prototype.findOne = function (query) {
  19087. query = query || {};
  19088. // Instantiate Resultset and exec find op passing firstOnly = true param
  19089. var result = this.chain().find(query,true).data();
  19090. if (Array.isArray(result) && result.length === 0) {
  19091. return null;
  19092. } else {
  19093. if (!this.cloneObjects) {
  19094. return result[0];
  19095. } else {
  19096. return clone(result[0], this.cloneMethod);
  19097. }
  19098. }
  19099. };
  19100. /**
  19101. * Chain method, used for beginning a series of chained find() and/or view() operations
  19102. * on a collection.
  19103. *
  19104. * @param {string|array=} transform - named transform or array of transform steps
  19105. * @param {object=} parameters - Object containing properties representing parameters to substitute
  19106. * @returns {Resultset} (this) resultset, or data array if any map or join functions where called
  19107. * @memberof Collection
  19108. */
  19109. Collection.prototype.chain = function (transform, parameters) {
  19110. var rs = new Resultset(this);
  19111. if (typeof transform === 'undefined') {
  19112. return rs;
  19113. }
  19114. return rs.transform(transform, parameters);
  19115. };
  19116. /**
  19117. * Find method, api is similar to mongodb.
  19118. * for more complex queries use [chain()]{@link Collection#chain} or [where()]{@link Collection#where}.
  19119. * @example {@tutorial Query Examples}
  19120. * @param {object} query - 'mongo-like' query object
  19121. * @returns {array} Array of matching documents
  19122. * @memberof Collection
  19123. */
  19124. Collection.prototype.find = function (query) {
  19125. return this.chain().find(query).data();
  19126. };
  19127. /**
  19128. * Find object by unindexed field by property equal to value,
  19129. * simply iterates and returns the first element matching the query
  19130. */
  19131. Collection.prototype.findOneUnindexed = function (prop, value) {
  19132. var i = this.data.length,
  19133. doc;
  19134. while (i--) {
  19135. if (Utils.getIn(this.data[i], prop, true) === value) {
  19136. doc = this.data[i];
  19137. return doc;
  19138. }
  19139. }
  19140. return null;
  19141. };
  19142. /**
  19143. * Transaction methods
  19144. */
  19145. /** start the transation */
  19146. Collection.prototype.startTransaction = function () {
  19147. if (this.transactional) {
  19148. this.cachedData = clone(this.data, this.cloneMethod);
  19149. this.cachedIndex = this.idIndex;
  19150. this.cachedBinaryIndex = this.binaryIndices;
  19151. // propagate startTransaction to dynamic views
  19152. for (var idx = 0; idx < this.DynamicViews.length; idx++) {
  19153. this.DynamicViews[idx].startTransaction();
  19154. }
  19155. }
  19156. };
  19157. /** commit the transation */
  19158. Collection.prototype.commit = function () {
  19159. if (this.transactional) {
  19160. this.cachedData = null;
  19161. this.cachedIndex = null;
  19162. this.cachedBinaryIndex = null;
  19163. // propagate commit to dynamic views
  19164. for (var idx = 0; idx < this.DynamicViews.length; idx++) {
  19165. this.DynamicViews[idx].commit();
  19166. }
  19167. }
  19168. };
  19169. /** roll back the transation */
  19170. Collection.prototype.rollback = function () {
  19171. if (this.transactional) {
  19172. if (this.cachedData !== null && this.cachedIndex !== null) {
  19173. this.data = this.cachedData;
  19174. this.idIndex = this.cachedIndex;
  19175. this.binaryIndices = this.cachedBinaryIndex;
  19176. }
  19177. // propagate rollback to dynamic views
  19178. for (var idx = 0; idx < this.DynamicViews.length; idx++) {
  19179. this.DynamicViews[idx].rollback();
  19180. }
  19181. }
  19182. };
  19183. // async executor. This is only to enable callbacks at the end of the execution.
  19184. Collection.prototype.async = function (fun, callback) {
  19185. setTimeout(function () {
  19186. if (typeof fun === 'function') {
  19187. fun();
  19188. callback();
  19189. } else {
  19190. throw new TypeError('Argument passed for async execution is not a function');
  19191. }
  19192. }, 0);
  19193. };
  19194. /**
  19195. * Query the collection by supplying a javascript filter function.
  19196. * @example
  19197. * var results = coll.where(function(obj) {
  19198. * return obj.legs === 8;
  19199. * });
  19200. *
  19201. * @param {function} fun - filter function to run against all collection docs
  19202. * @returns {array} all documents which pass your filter function
  19203. * @memberof Collection
  19204. */
  19205. Collection.prototype.where = function (fun) {
  19206. return this.chain().where(fun).data();
  19207. };
  19208. /**
  19209. * Map Reduce operation
  19210. *
  19211. * @param {function} mapFunction - function to use as map function
  19212. * @param {function} reduceFunction - function to use as reduce function
  19213. * @returns {data} The result of your mapReduce operation
  19214. * @memberof Collection
  19215. */
  19216. Collection.prototype.mapReduce = function (mapFunction, reduceFunction) {
  19217. try {
  19218. return reduceFunction(this.data.map(mapFunction));
  19219. } catch (err) {
  19220. throw err;
  19221. }
  19222. };
  19223. /**
  19224. * Join two collections on specified properties
  19225. *
  19226. * @param {array|Resultset|Collection} joinData - array of documents to 'join' to this collection
  19227. * @param {string} leftJoinProp - property name in collection
  19228. * @param {string} rightJoinProp - property name in joinData
  19229. * @param {function=} mapFun - (Optional) map function to use
  19230. * @param {object=} dataOptions - options to data() before input to your map function
  19231. * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun
  19232. * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object
  19233. * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method.
  19234. * @returns {Resultset} Result of the mapping operation
  19235. * @memberof Collection
  19236. */
  19237. Collection.prototype.eqJoin = function (joinData, leftJoinProp, rightJoinProp, mapFun, dataOptions) {
  19238. // logic in Resultset class
  19239. return new Resultset(this).eqJoin(joinData, leftJoinProp, rightJoinProp, mapFun, dataOptions);
  19240. };
  19241. /* ------ STAGING API -------- */
  19242. /**
  19243. * stages: a map of uniquely identified 'stages', which hold copies of objects to be
  19244. * manipulated without affecting the data in the original collection
  19245. */
  19246. Collection.prototype.stages = {};
  19247. /**
  19248. * (Staging API) create a stage and/or retrieve it
  19249. * @memberof Collection
  19250. */
  19251. Collection.prototype.getStage = function (name) {
  19252. if (!this.stages[name]) {
  19253. this.stages[name] = {};
  19254. }
  19255. return this.stages[name];
  19256. };
  19257. /**
  19258. * a collection of objects recording the changes applied through a commmitStage
  19259. */
  19260. Collection.prototype.commitLog = [];
  19261. /**
  19262. * (Staging API) create a copy of an object and insert it into a stage
  19263. * @memberof Collection
  19264. */
  19265. Collection.prototype.stage = function (stageName, obj) {
  19266. var copy = JSON.parse(JSON.stringify(obj));
  19267. this.getStage(stageName)[obj.$loki] = copy;
  19268. return copy;
  19269. };
  19270. /**
  19271. * (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt
  19272. * then create a message to be inserted in the commitlog
  19273. * @param {string} stageName - name of stage
  19274. * @param {string} message
  19275. * @memberof Collection
  19276. */
  19277. Collection.prototype.commitStage = function (stageName, message) {
  19278. var stage = this.getStage(stageName),
  19279. prop,
  19280. timestamp = new Date().getTime();
  19281. for (prop in stage) {
  19282. this.update(stage[prop]);
  19283. this.commitLog.push({
  19284. timestamp: timestamp,
  19285. message: message,
  19286. data: JSON.parse(JSON.stringify(stage[prop]))
  19287. });
  19288. }
  19289. this.stages[stageName] = {};
  19290. };
  19291. Collection.prototype.no_op = function () {
  19292. return;
  19293. };
  19294. /**
  19295. * @memberof Collection
  19296. */
  19297. Collection.prototype.extract = function (field) {
  19298. var i = 0,
  19299. len = this.data.length,
  19300. isDotNotation = isDeepProperty(field),
  19301. result = [];
  19302. for (i; i < len; i += 1) {
  19303. result.push(deepProperty(this.data[i], field, isDotNotation));
  19304. }
  19305. return result;
  19306. };
  19307. /**
  19308. * @memberof Collection
  19309. */
  19310. Collection.prototype.max = function (field) {
  19311. return Math.max.apply(null, this.extract(field));
  19312. };
  19313. /**
  19314. * @memberof Collection
  19315. */
  19316. Collection.prototype.min = function (field) {
  19317. return Math.min.apply(null, this.extract(field));
  19318. };
  19319. /**
  19320. * @memberof Collection
  19321. */
  19322. Collection.prototype.maxRecord = function (field) {
  19323. var i = 0,
  19324. len = this.data.length,
  19325. deep = isDeepProperty(field),
  19326. result = {
  19327. index: 0,
  19328. value: undefined
  19329. },
  19330. max;
  19331. for (i; i < len; i += 1) {
  19332. if (max !== undefined) {
  19333. if (max < deepProperty(this.data[i], field, deep)) {
  19334. max = deepProperty(this.data[i], field, deep);
  19335. result.index = this.data[i].$loki;
  19336. }
  19337. } else {
  19338. max = deepProperty(this.data[i], field, deep);
  19339. result.index = this.data[i].$loki;
  19340. }
  19341. }
  19342. result.value = max;
  19343. return result;
  19344. };
  19345. /**
  19346. * @memberof Collection
  19347. */
  19348. Collection.prototype.minRecord = function (field) {
  19349. var i = 0,
  19350. len = this.data.length,
  19351. deep = isDeepProperty(field),
  19352. result = {
  19353. index: 0,
  19354. value: undefined
  19355. },
  19356. min;
  19357. for (i; i < len; i += 1) {
  19358. if (min !== undefined) {
  19359. if (min > deepProperty(this.data[i], field, deep)) {
  19360. min = deepProperty(this.data[i], field, deep);
  19361. result.index = this.data[i].$loki;
  19362. }
  19363. } else {
  19364. min = deepProperty(this.data[i], field, deep);
  19365. result.index = this.data[i].$loki;
  19366. }
  19367. }
  19368. result.value = min;
  19369. return result;
  19370. };
  19371. /**
  19372. * @memberof Collection
  19373. */
  19374. Collection.prototype.extractNumerical = function (field) {
  19375. return this.extract(field).map(parseBase10).filter(Number).filter(function (n) {
  19376. return !(isNaN(n));
  19377. });
  19378. };
  19379. /**
  19380. * Calculates the average numerical value of a property
  19381. *
  19382. * @param {string} field - name of property in docs to average
  19383. * @returns {number} average of property in all docs in the collection
  19384. * @memberof Collection
  19385. */
  19386. Collection.prototype.avg = function (field) {
  19387. return average(this.extractNumerical(field));
  19388. };
  19389. /**
  19390. * Calculate standard deviation of a field
  19391. * @memberof Collection
  19392. * @param {string} field
  19393. */
  19394. Collection.prototype.stdDev = function (field) {
  19395. return standardDeviation(this.extractNumerical(field));
  19396. };
  19397. /**
  19398. * @memberof Collection
  19399. * @param {string} field
  19400. */
  19401. Collection.prototype.mode = function (field) {
  19402. var dict = {},
  19403. data = this.extract(field);
  19404. data.forEach(function (obj) {
  19405. if (dict[obj]) {
  19406. dict[obj] += 1;
  19407. } else {
  19408. dict[obj] = 1;
  19409. }
  19410. });
  19411. var max,
  19412. prop, mode;
  19413. for (prop in dict) {
  19414. if (max) {
  19415. if (max < dict[prop]) {
  19416. mode = prop;
  19417. }
  19418. } else {
  19419. mode = prop;
  19420. max = dict[prop];
  19421. }
  19422. }
  19423. return mode;
  19424. };
  19425. /**
  19426. * @memberof Collection
  19427. * @param {string} field - property name
  19428. */
  19429. Collection.prototype.median = function (field) {
  19430. var values = this.extractNumerical(field);
  19431. values.sort(sub);
  19432. var half = Math.floor(values.length / 2);
  19433. if (values.length % 2) {
  19434. return values[half];
  19435. } else {
  19436. return (values[half - 1] + values[half]) / 2.0;
  19437. }
  19438. };
  19439. /**
  19440. * General utils, including statistical functions
  19441. */
  19442. function isDeepProperty(field) {
  19443. return field.indexOf('.') !== -1;
  19444. }
  19445. function parseBase10(num) {
  19446. return parseFloat(num, 10);
  19447. }
  19448. function isNotUndefined(obj) {
  19449. return obj !== undefined;
  19450. }
  19451. function add(a, b) {
  19452. return a + b;
  19453. }
  19454. function sub(a, b) {
  19455. return a - b;
  19456. }
  19457. function median(values) {
  19458. values.sort(sub);
  19459. var half = Math.floor(values.length / 2);
  19460. return (values.length % 2) ? values[half] : ((values[half - 1] + values[half]) / 2.0);
  19461. }
  19462. function average(array) {
  19463. return (array.reduce(add, 0)) / array.length;
  19464. }
  19465. function standardDeviation(values) {
  19466. var avg = average(values);
  19467. var squareDiffs = values.map(function (value) {
  19468. var diff = value - avg;
  19469. var sqrDiff = diff * diff;
  19470. return sqrDiff;
  19471. });
  19472. var avgSquareDiff = average(squareDiffs);
  19473. var stdDev = Math.sqrt(avgSquareDiff);
  19474. return stdDev;
  19475. }
  19476. function deepProperty(obj, property, isDeep) {
  19477. if (isDeep === false) {
  19478. // pass without processing
  19479. return obj[property];
  19480. }
  19481. var pieces = property.split('.'),
  19482. root = obj;
  19483. while (pieces.length > 0) {
  19484. root = root[pieces.shift()];
  19485. }
  19486. return root;
  19487. }
  19488. function binarySearch(array, item, fun) {
  19489. var lo = 0,
  19490. hi = array.length,
  19491. compared,
  19492. mid;
  19493. while (lo < hi) {
  19494. mid = (lo + hi) >> 1;
  19495. compared = fun.apply(null, [item, array[mid]]);
  19496. if (compared === 0) {
  19497. return {
  19498. found: true,
  19499. index: mid
  19500. };
  19501. } else if (compared < 0) {
  19502. hi = mid;
  19503. } else {
  19504. lo = mid + 1;
  19505. }
  19506. }
  19507. return {
  19508. found: false,
  19509. index: hi
  19510. };
  19511. }
  19512. function BSonSort(fun) {
  19513. return function (array, item) {
  19514. return binarySearch(array, item, fun);
  19515. };
  19516. }
  19517. function KeyValueStore() {}
  19518. KeyValueStore.prototype = {
  19519. keys: [],
  19520. values: [],
  19521. sort: function (a, b) {
  19522. return (a < b) ? -1 : ((a > b) ? 1 : 0);
  19523. },
  19524. setSort: function (fun) {
  19525. this.bs = new BSonSort(fun);
  19526. },
  19527. bs: function () {
  19528. return new BSonSort(this.sort);
  19529. },
  19530. set: function (key, value) {
  19531. var pos = this.bs(this.keys, key);
  19532. if (pos.found) {
  19533. this.values[pos.index] = value;
  19534. } else {
  19535. this.keys.splice(pos.index, 0, key);
  19536. this.values.splice(pos.index, 0, value);
  19537. }
  19538. },
  19539. get: function (key) {
  19540. return this.values[binarySearch(this.keys, key, this.sort).index];
  19541. }
  19542. };
  19543. function UniqueIndex(uniqueField) {
  19544. this.field = uniqueField;
  19545. this.keyMap = {};
  19546. this.lokiMap = {};
  19547. }
  19548. UniqueIndex.prototype.keyMap = {};
  19549. UniqueIndex.prototype.lokiMap = {};
  19550. UniqueIndex.prototype.set = function (obj) {
  19551. var fieldValue = obj[this.field];
  19552. if (fieldValue !== null && typeof (fieldValue) !== 'undefined') {
  19553. if (this.keyMap[fieldValue]) {
  19554. throw new Error('Duplicate key for property ' + this.field + ': ' + fieldValue);
  19555. } else {
  19556. this.keyMap[fieldValue] = obj;
  19557. this.lokiMap[obj.$loki] = fieldValue;
  19558. }
  19559. }
  19560. };
  19561. UniqueIndex.prototype.get = function (key) {
  19562. return this.keyMap[key];
  19563. };
  19564. UniqueIndex.prototype.byId = function (id) {
  19565. return this.keyMap[this.lokiMap[id]];
  19566. };
  19567. /**
  19568. * Updates a document's unique index given an updated object.
  19569. * @param {Object} obj Original document object
  19570. * @param {Object} doc New document object (likely the same as obj)
  19571. */
  19572. UniqueIndex.prototype.update = function (obj, doc) {
  19573. if (this.lokiMap[obj.$loki] !== doc[this.field]) {
  19574. var old = this.lokiMap[obj.$loki];
  19575. this.set(doc);
  19576. // make the old key fail bool test, while avoiding the use of delete (mem-leak prone)
  19577. this.keyMap[old] = undefined;
  19578. } else {
  19579. this.keyMap[obj[this.field]] = doc;
  19580. }
  19581. };
  19582. UniqueIndex.prototype.remove = function (key) {
  19583. var obj = this.keyMap[key];
  19584. if (obj !== null && typeof obj !== 'undefined') {
  19585. this.keyMap[key] = undefined;
  19586. this.lokiMap[obj.$loki] = undefined;
  19587. } else {
  19588. throw new Error('Key is not in unique index: ' + this.field);
  19589. }
  19590. };
  19591. UniqueIndex.prototype.clear = function () {
  19592. this.keyMap = {};
  19593. this.lokiMap = {};
  19594. };
  19595. function ExactIndex(exactField) {
  19596. this.index = {};
  19597. this.field = exactField;
  19598. }
  19599. // add the value you want returned to the key in the index
  19600. ExactIndex.prototype = {
  19601. set: function add(key, val) {
  19602. if (this.index[key]) {
  19603. this.index[key].push(val);
  19604. } else {
  19605. this.index[key] = [val];
  19606. }
  19607. },
  19608. // remove the value from the index, if the value was the last one, remove the key
  19609. remove: function remove(key, val) {
  19610. var idxSet = this.index[key];
  19611. for (var i in idxSet) {
  19612. if (idxSet[i] == val) {
  19613. idxSet.splice(i, 1);
  19614. }
  19615. }
  19616. if (idxSet.length < 1) {
  19617. this.index[key] = undefined;
  19618. }
  19619. },
  19620. // get the values related to the key, could be more than one
  19621. get: function get(key) {
  19622. return this.index[key];
  19623. },
  19624. // clear will zap the index
  19625. clear: function clear(key) {
  19626. this.index = {};
  19627. }
  19628. };
  19629. function SortedIndex(sortedField) {
  19630. this.field = sortedField;
  19631. }
  19632. SortedIndex.prototype = {
  19633. keys: [],
  19634. values: [],
  19635. // set the default sort
  19636. sort: function (a, b) {
  19637. return (a < b) ? -1 : ((a > b) ? 1 : 0);
  19638. },
  19639. bs: function () {
  19640. return new BSonSort(this.sort);
  19641. },
  19642. // and allow override of the default sort
  19643. setSort: function (fun) {
  19644. this.bs = new BSonSort(fun);
  19645. },
  19646. // add the value you want returned to the key in the index
  19647. set: function (key, value) {
  19648. var pos = binarySearch(this.keys, key, this.sort);
  19649. if (pos.found) {
  19650. this.values[pos.index].push(value);
  19651. } else {
  19652. this.keys.splice(pos.index, 0, key);
  19653. this.values.splice(pos.index, 0, [value]);
  19654. }
  19655. },
  19656. // get all values which have a key == the given key
  19657. get: function (key) {
  19658. var bsr = binarySearch(this.keys, key, this.sort);
  19659. if (bsr.found) {
  19660. return this.values[bsr.index];
  19661. } else {
  19662. return [];
  19663. }
  19664. },
  19665. // get all values which have a key < the given key
  19666. getLt: function (key) {
  19667. var bsr = binarySearch(this.keys, key, this.sort);
  19668. var pos = bsr.index;
  19669. if (bsr.found) pos--;
  19670. return this.getAll(key, 0, pos);
  19671. },
  19672. // get all values which have a key > the given key
  19673. getGt: function (key) {
  19674. var bsr = binarySearch(this.keys, key, this.sort);
  19675. var pos = bsr.index;
  19676. if (bsr.found) pos++;
  19677. return this.getAll(key, pos, this.keys.length);
  19678. },
  19679. // get all vals from start to end
  19680. getAll: function (key, start, end) {
  19681. var results = [];
  19682. for (var i = start; i < end; i++) {
  19683. results = results.concat(this.values[i]);
  19684. }
  19685. return results;
  19686. },
  19687. // just in case someone wants to do something smart with ranges
  19688. getPos: function (key) {
  19689. return binarySearch(this.keys, key, this.sort);
  19690. },
  19691. // remove the value from the index, if the value was the last one, remove the key
  19692. remove: function (key, value) {
  19693. var pos = binarySearch(this.keys, key, this.sort).index;
  19694. var idxSet = this.values[pos];
  19695. for (var i in idxSet) {
  19696. if (idxSet[i] == value) idxSet.splice(i, 1);
  19697. }
  19698. if (idxSet.length < 1) {
  19699. this.keys.splice(pos, 1);
  19700. this.values.splice(pos, 1);
  19701. }
  19702. },
  19703. // clear will zap the index
  19704. clear: function () {
  19705. this.keys = [];
  19706. this.values = [];
  19707. }
  19708. };
  19709. Loki.LokiOps = LokiOps;
  19710. Loki.Collection = Collection;
  19711. Loki.KeyValueStore = KeyValueStore;
  19712. Loki.LokiMemoryAdapter = LokiMemoryAdapter;
  19713. Loki.LokiPartitioningAdapter = LokiPartitioningAdapter;
  19714. Loki.LokiLocalStorageAdapter = LokiLocalStorageAdapter;
  19715. Loki.LokiFsAdapter = LokiFsAdapter;
  19716. Loki.persistenceAdapters = {
  19717. fs: LokiFsAdapter,
  19718. localStorage: LokiLocalStorageAdapter
  19719. };
  19720. Loki.aeq = aeqHelper;
  19721. Loki.lt = ltHelper;
  19722. Loki.gt = gtHelper;
  19723. Loki.Comparators = Comparators;
  19724. return Loki;
  19725. }());
  19726. }));
  19727. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  19728. },{"./loki-indexed-adapter.js":171,"_process":202,"fs":23}],173:[function(require,module,exports){
  19729. /**
  19730. * martinez v0.4.3
  19731. * Martinez polygon clipping algorithm, does boolean operation on polygons (multipolygons, polygons with holes etc): intersection, union, difference, xor
  19732. *
  19733. * @author Alex Milevski <info@w8r.name>
  19734. * @license MIT
  19735. * @preserve
  19736. */
  19737. (function (global, factory) {
  19738. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  19739. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  19740. (factory((global.martinez = {})));
  19741. }(this, (function (exports) { 'use strict';
  19742. function DEFAULT_COMPARE (a, b) { return a > b ? 1 : a < b ? -1 : 0; }
  19743. var SplayTree = function SplayTree(compare, noDuplicates) {
  19744. if ( compare === void 0 ) compare = DEFAULT_COMPARE;
  19745. if ( noDuplicates === void 0 ) noDuplicates = false;
  19746. this._compare = compare;
  19747. this._root = null;
  19748. this._size = 0;
  19749. this._noDuplicates = !!noDuplicates;
  19750. };
  19751. var prototypeAccessors = { size: { configurable: true } };
  19752. SplayTree.prototype.rotateLeft = function rotateLeft (x) {
  19753. var y = x.right;
  19754. if (y) {
  19755. x.right = y.left;
  19756. if (y.left) { y.left.parent = x; }
  19757. y.parent = x.parent;
  19758. }
  19759. if (!x.parent) { this._root = y; }
  19760. else if (x === x.parent.left) { x.parent.left = y; }
  19761. else { x.parent.right = y; }
  19762. if (y) { y.left = x; }
  19763. x.parent = y;
  19764. };
  19765. SplayTree.prototype.rotateRight = function rotateRight (x) {
  19766. var y = x.left;
  19767. if (y) {
  19768. x.left = y.right;
  19769. if (y.right) { y.right.parent = x; }
  19770. y.parent = x.parent;
  19771. }
  19772. if (!x.parent) { this._root = y; }
  19773. else if(x === x.parent.left) { x.parent.left = y; }
  19774. else { x.parent.right = y; }
  19775. if (y) { y.right = x; }
  19776. x.parent = y;
  19777. };
  19778. SplayTree.prototype._splay = function _splay (x) {
  19779. var this$1 = this;
  19780. while (x.parent) {
  19781. var p = x.parent;
  19782. if (!p.parent) {
  19783. if (p.left === x) { this$1.rotateRight(p); }
  19784. else { this$1.rotateLeft(p); }
  19785. } else if (p.left === x && p.parent.left === p) {
  19786. this$1.rotateRight(p.parent);
  19787. this$1.rotateRight(p);
  19788. } else if (p.right === x && p.parent.right === p) {
  19789. this$1.rotateLeft(p.parent);
  19790. this$1.rotateLeft(p);
  19791. } else if (p.left === x && p.parent.right === p) {
  19792. this$1.rotateRight(p);
  19793. this$1.rotateLeft(p);
  19794. } else {
  19795. this$1.rotateLeft(p);
  19796. this$1.rotateRight(p);
  19797. }
  19798. }
  19799. };
  19800. SplayTree.prototype.splay = function splay (x) {
  19801. var this$1 = this;
  19802. var p, gp, ggp, l, r;
  19803. while (x.parent) {
  19804. p = x.parent;
  19805. gp = p.parent;
  19806. if (gp && gp.parent) {
  19807. ggp = gp.parent;
  19808. if (ggp.left === gp) { ggp.left= x; }
  19809. else { ggp.right = x; }
  19810. x.parent = ggp;
  19811. } else {
  19812. x.parent = null;
  19813. this$1._root = x;
  19814. }
  19815. l = x.left; r = x.right;
  19816. if (x === p.left) { // left
  19817. if (gp) {
  19818. if (gp.left === p) {
  19819. /* zig-zig */
  19820. if (p.right) {
  19821. gp.left = p.right;
  19822. gp.left.parent = gp;
  19823. } else { gp.left = null; }
  19824. p.right = gp;
  19825. gp.parent = p;
  19826. } else {
  19827. /* zig-zag */
  19828. if (l) {
  19829. gp.right = l;
  19830. l.parent = gp;
  19831. } else { gp.right = null; }
  19832. x.left = gp;
  19833. gp.parent = x;
  19834. }
  19835. }
  19836. if (r) {
  19837. p.left = r;
  19838. r.parent = p;
  19839. } else { p.left = null; }
  19840. x.right= p;
  19841. p.parent = x;
  19842. } else { // right
  19843. if (gp) {
  19844. if (gp.right === p) {
  19845. /* zig-zig */
  19846. if (p.left) {
  19847. gp.right = p.left;
  19848. gp.right.parent = gp;
  19849. } else { gp.right = null; }
  19850. p.left = gp;
  19851. gp.parent = p;
  19852. } else {
  19853. /* zig-zag */
  19854. if (r) {
  19855. gp.left = r;
  19856. r.parent = gp;
  19857. } else { gp.left = null; }
  19858. x.right = gp;
  19859. gp.parent = x;
  19860. }
  19861. }
  19862. if (l) {
  19863. p.right = l;
  19864. l.parent = p;
  19865. } else { p.right = null; }
  19866. x.left = p;
  19867. p.parent = x;
  19868. }
  19869. }
  19870. };
  19871. SplayTree.prototype.replace = function replace (u, v) {
  19872. if (!u.parent) { this._root = v; }
  19873. else if (u === u.parent.left) { u.parent.left = v; }
  19874. else { u.parent.right = v; }
  19875. if (v) { v.parent = u.parent; }
  19876. };
  19877. SplayTree.prototype.minNode = function minNode (u) {
  19878. if ( u === void 0 ) u = this._root;
  19879. if (u) { while (u.left) { u = u.left; } }
  19880. return u;
  19881. };
  19882. SplayTree.prototype.maxNode = function maxNode (u) {
  19883. if ( u === void 0 ) u = this._root;
  19884. if (u) { while (u.right) { u = u.right; } }
  19885. return u;
  19886. };
  19887. SplayTree.prototype.insert = function insert (key, data) {
  19888. var z = this._root;
  19889. var p = null;
  19890. var comp = this._compare;
  19891. var cmp;
  19892. if (this._noDuplicates) {
  19893. while (z) {
  19894. p = z;
  19895. cmp = comp(z.key, key);
  19896. if (cmp === 0) { return; }
  19897. else if (comp(z.key, key) < 0) { z = z.right; }
  19898. else { z = z.left; }
  19899. }
  19900. } else {
  19901. while (z) {
  19902. p = z;
  19903. if (comp(z.key, key) < 0) { z = z.right; }
  19904. else { z = z.left; }
  19905. }
  19906. }
  19907. z = { key: key, data: data, left: null, right: null, parent: p };
  19908. if (!p) { this._root = z; }
  19909. else if (comp(p.key, z.key) < 0) { p.right = z; }
  19910. else { p.left= z; }
  19911. this.splay(z);
  19912. this._size++;
  19913. return z;
  19914. };
  19915. SplayTree.prototype.find = function find (key) {
  19916. var z = this._root;
  19917. var comp = this._compare;
  19918. while (z) {
  19919. var cmp = comp(z.key, key);
  19920. if (cmp < 0) { z = z.right; }
  19921. else if (cmp > 0) { z = z.left; }
  19922. else { return z; }
  19923. }
  19924. return null;
  19925. };
  19926. /**
  19927. * Whether the tree contains a node with the given key
  19928. * @param{Key} key
  19929. * @return {boolean} true/false
  19930. */
  19931. SplayTree.prototype.contains = function contains (key) {
  19932. var node = this._root;
  19933. var comparator = this._compare;
  19934. while (node){
  19935. var cmp = comparator(key, node.key);
  19936. if (cmp === 0) { return true; }
  19937. else if (cmp < 0) { node = node.left; }
  19938. else { node = node.right; }
  19939. }
  19940. return false;
  19941. };
  19942. SplayTree.prototype.remove = function remove (key) {
  19943. var z = this.find(key);
  19944. if (!z) { return false; }
  19945. this.splay(z);
  19946. if (!z.left) { this.replace(z, z.right); }
  19947. else if (!z.right) { this.replace(z, z.left); }
  19948. else {
  19949. var y = this.minNode(z.right);
  19950. if (y.parent !== z) {
  19951. this.replace(y, y.right);
  19952. y.right = z.right;
  19953. y.right.parent = y;
  19954. }
  19955. this.replace(z, y);
  19956. y.left = z.left;
  19957. y.left.parent = y;
  19958. }
  19959. this._size--;
  19960. return true;
  19961. };
  19962. SplayTree.prototype.removeNode = function removeNode (z) {
  19963. if (!z) { return false; }
  19964. this.splay(z);
  19965. if (!z.left) { this.replace(z, z.right); }
  19966. else if (!z.right) { this.replace(z, z.left); }
  19967. else {
  19968. var y = this.minNode(z.right);
  19969. if (y.parent !== z) {
  19970. this.replace(y, y.right);
  19971. y.right = z.right;
  19972. y.right.parent = y;
  19973. }
  19974. this.replace(z, y);
  19975. y.left = z.left;
  19976. y.left.parent = y;
  19977. }
  19978. this._size--;
  19979. return true;
  19980. };
  19981. SplayTree.prototype.erase = function erase (key) {
  19982. var z = this.find(key);
  19983. if (!z) { return; }
  19984. this.splay(z);
  19985. var s = z.left;
  19986. var t = z.right;
  19987. var sMax = null;
  19988. if (s) {
  19989. s.parent = null;
  19990. sMax = this.maxNode(s);
  19991. this.splay(sMax);
  19992. this._root = sMax;
  19993. }
  19994. if (t) {
  19995. if (s) { sMax.right = t; }
  19996. else { this._root = t; }
  19997. t.parent = sMax;
  19998. }
  19999. this._size--;
  20000. };
  20001. /**
  20002. * Removes and returns the node with smallest key
  20003. * @return {?Node}
  20004. */
  20005. SplayTree.prototype.pop = function pop () {
  20006. var node = this._root, returnValue = null;
  20007. if (node) {
  20008. while (node.left) { node = node.left; }
  20009. returnValue = { key: node.key, data: node.data };
  20010. this.remove(node.key);
  20011. }
  20012. return returnValue;
  20013. };
  20014. /* eslint-disable class-methods-use-this */
  20015. /**
  20016. * Successor node
  20017. * @param{Node} node
  20018. * @return {?Node}
  20019. */
  20020. SplayTree.prototype.next = function next (node) {
  20021. var successor = node;
  20022. if (successor) {
  20023. if (successor.right) {
  20024. successor = successor.right;
  20025. while (successor && successor.left) { successor = successor.left; }
  20026. } else {
  20027. successor = node.parent;
  20028. while (successor && successor.right === node) {
  20029. node = successor; successor = successor.parent;
  20030. }
  20031. }
  20032. }
  20033. return successor;
  20034. };
  20035. /**
  20036. * Predecessor node
  20037. * @param{Node} node
  20038. * @return {?Node}
  20039. */
  20040. SplayTree.prototype.prev = function prev (node) {
  20041. var predecessor = node;
  20042. if (predecessor) {
  20043. if (predecessor.left) {
  20044. predecessor = predecessor.left;
  20045. while (predecessor && predecessor.right) { predecessor = predecessor.right; }
  20046. } else {
  20047. predecessor = node.parent;
  20048. while (predecessor && predecessor.left === node) {
  20049. node = predecessor;
  20050. predecessor = predecessor.parent;
  20051. }
  20052. }
  20053. }
  20054. return predecessor;
  20055. };
  20056. /* eslint-enable class-methods-use-this */
  20057. /**
  20058. * @param{forEachCallback} callback
  20059. * @return {SplayTree}
  20060. */
  20061. SplayTree.prototype.forEach = function forEach (callback) {
  20062. var current = this._root;
  20063. var s = [], done = false, i = 0;
  20064. while (!done) {
  20065. // Reach the left most Node of the current Node
  20066. if (current) {
  20067. // Place pointer to a tree node on the stack
  20068. // before traversing the node's left subtree
  20069. s.push(current);
  20070. current = current.left;
  20071. } else {
  20072. // BackTrack from the empty subtree and visit the Node
  20073. // at the top of the stack; however, if the stack is
  20074. // empty you are done
  20075. if (s.length > 0) {
  20076. current = s.pop();
  20077. callback(current, i++);
  20078. // We have visited the node and its left
  20079. // subtree. Now, it's right subtree's turn
  20080. current = current.right;
  20081. } else { done = true; }
  20082. }
  20083. }
  20084. return this;
  20085. };
  20086. /**
  20087. * Walk key range from `low` to `high`. Stops if `fn` returns a value.
  20088. * @param{Key} low
  20089. * @param{Key} high
  20090. * @param{Function} fn
  20091. * @param{*?} ctx
  20092. * @return {SplayTree}
  20093. */
  20094. SplayTree.prototype.range = function range (low, high, fn, ctx) {
  20095. var this$1 = this;
  20096. var Q = [];
  20097. var compare = this._compare;
  20098. var node = this._root, cmp;
  20099. while (Q.length !== 0 || node) {
  20100. if (node) {
  20101. Q.push(node);
  20102. node = node.left;
  20103. } else {
  20104. node = Q.pop();
  20105. cmp = compare(node.key, high);
  20106. if (cmp > 0) {
  20107. break;
  20108. } else if (compare(node.key, low) >= 0) {
  20109. if (fn.call(ctx, node)) { return this$1; } // stop if smth is returned
  20110. }
  20111. node = node.right;
  20112. }
  20113. }
  20114. return this;
  20115. };
  20116. /**
  20117. * Returns all keys in order
  20118. * @return {Array<Key>}
  20119. */
  20120. SplayTree.prototype.keys = function keys () {
  20121. var current = this._root;
  20122. var s = [], r = [], done = false;
  20123. while (!done) {
  20124. if (current) {
  20125. s.push(current);
  20126. current = current.left;
  20127. } else {
  20128. if (s.length > 0) {
  20129. current = s.pop();
  20130. r.push(current.key);
  20131. current = current.right;
  20132. } else { done = true; }
  20133. }
  20134. }
  20135. return r;
  20136. };
  20137. /**
  20138. * Returns `data` fields of all nodes in order.
  20139. * @return {Array<Value>}
  20140. */
  20141. SplayTree.prototype.values = function values () {
  20142. var current = this._root;
  20143. var s = [], r = [], done = false;
  20144. while (!done) {
  20145. if (current) {
  20146. s.push(current);
  20147. current = current.left;
  20148. } else {
  20149. if (s.length > 0) {
  20150. current = s.pop();
  20151. r.push(current.data);
  20152. current = current.right;
  20153. } else { done = true; }
  20154. }
  20155. }
  20156. return r;
  20157. };
  20158. /**
  20159. * Returns node at given index
  20160. * @param{number} index
  20161. * @return {?Node}
  20162. */
  20163. SplayTree.prototype.at = function at (index) {
  20164. // removed after a consideration, more misleading than useful
  20165. // index = index % this.size;
  20166. // if (index < 0) index = this.size - index;
  20167. var current = this._root;
  20168. var s = [], done = false, i = 0;
  20169. while (!done) {
  20170. if (current) {
  20171. s.push(current);
  20172. current = current.left;
  20173. } else {
  20174. if (s.length > 0) {
  20175. current = s.pop();
  20176. if (i === index) { return current; }
  20177. i++;
  20178. current = current.right;
  20179. } else { done = true; }
  20180. }
  20181. }
  20182. return null;
  20183. };
  20184. /**
  20185. * Bulk-load items. Both array have to be same size
  20186. * @param{Array<Key>} keys
  20187. * @param{Array<Value>}[values]
  20188. * @param{Boolean} [presort=false] Pre-sort keys and values, using
  20189. * tree's comparator. Sorting is done
  20190. * in-place
  20191. * @return {AVLTree}
  20192. */
  20193. SplayTree.prototype.load = function load (keys, values, presort) {
  20194. if ( keys === void 0 ) keys = [];
  20195. if ( values === void 0 ) values = [];
  20196. if ( presort === void 0 ) presort = false;
  20197. if (this._size !== 0) { throw new Error('bulk-load: tree is not empty'); }
  20198. var size = keys.length;
  20199. if (presort) { sort(keys, values, 0, size - 1, this._compare); }
  20200. this._root = loadRecursive(null, keys, values, 0, size);
  20201. this._size = size;
  20202. return this;
  20203. };
  20204. SplayTree.prototype.min = function min () {
  20205. var node = this.minNode(this._root);
  20206. if (node) { return node.key; }
  20207. else { return null; }
  20208. };
  20209. SplayTree.prototype.max = function max () {
  20210. var node = this.maxNode(this._root);
  20211. if (node) { return node.key; }
  20212. else { return null; }
  20213. };
  20214. SplayTree.prototype.isEmpty = function isEmpty () { return this._root === null; };
  20215. prototypeAccessors.size.get = function () { return this._size; };
  20216. /**
  20217. * Create a tree and load it with items
  20218. * @param{Array<Key>} keys
  20219. * @param{Array<Value>?} [values]
  20220. * @param{Function?} [comparator]
  20221. * @param{Boolean?} [presort=false] Pre-sort keys and values, using
  20222. * tree's comparator. Sorting is done
  20223. * in-place
  20224. * @param{Boolean?} [noDuplicates=false] Allow duplicates
  20225. * @return {SplayTree}
  20226. */
  20227. SplayTree.createTree = function createTree (keys, values, comparator, presort, noDuplicates) {
  20228. return new SplayTree(comparator, noDuplicates).load(keys, values, presort);
  20229. };
  20230. Object.defineProperties( SplayTree.prototype, prototypeAccessors );
  20231. function loadRecursive (parent, keys, values, start, end) {
  20232. var size = end - start;
  20233. if (size > 0) {
  20234. var middle = start + Math.floor(size / 2);
  20235. var key = keys[middle];
  20236. var data = values[middle];
  20237. var node = { key: key, data: data, parent: parent };
  20238. node.left = loadRecursive(node, keys, values, start, middle);
  20239. node.right = loadRecursive(node, keys, values, middle + 1, end);
  20240. return node;
  20241. }
  20242. return null;
  20243. }
  20244. function sort(keys, values, left, right, compare) {
  20245. if (left >= right) { return; }
  20246. var pivot = keys[(left + right) >> 1];
  20247. var i = left - 1;
  20248. var j = right + 1;
  20249. while (true) {
  20250. do { i++; } while (compare(keys[i], pivot) < 0);
  20251. do { j--; } while (compare(keys[j], pivot) > 0);
  20252. if (i >= j) { break; }
  20253. var tmp = keys[i];
  20254. keys[i] = keys[j];
  20255. keys[j] = tmp;
  20256. tmp = values[i];
  20257. values[i] = values[j];
  20258. values[j] = tmp;
  20259. }
  20260. sort(keys, values, left, j, compare);
  20261. sort(keys, values, j + 1, right, compare);
  20262. }
  20263. var NORMAL = 0;
  20264. var NON_CONTRIBUTING = 1;
  20265. var SAME_TRANSITION = 2;
  20266. var DIFFERENT_TRANSITION = 3;
  20267. var INTERSECTION = 0;
  20268. var UNION = 1;
  20269. var DIFFERENCE = 2;
  20270. var XOR = 3;
  20271. /**
  20272. * @param {SweepEvent} event
  20273. * @param {SweepEvent} prev
  20274. * @param {Operation} operation
  20275. */
  20276. function computeFields (event, prev, operation) {
  20277. // compute inOut and otherInOut fields
  20278. if (prev === null) {
  20279. event.inOut = false;
  20280. event.otherInOut = true;
  20281. // previous line segment in sweepline belongs to the same polygon
  20282. } else {
  20283. if (event.isSubject === prev.isSubject) {
  20284. event.inOut = !prev.inOut;
  20285. event.otherInOut = prev.otherInOut;
  20286. // previous line segment in sweepline belongs to the clipping polygon
  20287. } else {
  20288. event.inOut = !prev.otherInOut;
  20289. event.otherInOut = prev.isVertical() ? !prev.inOut : prev.inOut;
  20290. }
  20291. // compute prevInResult field
  20292. if (prev) {
  20293. event.prevInResult = (!inResult(prev, operation) || prev.isVertical())
  20294. ? prev.prevInResult : prev;
  20295. }
  20296. }
  20297. // check if the line segment belongs to the Boolean operation
  20298. event.inResult = inResult(event, operation);
  20299. }
  20300. /* eslint-disable indent */
  20301. function inResult(event, operation) {
  20302. switch (event.type) {
  20303. case NORMAL:
  20304. switch (operation) {
  20305. case INTERSECTION:
  20306. return !event.otherInOut;
  20307. case UNION:
  20308. return event.otherInOut;
  20309. case DIFFERENCE:
  20310. // return (event.isSubject && !event.otherInOut) ||
  20311. // (!event.isSubject && event.otherInOut);
  20312. return (event.isSubject && event.otherInOut) ||
  20313. (!event.isSubject && !event.otherInOut);
  20314. case XOR:
  20315. return true;
  20316. }
  20317. break;
  20318. case SAME_TRANSITION:
  20319. return operation === INTERSECTION || operation === UNION;
  20320. case DIFFERENT_TRANSITION:
  20321. return operation === DIFFERENCE;
  20322. case NON_CONTRIBUTING:
  20323. return false;
  20324. }
  20325. return false;
  20326. }
  20327. /* eslint-enable indent */
  20328. var SweepEvent = function SweepEvent (point, left, otherEvent, isSubject, edgeType) {
  20329. /**
  20330. * Is left endpoint?
  20331. * @type {Boolean}
  20332. */
  20333. this.left = left;
  20334. /**
  20335. * @type {Array.<Number>}
  20336. */
  20337. this.point = point;
  20338. /**
  20339. * Other edge reference
  20340. * @type {SweepEvent}
  20341. */
  20342. this.otherEvent = otherEvent;
  20343. /**
  20344. * Belongs to source or clipping polygon
  20345. * @type {Boolean}
  20346. */
  20347. this.isSubject = isSubject;
  20348. /**
  20349. * Edge contribution type
  20350. * @type {Number}
  20351. */
  20352. this.type = edgeType || NORMAL;
  20353. /**
  20354. * In-out transition for the sweepline crossing polygon
  20355. * @type {Boolean}
  20356. */
  20357. this.inOut = false;
  20358. /**
  20359. * @type {Boolean}
  20360. */
  20361. this.otherInOut = false;
  20362. /**
  20363. * Previous event in result?
  20364. * @type {SweepEvent}
  20365. */
  20366. this.prevInResult = null;
  20367. /**
  20368. * Does event belong to result?
  20369. * @type {Boolean}
  20370. */
  20371. this.inResult = false;
  20372. // connection step
  20373. /**
  20374. * @type {Boolean}
  20375. */
  20376. this.resultInOut = false;
  20377. this.isExteriorRing = true;
  20378. };
  20379. /**
  20380. * @param{Array.<Number>}p
  20381. * @return {Boolean}
  20382. */
  20383. SweepEvent.prototype.isBelow = function isBelow (p) {
  20384. var p0 = this.point, p1 = this.otherEvent.point;
  20385. return this.left
  20386. ? (p0[0] - p[0]) * (p1[1] - p[1]) - (p1[0] - p[0]) * (p0[1] - p[1]) > 0
  20387. // signedArea(this.point, this.otherEvent.point, p) > 0 :
  20388. : (p1[0] - p[0]) * (p0[1] - p[1]) - (p0[0] - p[0]) * (p1[1] - p[1]) > 0;
  20389. //signedArea(this.otherEvent.point, this.point, p) > 0;
  20390. };
  20391. /**
  20392. * @param{Array.<Number>}p
  20393. * @return {Boolean}
  20394. */
  20395. SweepEvent.prototype.isAbove = function isAbove (p) {
  20396. return !this.isBelow(p);
  20397. };
  20398. /**
  20399. * @return {Boolean}
  20400. */
  20401. SweepEvent.prototype.isVertical = function isVertical () {
  20402. return this.point[0] === this.otherEvent.point[0];
  20403. };
  20404. SweepEvent.prototype.clone = function clone () {
  20405. var copy = new SweepEvent(
  20406. this.point, this.left, this.otherEvent, this.isSubject, this.type);
  20407. copy.inResult = this.inResult;
  20408. copy.prevInResult = this.prevInResult;
  20409. copy.isExteriorRing = this.isExteriorRing;
  20410. copy.inOut = this.inOut;
  20411. copy.otherInOut = this.otherInOut;
  20412. return copy;
  20413. };
  20414. function equals(p1, p2) {
  20415. if (p1[0] === p2[0]) {
  20416. if (p1[1] === p2[1]) {
  20417. return true;
  20418. } else {
  20419. return false;
  20420. }
  20421. }
  20422. return false;
  20423. }
  20424. // const EPSILON = 1e-9;
  20425. // const abs = Math.abs;
  20426. // TODO https://github.com/w8r/martinez/issues/6#issuecomment-262847164
  20427. // Precision problem.
  20428. //
  20429. // module.exports = function equals(p1, p2) {
  20430. // return abs(p1[0] - p2[0]) <= EPSILON && abs(p1[1] - p2[1]) <= EPSILON;
  20431. // };
  20432. /**
  20433. * Signed area of the triangle (p0, p1, p2)
  20434. * @param {Array.<Number>} p0
  20435. * @param {Array.<Number>} p1
  20436. * @param {Array.<Number>} p2
  20437. * @return {Number}
  20438. */
  20439. function signedArea(p0, p1, p2) {
  20440. return (p0[0] - p2[0]) * (p1[1] - p2[1]) - (p1[0] - p2[0]) * (p0[1] - p2[1]);
  20441. }
  20442. /**
  20443. * @param {SweepEvent} e1
  20444. * @param {SweepEvent} e2
  20445. * @return {Number}
  20446. */
  20447. function compareEvents(e1, e2) {
  20448. var p1 = e1.point;
  20449. var p2 = e2.point;
  20450. // Different x-coordinate
  20451. if (p1[0] > p2[0]) { return 1; }
  20452. if (p1[0] < p2[0]) { return -1; }
  20453. // Different points, but same x-coordinate
  20454. // Event with lower y-coordinate is processed first
  20455. if (p1[1] !== p2[1]) { return p1[1] > p2[1] ? 1 : -1; }
  20456. return specialCases(e1, e2, p1, p2);
  20457. }
  20458. /* eslint-disable no-unused-vars */
  20459. function specialCases(e1, e2, p1, p2) {
  20460. // Same coordinates, but one is a left endpoint and the other is
  20461. // a right endpoint. The right endpoint is processed first
  20462. if (e1.left !== e2.left)
  20463. { return e1.left ? 1 : -1; }
  20464. // const p2 = e1.otherEvent.point, p3 = e2.otherEvent.point;
  20465. // const sa = (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
  20466. // Same coordinates, both events
  20467. // are left endpoints or right endpoints.
  20468. // not collinear
  20469. if (signedArea(p1, e1.otherEvent.point, e2.otherEvent.point) !== 0) {
  20470. // the event associate to the bottom segment is processed first
  20471. return (!e1.isBelow(e2.otherEvent.point)) ? 1 : -1;
  20472. }
  20473. return (!e1.isSubject && e2.isSubject) ? 1 : -1;
  20474. }
  20475. /* eslint-enable no-unused-vars */
  20476. /**
  20477. * @param {SweepEvent} se
  20478. * @param {Array.<Number>} p
  20479. * @param {Queue} queue
  20480. * @return {Queue}
  20481. */
  20482. function divideSegment(se, p, queue) {
  20483. var r = new SweepEvent(p, false, se, se.isSubject);
  20484. var l = new SweepEvent(p, true, se.otherEvent, se.isSubject);
  20485. /* eslint-disable no-console */
  20486. if (equals(se.point, se.otherEvent.point)) {
  20487. console.warn('what is that, a collapsed segment?', se);
  20488. }
  20489. /* eslint-enable no-console */
  20490. r.contourId = l.contourId = se.contourId;
  20491. // avoid a rounding error. The left event would be processed after the right event
  20492. if (compareEvents(l, se.otherEvent) > 0) {
  20493. se.otherEvent.left = true;
  20494. l.left = false;
  20495. }
  20496. // avoid a rounding error. The left event would be processed after the right event
  20497. // if (compareEvents(se, r) > 0) {}
  20498. se.otherEvent.otherEvent = l;
  20499. se.otherEvent = r;
  20500. queue.push(l);
  20501. queue.push(r);
  20502. return queue;
  20503. }
  20504. //const EPS = 1e-9;
  20505. /**
  20506. * Finds the magnitude of the cross product of two vectors (if we pretend
  20507. * they're in three dimensions)
  20508. *
  20509. * @param {Object} a First vector
  20510. * @param {Object} b Second vector
  20511. * @private
  20512. * @returns {Number} The magnitude of the cross product
  20513. */
  20514. function crossProduct(a, b) {
  20515. return (a[0] * b[1]) - (a[1] * b[0]);
  20516. }
  20517. /**
  20518. * Finds the dot product of two vectors.
  20519. *
  20520. * @param {Object} a First vector
  20521. * @param {Object} b Second vector
  20522. * @private
  20523. * @returns {Number} The dot product
  20524. */
  20525. function dotProduct(a, b) {
  20526. return (a[0] * b[0]) + (a[1] * b[1]);
  20527. }
  20528. /**
  20529. * Finds the intersection (if any) between two line segments a and b, given the
  20530. * line segments' end points a1, a2 and b1, b2.
  20531. *
  20532. * This algorithm is based on Schneider and Eberly.
  20533. * http://www.cimec.org.ar/~ncalvo/Schneider_Eberly.pdf
  20534. * Page 244.
  20535. *
  20536. * @param {Array.<Number>} a1 point of first line
  20537. * @param {Array.<Number>} a2 point of first line
  20538. * @param {Array.<Number>} b1 point of second line
  20539. * @param {Array.<Number>} b2 point of second line
  20540. * @param {Boolean=} noEndpointTouch whether to skip single touchpoints
  20541. * (meaning connected segments) as
  20542. * intersections
  20543. * @returns {Array.<Array.<Number>>|Null} If the lines intersect, the point of
  20544. * intersection. If they overlap, the two end points of the overlapping segment.
  20545. * Otherwise, null.
  20546. */
  20547. function intersection (a1, a2, b1, b2, noEndpointTouch) {
  20548. // The algorithm expects our lines in the form P + sd, where P is a point,
  20549. // s is on the interval [0, 1], and d is a vector.
  20550. // We are passed two points. P can be the first point of each pair. The
  20551. // vector, then, could be thought of as the distance (in x and y components)
  20552. // from the first point to the second point.
  20553. // So first, let's make our vectors:
  20554. var va = [a2[0] - a1[0], a2[1] - a1[1]];
  20555. var vb = [b2[0] - b1[0], b2[1] - b1[1]];
  20556. // We also define a function to convert back to regular point form:
  20557. /* eslint-disable arrow-body-style */
  20558. function toPoint(p, s, d) {
  20559. return [
  20560. p[0] + s * d[0],
  20561. p[1] + s * d[1]
  20562. ];
  20563. }
  20564. /* eslint-enable arrow-body-style */
  20565. // The rest is pretty much a straight port of the algorithm.
  20566. var e = [b1[0] - a1[0], b1[1] - a1[1]];
  20567. var kross = crossProduct(va, vb);
  20568. var sqrKross = kross * kross;
  20569. var sqrLenA = dotProduct(va, va);
  20570. //const sqrLenB = dotProduct(vb, vb);
  20571. // Check for line intersection. This works because of the properties of the
  20572. // cross product -- specifically, two vectors are parallel if and only if the
  20573. // cross product is the 0 vector. The full calculation involves relative error
  20574. // to account for possible very small line segments. See Schneider & Eberly
  20575. // for details.
  20576. if (sqrKross > 0/* EPS * sqrLenB * sqLenA */) {
  20577. // If they're not parallel, then (because these are line segments) they
  20578. // still might not actually intersect. This code checks that the
  20579. // intersection point of the lines is actually on both line segments.
  20580. var s = crossProduct(e, vb) / kross;
  20581. if (s < 0 || s > 1) {
  20582. // not on line segment a
  20583. return null;
  20584. }
  20585. var t = crossProduct(e, va) / kross;
  20586. if (t < 0 || t > 1) {
  20587. // not on line segment b
  20588. return null;
  20589. }
  20590. if (s === 0 || s === 1) {
  20591. // on an endpoint of line segment a
  20592. return noEndpointTouch ? null : [toPoint(a1, s, va)];
  20593. }
  20594. if (t === 0 || t === 1) {
  20595. // on an endpoint of line segment b
  20596. return noEndpointTouch ? null : [toPoint(b1, t, vb)];
  20597. }
  20598. return [toPoint(a1, s, va)];
  20599. }
  20600. // If we've reached this point, then the lines are either parallel or the
  20601. // same, but the segments could overlap partially or fully, or not at all.
  20602. // So we need to find the overlap, if any. To do that, we can use e, which is
  20603. // the (vector) difference between the two initial points. If this is parallel
  20604. // with the line itself, then the two lines are the same line, and there will
  20605. // be overlap.
  20606. //const sqrLenE = dotProduct(e, e);
  20607. kross = crossProduct(e, va);
  20608. sqrKross = kross * kross;
  20609. if (sqrKross > 0 /* EPS * sqLenB * sqLenE */) {
  20610. // Lines are just parallel, not the same. No overlap.
  20611. return null;
  20612. }
  20613. var sa = dotProduct(va, e) / sqrLenA;
  20614. var sb = sa + dotProduct(va, vb) / sqrLenA;
  20615. var smin = Math.min(sa, sb);
  20616. var smax = Math.max(sa, sb);
  20617. // this is, essentially, the FindIntersection acting on floats from
  20618. // Schneider & Eberly, just inlined into this function.
  20619. if (smin <= 1 && smax >= 0) {
  20620. // overlap on an end point
  20621. if (smin === 1) {
  20622. return noEndpointTouch ? null : [toPoint(a1, smin > 0 ? smin : 0, va)];
  20623. }
  20624. if (smax === 0) {
  20625. return noEndpointTouch ? null : [toPoint(a1, smax < 1 ? smax : 1, va)];
  20626. }
  20627. if (noEndpointTouch && smin === 0 && smax === 1) { return null; }
  20628. // There's overlap on a segment -- two points of intersection. Return both.
  20629. return [
  20630. toPoint(a1, smin > 0 ? smin : 0, va),
  20631. toPoint(a1, smax < 1 ? smax : 1, va)
  20632. ];
  20633. }
  20634. return null;
  20635. }
  20636. /**
  20637. * @param {SweepEvent} se1
  20638. * @param {SweepEvent} se2
  20639. * @param {Queue} queue
  20640. * @return {Number}
  20641. */
  20642. function possibleIntersection (se1, se2, queue) {
  20643. // that disallows self-intersecting polygons,
  20644. // did cost us half a day, so I'll leave it
  20645. // out of respect
  20646. // if (se1.isSubject === se2.isSubject) return;
  20647. var inter = intersection(
  20648. se1.point, se1.otherEvent.point,
  20649. se2.point, se2.otherEvent.point
  20650. );
  20651. var nintersections = inter ? inter.length : 0;
  20652. if (nintersections === 0) { return 0; } // no intersection
  20653. // the line segments intersect at an endpoint of both line segments
  20654. if ((nintersections === 1) &&
  20655. (equals(se1.point, se2.point) ||
  20656. equals(se1.otherEvent.point, se2.otherEvent.point))) {
  20657. return 0;
  20658. }
  20659. if (nintersections === 2 && se1.isSubject === se2.isSubject) {
  20660. // if(se1.contourId === se2.contourId){
  20661. // console.warn('Edges of the same polygon overlap',
  20662. // se1.point, se1.otherEvent.point, se2.point, se2.otherEvent.point);
  20663. // }
  20664. //throw new Error('Edges of the same polygon overlap');
  20665. return 0;
  20666. }
  20667. // The line segments associated to se1 and se2 intersect
  20668. if (nintersections === 1) {
  20669. // if the intersection point is not an endpoint of se1
  20670. if (!equals(se1.point, inter[0]) && !equals(se1.otherEvent.point, inter[0])) {
  20671. divideSegment(se1, inter[0], queue);
  20672. }
  20673. // if the intersection point is not an endpoint of se2
  20674. if (!equals(se2.point, inter[0]) && !equals(se2.otherEvent.point, inter[0])) {
  20675. divideSegment(se2, inter[0], queue);
  20676. }
  20677. return 1;
  20678. }
  20679. // The line segments associated to se1 and se2 overlap
  20680. var events = [];
  20681. var leftCoincide = false;
  20682. var rightCoincide = false;
  20683. if (equals(se1.point, se2.point)) {
  20684. leftCoincide = true; // linked
  20685. } else if (compareEvents(se1, se2) === 1) {
  20686. events.push(se2, se1);
  20687. } else {
  20688. events.push(se1, se2);
  20689. }
  20690. if (equals(se1.otherEvent.point, se2.otherEvent.point)) {
  20691. rightCoincide = true;
  20692. } else if (compareEvents(se1.otherEvent, se2.otherEvent) === 1) {
  20693. events.push(se2.otherEvent, se1.otherEvent);
  20694. } else {
  20695. events.push(se1.otherEvent, se2.otherEvent);
  20696. }
  20697. if ((leftCoincide && rightCoincide) || leftCoincide) {
  20698. // both line segments are equal or share the left endpoint
  20699. se2.type = NON_CONTRIBUTING;
  20700. se1.type = (se2.inOut === se1.inOut)
  20701. ? SAME_TRANSITION : DIFFERENT_TRANSITION;
  20702. if (leftCoincide && !rightCoincide) {
  20703. // honestly no idea, but changing events selection from [2, 1]
  20704. // to [0, 1] fixes the overlapping self-intersecting polygons issue
  20705. divideSegment(events[1].otherEvent, events[0].point, queue);
  20706. }
  20707. return 2;
  20708. }
  20709. // the line segments share the right endpoint
  20710. if (rightCoincide) {
  20711. divideSegment(events[0], events[1].point, queue);
  20712. return 3;
  20713. }
  20714. // no line segment includes totally the other one
  20715. if (events[0] !== events[3].otherEvent) {
  20716. divideSegment(events[0], events[1].point, queue);
  20717. divideSegment(events[1], events[2].point, queue);
  20718. return 3;
  20719. }
  20720. // one line segment includes the other one
  20721. divideSegment(events[0], events[1].point, queue);
  20722. divideSegment(events[3].otherEvent, events[2].point, queue);
  20723. return 3;
  20724. }
  20725. /**
  20726. * @param {SweepEvent} le1
  20727. * @param {SweepEvent} le2
  20728. * @return {Number}
  20729. */
  20730. function compareSegments(le1, le2) {
  20731. if (le1 === le2) { return 0; }
  20732. // Segments are not collinear
  20733. if (signedArea(le1.point, le1.otherEvent.point, le2.point) !== 0 ||
  20734. signedArea(le1.point, le1.otherEvent.point, le2.otherEvent.point) !== 0) {
  20735. // If they share their left endpoint use the right endpoint to sort
  20736. if (equals(le1.point, le2.point)) { return le1.isBelow(le2.otherEvent.point) ? -1 : 1; }
  20737. // Different left endpoint: use the left endpoint to sort
  20738. if (le1.point[0] === le2.point[0]) { return le1.point[1] < le2.point[1] ? -1 : 1; }
  20739. // has the line segment associated to e1 been inserted
  20740. // into S after the line segment associated to e2 ?
  20741. if (compareEvents(le1, le2) === 1) { return le2.isAbove(le1.point) ? -1 : 1; }
  20742. // The line segment associated to e2 has been inserted
  20743. // into S after the line segment associated to e1
  20744. return le1.isBelow(le2.point) ? -1 : 1;
  20745. }
  20746. if (le1.isSubject === le2.isSubject) { // same polygon
  20747. var p1 = le1.point, p2 = le2.point;
  20748. if (p1[0] === p2[0] && p1[1] === p2[1]/*equals(le1.point, le2.point)*/) {
  20749. p1 = le1.otherEvent.point; p2 = le2.otherEvent.point;
  20750. if (p1[0] === p2[0] && p1[1] === p2[1]) { return 0; }
  20751. else { return le1.contourId > le2.contourId ? 1 : -1; }
  20752. }
  20753. } else { // Segments are collinear, but belong to separate polygons
  20754. return le1.isSubject ? -1 : 1;
  20755. }
  20756. return compareEvents(le1, le2) === 1 ? 1 : -1;
  20757. }
  20758. function subdivide(eventQueue, subject, clipping, sbbox, cbbox, operation) {
  20759. var sweepLine = new SplayTree(compareSegments);
  20760. var sortedEvents = [];
  20761. var rightbound = Math.min(sbbox[2], cbbox[2]);
  20762. var prev, next, begin;
  20763. while (eventQueue.length !== 0) {
  20764. var event = eventQueue.pop();
  20765. sortedEvents.push(event);
  20766. // optimization by bboxes for intersection and difference goes here
  20767. if ((operation === INTERSECTION && event.point[0] > rightbound) ||
  20768. (operation === DIFFERENCE && event.point[0] > sbbox[2])) {
  20769. break;
  20770. }
  20771. if (event.left) {
  20772. next = prev = sweepLine.insert(event);
  20773. begin = sweepLine.minNode();
  20774. if (prev !== begin) { prev = sweepLine.prev(prev); }
  20775. else { prev = null; }
  20776. next = sweepLine.next(next);
  20777. var prevEvent = prev ? prev.key : null;
  20778. var prevprevEvent = (void 0);
  20779. computeFields(event, prevEvent, operation);
  20780. if (next) {
  20781. if (possibleIntersection(event, next.key, eventQueue) === 2) {
  20782. computeFields(event, prevEvent, operation);
  20783. computeFields(event, next.key, operation);
  20784. }
  20785. }
  20786. if (prev) {
  20787. if (possibleIntersection(prev.key, event, eventQueue) === 2) {
  20788. var prevprev = prev;
  20789. if (prevprev !== begin) { prevprev = sweepLine.prev(prevprev); }
  20790. else { prevprev = null; }
  20791. prevprevEvent = prevprev ? prevprev.key : null;
  20792. computeFields(prevEvent, prevprevEvent, operation);
  20793. computeFields(event, prevEvent, operation);
  20794. }
  20795. }
  20796. } else {
  20797. event = event.otherEvent;
  20798. next = prev = sweepLine.find(event);
  20799. if (prev && next) {
  20800. if (prev !== begin) { prev = sweepLine.prev(prev); }
  20801. else { prev = null; }
  20802. next = sweepLine.next(next);
  20803. sweepLine.remove(event);
  20804. if (next && prev) {
  20805. possibleIntersection(prev.key, next.key, eventQueue);
  20806. }
  20807. }
  20808. }
  20809. }
  20810. return sortedEvents;
  20811. }
  20812. /**
  20813. * @param {Array.<SweepEvent>} sortedEvents
  20814. * @return {Array.<SweepEvent>}
  20815. */
  20816. function orderEvents(sortedEvents) {
  20817. var event, i, len, tmp;
  20818. var resultEvents = [];
  20819. for (i = 0, len = sortedEvents.length; i < len; i++) {
  20820. event = sortedEvents[i];
  20821. if ((event.left && event.inResult) ||
  20822. (!event.left && event.otherEvent.inResult)) {
  20823. resultEvents.push(event);
  20824. }
  20825. }
  20826. // Due to overlapping edges the resultEvents array can be not wholly sorted
  20827. var sorted = false;
  20828. while (!sorted) {
  20829. sorted = true;
  20830. for (i = 0, len = resultEvents.length; i < len; i++) {
  20831. if ((i + 1) < len &&
  20832. compareEvents(resultEvents[i], resultEvents[i + 1]) === 1) {
  20833. tmp = resultEvents[i];
  20834. resultEvents[i] = resultEvents[i + 1];
  20835. resultEvents[i + 1] = tmp;
  20836. sorted = false;
  20837. }
  20838. }
  20839. }
  20840. for (i = 0, len = resultEvents.length; i < len; i++) {
  20841. event = resultEvents[i];
  20842. event.pos = i;
  20843. }
  20844. // imagine, the right event is found in the beginning of the queue,
  20845. // when his left counterpart is not marked yet
  20846. for (i = 0, len = resultEvents.length; i < len; i++) {
  20847. event = resultEvents[i];
  20848. if (!event.left) {
  20849. tmp = event.pos;
  20850. event.pos = event.otherEvent.pos;
  20851. event.otherEvent.pos = tmp;
  20852. }
  20853. }
  20854. return resultEvents;
  20855. }
  20856. /**
  20857. * @param {Number} pos
  20858. * @param {Array.<SweepEvent>} resultEvents
  20859. * @param {Object>} processed
  20860. * @return {Number}
  20861. */
  20862. function nextPos(pos, resultEvents, processed, origIndex) {
  20863. var newPos = pos + 1;
  20864. var length = resultEvents.length;
  20865. if (newPos > length - 1) { return pos - 1; }
  20866. var p = resultEvents[pos].point;
  20867. var p1 = resultEvents[newPos].point;
  20868. // while in range and not the current one by value
  20869. while (newPos < length && p1[0] === p[0] && p1[1] === p[1]) {
  20870. if (!processed[newPos]) {
  20871. return newPos;
  20872. } else {
  20873. newPos++;
  20874. }
  20875. p1 = resultEvents[newPos].point;
  20876. }
  20877. newPos = pos - 1;
  20878. while (processed[newPos] && newPos >= origIndex) {
  20879. newPos--;
  20880. }
  20881. return newPos;
  20882. }
  20883. /**
  20884. * @param {Array.<SweepEvent>} sortedEvents
  20885. * @return {Array.<*>} polygons
  20886. */
  20887. function connectEdges(sortedEvents, operation) {
  20888. var i, len;
  20889. var resultEvents = orderEvents(sortedEvents);
  20890. // "false"-filled array
  20891. var processed = {};
  20892. var result = [];
  20893. var event;
  20894. for (i = 0, len = resultEvents.length; i < len; i++) {
  20895. if (processed[i]) { continue; }
  20896. var contour = [[]];
  20897. if (!resultEvents[i].isExteriorRing) {
  20898. if (operation === DIFFERENCE && !resultEvents[i].isSubject && result.length === 0) {
  20899. result.push(contour);
  20900. } else if (result.length === 0) {
  20901. result.push([[contour]]);
  20902. } else {
  20903. result[result.length - 1].push(contour[0]);
  20904. }
  20905. } else if (operation === DIFFERENCE && !resultEvents[i].isSubject && result.length > 1) {
  20906. result[result.length - 1].push(contour[0]);
  20907. } else {
  20908. result.push(contour);
  20909. }
  20910. var ringId = result.length - 1;
  20911. var pos = i;
  20912. var initial = resultEvents[i].point;
  20913. contour[0].push(initial);
  20914. while (pos >= i) {
  20915. event = resultEvents[pos];
  20916. processed[pos] = true;
  20917. if (event.left) {
  20918. event.resultInOut = false;
  20919. event.contourId = ringId;
  20920. } else {
  20921. event.otherEvent.resultInOut = true;
  20922. event.otherEvent.contourId = ringId;
  20923. }
  20924. pos = event.pos;
  20925. processed[pos] = true;
  20926. contour[0].push(resultEvents[pos].point);
  20927. pos = nextPos(pos, resultEvents, processed, i);
  20928. }
  20929. pos = pos === -1 ? i : pos;
  20930. event = resultEvents[pos];
  20931. processed[pos] = processed[event.pos] = true;
  20932. event.otherEvent.resultInOut = true;
  20933. event.otherEvent.contourId = ringId;
  20934. }
  20935. // Handle if the result is a polygon (eg not multipoly)
  20936. // Commented it again, let's see what do we mean by that
  20937. // if (result.length === 1) result = result[0];
  20938. return result;
  20939. }
  20940. var tinyqueue = TinyQueue;
  20941. var default_1 = TinyQueue;
  20942. function TinyQueue(data, compare) {
  20943. var this$1 = this;
  20944. if (!(this instanceof TinyQueue)) { return new TinyQueue(data, compare); }
  20945. this.data = data || [];
  20946. this.length = this.data.length;
  20947. this.compare = compare || defaultCompare;
  20948. if (this.length > 0) {
  20949. for (var i = (this.length >> 1) - 1; i >= 0; i--) { this$1._down(i); }
  20950. }
  20951. }
  20952. function defaultCompare(a, b) {
  20953. return a < b ? -1 : a > b ? 1 : 0;
  20954. }
  20955. TinyQueue.prototype = {
  20956. push: function (item) {
  20957. this.data.push(item);
  20958. this.length++;
  20959. this._up(this.length - 1);
  20960. },
  20961. pop: function () {
  20962. if (this.length === 0) { return undefined; }
  20963. var top = this.data[0];
  20964. this.length--;
  20965. if (this.length > 0) {
  20966. this.data[0] = this.data[this.length];
  20967. this._down(0);
  20968. }
  20969. this.data.pop();
  20970. return top;
  20971. },
  20972. peek: function () {
  20973. return this.data[0];
  20974. },
  20975. _up: function (pos) {
  20976. var data = this.data;
  20977. var compare = this.compare;
  20978. var item = data[pos];
  20979. while (pos > 0) {
  20980. var parent = (pos - 1) >> 1;
  20981. var current = data[parent];
  20982. if (compare(item, current) >= 0) { break; }
  20983. data[pos] = current;
  20984. pos = parent;
  20985. }
  20986. data[pos] = item;
  20987. },
  20988. _down: function (pos) {
  20989. var this$1 = this;
  20990. var data = this.data;
  20991. var compare = this.compare;
  20992. var halfLength = this.length >> 1;
  20993. var item = data[pos];
  20994. while (pos < halfLength) {
  20995. var left = (pos << 1) + 1;
  20996. var right = left + 1;
  20997. var best = data[left];
  20998. if (right < this$1.length && compare(data[right], best) < 0) {
  20999. left = right;
  21000. best = data[right];
  21001. }
  21002. if (compare(best, item) >= 0) { break; }
  21003. data[pos] = best;
  21004. pos = left;
  21005. }
  21006. data[pos] = item;
  21007. }
  21008. };
  21009. tinyqueue.default = default_1;
  21010. var max = Math.max;
  21011. var min = Math.min;
  21012. var contourId = 0;
  21013. function processPolygon(contourOrHole, isSubject, depth, Q, bbox, isExteriorRing) {
  21014. var i, len, s1, s2, e1, e2;
  21015. for (i = 0, len = contourOrHole.length - 1; i < len; i++) {
  21016. s1 = contourOrHole[i];
  21017. s2 = contourOrHole[i + 1];
  21018. e1 = new SweepEvent(s1, false, undefined, isSubject);
  21019. e2 = new SweepEvent(s2, false, e1, isSubject);
  21020. e1.otherEvent = e2;
  21021. if (s1[0] === s2[0] && s1[1] === s2[1]) {
  21022. continue; // skip collapsed edges, or it breaks
  21023. }
  21024. e1.contourId = e2.contourId = depth;
  21025. if (!isExteriorRing) {
  21026. e1.isExteriorRing = false;
  21027. e2.isExteriorRing = false;
  21028. }
  21029. if (compareEvents(e1, e2) > 0) {
  21030. e2.left = true;
  21031. } else {
  21032. e1.left = true;
  21033. }
  21034. var x = s1[0], y = s1[1];
  21035. bbox[0] = min(bbox[0], x);
  21036. bbox[1] = min(bbox[1], y);
  21037. bbox[2] = max(bbox[2], x);
  21038. bbox[3] = max(bbox[3], y);
  21039. // Pushing it so the queue is sorted from left to right,
  21040. // with object on the left having the highest priority.
  21041. Q.push(e1);
  21042. Q.push(e2);
  21043. }
  21044. }
  21045. function fillQueue(subject, clipping, sbbox, cbbox, operation) {
  21046. var eventQueue = new tinyqueue(null, compareEvents);
  21047. var polygonSet, isExteriorRing, i, ii, j, jj; //, k, kk;
  21048. for (i = 0, ii = subject.length; i < ii; i++) {
  21049. polygonSet = subject[i];
  21050. for (j = 0, jj = polygonSet.length; j < jj; j++) {
  21051. isExteriorRing = j === 0;
  21052. if (isExteriorRing) { contourId++; }
  21053. processPolygon(polygonSet[j], true, contourId, eventQueue, sbbox, isExteriorRing);
  21054. }
  21055. }
  21056. for (i = 0, ii = clipping.length; i < ii; i++) {
  21057. polygonSet = clipping[i];
  21058. for (j = 0, jj = polygonSet.length; j < jj; j++) {
  21059. isExteriorRing = j === 0;
  21060. if (operation === DIFFERENCE) { isExteriorRing = false; }
  21061. if (isExteriorRing) { contourId++; }
  21062. processPolygon(polygonSet[j], false, contourId, eventQueue, cbbox, isExteriorRing);
  21063. }
  21064. }
  21065. return eventQueue;
  21066. }
  21067. var EMPTY = [];
  21068. function trivialOperation(subject, clipping, operation) {
  21069. var result = null;
  21070. if (subject.length * clipping.length === 0) {
  21071. if (operation === INTERSECTION) {
  21072. result = EMPTY;
  21073. } else if (operation === DIFFERENCE) {
  21074. result = subject;
  21075. } else if (operation === UNION ||
  21076. operation === XOR) {
  21077. result = (subject.length === 0) ? clipping : subject;
  21078. }
  21079. }
  21080. return result;
  21081. }
  21082. function compareBBoxes(subject, clipping, sbbox, cbbox, operation) {
  21083. var result = null;
  21084. if (sbbox[0] > cbbox[2] ||
  21085. cbbox[0] > sbbox[2] ||
  21086. sbbox[1] > cbbox[3] ||
  21087. cbbox[1] > sbbox[3]) {
  21088. if (operation === INTERSECTION) {
  21089. result = EMPTY;
  21090. } else if (operation === DIFFERENCE) {
  21091. result = subject;
  21092. } else if (operation === UNION ||
  21093. operation === XOR) {
  21094. result = subject.concat(clipping);
  21095. }
  21096. }
  21097. return result;
  21098. }
  21099. function boolean(subject, clipping, operation) {
  21100. if (typeof subject[0][0][0] === 'number') {
  21101. subject = [subject];
  21102. }
  21103. if (typeof clipping[0][0][0] === 'number') {
  21104. clipping = [clipping];
  21105. }
  21106. var trivial = trivialOperation(subject, clipping, operation);
  21107. if (trivial) {
  21108. return trivial === EMPTY ? null : trivial;
  21109. }
  21110. var sbbox = [Infinity, Infinity, -Infinity, -Infinity];
  21111. var cbbox = [Infinity, Infinity, -Infinity, -Infinity];
  21112. //console.time('fill queue');
  21113. var eventQueue = fillQueue(subject, clipping, sbbox, cbbox, operation);
  21114. //console.timeEnd('fill queue');
  21115. trivial = compareBBoxes(subject, clipping, sbbox, cbbox, operation);
  21116. if (trivial) {
  21117. return trivial === EMPTY ? null : trivial;
  21118. }
  21119. //console.time('subdivide edges');
  21120. var sortedEvents = subdivide(eventQueue, subject, clipping, sbbox, cbbox, operation);
  21121. //console.timeEnd('subdivide edges');
  21122. //console.time('connect vertices');
  21123. var result = connectEdges(sortedEvents, operation);
  21124. //console.timeEnd('connect vertices');
  21125. return result;
  21126. }
  21127. function union (subject, clipping) {
  21128. return boolean(subject, clipping, UNION);
  21129. }
  21130. function diff (subject, clipping) {
  21131. return boolean(subject, clipping, DIFFERENCE);
  21132. }
  21133. function xor (subject, clipping){
  21134. return boolean(subject, clipping, XOR);
  21135. }
  21136. function intersection$1 (subject, clipping) {
  21137. return boolean(subject, clipping, INTERSECTION);
  21138. }
  21139. /**
  21140. * @enum {Number}
  21141. */
  21142. var operations = { UNION: UNION, DIFFERENCE: DIFFERENCE, INTERSECTION: INTERSECTION, XOR: XOR };
  21143. exports.union = union;
  21144. exports.diff = diff;
  21145. exports.xor = xor;
  21146. exports.intersection = intersection$1;
  21147. exports.operations = operations;
  21148. Object.defineProperty(exports, '__esModule', { value: true });
  21149. })));
  21150. },{}],174:[function(require,module,exports){
  21151. const turf = {
  21152. nearestPointOnLine: require('@turf/nearest-point-on-line').default,
  21153. booleanPointInPolygon: require('@turf/boolean-point-in-polygon').default
  21154. }
  21155. function nearestPointOnGeometry (feature, pt, options) {
  21156. var result
  21157. if (!feature.geometry) {
  21158. return null
  21159. }
  21160. switch (feature.geometry.type) {
  21161. case 'LineString':
  21162. case 'MultiLineString':
  21163. return turf.nearestPointOnLine(feature, pt, options)
  21164. case 'Polygon':
  21165. if (turf.booleanPointInPolygon(pt, feature, options)) {
  21166. let result = JSON.parse(JSON.stringify(pt))
  21167. result.properties = {
  21168. 'dist': 0,
  21169. 'location': 0
  21170. }
  21171. return result
  21172. } else {
  21173. let modifiedFeature = JSON.parse(JSON.stringify(feature))
  21174. modifiedFeature.geometry.type = 'MultiLineString'
  21175. return nearestPointOnGeometry(modifiedFeature, pt, options)
  21176. }
  21177. case 'MultiPolygon':
  21178. result = feature.geometry.coordinates.map(coord => {
  21179. let modifiedFeature = {
  21180. type: 'Feature',
  21181. geometry: {
  21182. type: 'Polygon',
  21183. coordinates: coord
  21184. }
  21185. }
  21186. return nearestPointOnGeometry(modifiedFeature, pt, options)
  21187. })
  21188. result = result.filter(o => o)
  21189. result = result.sort((a, b) => {
  21190. if (!a || !b) {
  21191. return null
  21192. }
  21193. return a.properties.dist - b.properties.dist
  21194. })
  21195. if (result.length > 0) {
  21196. return result[0]
  21197. }
  21198. return
  21199. case 'GeometryCollection':
  21200. result = feature.geometry.geometries.map(geom => {
  21201. let modifiedFeature = {
  21202. type: 'Feature',
  21203. geometry: geom
  21204. }
  21205. return nearestPointOnGeometry(modifiedFeature, pt, options)
  21206. })
  21207. result = result.filter(o => o)
  21208. result = result.sort((a, b) => {
  21209. if (!a || !b) {
  21210. return null
  21211. }
  21212. return a.properties.dist - b.properties.dist
  21213. })
  21214. if (result.length > 0) {
  21215. return result[0]
  21216. }
  21217. return
  21218. default:
  21219. console.log('nearestPointOnGeometry: don\'t know how to handle ' + feature.geometry.type)
  21220. }
  21221. }
  21222. module.exports = nearestPointOnGeometry
  21223. },{"@turf/boolean-point-in-polygon":7,"@turf/nearest-point-on-line":17}],175:[function(require,module,exports){
  21224. module.exports = require('./polygon-features.json')
  21225. },{"./polygon-features.json":176}],176:[function(require,module,exports){
  21226. module.exports=[
  21227. {
  21228. "key": "building",
  21229. "polygon": "all"
  21230. },
  21231. {
  21232. "key": "highway",
  21233. "polygon": "whitelist",
  21234. "values": [
  21235. "services",
  21236. "rest_area",
  21237. "escape",
  21238. "elevator"
  21239. ]
  21240. },
  21241. {
  21242. "key": "natural",
  21243. "polygon": "blacklist",
  21244. "values": [
  21245. "coastline",
  21246. "cliff",
  21247. "ridge",
  21248. "arete",
  21249. "tree_row"
  21250. ]
  21251. },
  21252. {
  21253. "key": "landuse",
  21254. "polygon": "all"
  21255. },
  21256. {
  21257. "key": "waterway",
  21258. "polygon": "whitelist",
  21259. "values": [
  21260. "riverbank",
  21261. "dock",
  21262. "boatyard",
  21263. "dam"
  21264. ]
  21265. },
  21266. {
  21267. "key": "amenity",
  21268. "polygon": "all"
  21269. },
  21270. {
  21271. "key": "leisure",
  21272. "polygon": "all"
  21273. },
  21274. {
  21275. "key": "barrier",
  21276. "polygon": "whitelist",
  21277. "values": [
  21278. "city_wall",
  21279. "ditch",
  21280. "hedge",
  21281. "retaining_wall",
  21282. "wall",
  21283. "spikes"
  21284. ]
  21285. },
  21286. {
  21287. "key": "railway",
  21288. "polygon": "whitelist",
  21289. "values": [
  21290. "station",
  21291. "turntable",
  21292. "roundhouse",
  21293. "platform"
  21294. ]
  21295. },
  21296. {
  21297. "key": "area",
  21298. "polygon": "all"
  21299. },
  21300. {
  21301. "key": "boundary",
  21302. "polygon": "all"
  21303. },
  21304. {
  21305. "key": "man_made",
  21306. "polygon": "blacklist",
  21307. "values": [
  21308. "cutline",
  21309. "embankment",
  21310. "pipeline"
  21311. ]
  21312. },
  21313. {
  21314. "key": "power",
  21315. "polygon": "whitelist",
  21316. "values": [
  21317. "plant",
  21318. "substation",
  21319. "generator",
  21320. "transformer"
  21321. ]
  21322. },
  21323. {
  21324. "key": "place",
  21325. "polygon": "all"
  21326. },
  21327. {
  21328. "key": "shop",
  21329. "polygon": "all"
  21330. },
  21331. {
  21332. "key": "aeroway",
  21333. "polygon": "blacklist",
  21334. "values": [
  21335. "taxiway"
  21336. ]
  21337. },
  21338. {
  21339. "key": "tourism",
  21340. "polygon": "all"
  21341. },
  21342. {
  21343. "key": "historic",
  21344. "polygon": "all"
  21345. },
  21346. {
  21347. "key": "public_transport",
  21348. "polygon": "all"
  21349. },
  21350. {
  21351. "key": "office",
  21352. "polygon": "all"
  21353. },
  21354. {
  21355. "key": "building:part",
  21356. "polygon": "all"
  21357. },
  21358. {
  21359. "key": "military",
  21360. "polygon": "all"
  21361. },
  21362. {
  21363. "key": "ruins",
  21364. "polygon": "all"
  21365. },
  21366. {
  21367. "key": "area:highway",
  21368. "polygon": "all"
  21369. },
  21370. {
  21371. "key": "craft",
  21372. "polygon": "all"
  21373. },
  21374. {
  21375. "key": "golf",
  21376. "polygon": "all"
  21377. },
  21378. {
  21379. "key": "indoor",
  21380. "polygon": "all"
  21381. }
  21382. ]
  21383. },{}],177:[function(require,module,exports){
  21384. var _ = require("./lodash.custom.js");
  21385. var rewind = require("geojson-rewind");
  21386. // see https://wiki.openstreetmap.org/wiki/Overpass_turbo/Polygon_Features
  21387. var polygonFeatures = {};
  21388. require("osm-polygon-features").forEach(function(tags) {
  21389. if (tags.polygon === "all")
  21390. polygonFeatures[tags.key] = true;
  21391. else {
  21392. var list = (tags.polygon === "whitelist") ? "included_values" : "excluded_values",
  21393. tagValuesObj = {};
  21394. tags.values.forEach(function(value) { tagValuesObj[value] = true; });
  21395. polygonFeatures[tags.key] = {};
  21396. polygonFeatures[tags.key][list] = tagValuesObj;
  21397. }
  21398. });
  21399. // default deduplication helper function
  21400. function default_deduplicator(objectA, objectB) {
  21401. // default deduplication handler:
  21402. // if object versions differ, use highest available version
  21403. if ((objectA.version || objectB.version) &&
  21404. (objectA.version !== objectB.version)) {
  21405. return (+objectA.version || 0) > (+objectB.version || 0)
  21406. ? objectA
  21407. : objectB;
  21408. }
  21409. // otherwise: return merged obj properties
  21410. return _.merge(objectA, objectB);
  21411. }
  21412. var osmtogeojson = {};
  21413. osmtogeojson = function( data, options, featureCallback ) {
  21414. options = _.merge(
  21415. {
  21416. verbose: false,
  21417. flatProperties: true,
  21418. uninterestingTags: {
  21419. "source": true,
  21420. "source_ref": true,
  21421. "source:ref": true,
  21422. "history": true,
  21423. "attribution": true,
  21424. "created_by": true,
  21425. "tiger:county": true,
  21426. "tiger:tlid": true,
  21427. "tiger:upload_uuid": true
  21428. },
  21429. polygonFeatures: polygonFeatures,
  21430. deduplicator: default_deduplicator
  21431. },
  21432. options
  21433. );
  21434. var result;
  21435. if ( ((typeof XMLDocument !== "undefined") && data instanceof XMLDocument ||
  21436. (typeof XMLDocument === "undefined") && data.childNodes) )
  21437. result = _osmXML2geoJSON(data);
  21438. else
  21439. result = _overpassJSON2geoJSON(data);
  21440. return result;
  21441. function _overpassJSON2geoJSON(json) {
  21442. // sort elements
  21443. var nodes = new Array();
  21444. var ways = new Array();
  21445. var rels = new Array();
  21446. // helper functions
  21447. function centerGeometry(object) {
  21448. var pseudoNode = _.clone(object);
  21449. pseudoNode.lat = object.center.lat;
  21450. pseudoNode.lon = object.center.lon;
  21451. pseudoNode.__is_center_placeholder = true;
  21452. nodes.push(pseudoNode);
  21453. }
  21454. function boundsGeometry(object) {
  21455. var pseudoWay = _.clone(object);
  21456. pseudoWay.nodes = [];
  21457. function addPseudoNode(lat,lon,i) {
  21458. var pseudoNode = {
  21459. type:"node",
  21460. id: "_"+pseudoWay.type+"/"+pseudoWay.id+"bounds"+i,
  21461. lat: lat,
  21462. lon: lon
  21463. }
  21464. pseudoWay.nodes.push(pseudoNode.id);
  21465. nodes.push(pseudoNode);
  21466. }
  21467. addPseudoNode(pseudoWay.bounds.minlat,pseudoWay.bounds.minlon,1);
  21468. addPseudoNode(pseudoWay.bounds.maxlat,pseudoWay.bounds.minlon,2);
  21469. addPseudoNode(pseudoWay.bounds.maxlat,pseudoWay.bounds.maxlon,3);
  21470. addPseudoNode(pseudoWay.bounds.minlat,pseudoWay.bounds.maxlon,4);
  21471. pseudoWay.nodes.push(pseudoWay.nodes[0]);
  21472. pseudoWay.__is_bounds_placeholder = true;
  21473. ways.push(pseudoWay);
  21474. }
  21475. function fullGeometryWay(way) {
  21476. function addFullGeometryNode(lat,lon,id) {
  21477. var geometryNode = {
  21478. type:"node",
  21479. id: id,
  21480. lat: lat,
  21481. lon: lon
  21482. }
  21483. nodes.push(geometryNode);
  21484. }
  21485. if (!_.isArray(way.nodes)) {
  21486. way.nodes = way.geometry.map(function(nd) {
  21487. if (nd !== null) // have to skip ref-less nodes
  21488. return "_anonymous@"+nd.lat+"/"+nd.lon;
  21489. else
  21490. return "_anonymous@unknown_location";
  21491. });
  21492. }
  21493. way.geometry.forEach(function(nd, i) {
  21494. if (nd) {
  21495. addFullGeometryNode(
  21496. nd.lat,
  21497. nd.lon,
  21498. way.nodes[i]
  21499. );
  21500. }
  21501. });
  21502. }
  21503. function fullGeometryRelation(rel) {
  21504. function addFullGeometryNode(lat,lon,id) {
  21505. var geometryNode = {
  21506. type:"node",
  21507. id: id,
  21508. lat: lat,
  21509. lon: lon
  21510. }
  21511. nodes.push(geometryNode);
  21512. }
  21513. function addFullGeometryWay(geometry,id) {
  21514. // shared multipolygon ways cannot be defined multiple times with the same id.
  21515. if (ways.some(function (way) { // todo: this is slow :(
  21516. return way.type == "way" && way.id == id;
  21517. })) return;
  21518. var geometryWay = {
  21519. type: "way",
  21520. id: id,
  21521. nodes:[]
  21522. }
  21523. function addFullGeometryWayPseudoNode(lat,lon) {
  21524. // todo? do not save the same pseudo node multiple times
  21525. var geometryPseudoNode = {
  21526. type:"node",
  21527. id: "_anonymous@"+lat+"/"+lon,
  21528. lat: lat,
  21529. lon: lon
  21530. }
  21531. geometryWay.nodes.push(geometryPseudoNode.id);
  21532. nodes.push(geometryPseudoNode);
  21533. }
  21534. geometry.forEach(function(nd) {
  21535. if (nd) {
  21536. addFullGeometryWayPseudoNode(
  21537. nd.lat,
  21538. nd.lon
  21539. );
  21540. } else {
  21541. geometryWay.nodes.push(undefined);
  21542. }
  21543. });
  21544. ways.push(geometryWay);
  21545. }
  21546. rel.members.forEach(function(member, i) {
  21547. if (member.type == "node") {
  21548. if (member.lat) {
  21549. addFullGeometryNode(
  21550. member.lat,
  21551. member.lon,
  21552. member.ref
  21553. );
  21554. }
  21555. } else if (member.type == "way") {
  21556. if (member.geometry) {
  21557. member.ref = "_fullGeom"+member.ref;
  21558. addFullGeometryWay(
  21559. member.geometry,
  21560. member.ref
  21561. );
  21562. }
  21563. }
  21564. });
  21565. }
  21566. // create copies of individual json objects to make sure the original data doesn't get altered
  21567. // todo: cloning is slow: see if this can be done differently!
  21568. for (var i=0;i<json.elements.length;i++) {
  21569. switch (json.elements[i].type) {
  21570. case "node":
  21571. var node = json.elements[i];
  21572. nodes.push(node);
  21573. break;
  21574. case "way":
  21575. var way = _.clone(json.elements[i]);
  21576. way.nodes = _.clone(way.nodes);
  21577. ways.push(way);
  21578. if (way.center)
  21579. centerGeometry(way);
  21580. if (way.geometry)
  21581. fullGeometryWay(way);
  21582. else if (way.bounds)
  21583. boundsGeometry(way);
  21584. break;
  21585. case "relation":
  21586. var rel = _.clone(json.elements[i]);
  21587. rel.members = _.clone(rel.members);
  21588. rels.push(rel);
  21589. var has_full_geometry = rel.members && rel.members.some(function (member) {
  21590. return member.type == "node" && member.lat ||
  21591. member.type == "way" && member.geometry && member.geometry.length > 0
  21592. });
  21593. if (rel.center)
  21594. centerGeometry(rel);
  21595. if (has_full_geometry)
  21596. fullGeometryRelation(rel);
  21597. else if (rel.bounds)
  21598. boundsGeometry(rel);
  21599. break;
  21600. default:
  21601. // type=area (from coord-query) is an example for this case.
  21602. }
  21603. }
  21604. return _convert2geoJSON(nodes,ways,rels);
  21605. }
  21606. function _osmXML2geoJSON(xml) {
  21607. // sort elements
  21608. var nodes = new Array();
  21609. var ways = new Array();
  21610. var rels = new Array();
  21611. // helper function
  21612. function copy_attribute( x, o, attr ) {
  21613. if (x.hasAttribute(attr))
  21614. o[attr] = x.getAttribute(attr);
  21615. }
  21616. function centerGeometry(object, centroid) {
  21617. var pseudoNode = _.clone(object);
  21618. copy_attribute(centroid, pseudoNode, 'lat');
  21619. copy_attribute(centroid, pseudoNode, 'lon');
  21620. pseudoNode.__is_center_placeholder = true;
  21621. nodes.push(pseudoNode);
  21622. }
  21623. function boundsGeometry(object, bounds) {
  21624. var pseudoWay = _.clone(object);
  21625. pseudoWay.nodes = [];
  21626. function addPseudoNode(lat,lon,i) {
  21627. var pseudoNode = {
  21628. type:"node",
  21629. id: "_"+pseudoWay.type+"/"+pseudoWay.id+"bounds"+i,
  21630. lat: lat,
  21631. lon: lon
  21632. }
  21633. pseudoWay.nodes.push(pseudoNode.id);
  21634. nodes.push(pseudoNode);
  21635. }
  21636. addPseudoNode(bounds.getAttribute('minlat'),bounds.getAttribute('minlon'),1);
  21637. addPseudoNode(bounds.getAttribute('maxlat'),bounds.getAttribute('minlon'),2);
  21638. addPseudoNode(bounds.getAttribute('maxlat'),bounds.getAttribute('maxlon'),3);
  21639. addPseudoNode(bounds.getAttribute('minlat'),bounds.getAttribute('maxlon'),4);
  21640. pseudoWay.nodes.push(pseudoWay.nodes[0]);
  21641. pseudoWay.__is_bounds_placeholder = true;
  21642. ways.push(pseudoWay);
  21643. }
  21644. function fullGeometryWay(way, nds) {
  21645. function addFullGeometryNode(lat,lon,id) {
  21646. var geometryNode = {
  21647. type:"node",
  21648. id: id,
  21649. lat: lat,
  21650. lon: lon
  21651. }
  21652. nodes.push(geometryNode);
  21653. return geometryNode.id;
  21654. }
  21655. if (!_.isArray(way.nodes)) {
  21656. way.nodes = [];
  21657. _.each( nds, function( nd, i ) {
  21658. way.nodes.push("_anonymous@"+nd.getAttribute('lat')+"/"+nd.getAttribute('lon'));
  21659. });
  21660. }
  21661. _.each( nds, function( nd, i ) {
  21662. if (nd.getAttribute('lat')) {
  21663. addFullGeometryNode(
  21664. nd.getAttribute('lat'),
  21665. nd.getAttribute('lon'),
  21666. way.nodes[i]
  21667. );
  21668. }
  21669. });
  21670. }
  21671. function fullGeometryRelation(rel, members) {
  21672. function addFullGeometryNode(lat,lon,id) {
  21673. var geometryNode = {
  21674. type:"node",
  21675. id: id,
  21676. lat: lat,
  21677. lon: lon
  21678. }
  21679. nodes.push(geometryNode);
  21680. }
  21681. function addFullGeometryWay(nds,id) {
  21682. // shared multipolygon ways cannot be defined multiple times with the same id.
  21683. if (ways.some(function (way) { // todo: this is slow :(
  21684. return way.type == "way" && way.id == id;
  21685. })) return;
  21686. var geometryWay = {
  21687. type: "way",
  21688. id: id,
  21689. nodes:[]
  21690. }
  21691. function addFullGeometryWayPseudoNode(lat,lon) {
  21692. // todo? do not save the same pseudo node multiple times
  21693. var geometryPseudoNode = {
  21694. type:"node",
  21695. id: "_anonymous@"+lat+"/"+lon,
  21696. lat: lat,
  21697. lon: lon
  21698. }
  21699. geometryWay.nodes.push(geometryPseudoNode.id);
  21700. nodes.push(geometryPseudoNode);
  21701. }
  21702. _.each(nds, function(nd) {
  21703. if (nd.getAttribute('lat')) {
  21704. addFullGeometryWayPseudoNode(
  21705. nd.getAttribute('lat'),
  21706. nd.getAttribute('lon')
  21707. );
  21708. } else {
  21709. geometryWay.nodes.push(undefined);
  21710. }
  21711. });
  21712. ways.push(geometryWay);
  21713. }
  21714. _.each( members, function( member, i ) {
  21715. if (rel.members[i].type == "node") {
  21716. if (member.getAttribute('lat')) {
  21717. addFullGeometryNode(
  21718. member.getAttribute('lat'),
  21719. member.getAttribute('lon'),
  21720. rel.members[i].ref
  21721. );
  21722. }
  21723. } else if (rel.members[i].type == "way") {
  21724. if (member.getElementsByTagName('nd').length > 0) {
  21725. rel.members[i].ref = "_fullGeom"+rel.members[i].ref;
  21726. addFullGeometryWay(
  21727. member.getElementsByTagName('nd'),
  21728. rel.members[i].ref
  21729. );
  21730. }
  21731. }
  21732. });
  21733. }
  21734. // nodes
  21735. _.each( xml.getElementsByTagName('node'), function( node, i ) {
  21736. var tags = {};
  21737. _.each( node.getElementsByTagName('tag'), function( tag ) {
  21738. tags[tag.getAttribute('k')] = tag.getAttribute('v');
  21739. });
  21740. var nodeObject = {
  21741. 'type': 'node'
  21742. };
  21743. copy_attribute( node, nodeObject, 'id' );
  21744. copy_attribute( node, nodeObject, 'lat' );
  21745. copy_attribute( node, nodeObject, 'lon' );
  21746. copy_attribute( node, nodeObject, 'version' );
  21747. copy_attribute( node, nodeObject, 'timestamp' );
  21748. copy_attribute( node, nodeObject, 'changeset' );
  21749. copy_attribute( node, nodeObject, 'uid' );
  21750. copy_attribute( node, nodeObject, 'user' );
  21751. if (!_.isEmpty(tags))
  21752. nodeObject.tags = tags;
  21753. nodes.push(nodeObject);
  21754. });
  21755. // ways
  21756. var centroid,bounds;
  21757. _.each( xml.getElementsByTagName('way'), function( way, i ) {
  21758. var tags = {};
  21759. var wnodes = [];
  21760. _.each( way.getElementsByTagName('tag'), function( tag ) {
  21761. tags[tag.getAttribute('k')] = tag.getAttribute('v');
  21762. });
  21763. var has_full_geometry = false;
  21764. _.each( way.getElementsByTagName('nd'), function( nd, i ) {
  21765. var id;
  21766. if (id = nd.getAttribute('ref'))
  21767. wnodes[i] = id;
  21768. if (!has_full_geometry && nd.getAttribute('lat'))
  21769. has_full_geometry = true;
  21770. });
  21771. var wayObject = {
  21772. "type": "way"
  21773. };
  21774. copy_attribute( way, wayObject, 'id' );
  21775. copy_attribute( way, wayObject, 'version' );
  21776. copy_attribute( way, wayObject, 'timestamp' );
  21777. copy_attribute( way, wayObject, 'changeset' );
  21778. copy_attribute( way, wayObject, 'uid' );
  21779. copy_attribute( way, wayObject, 'user' );
  21780. if (wnodes.length > 0)
  21781. wayObject.nodes = wnodes;
  21782. if (!_.isEmpty(tags))
  21783. wayObject.tags = tags;
  21784. if (centroid = way.getElementsByTagName('center')[0])
  21785. centerGeometry(wayObject,centroid);
  21786. if (has_full_geometry)
  21787. fullGeometryWay(wayObject, way.getElementsByTagName('nd'));
  21788. else if (bounds = way.getElementsByTagName('bounds')[0])
  21789. boundsGeometry(wayObject,bounds);
  21790. ways.push(wayObject);
  21791. });
  21792. // relations
  21793. _.each( xml.getElementsByTagName('relation'), function( relation, i ) {
  21794. var tags = {};
  21795. var members = [];
  21796. _.each( relation.getElementsByTagName('tag'), function( tag ) {
  21797. tags[tag.getAttribute('k')] = tag.getAttribute('v');
  21798. });
  21799. var has_full_geometry = false;
  21800. _.each( relation.getElementsByTagName('member'), function( member, i ) {
  21801. members[i] = {};
  21802. copy_attribute( member, members[i], 'ref' );
  21803. copy_attribute( member, members[i], 'role' );
  21804. copy_attribute( member, members[i], 'type' );
  21805. if (!has_full_geometry &&
  21806. (members[i].type == 'node' && member.getAttribute('lat')) ||
  21807. (members[i].type == 'way' && member.getElementsByTagName('nd').length>0) )
  21808. has_full_geometry = true;
  21809. });
  21810. var relObject = {
  21811. "type": "relation"
  21812. }
  21813. copy_attribute( relation, relObject, 'id' );
  21814. copy_attribute( relation, relObject, 'version' );
  21815. copy_attribute( relation, relObject, 'timestamp' );
  21816. copy_attribute( relation, relObject, 'changeset' );
  21817. copy_attribute( relation, relObject, 'uid' );
  21818. copy_attribute( relation, relObject, 'user' );
  21819. if (members.length > 0)
  21820. relObject.members = members;
  21821. if (!_.isEmpty(tags))
  21822. relObject.tags = tags;
  21823. if (centroid = relation.getElementsByTagName('center')[0])
  21824. centerGeometry(relObject,centroid);
  21825. if (has_full_geometry)
  21826. fullGeometryRelation(relObject, relation.getElementsByTagName('member'));
  21827. else if (bounds = relation.getElementsByTagName('bounds')[0])
  21828. boundsGeometry(relObject,bounds);
  21829. rels.push(relObject);
  21830. });
  21831. return _convert2geoJSON(nodes,ways,rels);
  21832. }
  21833. function _convert2geoJSON(nodes,ways,rels) {
  21834. // helper function that checks if there are any tags other than "created_by", "source", etc. or any tag provided in ignore_tags
  21835. function has_interesting_tags(t, ignore_tags) {
  21836. if (typeof ignore_tags !== "object")
  21837. ignore_tags={};
  21838. if (typeof options.uninterestingTags === "function")
  21839. return !options.uninterestingTags(t, ignore_tags);
  21840. for (var k in t)
  21841. if (!(options.uninterestingTags[k]===true) &&
  21842. !(ignore_tags[k]===true || ignore_tags[k]===t[k]))
  21843. return true;
  21844. return false;
  21845. };
  21846. // helper function to extract meta information
  21847. function build_meta_information(object) {
  21848. var res = {
  21849. "timestamp": object.timestamp,
  21850. "version": object.version,
  21851. "changeset": object.changeset,
  21852. "user": object.user,
  21853. "uid": object.uid
  21854. };
  21855. for (var k in res)
  21856. if (res[k] === undefined)
  21857. delete res[k];
  21858. return res;
  21859. }
  21860. // some data processing (e.g. filter nodes only used for ways)
  21861. var nodeids = new Object();
  21862. var poinids = new Object();
  21863. for (var i=0;i<nodes.length;i++) {
  21864. var node = nodes[i];
  21865. if (nodeids[node.id] !== undefined) {
  21866. // handle input data duplication
  21867. node = options.deduplicator(node, nodeids[node.id]);
  21868. }
  21869. nodeids[node.id] = node;
  21870. if (typeof node.tags != 'undefined' &&
  21871. has_interesting_tags(node.tags)) // this checks if the node has any tags other than "created_by"
  21872. poinids[node.id] = true;
  21873. }
  21874. // todo -> after deduplication of relations??
  21875. for (var i=0;i<rels.length;i++) {
  21876. if (_.isArray(rels[i].members)) {
  21877. for (var j=0;j<rels[i].members.length;j++) {
  21878. if (rels[i].members[j].type == "node")
  21879. poinids[rels[i].members[j].ref] = true;
  21880. }
  21881. }
  21882. }
  21883. var wayids = new Object();
  21884. var waynids = new Object();
  21885. for (var i=0;i<ways.length;i++) {
  21886. var way = ways[i];
  21887. if (wayids[way.id]) {
  21888. // handle input data duplication
  21889. way = options.deduplicator(way, wayids[way.id]);
  21890. }
  21891. wayids[way.id] = way;
  21892. if (_.isArray(way.nodes)) {
  21893. for (var j=0;j<way.nodes.length;j++) {
  21894. if (typeof way.nodes[j] === "object") continue; // ignore already replaced way node objects
  21895. waynids[way.nodes[j]] = true;
  21896. way.nodes[j] = nodeids[way.nodes[j]];
  21897. }
  21898. }
  21899. }
  21900. var pois = new Array();
  21901. for (var id in nodeids) {
  21902. var node = nodeids[id];
  21903. if (!waynids[id] || poinids[id])
  21904. pois.push(node);
  21905. }
  21906. var relids = new Array();
  21907. for (var i=0;i<rels.length;i++) {
  21908. var rel = rels[i];
  21909. if (relids[rel.id]) {
  21910. // handle input data duplication
  21911. rel = options.deduplicator(rel, relids[rel.id]);
  21912. }
  21913. relids[rel.id] = rel;
  21914. }
  21915. var relsmap = {node: {}, way: {}, relation: {}};
  21916. for (var id in relids) {
  21917. var rel = relids[id];
  21918. if (!_.isArray(rel.members)) {
  21919. if (options.verbose) console.warn('Relation',rel.type+'/'+rel.id,'ignored because it has no members');
  21920. continue; // ignore relations without members (e.g. returned by an ids_only query)
  21921. }
  21922. for (var j=0;j<rel.members.length;j++) {
  21923. var m_type = rel.members[j].type;
  21924. var m_ref = rel.members[j].ref;
  21925. if (typeof m_ref !== "number") {
  21926. // de-namespace full geometry content
  21927. m_ref = m_ref.replace("_fullGeom", "");
  21928. }
  21929. if (!relsmap[m_type]) {
  21930. if (options.verbose) console.warn('Relation',rel.type+'/'+rel.id,'member',m_type+'/'+m_ref,'ignored because it has an invalid type');
  21931. continue;
  21932. }
  21933. if (typeof relsmap[m_type][m_ref] === "undefined")
  21934. relsmap[m_type][m_ref] = [];
  21935. relsmap[m_type][m_ref].push({
  21936. "role" : rel.members[j].role,
  21937. "rel" : rel.id,
  21938. "reltags" : rel.tags,
  21939. });
  21940. }
  21941. }
  21942. // construct geojson
  21943. var geojson;
  21944. var geojsonnodes = [];
  21945. for (i=0;i<pois.length;i++) {
  21946. if (typeof pois[i].lon == "undefined" || typeof pois[i].lat == "undefined") {
  21947. if (options.verbose) console.warn('POI',pois[i].type+'/'+pois[i].id,'ignored because it lacks coordinates');
  21948. continue; // lon and lat are required for showing a point
  21949. }
  21950. var feature = {
  21951. "type" : "Feature",
  21952. "id" : pois[i].type+"/"+pois[i].id,
  21953. "properties" : {
  21954. "type" : pois[i].type,
  21955. "id" : pois[i].id,
  21956. "tags" : pois[i].tags || {},
  21957. "relations" : relsmap["node"][pois[i].id] || [],
  21958. "meta": build_meta_information(pois[i])
  21959. },
  21960. "geometry" : {
  21961. "type" : "Point",
  21962. "coordinates" : [+pois[i].lon, +pois[i].lat],
  21963. }
  21964. };
  21965. if (pois[i].__is_center_placeholder)
  21966. feature.properties["geometry"] = "center";
  21967. if (!featureCallback)
  21968. geojsonnodes.push(feature);
  21969. else
  21970. featureCallback(feature);
  21971. }
  21972. var geojsonlines = [];
  21973. var geojsonpolygons = [];
  21974. // process multipolygons
  21975. for (var i=0;i<rels.length;i++) {
  21976. // todo: refactor such that this loops over relids instead of rels?
  21977. if (relids[rels[i].id] !== rels[i]) {
  21978. // skip relation because it's a deduplication artifact
  21979. continue;
  21980. }
  21981. if ((typeof rels[i].tags != "undefined") &&
  21982. (rels[i].tags["type"] == "route" || rels[i].tags["type"] == "waterway")) {
  21983. if (!_.isArray(rels[i].members)) {
  21984. if (options.verbose) console.warn('Route',rels[i].type+'/'+rels[i].id,'ignored because it has no members');
  21985. continue; // ignore relations without members (e.g. returned by an ids_only query)
  21986. }
  21987. rels[i].members.forEach(function(m) {
  21988. if (wayids[m.ref] && !has_interesting_tags(wayids[m.ref].tags))
  21989. wayids[m.ref].is_skippablerelationmember = true;
  21990. });
  21991. feature = construct_multilinestring(rels[i]);
  21992. if (feature === false) {
  21993. if (options.verbose) console.warn('Route relation',rels[i].type+'/'+rels[i].id,'ignored because it has invalid geometry');
  21994. continue; // abort if feature could not be constructed
  21995. }
  21996. if (!featureCallback)
  21997. geojsonpolygons.push(feature);
  21998. else
  21999. featureCallback(rewind(feature));
  22000. function construct_multilinestring(rel) {
  22001. var is_tainted = false;
  22002. // prepare route members
  22003. var members;
  22004. members = rel.members.filter(function(m) {return m.type === "way";});
  22005. members = members.map(function(m) {
  22006. var way = wayids[m.ref];
  22007. if (way === undefined || way.nodes === undefined) { // check for missing ways
  22008. if (options.verbose) console.warn('Route '+rel.type+'/'+rel.id, 'tainted by a missing or incomplete way', m.type+'/'+m.ref);
  22009. is_tainted = true;
  22010. return;
  22011. }
  22012. return { // TODO: this is slow! :(
  22013. id: m.ref,
  22014. role: m.role,
  22015. way: way,
  22016. nodes: way.nodes.filter(function(n) {
  22017. if (n !== undefined)
  22018. return true;
  22019. is_tainted = true;
  22020. if (options.verbose) console.warn('Route', rel.type+'/'+rel.id, 'tainted by a way', m.type+'/'+m.ref, 'with a missing node');
  22021. return false;
  22022. })
  22023. };
  22024. });
  22025. members = _.compact(members);
  22026. // construct connected linestrings
  22027. var linestrings;
  22028. linestrings = join(members);
  22029. // sanitize mp-coordinates (remove empty clusters or rings, {lat,lon,...} to [lon,lat]
  22030. var coords = [];
  22031. coords = _.compact(linestrings.map(function(linestring) {
  22032. return _.compact(linestring.map(function(node) {
  22033. return [+node.lon,+node.lat];
  22034. }));
  22035. }));
  22036. if (coords.length == 0) {
  22037. if (options.verbose) console.warn('Route', rel.type+'/'+rel.id, 'contains no coordinates');
  22038. return false; // ignore routes without coordinates
  22039. }
  22040. // mp parsed, now construct the geoJSON
  22041. var feature = {
  22042. "type" : "Feature",
  22043. "id" : rel.type+"/"+rel.id,
  22044. "properties" : {
  22045. "type" : rel.type,
  22046. "id" : rel.id,
  22047. "tags" : rel.tags || {},
  22048. "relations" : relsmap[rel.type][rel.id] || [],
  22049. "meta": build_meta_information(rel)
  22050. },
  22051. "geometry" : {
  22052. "type" : coords.length === 1 ? "LineString" : "MultiLineString",
  22053. "coordinates" : coords.length === 1 ? coords[0] : coords,
  22054. }
  22055. }
  22056. if (is_tainted) {
  22057. if (options.verbose) console.warn('Route', rel.type+'/'+rel.id, 'is tainted');
  22058. feature.properties["tainted"] = true;
  22059. }
  22060. return feature;
  22061. }
  22062. } // end construct multilinestring for route relations
  22063. if ((typeof rels[i].tags != "undefined") &&
  22064. (rels[i].tags["type"] == "multipolygon" || rels[i].tags["type"] == "boundary")) {
  22065. if (!_.isArray(rels[i].members)) {
  22066. if (options.verbose) console.warn('Multipolygon',rels[i].type+'/'+rels[i].id,'ignored because it has no members');
  22067. continue; // ignore relations without members (e.g. returned by an ids_only query)
  22068. }
  22069. var outer_count = 0;
  22070. for (var j=0;j<rels[i].members.length;j++)
  22071. if (rels[i].members[j].role == "outer")
  22072. outer_count++;
  22073. else if (options.verbose && rels[i].members[j].role != "inner")
  22074. console.warn('Multipolygon',rels[i].type+'/'+rels[i].id,'member',rels[i].members[j].type+'/'+rels[i].members[j].ref,'ignored because it has an invalid role: "' + rels[i].members[j].role + '"');
  22075. rels[i].members.forEach(function(m) {
  22076. if (wayids[m.ref]) {
  22077. // this even works in the following corner case:
  22078. // a multipolygon amenity=xxx with outer line tagged amenity=yyy
  22079. // see https://github.com/tyrasd/osmtogeojson/issues/7
  22080. if (m.role==="outer" && !has_interesting_tags(wayids[m.ref].tags,rels[i].tags))
  22081. wayids[m.ref].is_skippablerelationmember = true;
  22082. if (m.role==="inner" && !has_interesting_tags(wayids[m.ref].tags))
  22083. wayids[m.ref].is_skippablerelationmember = true;
  22084. }
  22085. });
  22086. if (outer_count == 0) {
  22087. if (options.verbose) console.warn('Multipolygon relation',rels[i].type+'/'+rels[i].id,'ignored because it has no outer ways');
  22088. continue; // ignore multipolygons without outer ways
  22089. }
  22090. var simple_mp = false;
  22091. if (outer_count == 1 && !has_interesting_tags(rels[i].tags, {"type":true}))
  22092. simple_mp = true;
  22093. var feature = null;
  22094. if (!simple_mp) {
  22095. feature = construct_multipolygon(rels[i], rels[i]);
  22096. } else {
  22097. // simple multipolygon
  22098. var outer_way = rels[i].members.filter(function(m) {return m.role === "outer";})[0];
  22099. outer_way = wayids[outer_way.ref];
  22100. if (outer_way === undefined) {
  22101. if (options.verbose) console.warn('Multipolygon relation',rels[i].type+'/'+rels[i].id,'ignored because outer way', outer_way.type+'/'+outer_way.ref,'is missing');
  22102. continue; // abort if outer way object is not present
  22103. }
  22104. outer_way.is_skippablerelationmember = true;
  22105. feature = construct_multipolygon(outer_way, rels[i]);
  22106. }
  22107. if (feature === false) {
  22108. if (options.verbose) console.warn('Multipolygon relation',rels[i].type+'/'+rels[i].id,'ignored because it has invalid geometry');
  22109. continue; // abort if feature could not be constructed
  22110. }
  22111. if (!featureCallback)
  22112. geojsonpolygons.push(feature);
  22113. else
  22114. featureCallback(rewind(feature));
  22115. function construct_multipolygon(tag_object, rel) {
  22116. var is_tainted = false;
  22117. var mp_geometry = simple_mp ? 'way' : 'relation',
  22118. mp_id = typeof tag_object.id === "number" ? tag_object.id : +(tag_object.id.replace("_fullGeom", ""));
  22119. // prepare mp members
  22120. var members;
  22121. members = rel.members.filter(function(m) {return m.type === "way";});
  22122. members = members.map(function(m) {
  22123. var way = wayids[m.ref];
  22124. if (way === undefined || way.nodes === undefined) { // check for missing ways
  22125. if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'tainted by a missing or incomplete way', m.type+'/'+m.ref);
  22126. is_tainted = true;
  22127. return;
  22128. }
  22129. return { // TODO: this is slow! :(
  22130. id: m.ref,
  22131. role: m.role || "outer",
  22132. way: way,
  22133. nodes: way.nodes.filter(function(n) {
  22134. if (n !== undefined)
  22135. return true;
  22136. is_tainted = true;
  22137. if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'tainted by a way', m.type+'/'+m.ref, 'with a missing node');
  22138. return false;
  22139. })
  22140. };
  22141. });
  22142. members = _.compact(members);
  22143. // construct outer and inner rings
  22144. var outers, inners;
  22145. outers = join(members.filter(function(m) {return m.role==="outer";}));
  22146. inners = join(members.filter(function(m) {return m.role==="inner";}));
  22147. // sort rings
  22148. var mp;
  22149. function findOuter(inner) {
  22150. var polygonIntersectsPolygon = function(outer, inner) {
  22151. for (var i=0; i<inner.length; i++)
  22152. if (pointInPolygon(inner[i], outer))
  22153. return true;
  22154. return false;
  22155. }
  22156. var mapCoordinates = function(from) {
  22157. return from.map(function(n) {
  22158. return [+n.lat,+n.lon];
  22159. });
  22160. }
  22161. // stolen from iD/geo.js,
  22162. // based on https://github.com/substack/point-in-polygon,
  22163. // ray-casting algorithm based on http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  22164. var pointInPolygon = function(point, polygon) {
  22165. var x = point[0], y = point[1], inside = false;
  22166. for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
  22167. var xi = polygon[i][0], yi = polygon[i][1];
  22168. var xj = polygon[j][0], yj = polygon[j][1];
  22169. var intersect = ((yi > y) != (yj > y)) &&
  22170. (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
  22171. if (intersect) inside = !inside;
  22172. }
  22173. return inside;
  22174. };
  22175. // stolen from iD/relation.js
  22176. var o, outer;
  22177. // todo: all this coordinate mapping makes this unneccesarily slow.
  22178. // see the "todo: this is slow! :(" above.
  22179. inner = mapCoordinates(inner);
  22180. /*for (o = 0; o < outers.length; o++) {
  22181. outer = mapCoordinates(outers[o]);
  22182. if (polygonContainsPolygon(outer, inner))
  22183. return o;
  22184. }*/
  22185. for (o = 0; o < outers.length; o++) {
  22186. outer = mapCoordinates(outers[o]);
  22187. if (polygonIntersectsPolygon(outer, inner))
  22188. return o;
  22189. }
  22190. }
  22191. mp = outers.map(function(o) {return [o];});
  22192. for (var j=0; j<inners.length; j++) {
  22193. var o = findOuter(inners[j]);
  22194. if (o !== undefined)
  22195. mp[o].push(inners[j]);
  22196. else
  22197. if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'contains an inner ring with no containing outer');
  22198. // so, no outer ring for this inner ring is found.
  22199. // We're going to ignore holes in empty space.
  22200. ;
  22201. }
  22202. // sanitize mp-coordinates (remove empty clusters or rings, {lat,lon,...} to [lon,lat]
  22203. var mp_coords = [];
  22204. mp_coords = _.compact(mp.map(function(cluster) {
  22205. var cl = _.compact(cluster.map(function(ring) {
  22206. if (ring.length < 4) { // todo: is this correct: ring.length < 4 ?
  22207. if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'contains a ring with less than four nodes');
  22208. return;
  22209. }
  22210. return _.compact(ring.map(function(node) {
  22211. return [+node.lon,+node.lat];
  22212. }));
  22213. }));
  22214. if (cl.length == 0) {
  22215. if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'contains an empty ring cluster');
  22216. return;
  22217. }
  22218. return cl;
  22219. }));
  22220. if (mp_coords.length == 0) {
  22221. if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'contains no coordinates');
  22222. return false; // ignore multipolygons without coordinates
  22223. }
  22224. var mp_type = "MultiPolygon";
  22225. if (mp_coords.length === 1) {
  22226. mp_type = "Polygon";
  22227. mp_coords = mp_coords[0];
  22228. }
  22229. // mp parsed, now construct the geoJSON
  22230. var feature = {
  22231. "type" : "Feature",
  22232. "id" : tag_object.type+"/"+mp_id,
  22233. "properties" : {
  22234. "type" : tag_object.type,
  22235. "id" : mp_id,
  22236. "tags" : tag_object.tags || {},
  22237. "relations" : relsmap[tag_object.type][tag_object.id] || [],
  22238. "meta": build_meta_information(tag_object)
  22239. },
  22240. "geometry" : {
  22241. "type" : mp_type,
  22242. "coordinates" : mp_coords,
  22243. }
  22244. }
  22245. if (is_tainted) {
  22246. if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'is tainted');
  22247. feature.properties["tainted"] = true;
  22248. }
  22249. return feature;
  22250. }
  22251. }
  22252. }
  22253. // process lines and polygons
  22254. for (var i=0;i<ways.length;i++) {
  22255. // todo: refactor such that this loops over wayids instead of ways?
  22256. if (wayids[ways[i].id] !== ways[i]) {
  22257. // skip way because it's a deduplication artifact
  22258. continue;
  22259. }
  22260. if (!_.isArray(ways[i].nodes)) {
  22261. if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'ignored because it has no nodes');
  22262. continue; // ignore ways without nodes (e.g. returned by an ids_only query)
  22263. }
  22264. if (ways[i].is_skippablerelationmember)
  22265. continue; // ignore ways which are already rendered as (part of) a multipolygon
  22266. if (typeof ways[i].id !== "number") {
  22267. // remove full geometry namespace for output
  22268. ways[i].id = +ways[i].id.replace("_fullGeom", "");
  22269. }
  22270. ways[i].tainted = false;
  22271. ways[i].hidden = false;
  22272. var coords = new Array();
  22273. for (j=0;j<ways[i].nodes.length;j++) {
  22274. if (typeof ways[i].nodes[j] == "object")
  22275. coords.push([+ways[i].nodes[j].lon, +ways[i].nodes[j].lat]);
  22276. else {
  22277. if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'is tainted by an invalid node');
  22278. ways[i].tainted = true;
  22279. }
  22280. }
  22281. if (coords.length <= 1) { // invalid way geometry
  22282. if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'ignored because it contains too few nodes');
  22283. continue;
  22284. }
  22285. var way_type = "LineString"; // default
  22286. if (typeof ways[i].nodes[0] != "undefined" && typeof ways[i].nodes[ways[i].nodes.length-1] != "undefined" && // way has its start/end nodes loaded
  22287. ways[i].nodes[0].id === ways[i].nodes[ways[i].nodes.length-1].id && // ... and forms a closed ring
  22288. (
  22289. typeof ways[i].tags != "undefined" && // ... and has tags
  22290. _isPolygonFeature(ways[i].tags) // ... and tags say it is a polygon
  22291. || // or is a placeholder for a bounds geometry
  22292. ways[i].__is_bounds_placeholder
  22293. )
  22294. ) {
  22295. way_type = "Polygon";
  22296. coords = [coords];
  22297. }
  22298. var feature = {
  22299. "type" : "Feature",
  22300. "id" : ways[i].type+"/"+ways[i].id,
  22301. "properties" : {
  22302. "type" : ways[i].type,
  22303. "id" : ways[i].id,
  22304. "tags" : ways[i].tags || {},
  22305. "relations" : relsmap["way"][ways[i].id] || [],
  22306. "meta": build_meta_information(ways[i])
  22307. },
  22308. "geometry" : {
  22309. "type" : way_type,
  22310. "coordinates" : coords,
  22311. }
  22312. }
  22313. if (ways[i].tainted) {
  22314. if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'is tainted');
  22315. feature.properties["tainted"] = true;
  22316. }
  22317. if (ways[i].__is_bounds_placeholder)
  22318. feature.properties["geometry"] = "bounds";
  22319. if (!featureCallback) {
  22320. if (way_type == "LineString")
  22321. geojsonlines.push(feature);
  22322. else
  22323. geojsonpolygons.push(feature);
  22324. } else {
  22325. featureCallback(rewind(feature));
  22326. }
  22327. }
  22328. if (featureCallback)
  22329. return true;
  22330. geojson = {
  22331. "type": "FeatureCollection",
  22332. "features": []
  22333. };
  22334. geojson.features = geojson.features.concat(geojsonpolygons);
  22335. geojson.features = geojson.features.concat(geojsonlines);
  22336. geojson.features = geojson.features.concat(geojsonnodes);
  22337. // optionally, flatten properties
  22338. if (options.flatProperties) {
  22339. geojson.features.forEach(function(f) {
  22340. f.properties = _.merge(
  22341. f.properties.meta,
  22342. f.properties.tags,
  22343. {id: f.properties.type+"/"+f.properties.id}
  22344. );
  22345. });
  22346. }
  22347. // fix polygon winding
  22348. geojson = rewind(geojson);
  22349. return geojson;
  22350. }
  22351. function _isPolygonFeature( tags ) {
  22352. var polygonFeatures = options.polygonFeatures;
  22353. if (typeof polygonFeatures === "function")
  22354. return polygonFeatures(tags);
  22355. // explicitely tagged non-areas
  22356. if ( tags['area'] === 'no' )
  22357. return false;
  22358. // assuming that a typical OSM way has in average less tags than
  22359. // the polygonFeatures list, this way around should be faster
  22360. for ( var key in tags ) {
  22361. var val = tags[key];
  22362. var pfk = polygonFeatures[key];
  22363. // continue with next if tag is unknown or not "categorizing"
  22364. if ( typeof pfk === 'undefined' )
  22365. continue;
  22366. // continue with next if tag is explicitely un-set ("building=no")
  22367. if ( val === 'no' )
  22368. continue;
  22369. // check polygon features for: general acceptance, included or excluded values
  22370. if ( pfk === true )
  22371. return true;
  22372. if ( pfk.included_values && pfk.included_values[val] === true )
  22373. return true;
  22374. if ( pfk.excluded_values && pfk.excluded_values[val] !== true )
  22375. return true;
  22376. }
  22377. // if no tags matched, this ain't no area.
  22378. return false;
  22379. }
  22380. };
  22381. // helper that joins adjacent osm ways into linestrings or linear rings
  22382. function join(ways) {
  22383. var _first = function(arr) {return arr[0]};
  22384. var _last = function(arr) {return arr[arr.length-1]};
  22385. var _fitTogether = function(n1, n2) {
  22386. return n1 !== undefined && n2 !== undefined && n1.id === n2.id;
  22387. }
  22388. // stolen from iD/relation.js
  22389. var joined = [], current, first, last, i, how, what;
  22390. while (ways.length) {
  22391. current = ways.pop().nodes.slice();
  22392. joined.push(current);
  22393. while (ways.length && !_fitTogether(_first(current), _last(current))) {
  22394. first = _first(current);
  22395. last = _last(current);
  22396. for (i = 0; i < ways.length; i++) {
  22397. what = ways[i].nodes;
  22398. if (_fitTogether(last, _first(what))) {
  22399. how = current.push;
  22400. what = what.slice(1);
  22401. break;
  22402. } else if (_fitTogether(last, _last(what))) {
  22403. how = current.push;
  22404. what = what.slice(0, -1).reverse();
  22405. break;
  22406. } else if (_fitTogether(first, _last(what))) {
  22407. how = current.unshift;
  22408. what = what.slice(0, -1);
  22409. break;
  22410. } else if (_fitTogether(first, _first(what))) {
  22411. how = current.unshift;
  22412. what = what.slice(1).reverse();
  22413. break;
  22414. } else {
  22415. what = how = null;
  22416. }
  22417. }
  22418. if (!what)
  22419. break; // Invalid geometry (dangling way, unclosed ring)
  22420. ways.splice(i, 1);
  22421. how.apply(current, what);
  22422. }
  22423. }
  22424. return joined;
  22425. }
  22426. // for backwards compatibility
  22427. osmtogeojson.toGeojson = osmtogeojson;
  22428. module.exports = osmtogeojson;
  22429. },{"./lodash.custom.js":178,"geojson-rewind":45,"osm-polygon-features":175}],178:[function(require,module,exports){
  22430. (function (global){
  22431. /**
  22432. * @license
  22433. * lodash (Custom Build) <https://lodash.com/>
  22434. * Build: `lodash exports="node" include="clone,merge,isEmpty,isArray,compact,each" -d`
  22435. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  22436. * Released under MIT license <https://lodash.com/license>
  22437. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  22438. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  22439. */
  22440. ;(function() {
  22441. /** Used as a safe reference for `undefined` in pre-ES5 environments. */
  22442. var undefined;
  22443. /** Used as the semantic version number. */
  22444. var VERSION = '4.15.0';
  22445. /** Used as the size to enable large array optimizations. */
  22446. var LARGE_ARRAY_SIZE = 200;
  22447. /** Used as the `TypeError` message for "Functions" methods. */
  22448. var FUNC_ERROR_TEXT = 'Expected a function';
  22449. /** Used to stand-in for `undefined` hash values. */
  22450. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  22451. /** Used to compose bitmasks for comparison styles. */
  22452. var UNORDERED_COMPARE_FLAG = 1,
  22453. PARTIAL_COMPARE_FLAG = 2;
  22454. /** Used as references for various `Number` constants. */
  22455. var INFINITY = 1 / 0,
  22456. MAX_SAFE_INTEGER = 9007199254740991;
  22457. /** `Object#toString` result references. */
  22458. var argsTag = '[object Arguments]',
  22459. arrayTag = '[object Array]',
  22460. boolTag = '[object Boolean]',
  22461. dateTag = '[object Date]',
  22462. errorTag = '[object Error]',
  22463. funcTag = '[object Function]',
  22464. genTag = '[object GeneratorFunction]',
  22465. mapTag = '[object Map]',
  22466. numberTag = '[object Number]',
  22467. objectTag = '[object Object]',
  22468. promiseTag = '[object Promise]',
  22469. regexpTag = '[object RegExp]',
  22470. setTag = '[object Set]',
  22471. stringTag = '[object String]',
  22472. symbolTag = '[object Symbol]',
  22473. weakMapTag = '[object WeakMap]';
  22474. var arrayBufferTag = '[object ArrayBuffer]',
  22475. dataViewTag = '[object DataView]',
  22476. float32Tag = '[object Float32Array]',
  22477. float64Tag = '[object Float64Array]',
  22478. int8Tag = '[object Int8Array]',
  22479. int16Tag = '[object Int16Array]',
  22480. int32Tag = '[object Int32Array]',
  22481. uint8Tag = '[object Uint8Array]',
  22482. uint8ClampedTag = '[object Uint8ClampedArray]',
  22483. uint16Tag = '[object Uint16Array]',
  22484. uint32Tag = '[object Uint32Array]';
  22485. /** Used to match property names within property paths. */
  22486. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  22487. reIsPlainProp = /^\w*$/,
  22488. reLeadingDot = /^\./,
  22489. rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  22490. /**
  22491. * Used to match `RegExp`
  22492. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  22493. */
  22494. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  22495. /** Used to match backslashes in property paths. */
  22496. var reEscapeChar = /\\(\\)?/g;
  22497. /** Used to match `RegExp` flags from their coerced string values. */
  22498. var reFlags = /\w*$/;
  22499. /** Used to detect host constructors (Safari). */
  22500. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  22501. /** Used to detect unsigned integer values. */
  22502. var reIsUint = /^(?:0|[1-9]\d*)$/;
  22503. /** Used to identify `toStringTag` values of typed arrays. */
  22504. var typedArrayTags = {};
  22505. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  22506. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  22507. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  22508. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  22509. typedArrayTags[uint32Tag] = true;
  22510. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  22511. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  22512. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  22513. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  22514. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  22515. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  22516. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  22517. typedArrayTags[weakMapTag] = false;
  22518. /** Used to identify `toStringTag` values supported by `_.clone`. */
  22519. var cloneableTags = {};
  22520. cloneableTags[argsTag] = cloneableTags[arrayTag] =
  22521. cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
  22522. cloneableTags[boolTag] = cloneableTags[dateTag] =
  22523. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  22524. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  22525. cloneableTags[int32Tag] = cloneableTags[mapTag] =
  22526. cloneableTags[numberTag] = cloneableTags[objectTag] =
  22527. cloneableTags[regexpTag] = cloneableTags[setTag] =
  22528. cloneableTags[stringTag] = cloneableTags[symbolTag] =
  22529. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  22530. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  22531. cloneableTags[errorTag] = cloneableTags[funcTag] =
  22532. cloneableTags[weakMapTag] = false;
  22533. /** Detect free variable `global` from Node.js. */
  22534. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  22535. /** Detect free variable `self`. */
  22536. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  22537. /** Used as a reference to the global object. */
  22538. var root = freeGlobal || freeSelf || Function('return this')();
  22539. /** Detect free variable `exports`. */
  22540. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  22541. /** Detect free variable `module`. */
  22542. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  22543. /** Detect the popular CommonJS extension `module.exports`. */
  22544. var moduleExports = freeModule && freeModule.exports === freeExports;
  22545. /** Detect free variable `process` from Node.js. */
  22546. var freeProcess = moduleExports && freeGlobal.process;
  22547. /** Used to access faster Node.js helpers. */
  22548. var nodeUtil = (function() {
  22549. try {
  22550. return freeProcess && freeProcess.binding('util');
  22551. } catch (e) {}
  22552. }());
  22553. /* Node.js helper references. */
  22554. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  22555. /*--------------------------------------------------------------------------*/
  22556. /**
  22557. * Adds the key-value `pair` to `map`.
  22558. *
  22559. * @private
  22560. * @param {Object} map The map to modify.
  22561. * @param {Array} pair The key-value pair to add.
  22562. * @returns {Object} Returns `map`.
  22563. */
  22564. function addMapEntry(map, pair) {
  22565. // Don't return `map.set` because it's not chainable in IE 11.
  22566. map.set(pair[0], pair[1]);
  22567. return map;
  22568. }
  22569. /**
  22570. * Adds `value` to `set`.
  22571. *
  22572. * @private
  22573. * @param {Object} set The set to modify.
  22574. * @param {*} value The value to add.
  22575. * @returns {Object} Returns `set`.
  22576. */
  22577. function addSetEntry(set, value) {
  22578. // Don't return `set.add` because it's not chainable in IE 11.
  22579. set.add(value);
  22580. return set;
  22581. }
  22582. /**
  22583. * A faster alternative to `Function#apply`, this function invokes `func`
  22584. * with the `this` binding of `thisArg` and the arguments of `args`.
  22585. *
  22586. * @private
  22587. * @param {Function} func The function to invoke.
  22588. * @param {*} thisArg The `this` binding of `func`.
  22589. * @param {Array} args The arguments to invoke `func` with.
  22590. * @returns {*} Returns the result of `func`.
  22591. */
  22592. function apply(func, thisArg, args) {
  22593. switch (args.length) {
  22594. case 0: return func.call(thisArg);
  22595. case 1: return func.call(thisArg, args[0]);
  22596. case 2: return func.call(thisArg, args[0], args[1]);
  22597. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  22598. }
  22599. return func.apply(thisArg, args);
  22600. }
  22601. /**
  22602. * A specialized version of `_.forEach` for arrays without support for
  22603. * iteratee shorthands.
  22604. *
  22605. * @private
  22606. * @param {Array} [array] The array to iterate over.
  22607. * @param {Function} iteratee The function invoked per iteration.
  22608. * @returns {Array} Returns `array`.
  22609. */
  22610. function arrayEach(array, iteratee) {
  22611. var index = -1,
  22612. length = array ? array.length : 0;
  22613. while (++index < length) {
  22614. if (iteratee(array[index], index, array) === false) {
  22615. break;
  22616. }
  22617. }
  22618. return array;
  22619. }
  22620. /**
  22621. * Appends the elements of `values` to `array`.
  22622. *
  22623. * @private
  22624. * @param {Array} array The array to modify.
  22625. * @param {Array} values The values to append.
  22626. * @returns {Array} Returns `array`.
  22627. */
  22628. function arrayPush(array, values) {
  22629. var index = -1,
  22630. length = values.length,
  22631. offset = array.length;
  22632. while (++index < length) {
  22633. array[offset + index] = values[index];
  22634. }
  22635. return array;
  22636. }
  22637. /**
  22638. * A specialized version of `_.reduce` for arrays without support for
  22639. * iteratee shorthands.
  22640. *
  22641. * @private
  22642. * @param {Array} [array] The array to iterate over.
  22643. * @param {Function} iteratee The function invoked per iteration.
  22644. * @param {*} [accumulator] The initial value.
  22645. * @param {boolean} [initAccum] Specify using the first element of `array` as
  22646. * the initial value.
  22647. * @returns {*} Returns the accumulated value.
  22648. */
  22649. function arrayReduce(array, iteratee, accumulator, initAccum) {
  22650. var index = -1,
  22651. length = array ? array.length : 0;
  22652. if (initAccum && length) {
  22653. accumulator = array[++index];
  22654. }
  22655. while (++index < length) {
  22656. accumulator = iteratee(accumulator, array[index], index, array);
  22657. }
  22658. return accumulator;
  22659. }
  22660. /**
  22661. * A specialized version of `_.some` for arrays without support for iteratee
  22662. * shorthands.
  22663. *
  22664. * @private
  22665. * @param {Array} [array] The array to iterate over.
  22666. * @param {Function} predicate The function invoked per iteration.
  22667. * @returns {boolean} Returns `true` if any element passes the predicate check,
  22668. * else `false`.
  22669. */
  22670. function arraySome(array, predicate) {
  22671. var index = -1,
  22672. length = array ? array.length : 0;
  22673. while (++index < length) {
  22674. if (predicate(array[index], index, array)) {
  22675. return true;
  22676. }
  22677. }
  22678. return false;
  22679. }
  22680. /**
  22681. * The base implementation of `_.property` without support for deep paths.
  22682. *
  22683. * @private
  22684. * @param {string} key The key of the property to get.
  22685. * @returns {Function} Returns the new accessor function.
  22686. */
  22687. function baseProperty(key) {
  22688. return function(object) {
  22689. return object == null ? undefined : object[key];
  22690. };
  22691. }
  22692. /**
  22693. * The base implementation of `_.times` without support for iteratee shorthands
  22694. * or max array length checks.
  22695. *
  22696. * @private
  22697. * @param {number} n The number of times to invoke `iteratee`.
  22698. * @param {Function} iteratee The function invoked per iteration.
  22699. * @returns {Array} Returns the array of results.
  22700. */
  22701. function baseTimes(n, iteratee) {
  22702. var index = -1,
  22703. result = Array(n);
  22704. while (++index < n) {
  22705. result[index] = iteratee(index);
  22706. }
  22707. return result;
  22708. }
  22709. /**
  22710. * The base implementation of `_.unary` without support for storing metadata.
  22711. *
  22712. * @private
  22713. * @param {Function} func The function to cap arguments for.
  22714. * @returns {Function} Returns the new capped function.
  22715. */
  22716. function baseUnary(func) {
  22717. return function(value) {
  22718. return func(value);
  22719. };
  22720. }
  22721. /**
  22722. * Gets the value at `key` of `object`.
  22723. *
  22724. * @private
  22725. * @param {Object} [object] The object to query.
  22726. * @param {string} key The key of the property to get.
  22727. * @returns {*} Returns the property value.
  22728. */
  22729. function getValue(object, key) {
  22730. return object == null ? undefined : object[key];
  22731. }
  22732. /**
  22733. * Checks if `value` is a host object in IE < 9.
  22734. *
  22735. * @private
  22736. * @param {*} value The value to check.
  22737. * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
  22738. */
  22739. function isHostObject(value) {
  22740. // Many host objects are `Object` objects that can coerce to strings
  22741. // despite having improperly defined `toString` methods.
  22742. var result = false;
  22743. if (value != null && typeof value.toString != 'function') {
  22744. try {
  22745. result = !!(value + '');
  22746. } catch (e) {}
  22747. }
  22748. return result;
  22749. }
  22750. /**
  22751. * Converts `map` to its key-value pairs.
  22752. *
  22753. * @private
  22754. * @param {Object} map The map to convert.
  22755. * @returns {Array} Returns the key-value pairs.
  22756. */
  22757. function mapToArray(map) {
  22758. var index = -1,
  22759. result = Array(map.size);
  22760. map.forEach(function(value, key) {
  22761. result[++index] = [key, value];
  22762. });
  22763. return result;
  22764. }
  22765. /**
  22766. * Creates a unary function that invokes `func` with its argument transformed.
  22767. *
  22768. * @private
  22769. * @param {Function} func The function to wrap.
  22770. * @param {Function} transform The argument transform.
  22771. * @returns {Function} Returns the new function.
  22772. */
  22773. function overArg(func, transform) {
  22774. return function(arg) {
  22775. return func(transform(arg));
  22776. };
  22777. }
  22778. /**
  22779. * Converts `set` to an array of its values.
  22780. *
  22781. * @private
  22782. * @param {Object} set The set to convert.
  22783. * @returns {Array} Returns the values.
  22784. */
  22785. function setToArray(set) {
  22786. var index = -1,
  22787. result = Array(set.size);
  22788. set.forEach(function(value) {
  22789. result[++index] = value;
  22790. });
  22791. return result;
  22792. }
  22793. /*--------------------------------------------------------------------------*/
  22794. /** Used for built-in method references. */
  22795. var arrayProto = Array.prototype,
  22796. funcProto = Function.prototype,
  22797. objectProto = Object.prototype;
  22798. /** Used to detect overreaching core-js shims. */
  22799. var coreJsData = root['__core-js_shared__'];
  22800. /** Used to detect methods masquerading as native. */
  22801. var maskSrcKey = (function() {
  22802. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  22803. return uid ? ('Symbol(src)_1.' + uid) : '';
  22804. }());
  22805. /** Used to resolve the decompiled source of functions. */
  22806. var funcToString = funcProto.toString;
  22807. /** Used to check objects for own properties. */
  22808. var hasOwnProperty = objectProto.hasOwnProperty;
  22809. /** Used to infer the `Object` constructor. */
  22810. var objectCtorString = funcToString.call(Object);
  22811. /**
  22812. * Used to resolve the
  22813. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  22814. * of values.
  22815. */
  22816. var objectToString = objectProto.toString;
  22817. /** Used to detect if a method is native. */
  22818. var reIsNative = RegExp('^' +
  22819. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  22820. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  22821. );
  22822. /** Built-in value references. */
  22823. var Buffer = moduleExports ? root.Buffer : undefined,
  22824. Symbol = root.Symbol,
  22825. Uint8Array = root.Uint8Array,
  22826. getPrototype = overArg(Object.getPrototypeOf, Object),
  22827. objectCreate = Object.create,
  22828. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  22829. splice = arrayProto.splice;
  22830. /* Built-in method references for those with the same name as other `lodash` methods. */
  22831. var nativeGetSymbols = Object.getOwnPropertySymbols,
  22832. nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
  22833. nativeKeys = overArg(Object.keys, Object),
  22834. nativeMax = Math.max;
  22835. /* Built-in method references that are verified to be native. */
  22836. var DataView = getNative(root, 'DataView'),
  22837. Map = getNative(root, 'Map'),
  22838. Promise = getNative(root, 'Promise'),
  22839. Set = getNative(root, 'Set'),
  22840. WeakMap = getNative(root, 'WeakMap'),
  22841. nativeCreate = getNative(Object, 'create');
  22842. /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
  22843. var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');
  22844. /** Used to lookup unminified function names. */
  22845. var realNames = {};
  22846. /** Used to detect maps, sets, and weakmaps. */
  22847. var dataViewCtorString = toSource(DataView),
  22848. mapCtorString = toSource(Map),
  22849. promiseCtorString = toSource(Promise),
  22850. setCtorString = toSource(Set),
  22851. weakMapCtorString = toSource(WeakMap);
  22852. /** Used to convert symbols to primitives and strings. */
  22853. var symbolProto = Symbol ? Symbol.prototype : undefined,
  22854. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
  22855. symbolToString = symbolProto ? symbolProto.toString : undefined;
  22856. /*------------------------------------------------------------------------*/
  22857. /**
  22858. * Creates a `lodash` object which wraps `value` to enable implicit method
  22859. * chain sequences. Methods that operate on and return arrays, collections,
  22860. * and functions can be chained together. Methods that retrieve a single value
  22861. * or may return a primitive value will automatically end the chain sequence
  22862. * and return the unwrapped value. Otherwise, the value must be unwrapped
  22863. * with `_#value`.
  22864. *
  22865. * Explicit chain sequences, which must be unwrapped with `_#value`, may be
  22866. * enabled using `_.chain`.
  22867. *
  22868. * The execution of chained methods is lazy, that is, it's deferred until
  22869. * `_#value` is implicitly or explicitly called.
  22870. *
  22871. * Lazy evaluation allows several methods to support shortcut fusion.
  22872. * Shortcut fusion is an optimization to merge iteratee calls; this avoids
  22873. * the creation of intermediate arrays and can greatly reduce the number of
  22874. * iteratee executions. Sections of a chain sequence qualify for shortcut
  22875. * fusion if the section is applied to an array of at least `200` elements
  22876. * and any iteratees accept only one argument. The heuristic for whether a
  22877. * section qualifies for shortcut fusion is subject to change.
  22878. *
  22879. * Chaining is supported in custom builds as long as the `_#value` method is
  22880. * directly or indirectly included in the build.
  22881. *
  22882. * In addition to lodash methods, wrappers have `Array` and `String` methods.
  22883. *
  22884. * The wrapper `Array` methods are:
  22885. * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
  22886. *
  22887. * The wrapper `String` methods are:
  22888. * `replace` and `split`
  22889. *
  22890. * The wrapper methods that support shortcut fusion are:
  22891. * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
  22892. * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
  22893. * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
  22894. *
  22895. * The chainable wrapper methods are:
  22896. * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
  22897. * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
  22898. * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
  22899. * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
  22900. * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
  22901. * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
  22902. * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
  22903. * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
  22904. * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
  22905. * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
  22906. * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
  22907. * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
  22908. * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
  22909. * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
  22910. * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
  22911. * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
  22912. * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
  22913. * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
  22914. * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
  22915. * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
  22916. * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
  22917. * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
  22918. * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
  22919. * `zipObject`, `zipObjectDeep`, and `zipWith`
  22920. *
  22921. * The wrapper methods that are **not** chainable by default are:
  22922. * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
  22923. * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
  22924. * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
  22925. * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
  22926. * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
  22927. * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
  22928. * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
  22929. * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
  22930. * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
  22931. * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
  22932. * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
  22933. * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
  22934. * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
  22935. * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
  22936. * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
  22937. * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
  22938. * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
  22939. * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
  22940. * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
  22941. * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
  22942. * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
  22943. * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
  22944. * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
  22945. * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
  22946. * `upperFirst`, `value`, and `words`
  22947. *
  22948. * @name _
  22949. * @constructor
  22950. * @category Seq
  22951. * @param {*} value The value to wrap in a `lodash` instance.
  22952. * @returns {Object} Returns the new `lodash` wrapper instance.
  22953. * @example
  22954. *
  22955. * function square(n) {
  22956. * return n * n;
  22957. * }
  22958. *
  22959. * var wrapped = _([1, 2, 3]);
  22960. *
  22961. * // Returns an unwrapped value.
  22962. * wrapped.reduce(_.add);
  22963. * // => 6
  22964. *
  22965. * // Returns a wrapped value.
  22966. * var squares = wrapped.map(square);
  22967. *
  22968. * _.isArray(squares);
  22969. * // => false
  22970. *
  22971. * _.isArray(squares.value());
  22972. * // => true
  22973. */
  22974. function lodash() {
  22975. // No operation performed.
  22976. }
  22977. /*------------------------------------------------------------------------*/
  22978. /**
  22979. * Creates a hash object.
  22980. *
  22981. * @private
  22982. * @constructor
  22983. * @param {Array} [entries] The key-value pairs to cache.
  22984. */
  22985. function Hash(entries) {
  22986. var index = -1,
  22987. length = entries ? entries.length : 0;
  22988. this.clear();
  22989. while (++index < length) {
  22990. var entry = entries[index];
  22991. this.set(entry[0], entry[1]);
  22992. }
  22993. }
  22994. /**
  22995. * Removes all key-value entries from the hash.
  22996. *
  22997. * @private
  22998. * @name clear
  22999. * @memberOf Hash
  23000. */
  23001. function hashClear() {
  23002. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  23003. }
  23004. /**
  23005. * Removes `key` and its value from the hash.
  23006. *
  23007. * @private
  23008. * @name delete
  23009. * @memberOf Hash
  23010. * @param {Object} hash The hash to modify.
  23011. * @param {string} key The key of the value to remove.
  23012. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  23013. */
  23014. function hashDelete(key) {
  23015. return this.has(key) && delete this.__data__[key];
  23016. }
  23017. /**
  23018. * Gets the hash value for `key`.
  23019. *
  23020. * @private
  23021. * @name get
  23022. * @memberOf Hash
  23023. * @param {string} key The key of the value to get.
  23024. * @returns {*} Returns the entry value.
  23025. */
  23026. function hashGet(key) {
  23027. var data = this.__data__;
  23028. if (nativeCreate) {
  23029. var result = data[key];
  23030. return result === HASH_UNDEFINED ? undefined : result;
  23031. }
  23032. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  23033. }
  23034. /**
  23035. * Checks if a hash value for `key` exists.
  23036. *
  23037. * @private
  23038. * @name has
  23039. * @memberOf Hash
  23040. * @param {string} key The key of the entry to check.
  23041. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  23042. */
  23043. function hashHas(key) {
  23044. var data = this.__data__;
  23045. return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
  23046. }
  23047. /**
  23048. * Sets the hash `key` to `value`.
  23049. *
  23050. * @private
  23051. * @name set
  23052. * @memberOf Hash
  23053. * @param {string} key The key of the value to set.
  23054. * @param {*} value The value to set.
  23055. * @returns {Object} Returns the hash instance.
  23056. */
  23057. function hashSet(key, value) {
  23058. var data = this.__data__;
  23059. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  23060. return this;
  23061. }
  23062. // Add methods to `Hash`.
  23063. Hash.prototype.clear = hashClear;
  23064. Hash.prototype['delete'] = hashDelete;
  23065. Hash.prototype.get = hashGet;
  23066. Hash.prototype.has = hashHas;
  23067. Hash.prototype.set = hashSet;
  23068. /*------------------------------------------------------------------------*/
  23069. /**
  23070. * Creates an list cache object.
  23071. *
  23072. * @private
  23073. * @constructor
  23074. * @param {Array} [entries] The key-value pairs to cache.
  23075. */
  23076. function ListCache(entries) {
  23077. var index = -1,
  23078. length = entries ? entries.length : 0;
  23079. this.clear();
  23080. while (++index < length) {
  23081. var entry = entries[index];
  23082. this.set(entry[0], entry[1]);
  23083. }
  23084. }
  23085. /**
  23086. * Removes all key-value entries from the list cache.
  23087. *
  23088. * @private
  23089. * @name clear
  23090. * @memberOf ListCache
  23091. */
  23092. function listCacheClear() {
  23093. this.__data__ = [];
  23094. }
  23095. /**
  23096. * Removes `key` and its value from the list cache.
  23097. *
  23098. * @private
  23099. * @name delete
  23100. * @memberOf ListCache
  23101. * @param {string} key The key of the value to remove.
  23102. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  23103. */
  23104. function listCacheDelete(key) {
  23105. var data = this.__data__,
  23106. index = assocIndexOf(data, key);
  23107. if (index < 0) {
  23108. return false;
  23109. }
  23110. var lastIndex = data.length - 1;
  23111. if (index == lastIndex) {
  23112. data.pop();
  23113. } else {
  23114. splice.call(data, index, 1);
  23115. }
  23116. return true;
  23117. }
  23118. /**
  23119. * Gets the list cache value for `key`.
  23120. *
  23121. * @private
  23122. * @name get
  23123. * @memberOf ListCache
  23124. * @param {string} key The key of the value to get.
  23125. * @returns {*} Returns the entry value.
  23126. */
  23127. function listCacheGet(key) {
  23128. var data = this.__data__,
  23129. index = assocIndexOf(data, key);
  23130. return index < 0 ? undefined : data[index][1];
  23131. }
  23132. /**
  23133. * Checks if a list cache value for `key` exists.
  23134. *
  23135. * @private
  23136. * @name has
  23137. * @memberOf ListCache
  23138. * @param {string} key The key of the entry to check.
  23139. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  23140. */
  23141. function listCacheHas(key) {
  23142. return assocIndexOf(this.__data__, key) > -1;
  23143. }
  23144. /**
  23145. * Sets the list cache `key` to `value`.
  23146. *
  23147. * @private
  23148. * @name set
  23149. * @memberOf ListCache
  23150. * @param {string} key The key of the value to set.
  23151. * @param {*} value The value to set.
  23152. * @returns {Object} Returns the list cache instance.
  23153. */
  23154. function listCacheSet(key, value) {
  23155. var data = this.__data__,
  23156. index = assocIndexOf(data, key);
  23157. if (index < 0) {
  23158. data.push([key, value]);
  23159. } else {
  23160. data[index][1] = value;
  23161. }
  23162. return this;
  23163. }
  23164. // Add methods to `ListCache`.
  23165. ListCache.prototype.clear = listCacheClear;
  23166. ListCache.prototype['delete'] = listCacheDelete;
  23167. ListCache.prototype.get = listCacheGet;
  23168. ListCache.prototype.has = listCacheHas;
  23169. ListCache.prototype.set = listCacheSet;
  23170. /*------------------------------------------------------------------------*/
  23171. /**
  23172. * Creates a map cache object to store key-value pairs.
  23173. *
  23174. * @private
  23175. * @constructor
  23176. * @param {Array} [entries] The key-value pairs to cache.
  23177. */
  23178. function MapCache(entries) {
  23179. var index = -1,
  23180. length = entries ? entries.length : 0;
  23181. this.clear();
  23182. while (++index < length) {
  23183. var entry = entries[index];
  23184. this.set(entry[0], entry[1]);
  23185. }
  23186. }
  23187. /**
  23188. * Removes all key-value entries from the map.
  23189. *
  23190. * @private
  23191. * @name clear
  23192. * @memberOf MapCache
  23193. */
  23194. function mapCacheClear() {
  23195. this.__data__ = {
  23196. 'hash': new Hash,
  23197. 'map': new (Map || ListCache),
  23198. 'string': new Hash
  23199. };
  23200. }
  23201. /**
  23202. * Removes `key` and its value from the map.
  23203. *
  23204. * @private
  23205. * @name delete
  23206. * @memberOf MapCache
  23207. * @param {string} key The key of the value to remove.
  23208. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  23209. */
  23210. function mapCacheDelete(key) {
  23211. return getMapData(this, key)['delete'](key);
  23212. }
  23213. /**
  23214. * Gets the map value for `key`.
  23215. *
  23216. * @private
  23217. * @name get
  23218. * @memberOf MapCache
  23219. * @param {string} key The key of the value to get.
  23220. * @returns {*} Returns the entry value.
  23221. */
  23222. function mapCacheGet(key) {
  23223. return getMapData(this, key).get(key);
  23224. }
  23225. /**
  23226. * Checks if a map value for `key` exists.
  23227. *
  23228. * @private
  23229. * @name has
  23230. * @memberOf MapCache
  23231. * @param {string} key The key of the entry to check.
  23232. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  23233. */
  23234. function mapCacheHas(key) {
  23235. return getMapData(this, key).has(key);
  23236. }
  23237. /**
  23238. * Sets the map `key` to `value`.
  23239. *
  23240. * @private
  23241. * @name set
  23242. * @memberOf MapCache
  23243. * @param {string} key The key of the value to set.
  23244. * @param {*} value The value to set.
  23245. * @returns {Object} Returns the map cache instance.
  23246. */
  23247. function mapCacheSet(key, value) {
  23248. getMapData(this, key).set(key, value);
  23249. return this;
  23250. }
  23251. // Add methods to `MapCache`.
  23252. MapCache.prototype.clear = mapCacheClear;
  23253. MapCache.prototype['delete'] = mapCacheDelete;
  23254. MapCache.prototype.get = mapCacheGet;
  23255. MapCache.prototype.has = mapCacheHas;
  23256. MapCache.prototype.set = mapCacheSet;
  23257. /*------------------------------------------------------------------------*/
  23258. /**
  23259. *
  23260. * Creates an array cache object to store unique values.
  23261. *
  23262. * @private
  23263. * @constructor
  23264. * @param {Array} [values] The values to cache.
  23265. */
  23266. function SetCache(values) {
  23267. var index = -1,
  23268. length = values ? values.length : 0;
  23269. this.__data__ = new MapCache;
  23270. while (++index < length) {
  23271. this.add(values[index]);
  23272. }
  23273. }
  23274. /**
  23275. * Adds `value` to the array cache.
  23276. *
  23277. * @private
  23278. * @name add
  23279. * @memberOf SetCache
  23280. * @alias push
  23281. * @param {*} value The value to cache.
  23282. * @returns {Object} Returns the cache instance.
  23283. */
  23284. function setCacheAdd(value) {
  23285. this.__data__.set(value, HASH_UNDEFINED);
  23286. return this;
  23287. }
  23288. /**
  23289. * Checks if `value` is in the array cache.
  23290. *
  23291. * @private
  23292. * @name has
  23293. * @memberOf SetCache
  23294. * @param {*} value The value to search for.
  23295. * @returns {number} Returns `true` if `value` is found, else `false`.
  23296. */
  23297. function setCacheHas(value) {
  23298. return this.__data__.has(value);
  23299. }
  23300. // Add methods to `SetCache`.
  23301. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
  23302. SetCache.prototype.has = setCacheHas;
  23303. /*------------------------------------------------------------------------*/
  23304. /**
  23305. * Creates a stack cache object to store key-value pairs.
  23306. *
  23307. * @private
  23308. * @constructor
  23309. * @param {Array} [entries] The key-value pairs to cache.
  23310. */
  23311. function Stack(entries) {
  23312. this.__data__ = new ListCache(entries);
  23313. }
  23314. /**
  23315. * Removes all key-value entries from the stack.
  23316. *
  23317. * @private
  23318. * @name clear
  23319. * @memberOf Stack
  23320. */
  23321. function stackClear() {
  23322. this.__data__ = new ListCache;
  23323. }
  23324. /**
  23325. * Removes `key` and its value from the stack.
  23326. *
  23327. * @private
  23328. * @name delete
  23329. * @memberOf Stack
  23330. * @param {string} key The key of the value to remove.
  23331. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  23332. */
  23333. function stackDelete(key) {
  23334. return this.__data__['delete'](key);
  23335. }
  23336. /**
  23337. * Gets the stack value for `key`.
  23338. *
  23339. * @private
  23340. * @name get
  23341. * @memberOf Stack
  23342. * @param {string} key The key of the value to get.
  23343. * @returns {*} Returns the entry value.
  23344. */
  23345. function stackGet(key) {
  23346. return this.__data__.get(key);
  23347. }
  23348. /**
  23349. * Checks if a stack value for `key` exists.
  23350. *
  23351. * @private
  23352. * @name has
  23353. * @memberOf Stack
  23354. * @param {string} key The key of the entry to check.
  23355. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  23356. */
  23357. function stackHas(key) {
  23358. return this.__data__.has(key);
  23359. }
  23360. /**
  23361. * Sets the stack `key` to `value`.
  23362. *
  23363. * @private
  23364. * @name set
  23365. * @memberOf Stack
  23366. * @param {string} key The key of the value to set.
  23367. * @param {*} value The value to set.
  23368. * @returns {Object} Returns the stack cache instance.
  23369. */
  23370. function stackSet(key, value) {
  23371. var cache = this.__data__;
  23372. if (cache instanceof ListCache) {
  23373. var pairs = cache.__data__;
  23374. if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  23375. pairs.push([key, value]);
  23376. return this;
  23377. }
  23378. cache = this.__data__ = new MapCache(pairs);
  23379. }
  23380. cache.set(key, value);
  23381. return this;
  23382. }
  23383. // Add methods to `Stack`.
  23384. Stack.prototype.clear = stackClear;
  23385. Stack.prototype['delete'] = stackDelete;
  23386. Stack.prototype.get = stackGet;
  23387. Stack.prototype.has = stackHas;
  23388. Stack.prototype.set = stackSet;
  23389. /*------------------------------------------------------------------------*/
  23390. /**
  23391. * Creates an array of the enumerable property names of the array-like `value`.
  23392. *
  23393. * @private
  23394. * @param {*} value The value to query.
  23395. * @param {boolean} inherited Specify returning inherited property names.
  23396. * @returns {Array} Returns the array of property names.
  23397. */
  23398. function arrayLikeKeys(value, inherited) {
  23399. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  23400. // Safari 9 makes `arguments.length` enumerable in strict mode.
  23401. var result = (isArray(value) || isArguments(value))
  23402. ? baseTimes(value.length, String)
  23403. : [];
  23404. var length = result.length,
  23405. skipIndexes = !!length;
  23406. for (var key in value) {
  23407. if ((inherited || hasOwnProperty.call(value, key)) &&
  23408. !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
  23409. result.push(key);
  23410. }
  23411. }
  23412. return result;
  23413. }
  23414. /**
  23415. * This function is like `assignValue` except that it doesn't assign
  23416. * `undefined` values.
  23417. *
  23418. * @private
  23419. * @param {Object} object The object to modify.
  23420. * @param {string} key The key of the property to assign.
  23421. * @param {*} value The value to assign.
  23422. */
  23423. function assignMergeValue(object, key, value) {
  23424. if ((value !== undefined && !eq(object[key], value)) ||
  23425. (typeof key == 'number' && value === undefined && !(key in object))) {
  23426. object[key] = value;
  23427. }
  23428. }
  23429. /**
  23430. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  23431. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  23432. * for equality comparisons.
  23433. *
  23434. * @private
  23435. * @param {Object} object The object to modify.
  23436. * @param {string} key The key of the property to assign.
  23437. * @param {*} value The value to assign.
  23438. */
  23439. function assignValue(object, key, value) {
  23440. var objValue = object[key];
  23441. if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
  23442. (value === undefined && !(key in object))) {
  23443. object[key] = value;
  23444. }
  23445. }
  23446. /**
  23447. * Gets the index at which the `key` is found in `array` of key-value pairs.
  23448. *
  23449. * @private
  23450. * @param {Array} array The array to inspect.
  23451. * @param {*} key The key to search for.
  23452. * @returns {number} Returns the index of the matched value, else `-1`.
  23453. */
  23454. function assocIndexOf(array, key) {
  23455. var length = array.length;
  23456. while (length--) {
  23457. if (eq(array[length][0], key)) {
  23458. return length;
  23459. }
  23460. }
  23461. return -1;
  23462. }
  23463. /**
  23464. * The base implementation of `_.assign` without support for multiple sources
  23465. * or `customizer` functions.
  23466. *
  23467. * @private
  23468. * @param {Object} object The destination object.
  23469. * @param {Object} source The source object.
  23470. * @returns {Object} Returns `object`.
  23471. */
  23472. function baseAssign(object, source) {
  23473. return object && copyObject(source, keys(source), object);
  23474. }
  23475. /**
  23476. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  23477. * traversed objects.
  23478. *
  23479. * @private
  23480. * @param {*} value The value to clone.
  23481. * @param {boolean} [isDeep] Specify a deep clone.
  23482. * @param {boolean} [isFull] Specify a clone including symbols.
  23483. * @param {Function} [customizer] The function to customize cloning.
  23484. * @param {string} [key] The key of `value`.
  23485. * @param {Object} [object] The parent object of `value`.
  23486. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  23487. * @returns {*} Returns the cloned value.
  23488. */
  23489. function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
  23490. var result;
  23491. if (customizer) {
  23492. result = object ? customizer(value, key, object, stack) : customizer(value);
  23493. }
  23494. if (result !== undefined) {
  23495. return result;
  23496. }
  23497. if (!isObject(value)) {
  23498. return value;
  23499. }
  23500. var isArr = isArray(value);
  23501. if (isArr) {
  23502. result = initCloneArray(value);
  23503. if (!isDeep) {
  23504. return copyArray(value, result);
  23505. }
  23506. } else {
  23507. var tag = getTag(value),
  23508. isFunc = tag == funcTag || tag == genTag;
  23509. if (isBuffer(value)) {
  23510. return cloneBuffer(value, isDeep);
  23511. }
  23512. if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
  23513. if (isHostObject(value)) {
  23514. return object ? value : {};
  23515. }
  23516. result = initCloneObject(isFunc ? {} : value);
  23517. if (!isDeep) {
  23518. return copySymbols(value, baseAssign(result, value));
  23519. }
  23520. } else {
  23521. if (!cloneableTags[tag]) {
  23522. return object ? value : {};
  23523. }
  23524. result = initCloneByTag(value, tag, baseClone, isDeep);
  23525. }
  23526. }
  23527. // Check for circular references and return its corresponding clone.
  23528. stack || (stack = new Stack);
  23529. var stacked = stack.get(value);
  23530. if (stacked) {
  23531. return stacked;
  23532. }
  23533. stack.set(value, result);
  23534. if (!isArr) {
  23535. var props = isFull ? getAllKeys(value) : keys(value);
  23536. }
  23537. arrayEach(props || value, function(subValue, key) {
  23538. if (props) {
  23539. key = subValue;
  23540. subValue = value[key];
  23541. }
  23542. // Recursively populate clone (susceptible to call stack limits).
  23543. assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
  23544. });
  23545. return result;
  23546. }
  23547. /**
  23548. * The base implementation of `_.create` without support for assigning
  23549. * properties to the created object.
  23550. *
  23551. * @private
  23552. * @param {Object} prototype The object to inherit from.
  23553. * @returns {Object} Returns the new object.
  23554. */
  23555. function baseCreate(proto) {
  23556. return isObject(proto) ? objectCreate(proto) : {};
  23557. }
  23558. /**
  23559. * The base implementation of `_.forEach` without support for iteratee shorthands.
  23560. *
  23561. * @private
  23562. * @param {Array|Object} collection The collection to iterate over.
  23563. * @param {Function} iteratee The function invoked per iteration.
  23564. * @returns {Array|Object} Returns `collection`.
  23565. */
  23566. var baseEach = createBaseEach(baseForOwn);
  23567. /**
  23568. * The base implementation of `baseForOwn` which iterates over `object`
  23569. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  23570. * Iteratee functions may exit iteration early by explicitly returning `false`.
  23571. *
  23572. * @private
  23573. * @param {Object} object The object to iterate over.
  23574. * @param {Function} iteratee The function invoked per iteration.
  23575. * @param {Function} keysFunc The function to get the keys of `object`.
  23576. * @returns {Object} Returns `object`.
  23577. */
  23578. var baseFor = createBaseFor();
  23579. /**
  23580. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  23581. *
  23582. * @private
  23583. * @param {Object} object The object to iterate over.
  23584. * @param {Function} iteratee The function invoked per iteration.
  23585. * @returns {Object} Returns `object`.
  23586. */
  23587. function baseForOwn(object, iteratee) {
  23588. return object && baseFor(object, iteratee, keys);
  23589. }
  23590. /**
  23591. * The base implementation of `_.get` without support for default values.
  23592. *
  23593. * @private
  23594. * @param {Object} object The object to query.
  23595. * @param {Array|string} path The path of the property to get.
  23596. * @returns {*} Returns the resolved value.
  23597. */
  23598. function baseGet(object, path) {
  23599. path = isKey(path, object) ? [path] : castPath(path);
  23600. var index = 0,
  23601. length = path.length;
  23602. while (object != null && index < length) {
  23603. object = object[toKey(path[index++])];
  23604. }
  23605. return (index && index == length) ? object : undefined;
  23606. }
  23607. /**
  23608. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  23609. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  23610. * symbols of `object`.
  23611. *
  23612. * @private
  23613. * @param {Object} object The object to query.
  23614. * @param {Function} keysFunc The function to get the keys of `object`.
  23615. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  23616. * @returns {Array} Returns the array of property names and symbols.
  23617. */
  23618. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  23619. var result = keysFunc(object);
  23620. return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
  23621. }
  23622. /**
  23623. * The base implementation of `getTag`.
  23624. *
  23625. * @private
  23626. * @param {*} value The value to query.
  23627. * @returns {string} Returns the `toStringTag`.
  23628. */
  23629. function baseGetTag(value) {
  23630. return objectToString.call(value);
  23631. }
  23632. /**
  23633. * The base implementation of `_.hasIn` without support for deep paths.
  23634. *
  23635. * @private
  23636. * @param {Object} [object] The object to query.
  23637. * @param {Array|string} key The key to check.
  23638. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  23639. */
  23640. function baseHasIn(object, key) {
  23641. return object != null && key in Object(object);
  23642. }
  23643. /**
  23644. * The base implementation of `_.isEqual` which supports partial comparisons
  23645. * and tracks traversed objects.
  23646. *
  23647. * @private
  23648. * @param {*} value The value to compare.
  23649. * @param {*} other The other value to compare.
  23650. * @param {Function} [customizer] The function to customize comparisons.
  23651. * @param {boolean} [bitmask] The bitmask of comparison flags.
  23652. * The bitmask may be composed of the following flags:
  23653. * 1 - Unordered comparison
  23654. * 2 - Partial comparison
  23655. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  23656. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  23657. */
  23658. function baseIsEqual(value, other, customizer, bitmask, stack) {
  23659. if (value === other) {
  23660. return true;
  23661. }
  23662. if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
  23663. return value !== value && other !== other;
  23664. }
  23665. return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
  23666. }
  23667. /**
  23668. * A specialized version of `baseIsEqual` for arrays and objects which performs
  23669. * deep comparisons and tracks traversed objects enabling objects with circular
  23670. * references to be compared.
  23671. *
  23672. * @private
  23673. * @param {Object} object The object to compare.
  23674. * @param {Object} other The other object to compare.
  23675. * @param {Function} equalFunc The function to determine equivalents of values.
  23676. * @param {Function} [customizer] The function to customize comparisons.
  23677. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
  23678. * for more details.
  23679. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  23680. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  23681. */
  23682. function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
  23683. var objIsArr = isArray(object),
  23684. othIsArr = isArray(other),
  23685. objTag = arrayTag,
  23686. othTag = arrayTag;
  23687. if (!objIsArr) {
  23688. objTag = getTag(object);
  23689. objTag = objTag == argsTag ? objectTag : objTag;
  23690. }
  23691. if (!othIsArr) {
  23692. othTag = getTag(other);
  23693. othTag = othTag == argsTag ? objectTag : othTag;
  23694. }
  23695. var objIsObj = objTag == objectTag && !isHostObject(object),
  23696. othIsObj = othTag == objectTag && !isHostObject(other),
  23697. isSameTag = objTag == othTag;
  23698. if (isSameTag && !objIsObj) {
  23699. stack || (stack = new Stack);
  23700. return (objIsArr || isTypedArray(object))
  23701. ? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
  23702. : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
  23703. }
  23704. if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
  23705. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  23706. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  23707. if (objIsWrapped || othIsWrapped) {
  23708. var objUnwrapped = objIsWrapped ? object.value() : object,
  23709. othUnwrapped = othIsWrapped ? other.value() : other;
  23710. stack || (stack = new Stack);
  23711. return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
  23712. }
  23713. }
  23714. if (!isSameTag) {
  23715. return false;
  23716. }
  23717. stack || (stack = new Stack);
  23718. return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
  23719. }
  23720. /**
  23721. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  23722. *
  23723. * @private
  23724. * @param {Object} object The object to inspect.
  23725. * @param {Object} source The object of property values to match.
  23726. * @param {Array} matchData The property names, values, and compare flags to match.
  23727. * @param {Function} [customizer] The function to customize comparisons.
  23728. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  23729. */
  23730. function baseIsMatch(object, source, matchData, customizer) {
  23731. var index = matchData.length,
  23732. length = index,
  23733. noCustomizer = !customizer;
  23734. if (object == null) {
  23735. return !length;
  23736. }
  23737. object = Object(object);
  23738. while (index--) {
  23739. var data = matchData[index];
  23740. if ((noCustomizer && data[2])
  23741. ? data[1] !== object[data[0]]
  23742. : !(data[0] in object)
  23743. ) {
  23744. return false;
  23745. }
  23746. }
  23747. while (++index < length) {
  23748. data = matchData[index];
  23749. var key = data[0],
  23750. objValue = object[key],
  23751. srcValue = data[1];
  23752. if (noCustomizer && data[2]) {
  23753. if (objValue === undefined && !(key in object)) {
  23754. return false;
  23755. }
  23756. } else {
  23757. var stack = new Stack;
  23758. if (customizer) {
  23759. var result = customizer(objValue, srcValue, key, object, source, stack);
  23760. }
  23761. if (!(result === undefined
  23762. ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
  23763. : result
  23764. )) {
  23765. return false;
  23766. }
  23767. }
  23768. }
  23769. return true;
  23770. }
  23771. /**
  23772. * The base implementation of `_.isNative` without bad shim checks.
  23773. *
  23774. * @private
  23775. * @param {*} value The value to check.
  23776. * @returns {boolean} Returns `true` if `value` is a native function,
  23777. * else `false`.
  23778. */
  23779. function baseIsNative(value) {
  23780. if (!isObject(value) || isMasked(value)) {
  23781. return false;
  23782. }
  23783. var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  23784. return pattern.test(toSource(value));
  23785. }
  23786. /**
  23787. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  23788. *
  23789. * @private
  23790. * @param {*} value The value to check.
  23791. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  23792. */
  23793. function baseIsTypedArray(value) {
  23794. return isObjectLike(value) &&
  23795. isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
  23796. }
  23797. /**
  23798. * The base implementation of `_.iteratee`.
  23799. *
  23800. * @private
  23801. * @param {*} [value=_.identity] The value to convert to an iteratee.
  23802. * @returns {Function} Returns the iteratee.
  23803. */
  23804. function baseIteratee(value) {
  23805. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  23806. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  23807. if (typeof value == 'function') {
  23808. return value;
  23809. }
  23810. if (value == null) {
  23811. return identity;
  23812. }
  23813. if (typeof value == 'object') {
  23814. return isArray(value)
  23815. ? baseMatchesProperty(value[0], value[1])
  23816. : baseMatches(value);
  23817. }
  23818. return property(value);
  23819. }
  23820. /**
  23821. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  23822. *
  23823. * @private
  23824. * @param {Object} object The object to query.
  23825. * @returns {Array} Returns the array of property names.
  23826. */
  23827. function baseKeys(object) {
  23828. if (!isPrototype(object)) {
  23829. return nativeKeys(object);
  23830. }
  23831. var result = [];
  23832. for (var key in Object(object)) {
  23833. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  23834. result.push(key);
  23835. }
  23836. }
  23837. return result;
  23838. }
  23839. /**
  23840. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  23841. *
  23842. * @private
  23843. * @param {Object} object The object to query.
  23844. * @returns {Array} Returns the array of property names.
  23845. */
  23846. function baseKeysIn(object) {
  23847. if (!isObject(object)) {
  23848. return nativeKeysIn(object);
  23849. }
  23850. var isProto = isPrototype(object),
  23851. result = [];
  23852. for (var key in object) {
  23853. if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  23854. result.push(key);
  23855. }
  23856. }
  23857. return result;
  23858. }
  23859. /**
  23860. * The base implementation of `_.matches` which doesn't clone `source`.
  23861. *
  23862. * @private
  23863. * @param {Object} source The object of property values to match.
  23864. * @returns {Function} Returns the new spec function.
  23865. */
  23866. function baseMatches(source) {
  23867. var matchData = getMatchData(source);
  23868. if (matchData.length == 1 && matchData[0][2]) {
  23869. return matchesStrictComparable(matchData[0][0], matchData[0][1]);
  23870. }
  23871. return function(object) {
  23872. return object === source || baseIsMatch(object, source, matchData);
  23873. };
  23874. }
  23875. /**
  23876. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  23877. *
  23878. * @private
  23879. * @param {string} path The path of the property to get.
  23880. * @param {*} srcValue The value to match.
  23881. * @returns {Function} Returns the new spec function.
  23882. */
  23883. function baseMatchesProperty(path, srcValue) {
  23884. if (isKey(path) && isStrictComparable(srcValue)) {
  23885. return matchesStrictComparable(toKey(path), srcValue);
  23886. }
  23887. return function(object) {
  23888. var objValue = get(object, path);
  23889. return (objValue === undefined && objValue === srcValue)
  23890. ? hasIn(object, path)
  23891. : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
  23892. };
  23893. }
  23894. /**
  23895. * The base implementation of `_.merge` without support for multiple sources.
  23896. *
  23897. * @private
  23898. * @param {Object} object The destination object.
  23899. * @param {Object} source The source object.
  23900. * @param {number} srcIndex The index of `source`.
  23901. * @param {Function} [customizer] The function to customize merged values.
  23902. * @param {Object} [stack] Tracks traversed source values and their merged
  23903. * counterparts.
  23904. */
  23905. function baseMerge(object, source, srcIndex, customizer, stack) {
  23906. if (object === source) {
  23907. return;
  23908. }
  23909. if (!(isArray(source) || isTypedArray(source))) {
  23910. var props = baseKeysIn(source);
  23911. }
  23912. arrayEach(props || source, function(srcValue, key) {
  23913. if (props) {
  23914. key = srcValue;
  23915. srcValue = source[key];
  23916. }
  23917. if (isObject(srcValue)) {
  23918. stack || (stack = new Stack);
  23919. baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
  23920. }
  23921. else {
  23922. var newValue = customizer
  23923. ? customizer(object[key], srcValue, (key + ''), object, source, stack)
  23924. : undefined;
  23925. if (newValue === undefined) {
  23926. newValue = srcValue;
  23927. }
  23928. assignMergeValue(object, key, newValue);
  23929. }
  23930. });
  23931. }
  23932. /**
  23933. * A specialized version of `baseMerge` for arrays and objects which performs
  23934. * deep merges and tracks traversed objects enabling objects with circular
  23935. * references to be merged.
  23936. *
  23937. * @private
  23938. * @param {Object} object The destination object.
  23939. * @param {Object} source The source object.
  23940. * @param {string} key The key of the value to merge.
  23941. * @param {number} srcIndex The index of `source`.
  23942. * @param {Function} mergeFunc The function to merge values.
  23943. * @param {Function} [customizer] The function to customize assigned values.
  23944. * @param {Object} [stack] Tracks traversed source values and their merged
  23945. * counterparts.
  23946. */
  23947. function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
  23948. var objValue = object[key],
  23949. srcValue = source[key],
  23950. stacked = stack.get(srcValue);
  23951. if (stacked) {
  23952. assignMergeValue(object, key, stacked);
  23953. return;
  23954. }
  23955. var newValue = customizer
  23956. ? customizer(objValue, srcValue, (key + ''), object, source, stack)
  23957. : undefined;
  23958. var isCommon = newValue === undefined;
  23959. if (isCommon) {
  23960. newValue = srcValue;
  23961. if (isArray(srcValue) || isTypedArray(srcValue)) {
  23962. if (isArray(objValue)) {
  23963. newValue = objValue;
  23964. }
  23965. else if (isArrayLikeObject(objValue)) {
  23966. newValue = copyArray(objValue);
  23967. }
  23968. else {
  23969. isCommon = false;
  23970. newValue = baseClone(srcValue, true);
  23971. }
  23972. }
  23973. else if (isPlainObject(srcValue) || isArguments(srcValue)) {
  23974. if (isArguments(objValue)) {
  23975. newValue = toPlainObject(objValue);
  23976. }
  23977. else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
  23978. isCommon = false;
  23979. newValue = baseClone(srcValue, true);
  23980. }
  23981. else {
  23982. newValue = objValue;
  23983. }
  23984. }
  23985. else {
  23986. isCommon = false;
  23987. }
  23988. }
  23989. if (isCommon) {
  23990. // Recursively merge objects and arrays (susceptible to call stack limits).
  23991. stack.set(srcValue, newValue);
  23992. mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
  23993. stack['delete'](srcValue);
  23994. }
  23995. assignMergeValue(object, key, newValue);
  23996. }
  23997. /**
  23998. * A specialized version of `baseProperty` which supports deep paths.
  23999. *
  24000. * @private
  24001. * @param {Array|string} path The path of the property to get.
  24002. * @returns {Function} Returns the new accessor function.
  24003. */
  24004. function basePropertyDeep(path) {
  24005. return function(object) {
  24006. return baseGet(object, path);
  24007. };
  24008. }
  24009. /**
  24010. * The base implementation of `_.rest` which doesn't validate or coerce arguments.
  24011. *
  24012. * @private
  24013. * @param {Function} func The function to apply a rest parameter to.
  24014. * @param {number} [start=func.length-1] The start position of the rest parameter.
  24015. * @returns {Function} Returns the new function.
  24016. */
  24017. function baseRest(func, start) {
  24018. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  24019. return function() {
  24020. var args = arguments,
  24021. index = -1,
  24022. length = nativeMax(args.length - start, 0),
  24023. array = Array(length);
  24024. while (++index < length) {
  24025. array[index] = args[start + index];
  24026. }
  24027. index = -1;
  24028. var otherArgs = Array(start + 1);
  24029. while (++index < start) {
  24030. otherArgs[index] = args[index];
  24031. }
  24032. otherArgs[start] = array;
  24033. return apply(func, this, otherArgs);
  24034. };
  24035. }
  24036. /**
  24037. * The base implementation of `_.toString` which doesn't convert nullish
  24038. * values to empty strings.
  24039. *
  24040. * @private
  24041. * @param {*} value The value to process.
  24042. * @returns {string} Returns the string.
  24043. */
  24044. function baseToString(value) {
  24045. // Exit early for strings to avoid a performance hit in some environments.
  24046. if (typeof value == 'string') {
  24047. return value;
  24048. }
  24049. if (isSymbol(value)) {
  24050. return symbolToString ? symbolToString.call(value) : '';
  24051. }
  24052. var result = (value + '');
  24053. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  24054. }
  24055. /**
  24056. * Casts `value` to a path array if it's not one.
  24057. *
  24058. * @private
  24059. * @param {*} value The value to inspect.
  24060. * @returns {Array} Returns the cast property path array.
  24061. */
  24062. function castPath(value) {
  24063. return isArray(value) ? value : stringToPath(value);
  24064. }
  24065. /**
  24066. * Creates a clone of `buffer`.
  24067. *
  24068. * @private
  24069. * @param {Buffer} buffer The buffer to clone.
  24070. * @param {boolean} [isDeep] Specify a deep clone.
  24071. * @returns {Buffer} Returns the cloned buffer.
  24072. */
  24073. function cloneBuffer(buffer, isDeep) {
  24074. if (isDeep) {
  24075. return buffer.slice();
  24076. }
  24077. var result = new buffer.constructor(buffer.length);
  24078. buffer.copy(result);
  24079. return result;
  24080. }
  24081. /**
  24082. * Creates a clone of `arrayBuffer`.
  24083. *
  24084. * @private
  24085. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  24086. * @returns {ArrayBuffer} Returns the cloned array buffer.
  24087. */
  24088. function cloneArrayBuffer(arrayBuffer) {
  24089. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  24090. new Uint8Array(result).set(new Uint8Array(arrayBuffer));
  24091. return result;
  24092. }
  24093. /**
  24094. * Creates a clone of `dataView`.
  24095. *
  24096. * @private
  24097. * @param {Object} dataView The data view to clone.
  24098. * @param {boolean} [isDeep] Specify a deep clone.
  24099. * @returns {Object} Returns the cloned data view.
  24100. */
  24101. function cloneDataView(dataView, isDeep) {
  24102. var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  24103. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  24104. }
  24105. /**
  24106. * Creates a clone of `map`.
  24107. *
  24108. * @private
  24109. * @param {Object} map The map to clone.
  24110. * @param {Function} cloneFunc The function to clone values.
  24111. * @param {boolean} [isDeep] Specify a deep clone.
  24112. * @returns {Object} Returns the cloned map.
  24113. */
  24114. function cloneMap(map, isDeep, cloneFunc) {
  24115. var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
  24116. return arrayReduce(array, addMapEntry, new map.constructor);
  24117. }
  24118. /**
  24119. * Creates a clone of `regexp`.
  24120. *
  24121. * @private
  24122. * @param {Object} regexp The regexp to clone.
  24123. * @returns {Object} Returns the cloned regexp.
  24124. */
  24125. function cloneRegExp(regexp) {
  24126. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  24127. result.lastIndex = regexp.lastIndex;
  24128. return result;
  24129. }
  24130. /**
  24131. * Creates a clone of `set`.
  24132. *
  24133. * @private
  24134. * @param {Object} set The set to clone.
  24135. * @param {Function} cloneFunc The function to clone values.
  24136. * @param {boolean} [isDeep] Specify a deep clone.
  24137. * @returns {Object} Returns the cloned set.
  24138. */
  24139. function cloneSet(set, isDeep, cloneFunc) {
  24140. var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
  24141. return arrayReduce(array, addSetEntry, new set.constructor);
  24142. }
  24143. /**
  24144. * Creates a clone of the `symbol` object.
  24145. *
  24146. * @private
  24147. * @param {Object} symbol The symbol object to clone.
  24148. * @returns {Object} Returns the cloned symbol object.
  24149. */
  24150. function cloneSymbol(symbol) {
  24151. return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
  24152. }
  24153. /**
  24154. * Creates a clone of `typedArray`.
  24155. *
  24156. * @private
  24157. * @param {Object} typedArray The typed array to clone.
  24158. * @param {boolean} [isDeep] Specify a deep clone.
  24159. * @returns {Object} Returns the cloned typed array.
  24160. */
  24161. function cloneTypedArray(typedArray, isDeep) {
  24162. var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  24163. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  24164. }
  24165. /**
  24166. * Copies the values of `source` to `array`.
  24167. *
  24168. * @private
  24169. * @param {Array} source The array to copy values from.
  24170. * @param {Array} [array=[]] The array to copy values to.
  24171. * @returns {Array} Returns `array`.
  24172. */
  24173. function copyArray(source, array) {
  24174. var index = -1,
  24175. length = source.length;
  24176. array || (array = Array(length));
  24177. while (++index < length) {
  24178. array[index] = source[index];
  24179. }
  24180. return array;
  24181. }
  24182. /**
  24183. * Copies properties of `source` to `object`.
  24184. *
  24185. * @private
  24186. * @param {Object} source The object to copy properties from.
  24187. * @param {Array} props The property identifiers to copy.
  24188. * @param {Object} [object={}] The object to copy properties to.
  24189. * @param {Function} [customizer] The function to customize copied values.
  24190. * @returns {Object} Returns `object`.
  24191. */
  24192. function copyObject(source, props, object, customizer) {
  24193. object || (object = {});
  24194. var index = -1,
  24195. length = props.length;
  24196. while (++index < length) {
  24197. var key = props[index];
  24198. var newValue = customizer
  24199. ? customizer(object[key], source[key], key, object, source)
  24200. : undefined;
  24201. assignValue(object, key, newValue === undefined ? source[key] : newValue);
  24202. }
  24203. return object;
  24204. }
  24205. /**
  24206. * Copies own symbol properties of `source` to `object`.
  24207. *
  24208. * @private
  24209. * @param {Object} source The object to copy symbols from.
  24210. * @param {Object} [object={}] The object to copy symbols to.
  24211. * @returns {Object} Returns `object`.
  24212. */
  24213. function copySymbols(source, object) {
  24214. return copyObject(source, getSymbols(source), object);
  24215. }
  24216. /**
  24217. * Creates a function like `_.assign`.
  24218. *
  24219. * @private
  24220. * @param {Function} assigner The function to assign values.
  24221. * @returns {Function} Returns the new assigner function.
  24222. */
  24223. function createAssigner(assigner) {
  24224. return baseRest(function(object, sources) {
  24225. var index = -1,
  24226. length = sources.length,
  24227. customizer = length > 1 ? sources[length - 1] : undefined,
  24228. guard = length > 2 ? sources[2] : undefined;
  24229. customizer = (assigner.length > 3 && typeof customizer == 'function')
  24230. ? (length--, customizer)
  24231. : undefined;
  24232. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  24233. customizer = length < 3 ? undefined : customizer;
  24234. length = 1;
  24235. }
  24236. object = Object(object);
  24237. while (++index < length) {
  24238. var source = sources[index];
  24239. if (source) {
  24240. assigner(object, source, index, customizer);
  24241. }
  24242. }
  24243. return object;
  24244. });
  24245. }
  24246. /**
  24247. * Creates a `baseEach` or `baseEachRight` function.
  24248. *
  24249. * @private
  24250. * @param {Function} eachFunc The function to iterate over a collection.
  24251. * @param {boolean} [fromRight] Specify iterating from right to left.
  24252. * @returns {Function} Returns the new base function.
  24253. */
  24254. function createBaseEach(eachFunc, fromRight) {
  24255. return function(collection, iteratee) {
  24256. if (collection == null) {
  24257. return collection;
  24258. }
  24259. if (!isArrayLike(collection)) {
  24260. return eachFunc(collection, iteratee);
  24261. }
  24262. var length = collection.length,
  24263. index = fromRight ? length : -1,
  24264. iterable = Object(collection);
  24265. while ((fromRight ? index-- : ++index < length)) {
  24266. if (iteratee(iterable[index], index, iterable) === false) {
  24267. break;
  24268. }
  24269. }
  24270. return collection;
  24271. };
  24272. }
  24273. /**
  24274. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  24275. *
  24276. * @private
  24277. * @param {boolean} [fromRight] Specify iterating from right to left.
  24278. * @returns {Function} Returns the new base function.
  24279. */
  24280. function createBaseFor(fromRight) {
  24281. return function(object, iteratee, keysFunc) {
  24282. var index = -1,
  24283. iterable = Object(object),
  24284. props = keysFunc(object),
  24285. length = props.length;
  24286. while (length--) {
  24287. var key = props[fromRight ? length : ++index];
  24288. if (iteratee(iterable[key], key, iterable) === false) {
  24289. break;
  24290. }
  24291. }
  24292. return object;
  24293. };
  24294. }
  24295. /**
  24296. * A specialized version of `baseIsEqualDeep` for arrays with support for
  24297. * partial deep comparisons.
  24298. *
  24299. * @private
  24300. * @param {Array} array The array to compare.
  24301. * @param {Array} other The other array to compare.
  24302. * @param {Function} equalFunc The function to determine equivalents of values.
  24303. * @param {Function} customizer The function to customize comparisons.
  24304. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  24305. * for more details.
  24306. * @param {Object} stack Tracks traversed `array` and `other` objects.
  24307. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  24308. */
  24309. function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
  24310. var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
  24311. arrLength = array.length,
  24312. othLength = other.length;
  24313. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  24314. return false;
  24315. }
  24316. // Assume cyclic values are equal.
  24317. var stacked = stack.get(array);
  24318. if (stacked && stack.get(other)) {
  24319. return stacked == other;
  24320. }
  24321. var index = -1,
  24322. result = true,
  24323. seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined;
  24324. stack.set(array, other);
  24325. stack.set(other, array);
  24326. // Ignore non-index properties.
  24327. while (++index < arrLength) {
  24328. var arrValue = array[index],
  24329. othValue = other[index];
  24330. if (customizer) {
  24331. var compared = isPartial
  24332. ? customizer(othValue, arrValue, index, other, array, stack)
  24333. : customizer(arrValue, othValue, index, array, other, stack);
  24334. }
  24335. if (compared !== undefined) {
  24336. if (compared) {
  24337. continue;
  24338. }
  24339. result = false;
  24340. break;
  24341. }
  24342. // Recursively compare arrays (susceptible to call stack limits).
  24343. if (seen) {
  24344. if (!arraySome(other, function(othValue, othIndex) {
  24345. if (!seen.has(othIndex) &&
  24346. (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
  24347. return seen.add(othIndex);
  24348. }
  24349. })) {
  24350. result = false;
  24351. break;
  24352. }
  24353. } else if (!(
  24354. arrValue === othValue ||
  24355. equalFunc(arrValue, othValue, customizer, bitmask, stack)
  24356. )) {
  24357. result = false;
  24358. break;
  24359. }
  24360. }
  24361. stack['delete'](array);
  24362. stack['delete'](other);
  24363. return result;
  24364. }
  24365. /**
  24366. * A specialized version of `baseIsEqualDeep` for comparing objects of
  24367. * the same `toStringTag`.
  24368. *
  24369. * **Note:** This function only supports comparing values with tags of
  24370. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  24371. *
  24372. * @private
  24373. * @param {Object} object The object to compare.
  24374. * @param {Object} other The other object to compare.
  24375. * @param {string} tag The `toStringTag` of the objects to compare.
  24376. * @param {Function} equalFunc The function to determine equivalents of values.
  24377. * @param {Function} customizer The function to customize comparisons.
  24378. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  24379. * for more details.
  24380. * @param {Object} stack Tracks traversed `object` and `other` objects.
  24381. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  24382. */
  24383. function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
  24384. switch (tag) {
  24385. case dataViewTag:
  24386. if ((object.byteLength != other.byteLength) ||
  24387. (object.byteOffset != other.byteOffset)) {
  24388. return false;
  24389. }
  24390. object = object.buffer;
  24391. other = other.buffer;
  24392. case arrayBufferTag:
  24393. if ((object.byteLength != other.byteLength) ||
  24394. !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
  24395. return false;
  24396. }
  24397. return true;
  24398. case boolTag:
  24399. case dateTag:
  24400. case numberTag:
  24401. // Coerce booleans to `1` or `0` and dates to milliseconds.
  24402. // Invalid dates are coerced to `NaN`.
  24403. return eq(+object, +other);
  24404. case errorTag:
  24405. return object.name == other.name && object.message == other.message;
  24406. case regexpTag:
  24407. case stringTag:
  24408. // Coerce regexes to strings and treat strings, primitives and objects,
  24409. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  24410. // for more details.
  24411. return object == (other + '');
  24412. case mapTag:
  24413. var convert = mapToArray;
  24414. case setTag:
  24415. var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
  24416. convert || (convert = setToArray);
  24417. if (object.size != other.size && !isPartial) {
  24418. return false;
  24419. }
  24420. // Assume cyclic values are equal.
  24421. var stacked = stack.get(object);
  24422. if (stacked) {
  24423. return stacked == other;
  24424. }
  24425. bitmask |= UNORDERED_COMPARE_FLAG;
  24426. // Recursively compare objects (susceptible to call stack limits).
  24427. stack.set(object, other);
  24428. var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
  24429. stack['delete'](object);
  24430. return result;
  24431. case symbolTag:
  24432. if (symbolValueOf) {
  24433. return symbolValueOf.call(object) == symbolValueOf.call(other);
  24434. }
  24435. }
  24436. return false;
  24437. }
  24438. /**
  24439. * A specialized version of `baseIsEqualDeep` for objects with support for
  24440. * partial deep comparisons.
  24441. *
  24442. * @private
  24443. * @param {Object} object The object to compare.
  24444. * @param {Object} other The other object to compare.
  24445. * @param {Function} equalFunc The function to determine equivalents of values.
  24446. * @param {Function} customizer The function to customize comparisons.
  24447. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  24448. * for more details.
  24449. * @param {Object} stack Tracks traversed `object` and `other` objects.
  24450. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  24451. */
  24452. function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
  24453. var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
  24454. objProps = keys(object),
  24455. objLength = objProps.length,
  24456. othProps = keys(other),
  24457. othLength = othProps.length;
  24458. if (objLength != othLength && !isPartial) {
  24459. return false;
  24460. }
  24461. var index = objLength;
  24462. while (index--) {
  24463. var key = objProps[index];
  24464. if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
  24465. return false;
  24466. }
  24467. }
  24468. // Assume cyclic values are equal.
  24469. var stacked = stack.get(object);
  24470. if (stacked && stack.get(other)) {
  24471. return stacked == other;
  24472. }
  24473. var result = true;
  24474. stack.set(object, other);
  24475. stack.set(other, object);
  24476. var skipCtor = isPartial;
  24477. while (++index < objLength) {
  24478. key = objProps[index];
  24479. var objValue = object[key],
  24480. othValue = other[key];
  24481. if (customizer) {
  24482. var compared = isPartial
  24483. ? customizer(othValue, objValue, key, other, object, stack)
  24484. : customizer(objValue, othValue, key, object, other, stack);
  24485. }
  24486. // Recursively compare objects (susceptible to call stack limits).
  24487. if (!(compared === undefined
  24488. ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
  24489. : compared
  24490. )) {
  24491. result = false;
  24492. break;
  24493. }
  24494. skipCtor || (skipCtor = key == 'constructor');
  24495. }
  24496. if (result && !skipCtor) {
  24497. var objCtor = object.constructor,
  24498. othCtor = other.constructor;
  24499. // Non `Object` object instances with different constructors are not equal.
  24500. if (objCtor != othCtor &&
  24501. ('constructor' in object && 'constructor' in other) &&
  24502. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  24503. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  24504. result = false;
  24505. }
  24506. }
  24507. stack['delete'](object);
  24508. stack['delete'](other);
  24509. return result;
  24510. }
  24511. /**
  24512. * Creates an array of own enumerable property names and symbols of `object`.
  24513. *
  24514. * @private
  24515. * @param {Object} object The object to query.
  24516. * @returns {Array} Returns the array of property names and symbols.
  24517. */
  24518. function getAllKeys(object) {
  24519. return baseGetAllKeys(object, keys, getSymbols);
  24520. }
  24521. /**
  24522. * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
  24523. * this function returns the custom method, otherwise it returns `baseIteratee`.
  24524. * If arguments are provided, the chosen function is invoked with them and
  24525. * its result is returned.
  24526. *
  24527. * @private
  24528. * @param {*} [value] The value to convert to an iteratee.
  24529. * @param {number} [arity] The arity of the created iteratee.
  24530. * @returns {Function} Returns the chosen function or its result.
  24531. */
  24532. function getIteratee() {
  24533. var result = lodash.iteratee || iteratee;
  24534. result = result === iteratee ? baseIteratee : result;
  24535. return arguments.length ? result(arguments[0], arguments[1]) : result;
  24536. }
  24537. /**
  24538. * Gets the data for `map`.
  24539. *
  24540. * @private
  24541. * @param {Object} map The map to query.
  24542. * @param {string} key The reference key.
  24543. * @returns {*} Returns the map data.
  24544. */
  24545. function getMapData(map, key) {
  24546. var data = map.__data__;
  24547. return isKeyable(key)
  24548. ? data[typeof key == 'string' ? 'string' : 'hash']
  24549. : data.map;
  24550. }
  24551. /**
  24552. * Gets the property names, values, and compare flags of `object`.
  24553. *
  24554. * @private
  24555. * @param {Object} object The object to query.
  24556. * @returns {Array} Returns the match data of `object`.
  24557. */
  24558. function getMatchData(object) {
  24559. var result = keys(object),
  24560. length = result.length;
  24561. while (length--) {
  24562. var key = result[length],
  24563. value = object[key];
  24564. result[length] = [key, value, isStrictComparable(value)];
  24565. }
  24566. return result;
  24567. }
  24568. /**
  24569. * Gets the native function at `key` of `object`.
  24570. *
  24571. * @private
  24572. * @param {Object} object The object to query.
  24573. * @param {string} key The key of the method to get.
  24574. * @returns {*} Returns the function if it's native, else `undefined`.
  24575. */
  24576. function getNative(object, key) {
  24577. var value = getValue(object, key);
  24578. return baseIsNative(value) ? value : undefined;
  24579. }
  24580. /**
  24581. * Creates an array of the own enumerable symbol properties of `object`.
  24582. *
  24583. * @private
  24584. * @param {Object} object The object to query.
  24585. * @returns {Array} Returns the array of symbols.
  24586. */
  24587. var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
  24588. /**
  24589. * Gets the `toStringTag` of `value`.
  24590. *
  24591. * @private
  24592. * @param {*} value The value to query.
  24593. * @returns {string} Returns the `toStringTag`.
  24594. */
  24595. var getTag = baseGetTag;
  24596. // Fallback for data views, maps, sets, and weak maps in IE 11,
  24597. // for data views in Edge < 14, and promises in Node.js.
  24598. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
  24599. (Map && getTag(new Map) != mapTag) ||
  24600. (Promise && getTag(Promise.resolve()) != promiseTag) ||
  24601. (Set && getTag(new Set) != setTag) ||
  24602. (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  24603. getTag = function(value) {
  24604. var result = objectToString.call(value),
  24605. Ctor = result == objectTag ? value.constructor : undefined,
  24606. ctorString = Ctor ? toSource(Ctor) : undefined;
  24607. if (ctorString) {
  24608. switch (ctorString) {
  24609. case dataViewCtorString: return dataViewTag;
  24610. case mapCtorString: return mapTag;
  24611. case promiseCtorString: return promiseTag;
  24612. case setCtorString: return setTag;
  24613. case weakMapCtorString: return weakMapTag;
  24614. }
  24615. }
  24616. return result;
  24617. };
  24618. }
  24619. /**
  24620. * Checks if `path` exists on `object`.
  24621. *
  24622. * @private
  24623. * @param {Object} object The object to query.
  24624. * @param {Array|string} path The path to check.
  24625. * @param {Function} hasFunc The function to check properties.
  24626. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  24627. */
  24628. function hasPath(object, path, hasFunc) {
  24629. path = isKey(path, object) ? [path] : castPath(path);
  24630. var result,
  24631. index = -1,
  24632. length = path.length;
  24633. while (++index < length) {
  24634. var key = toKey(path[index]);
  24635. if (!(result = object != null && hasFunc(object, key))) {
  24636. break;
  24637. }
  24638. object = object[key];
  24639. }
  24640. if (result) {
  24641. return result;
  24642. }
  24643. var length = object ? object.length : 0;
  24644. return !!length && isLength(length) && isIndex(key, length) &&
  24645. (isArray(object) || isArguments(object));
  24646. }
  24647. /**
  24648. * Initializes an array clone.
  24649. *
  24650. * @private
  24651. * @param {Array} array The array to clone.
  24652. * @returns {Array} Returns the initialized clone.
  24653. */
  24654. function initCloneArray(array) {
  24655. var length = array.length,
  24656. result = array.constructor(length);
  24657. // Add properties assigned by `RegExp#exec`.
  24658. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
  24659. result.index = array.index;
  24660. result.input = array.input;
  24661. }
  24662. return result;
  24663. }
  24664. /**
  24665. * Initializes an object clone.
  24666. *
  24667. * @private
  24668. * @param {Object} object The object to clone.
  24669. * @returns {Object} Returns the initialized clone.
  24670. */
  24671. function initCloneObject(object) {
  24672. return (typeof object.constructor == 'function' && !isPrototype(object))
  24673. ? baseCreate(getPrototype(object))
  24674. : {};
  24675. }
  24676. /**
  24677. * Initializes an object clone based on its `toStringTag`.
  24678. *
  24679. * **Note:** This function only supports cloning values with tags of
  24680. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  24681. *
  24682. * @private
  24683. * @param {Object} object The object to clone.
  24684. * @param {string} tag The `toStringTag` of the object to clone.
  24685. * @param {Function} cloneFunc The function to clone values.
  24686. * @param {boolean} [isDeep] Specify a deep clone.
  24687. * @returns {Object} Returns the initialized clone.
  24688. */
  24689. function initCloneByTag(object, tag, cloneFunc, isDeep) {
  24690. var Ctor = object.constructor;
  24691. switch (tag) {
  24692. case arrayBufferTag:
  24693. return cloneArrayBuffer(object);
  24694. case boolTag:
  24695. case dateTag:
  24696. return new Ctor(+object);
  24697. case dataViewTag:
  24698. return cloneDataView(object, isDeep);
  24699. case float32Tag: case float64Tag:
  24700. case int8Tag: case int16Tag: case int32Tag:
  24701. case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
  24702. return cloneTypedArray(object, isDeep);
  24703. case mapTag:
  24704. return cloneMap(object, isDeep, cloneFunc);
  24705. case numberTag:
  24706. case stringTag:
  24707. return new Ctor(object);
  24708. case regexpTag:
  24709. return cloneRegExp(object);
  24710. case setTag:
  24711. return cloneSet(object, isDeep, cloneFunc);
  24712. case symbolTag:
  24713. return cloneSymbol(object);
  24714. }
  24715. }
  24716. /**
  24717. * Checks if `value` is a valid array-like index.
  24718. *
  24719. * @private
  24720. * @param {*} value The value to check.
  24721. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  24722. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  24723. */
  24724. function isIndex(value, length) {
  24725. length = length == null ? MAX_SAFE_INTEGER : length;
  24726. return !!length &&
  24727. (typeof value == 'number' || reIsUint.test(value)) &&
  24728. (value > -1 && value % 1 == 0 && value < length);
  24729. }
  24730. /**
  24731. * Checks if the given arguments are from an iteratee call.
  24732. *
  24733. * @private
  24734. * @param {*} value The potential iteratee value argument.
  24735. * @param {*} index The potential iteratee index or key argument.
  24736. * @param {*} object The potential iteratee object argument.
  24737. * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
  24738. * else `false`.
  24739. */
  24740. function isIterateeCall(value, index, object) {
  24741. if (!isObject(object)) {
  24742. return false;
  24743. }
  24744. var type = typeof index;
  24745. if (type == 'number'
  24746. ? (isArrayLike(object) && isIndex(index, object.length))
  24747. : (type == 'string' && index in object)
  24748. ) {
  24749. return eq(object[index], value);
  24750. }
  24751. return false;
  24752. }
  24753. /**
  24754. * Checks if `value` is a property name and not a property path.
  24755. *
  24756. * @private
  24757. * @param {*} value The value to check.
  24758. * @param {Object} [object] The object to query keys on.
  24759. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  24760. */
  24761. function isKey(value, object) {
  24762. if (isArray(value)) {
  24763. return false;
  24764. }
  24765. var type = typeof value;
  24766. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  24767. value == null || isSymbol(value)) {
  24768. return true;
  24769. }
  24770. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  24771. (object != null && value in Object(object));
  24772. }
  24773. /**
  24774. * Checks if `value` is suitable for use as unique object key.
  24775. *
  24776. * @private
  24777. * @param {*} value The value to check.
  24778. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  24779. */
  24780. function isKeyable(value) {
  24781. var type = typeof value;
  24782. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  24783. ? (value !== '__proto__')
  24784. : (value === null);
  24785. }
  24786. /**
  24787. * Checks if `func` has its source masked.
  24788. *
  24789. * @private
  24790. * @param {Function} func The function to check.
  24791. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  24792. */
  24793. function isMasked(func) {
  24794. return !!maskSrcKey && (maskSrcKey in func);
  24795. }
  24796. /**
  24797. * Checks if `value` is likely a prototype object.
  24798. *
  24799. * @private
  24800. * @param {*} value The value to check.
  24801. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  24802. */
  24803. function isPrototype(value) {
  24804. var Ctor = value && value.constructor,
  24805. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
  24806. return value === proto;
  24807. }
  24808. /**
  24809. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  24810. *
  24811. * @private
  24812. * @param {*} value The value to check.
  24813. * @returns {boolean} Returns `true` if `value` if suitable for strict
  24814. * equality comparisons, else `false`.
  24815. */
  24816. function isStrictComparable(value) {
  24817. return value === value && !isObject(value);
  24818. }
  24819. /**
  24820. * A specialized version of `matchesProperty` for source values suitable
  24821. * for strict equality comparisons, i.e. `===`.
  24822. *
  24823. * @private
  24824. * @param {string} key The key of the property to get.
  24825. * @param {*} srcValue The value to match.
  24826. * @returns {Function} Returns the new spec function.
  24827. */
  24828. function matchesStrictComparable(key, srcValue) {
  24829. return function(object) {
  24830. if (object == null) {
  24831. return false;
  24832. }
  24833. return object[key] === srcValue &&
  24834. (srcValue !== undefined || (key in Object(object)));
  24835. };
  24836. }
  24837. /**
  24838. * This function is like
  24839. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  24840. * except that it includes inherited enumerable properties.
  24841. *
  24842. * @private
  24843. * @param {Object} object The object to query.
  24844. * @returns {Array} Returns the array of property names.
  24845. */
  24846. function nativeKeysIn(object) {
  24847. var result = [];
  24848. if (object != null) {
  24849. for (var key in Object(object)) {
  24850. result.push(key);
  24851. }
  24852. }
  24853. return result;
  24854. }
  24855. /**
  24856. * Converts `string` to a property path array.
  24857. *
  24858. * @private
  24859. * @param {string} string The string to convert.
  24860. * @returns {Array} Returns the property path array.
  24861. */
  24862. var stringToPath = memoize(function(string) {
  24863. string = toString(string);
  24864. var result = [];
  24865. if (reLeadingDot.test(string)) {
  24866. result.push('');
  24867. }
  24868. string.replace(rePropName, function(match, number, quote, string) {
  24869. result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
  24870. });
  24871. return result;
  24872. });
  24873. /**
  24874. * Converts `value` to a string key if it's not a string or symbol.
  24875. *
  24876. * @private
  24877. * @param {*} value The value to inspect.
  24878. * @returns {string|symbol} Returns the key.
  24879. */
  24880. function toKey(value) {
  24881. if (typeof value == 'string' || isSymbol(value)) {
  24882. return value;
  24883. }
  24884. var result = (value + '');
  24885. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  24886. }
  24887. /**
  24888. * Converts `func` to its source code.
  24889. *
  24890. * @private
  24891. * @param {Function} func The function to process.
  24892. * @returns {string} Returns the source code.
  24893. */
  24894. function toSource(func) {
  24895. if (func != null) {
  24896. try {
  24897. return funcToString.call(func);
  24898. } catch (e) {}
  24899. try {
  24900. return (func + '');
  24901. } catch (e) {}
  24902. }
  24903. return '';
  24904. }
  24905. /*------------------------------------------------------------------------*/
  24906. /**
  24907. * Creates an array with all falsey values removed. The values `false`, `null`,
  24908. * `0`, `""`, `undefined`, and `NaN` are falsey.
  24909. *
  24910. * @static
  24911. * @memberOf _
  24912. * @since 0.1.0
  24913. * @category Array
  24914. * @param {Array} array The array to compact.
  24915. * @returns {Array} Returns the new array of filtered values.
  24916. * @example
  24917. *
  24918. * _.compact([0, 1, false, 2, '', 3]);
  24919. * // => [1, 2, 3]
  24920. */
  24921. function compact(array) {
  24922. var index = -1,
  24923. length = array ? array.length : 0,
  24924. resIndex = 0,
  24925. result = [];
  24926. while (++index < length) {
  24927. var value = array[index];
  24928. if (value) {
  24929. result[resIndex++] = value;
  24930. }
  24931. }
  24932. return result;
  24933. }
  24934. /*------------------------------------------------------------------------*/
  24935. /**
  24936. * Iterates over elements of `collection` and invokes `iteratee` for each element.
  24937. * The iteratee is invoked with three arguments: (value, index|key, collection).
  24938. * Iteratee functions may exit iteration early by explicitly returning `false`.
  24939. *
  24940. * **Note:** As with other "Collections" methods, objects with a "length"
  24941. * property are iterated like arrays. To avoid this behavior use `_.forIn`
  24942. * or `_.forOwn` for object iteration.
  24943. *
  24944. * @static
  24945. * @memberOf _
  24946. * @since 0.1.0
  24947. * @alias each
  24948. * @category Collection
  24949. * @param {Array|Object} collection The collection to iterate over.
  24950. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  24951. * @returns {Array|Object} Returns `collection`.
  24952. * @see _.forEachRight
  24953. * @example
  24954. *
  24955. * _([1, 2]).forEach(function(value) {
  24956. * console.log(value);
  24957. * });
  24958. * // => Logs `1` then `2`.
  24959. *
  24960. * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  24961. * console.log(key);
  24962. * });
  24963. * // => Logs 'a' then 'b' (iteration order is not guaranteed).
  24964. */
  24965. function forEach(collection, iteratee) {
  24966. var func = isArray(collection) ? arrayEach : baseEach;
  24967. return func(collection, getIteratee(iteratee, 3));
  24968. }
  24969. /*------------------------------------------------------------------------*/
  24970. /**
  24971. * Creates a function that memoizes the result of `func`. If `resolver` is
  24972. * provided, it determines the cache key for storing the result based on the
  24973. * arguments provided to the memoized function. By default, the first argument
  24974. * provided to the memoized function is used as the map cache key. The `func`
  24975. * is invoked with the `this` binding of the memoized function.
  24976. *
  24977. * **Note:** The cache is exposed as the `cache` property on the memoized
  24978. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  24979. * constructor with one whose instances implement the
  24980. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  24981. * method interface of `delete`, `get`, `has`, and `set`.
  24982. *
  24983. * @static
  24984. * @memberOf _
  24985. * @since 0.1.0
  24986. * @category Function
  24987. * @param {Function} func The function to have its output memoized.
  24988. * @param {Function} [resolver] The function to resolve the cache key.
  24989. * @returns {Function} Returns the new memoized function.
  24990. * @example
  24991. *
  24992. * var object = { 'a': 1, 'b': 2 };
  24993. * var other = { 'c': 3, 'd': 4 };
  24994. *
  24995. * var values = _.memoize(_.values);
  24996. * values(object);
  24997. * // => [1, 2]
  24998. *
  24999. * values(other);
  25000. * // => [3, 4]
  25001. *
  25002. * object.a = 2;
  25003. * values(object);
  25004. * // => [1, 2]
  25005. *
  25006. * // Modify the result cache.
  25007. * values.cache.set(object, ['a', 'b']);
  25008. * values(object);
  25009. * // => ['a', 'b']
  25010. *
  25011. * // Replace `_.memoize.Cache`.
  25012. * _.memoize.Cache = WeakMap;
  25013. */
  25014. function memoize(func, resolver) {
  25015. if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
  25016. throw new TypeError(FUNC_ERROR_TEXT);
  25017. }
  25018. var memoized = function() {
  25019. var args = arguments,
  25020. key = resolver ? resolver.apply(this, args) : args[0],
  25021. cache = memoized.cache;
  25022. if (cache.has(key)) {
  25023. return cache.get(key);
  25024. }
  25025. var result = func.apply(this, args);
  25026. memoized.cache = cache.set(key, result);
  25027. return result;
  25028. };
  25029. memoized.cache = new (memoize.Cache || MapCache);
  25030. return memoized;
  25031. }
  25032. // Assign cache to `_.memoize`.
  25033. memoize.Cache = MapCache;
  25034. /*------------------------------------------------------------------------*/
  25035. /**
  25036. * Creates a shallow clone of `value`.
  25037. *
  25038. * **Note:** This method is loosely based on the
  25039. * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
  25040. * and supports cloning arrays, array buffers, booleans, date objects, maps,
  25041. * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
  25042. * arrays. The own enumerable properties of `arguments` objects are cloned
  25043. * as plain objects. An empty object is returned for uncloneable values such
  25044. * as error objects, functions, DOM nodes, and WeakMaps.
  25045. *
  25046. * @static
  25047. * @memberOf _
  25048. * @since 0.1.0
  25049. * @category Lang
  25050. * @param {*} value The value to clone.
  25051. * @returns {*} Returns the cloned value.
  25052. * @see _.cloneDeep
  25053. * @example
  25054. *
  25055. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  25056. *
  25057. * var shallow = _.clone(objects);
  25058. * console.log(shallow[0] === objects[0]);
  25059. * // => true
  25060. */
  25061. function clone(value) {
  25062. return baseClone(value, false, true);
  25063. }
  25064. /**
  25065. * Performs a
  25066. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  25067. * comparison between two values to determine if they are equivalent.
  25068. *
  25069. * @static
  25070. * @memberOf _
  25071. * @since 4.0.0
  25072. * @category Lang
  25073. * @param {*} value The value to compare.
  25074. * @param {*} other The other value to compare.
  25075. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  25076. * @example
  25077. *
  25078. * var object = { 'a': 1 };
  25079. * var other = { 'a': 1 };
  25080. *
  25081. * _.eq(object, object);
  25082. * // => true
  25083. *
  25084. * _.eq(object, other);
  25085. * // => false
  25086. *
  25087. * _.eq('a', 'a');
  25088. * // => true
  25089. *
  25090. * _.eq('a', Object('a'));
  25091. * // => false
  25092. *
  25093. * _.eq(NaN, NaN);
  25094. * // => true
  25095. */
  25096. function eq(value, other) {
  25097. return value === other || (value !== value && other !== other);
  25098. }
  25099. /**
  25100. * Checks if `value` is likely an `arguments` object.
  25101. *
  25102. * @static
  25103. * @memberOf _
  25104. * @since 0.1.0
  25105. * @category Lang
  25106. * @param {*} value The value to check.
  25107. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  25108. * else `false`.
  25109. * @example
  25110. *
  25111. * _.isArguments(function() { return arguments; }());
  25112. * // => true
  25113. *
  25114. * _.isArguments([1, 2, 3]);
  25115. * // => false
  25116. */
  25117. function isArguments(value) {
  25118. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  25119. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
  25120. (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
  25121. }
  25122. /**
  25123. * Checks if `value` is classified as an `Array` object.
  25124. *
  25125. * @static
  25126. * @memberOf _
  25127. * @since 0.1.0
  25128. * @category Lang
  25129. * @param {*} value The value to check.
  25130. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  25131. * @example
  25132. *
  25133. * _.isArray([1, 2, 3]);
  25134. * // => true
  25135. *
  25136. * _.isArray(document.body.children);
  25137. * // => false
  25138. *
  25139. * _.isArray('abc');
  25140. * // => false
  25141. *
  25142. * _.isArray(_.noop);
  25143. * // => false
  25144. */
  25145. var isArray = Array.isArray;
  25146. /**
  25147. * Checks if `value` is array-like. A value is considered array-like if it's
  25148. * not a function and has a `value.length` that's an integer greater than or
  25149. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  25150. *
  25151. * @static
  25152. * @memberOf _
  25153. * @since 4.0.0
  25154. * @category Lang
  25155. * @param {*} value The value to check.
  25156. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  25157. * @example
  25158. *
  25159. * _.isArrayLike([1, 2, 3]);
  25160. * // => true
  25161. *
  25162. * _.isArrayLike(document.body.children);
  25163. * // => true
  25164. *
  25165. * _.isArrayLike('abc');
  25166. * // => true
  25167. *
  25168. * _.isArrayLike(_.noop);
  25169. * // => false
  25170. */
  25171. function isArrayLike(value) {
  25172. return value != null && isLength(value.length) && !isFunction(value);
  25173. }
  25174. /**
  25175. * This method is like `_.isArrayLike` except that it also checks if `value`
  25176. * is an object.
  25177. *
  25178. * @static
  25179. * @memberOf _
  25180. * @since 4.0.0
  25181. * @category Lang
  25182. * @param {*} value The value to check.
  25183. * @returns {boolean} Returns `true` if `value` is an array-like object,
  25184. * else `false`.
  25185. * @example
  25186. *
  25187. * _.isArrayLikeObject([1, 2, 3]);
  25188. * // => true
  25189. *
  25190. * _.isArrayLikeObject(document.body.children);
  25191. * // => true
  25192. *
  25193. * _.isArrayLikeObject('abc');
  25194. * // => false
  25195. *
  25196. * _.isArrayLikeObject(_.noop);
  25197. * // => false
  25198. */
  25199. function isArrayLikeObject(value) {
  25200. return isObjectLike(value) && isArrayLike(value);
  25201. }
  25202. /**
  25203. * Checks if `value` is a buffer.
  25204. *
  25205. * @static
  25206. * @memberOf _
  25207. * @since 4.3.0
  25208. * @category Lang
  25209. * @param {*} value The value to check.
  25210. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  25211. * @example
  25212. *
  25213. * _.isBuffer(new Buffer(2));
  25214. * // => true
  25215. *
  25216. * _.isBuffer(new Uint8Array(2));
  25217. * // => false
  25218. */
  25219. var isBuffer = nativeIsBuffer || stubFalse;
  25220. /**
  25221. * Checks if `value` is an empty object, collection, map, or set.
  25222. *
  25223. * Objects are considered empty if they have no own enumerable string keyed
  25224. * properties.
  25225. *
  25226. * Array-like values such as `arguments` objects, arrays, buffers, strings, or
  25227. * jQuery-like collections are considered empty if they have a `length` of `0`.
  25228. * Similarly, maps and sets are considered empty if they have a `size` of `0`.
  25229. *
  25230. * @static
  25231. * @memberOf _
  25232. * @since 0.1.0
  25233. * @category Lang
  25234. * @param {*} value The value to check.
  25235. * @returns {boolean} Returns `true` if `value` is empty, else `false`.
  25236. * @example
  25237. *
  25238. * _.isEmpty(null);
  25239. * // => true
  25240. *
  25241. * _.isEmpty(true);
  25242. * // => true
  25243. *
  25244. * _.isEmpty(1);
  25245. * // => true
  25246. *
  25247. * _.isEmpty([1, 2, 3]);
  25248. * // => false
  25249. *
  25250. * _.isEmpty({ 'a': 1 });
  25251. * // => false
  25252. */
  25253. function isEmpty(value) {
  25254. if (isArrayLike(value) &&
  25255. (isArray(value) || typeof value == 'string' ||
  25256. typeof value.splice == 'function' || isBuffer(value) || isArguments(value))) {
  25257. return !value.length;
  25258. }
  25259. var tag = getTag(value);
  25260. if (tag == mapTag || tag == setTag) {
  25261. return !value.size;
  25262. }
  25263. if (nonEnumShadows || isPrototype(value)) {
  25264. return !nativeKeys(value).length;
  25265. }
  25266. for (var key in value) {
  25267. if (hasOwnProperty.call(value, key)) {
  25268. return false;
  25269. }
  25270. }
  25271. return true;
  25272. }
  25273. /**
  25274. * Checks if `value` is classified as a `Function` object.
  25275. *
  25276. * @static
  25277. * @memberOf _
  25278. * @since 0.1.0
  25279. * @category Lang
  25280. * @param {*} value The value to check.
  25281. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  25282. * @example
  25283. *
  25284. * _.isFunction(_);
  25285. * // => true
  25286. *
  25287. * _.isFunction(/abc/);
  25288. * // => false
  25289. */
  25290. function isFunction(value) {
  25291. // The use of `Object#toString` avoids issues with the `typeof` operator
  25292. // in Safari 8-9 which returns 'object' for typed array and other constructors.
  25293. var tag = isObject(value) ? objectToString.call(value) : '';
  25294. return tag == funcTag || tag == genTag;
  25295. }
  25296. /**
  25297. * Checks if `value` is a valid array-like length.
  25298. *
  25299. * **Note:** This method is loosely based on
  25300. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  25301. *
  25302. * @static
  25303. * @memberOf _
  25304. * @since 4.0.0
  25305. * @category Lang
  25306. * @param {*} value The value to check.
  25307. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  25308. * @example
  25309. *
  25310. * _.isLength(3);
  25311. * // => true
  25312. *
  25313. * _.isLength(Number.MIN_VALUE);
  25314. * // => false
  25315. *
  25316. * _.isLength(Infinity);
  25317. * // => false
  25318. *
  25319. * _.isLength('3');
  25320. * // => false
  25321. */
  25322. function isLength(value) {
  25323. return typeof value == 'number' &&
  25324. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  25325. }
  25326. /**
  25327. * Checks if `value` is the
  25328. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  25329. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  25330. *
  25331. * @static
  25332. * @memberOf _
  25333. * @since 0.1.0
  25334. * @category Lang
  25335. * @param {*} value The value to check.
  25336. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  25337. * @example
  25338. *
  25339. * _.isObject({});
  25340. * // => true
  25341. *
  25342. * _.isObject([1, 2, 3]);
  25343. * // => true
  25344. *
  25345. * _.isObject(_.noop);
  25346. * // => true
  25347. *
  25348. * _.isObject(null);
  25349. * // => false
  25350. */
  25351. function isObject(value) {
  25352. var type = typeof value;
  25353. return !!value && (type == 'object' || type == 'function');
  25354. }
  25355. /**
  25356. * Checks if `value` is object-like. A value is object-like if it's not `null`
  25357. * and has a `typeof` result of "object".
  25358. *
  25359. * @static
  25360. * @memberOf _
  25361. * @since 4.0.0
  25362. * @category Lang
  25363. * @param {*} value The value to check.
  25364. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  25365. * @example
  25366. *
  25367. * _.isObjectLike({});
  25368. * // => true
  25369. *
  25370. * _.isObjectLike([1, 2, 3]);
  25371. * // => true
  25372. *
  25373. * _.isObjectLike(_.noop);
  25374. * // => false
  25375. *
  25376. * _.isObjectLike(null);
  25377. * // => false
  25378. */
  25379. function isObjectLike(value) {
  25380. return !!value && typeof value == 'object';
  25381. }
  25382. /**
  25383. * Checks if `value` is a plain object, that is, an object created by the
  25384. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  25385. *
  25386. * @static
  25387. * @memberOf _
  25388. * @since 0.8.0
  25389. * @category Lang
  25390. * @param {*} value The value to check.
  25391. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  25392. * @example
  25393. *
  25394. * function Foo() {
  25395. * this.a = 1;
  25396. * }
  25397. *
  25398. * _.isPlainObject(new Foo);
  25399. * // => false
  25400. *
  25401. * _.isPlainObject([1, 2, 3]);
  25402. * // => false
  25403. *
  25404. * _.isPlainObject({ 'x': 0, 'y': 0 });
  25405. * // => true
  25406. *
  25407. * _.isPlainObject(Object.create(null));
  25408. * // => true
  25409. */
  25410. function isPlainObject(value) {
  25411. if (!isObjectLike(value) ||
  25412. objectToString.call(value) != objectTag || isHostObject(value)) {
  25413. return false;
  25414. }
  25415. var proto = getPrototype(value);
  25416. if (proto === null) {
  25417. return true;
  25418. }
  25419. var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  25420. return (typeof Ctor == 'function' &&
  25421. Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
  25422. }
  25423. /**
  25424. * Checks if `value` is classified as a `Symbol` primitive or object.
  25425. *
  25426. * @static
  25427. * @memberOf _
  25428. * @since 4.0.0
  25429. * @category Lang
  25430. * @param {*} value The value to check.
  25431. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  25432. * @example
  25433. *
  25434. * _.isSymbol(Symbol.iterator);
  25435. * // => true
  25436. *
  25437. * _.isSymbol('abc');
  25438. * // => false
  25439. */
  25440. function isSymbol(value) {
  25441. return typeof value == 'symbol' ||
  25442. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  25443. }
  25444. /**
  25445. * Checks if `value` is classified as a typed array.
  25446. *
  25447. * @static
  25448. * @memberOf _
  25449. * @since 3.0.0
  25450. * @category Lang
  25451. * @param {*} value The value to check.
  25452. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  25453. * @example
  25454. *
  25455. * _.isTypedArray(new Uint8Array);
  25456. * // => true
  25457. *
  25458. * _.isTypedArray([]);
  25459. * // => false
  25460. */
  25461. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  25462. /**
  25463. * Converts `value` to a plain object flattening inherited enumerable string
  25464. * keyed properties of `value` to own properties of the plain object.
  25465. *
  25466. * @static
  25467. * @memberOf _
  25468. * @since 3.0.0
  25469. * @category Lang
  25470. * @param {*} value The value to convert.
  25471. * @returns {Object} Returns the converted plain object.
  25472. * @example
  25473. *
  25474. * function Foo() {
  25475. * this.b = 2;
  25476. * }
  25477. *
  25478. * Foo.prototype.c = 3;
  25479. *
  25480. * _.assign({ 'a': 1 }, new Foo);
  25481. * // => { 'a': 1, 'b': 2 }
  25482. *
  25483. * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
  25484. * // => { 'a': 1, 'b': 2, 'c': 3 }
  25485. */
  25486. function toPlainObject(value) {
  25487. return copyObject(value, keysIn(value));
  25488. }
  25489. /**
  25490. * Converts `value` to a string. An empty string is returned for `null`
  25491. * and `undefined` values. The sign of `-0` is preserved.
  25492. *
  25493. * @static
  25494. * @memberOf _
  25495. * @since 4.0.0
  25496. * @category Lang
  25497. * @param {*} value The value to process.
  25498. * @returns {string} Returns the string.
  25499. * @example
  25500. *
  25501. * _.toString(null);
  25502. * // => ''
  25503. *
  25504. * _.toString(-0);
  25505. * // => '-0'
  25506. *
  25507. * _.toString([1, 2, 3]);
  25508. * // => '1,2,3'
  25509. */
  25510. function toString(value) {
  25511. return value == null ? '' : baseToString(value);
  25512. }
  25513. /*------------------------------------------------------------------------*/
  25514. /**
  25515. * Gets the value at `path` of `object`. If the resolved value is
  25516. * `undefined`, the `defaultValue` is returned in its place.
  25517. *
  25518. * @static
  25519. * @memberOf _
  25520. * @since 3.7.0
  25521. * @category Object
  25522. * @param {Object} object The object to query.
  25523. * @param {Array|string} path The path of the property to get.
  25524. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  25525. * @returns {*} Returns the resolved value.
  25526. * @example
  25527. *
  25528. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  25529. *
  25530. * _.get(object, 'a[0].b.c');
  25531. * // => 3
  25532. *
  25533. * _.get(object, ['a', '0', 'b', 'c']);
  25534. * // => 3
  25535. *
  25536. * _.get(object, 'a.b.c', 'default');
  25537. * // => 'default'
  25538. */
  25539. function get(object, path, defaultValue) {
  25540. var result = object == null ? undefined : baseGet(object, path);
  25541. return result === undefined ? defaultValue : result;
  25542. }
  25543. /**
  25544. * Checks if `path` is a direct or inherited property of `object`.
  25545. *
  25546. * @static
  25547. * @memberOf _
  25548. * @since 4.0.0
  25549. * @category Object
  25550. * @param {Object} object The object to query.
  25551. * @param {Array|string} path The path to check.
  25552. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  25553. * @example
  25554. *
  25555. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  25556. *
  25557. * _.hasIn(object, 'a');
  25558. * // => true
  25559. *
  25560. * _.hasIn(object, 'a.b');
  25561. * // => true
  25562. *
  25563. * _.hasIn(object, ['a', 'b']);
  25564. * // => true
  25565. *
  25566. * _.hasIn(object, 'b');
  25567. * // => false
  25568. */
  25569. function hasIn(object, path) {
  25570. return object != null && hasPath(object, path, baseHasIn);
  25571. }
  25572. /**
  25573. * Creates an array of the own enumerable property names of `object`.
  25574. *
  25575. * **Note:** Non-object values are coerced to objects. See the
  25576. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  25577. * for more details.
  25578. *
  25579. * @static
  25580. * @since 0.1.0
  25581. * @memberOf _
  25582. * @category Object
  25583. * @param {Object} object The object to query.
  25584. * @returns {Array} Returns the array of property names.
  25585. * @example
  25586. *
  25587. * function Foo() {
  25588. * this.a = 1;
  25589. * this.b = 2;
  25590. * }
  25591. *
  25592. * Foo.prototype.c = 3;
  25593. *
  25594. * _.keys(new Foo);
  25595. * // => ['a', 'b'] (iteration order is not guaranteed)
  25596. *
  25597. * _.keys('hi');
  25598. * // => ['0', '1']
  25599. */
  25600. function keys(object) {
  25601. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  25602. }
  25603. /**
  25604. * Creates an array of the own and inherited enumerable property names of `object`.
  25605. *
  25606. * **Note:** Non-object values are coerced to objects.
  25607. *
  25608. * @static
  25609. * @memberOf _
  25610. * @since 3.0.0
  25611. * @category Object
  25612. * @param {Object} object The object to query.
  25613. * @returns {Array} Returns the array of property names.
  25614. * @example
  25615. *
  25616. * function Foo() {
  25617. * this.a = 1;
  25618. * this.b = 2;
  25619. * }
  25620. *
  25621. * Foo.prototype.c = 3;
  25622. *
  25623. * _.keysIn(new Foo);
  25624. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  25625. */
  25626. function keysIn(object) {
  25627. return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
  25628. }
  25629. /**
  25630. * This method is like `_.assign` except that it recursively merges own and
  25631. * inherited enumerable string keyed properties of source objects into the
  25632. * destination object. Source properties that resolve to `undefined` are
  25633. * skipped if a destination value exists. Array and plain object properties
  25634. * are merged recursively. Other objects and value types are overridden by
  25635. * assignment. Source objects are applied from left to right. Subsequent
  25636. * sources overwrite property assignments of previous sources.
  25637. *
  25638. * **Note:** This method mutates `object`.
  25639. *
  25640. * @static
  25641. * @memberOf _
  25642. * @since 0.5.0
  25643. * @category Object
  25644. * @param {Object} object The destination object.
  25645. * @param {...Object} [sources] The source objects.
  25646. * @returns {Object} Returns `object`.
  25647. * @example
  25648. *
  25649. * var object = {
  25650. * 'a': [{ 'b': 2 }, { 'd': 4 }]
  25651. * };
  25652. *
  25653. * var other = {
  25654. * 'a': [{ 'c': 3 }, { 'e': 5 }]
  25655. * };
  25656. *
  25657. * _.merge(object, other);
  25658. * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
  25659. */
  25660. var merge = createAssigner(function(object, source, srcIndex) {
  25661. baseMerge(object, source, srcIndex);
  25662. });
  25663. /*------------------------------------------------------------------------*/
  25664. /**
  25665. * This method returns the first argument it receives.
  25666. *
  25667. * @static
  25668. * @since 0.1.0
  25669. * @memberOf _
  25670. * @category Util
  25671. * @param {*} value Any value.
  25672. * @returns {*} Returns `value`.
  25673. * @example
  25674. *
  25675. * var object = { 'a': 1 };
  25676. *
  25677. * console.log(_.identity(object) === object);
  25678. * // => true
  25679. */
  25680. function identity(value) {
  25681. return value;
  25682. }
  25683. /**
  25684. * Creates a function that invokes `func` with the arguments of the created
  25685. * function. If `func` is a property name, the created function returns the
  25686. * property value for a given element. If `func` is an array or object, the
  25687. * created function returns `true` for elements that contain the equivalent
  25688. * source properties, otherwise it returns `false`.
  25689. *
  25690. * @static
  25691. * @since 4.0.0
  25692. * @memberOf _
  25693. * @category Util
  25694. * @param {*} [func=_.identity] The value to convert to a callback.
  25695. * @returns {Function} Returns the callback.
  25696. * @example
  25697. *
  25698. * var users = [
  25699. * { 'user': 'barney', 'age': 36, 'active': true },
  25700. * { 'user': 'fred', 'age': 40, 'active': false }
  25701. * ];
  25702. *
  25703. * // The `_.matches` iteratee shorthand.
  25704. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
  25705. * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
  25706. *
  25707. * // The `_.matchesProperty` iteratee shorthand.
  25708. * _.filter(users, _.iteratee(['user', 'fred']));
  25709. * // => [{ 'user': 'fred', 'age': 40 }]
  25710. *
  25711. * // The `_.property` iteratee shorthand.
  25712. * _.map(users, _.iteratee('user'));
  25713. * // => ['barney', 'fred']
  25714. *
  25715. * // Create custom iteratee shorthands.
  25716. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  25717. * return !_.isRegExp(func) ? iteratee(func) : function(string) {
  25718. * return func.test(string);
  25719. * };
  25720. * });
  25721. *
  25722. * _.filter(['abc', 'def'], /ef/);
  25723. * // => ['def']
  25724. */
  25725. function iteratee(func) {
  25726. return baseIteratee(typeof func == 'function' ? func : baseClone(func, true));
  25727. }
  25728. /**
  25729. * Creates a function that returns the value at `path` of a given object.
  25730. *
  25731. * @static
  25732. * @memberOf _
  25733. * @since 2.4.0
  25734. * @category Util
  25735. * @param {Array|string} path The path of the property to get.
  25736. * @returns {Function} Returns the new accessor function.
  25737. * @example
  25738. *
  25739. * var objects = [
  25740. * { 'a': { 'b': 2 } },
  25741. * { 'a': { 'b': 1 } }
  25742. * ];
  25743. *
  25744. * _.map(objects, _.property('a.b'));
  25745. * // => [2, 1]
  25746. *
  25747. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  25748. * // => [1, 2]
  25749. */
  25750. function property(path) {
  25751. return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
  25752. }
  25753. /**
  25754. * This method returns a new empty array.
  25755. *
  25756. * @static
  25757. * @memberOf _
  25758. * @since 4.13.0
  25759. * @category Util
  25760. * @returns {Array} Returns the new empty array.
  25761. * @example
  25762. *
  25763. * var arrays = _.times(2, _.stubArray);
  25764. *
  25765. * console.log(arrays);
  25766. * // => [[], []]
  25767. *
  25768. * console.log(arrays[0] === arrays[1]);
  25769. * // => false
  25770. */
  25771. function stubArray() {
  25772. return [];
  25773. }
  25774. /**
  25775. * This method returns `false`.
  25776. *
  25777. * @static
  25778. * @memberOf _
  25779. * @since 4.13.0
  25780. * @category Util
  25781. * @returns {boolean} Returns `false`.
  25782. * @example
  25783. *
  25784. * _.times(2, _.stubFalse);
  25785. * // => [false, false]
  25786. */
  25787. function stubFalse() {
  25788. return false;
  25789. }
  25790. /*------------------------------------------------------------------------*/
  25791. // Add methods that return wrapped values in chain sequences.
  25792. lodash.compact = compact;
  25793. lodash.iteratee = iteratee;
  25794. lodash.keys = keys;
  25795. lodash.keysIn = keysIn;
  25796. lodash.memoize = memoize;
  25797. lodash.merge = merge;
  25798. lodash.property = property;
  25799. lodash.toPlainObject = toPlainObject;
  25800. /*------------------------------------------------------------------------*/
  25801. // Add methods that return unwrapped values in chain sequences.
  25802. lodash.clone = clone;
  25803. lodash.eq = eq;
  25804. lodash.forEach = forEach;
  25805. lodash.get = get;
  25806. lodash.hasIn = hasIn;
  25807. lodash.identity = identity;
  25808. lodash.isArguments = isArguments;
  25809. lodash.isArray = isArray;
  25810. lodash.isArrayLike = isArrayLike;
  25811. lodash.isArrayLikeObject = isArrayLikeObject;
  25812. lodash.isBuffer = isBuffer;
  25813. lodash.isEmpty = isEmpty;
  25814. lodash.isFunction = isFunction;
  25815. lodash.isLength = isLength;
  25816. lodash.isObject = isObject;
  25817. lodash.isObjectLike = isObjectLike;
  25818. lodash.isPlainObject = isPlainObject;
  25819. lodash.isSymbol = isSymbol;
  25820. lodash.isTypedArray = isTypedArray;
  25821. lodash.stubArray = stubArray;
  25822. lodash.stubFalse = stubFalse;
  25823. lodash.toString = toString;
  25824. // Add aliases.
  25825. lodash.each = forEach;
  25826. /*------------------------------------------------------------------------*/
  25827. /**
  25828. * The semantic version number.
  25829. *
  25830. * @static
  25831. * @memberOf _
  25832. * @type {string}
  25833. */
  25834. lodash.VERSION = VERSION;
  25835. /*--------------------------------------------------------------------------*/
  25836. if (freeModule) {
  25837. // Export for Node.js.
  25838. (freeModule.exports = lodash)._ = lodash;
  25839. // Export for CommonJS support.
  25840. freeExports._ = lodash;
  25841. }
  25842. }.call(this));
  25843. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25844. },{}],179:[function(require,module,exports){
  25845. const strsearch2regexp = require('strsearch2regexp')
  25846. const filterJoin = require('./filterJoin')
  25847. function qlesc (str) {
  25848. return '"' + str.replace(/"/g, '\\"') + '"'
  25849. }
  25850. function compile (part) {
  25851. if (Array.isArray(part)) {
  25852. return part.map(compile).join('')
  25853. }
  25854. if (part.or) {
  25855. return { or: part.or.map(compile) }
  25856. }
  25857. let keyRegexp = (part.keyRegexp ? '~' : '')
  25858. switch (part.op) {
  25859. case 'has_key':
  25860. if (keyRegexp) {
  25861. return '[~' + qlesc(part.key) + '~"."]'
  25862. } else {
  25863. return '[' + keyRegexp + qlesc(part.key) + ']'
  25864. }
  25865. case '=':
  25866. case '!=':
  25867. case '~':
  25868. case '!~':
  25869. return '[' + keyRegexp + qlesc(part.key) + part.op + qlesc(part.value) + ']'
  25870. case '~i':
  25871. case '!~i':
  25872. return '[' + keyRegexp + qlesc(part.key) + part.op.substr(0, part.op.length - 1) + qlesc(part.value) + ',i]'
  25873. case 'has':
  25874. return '[' + keyRegexp + qlesc(part.key) + '~' + qlesc('^(.*;|)' + part.value + '(|;.*)$') + ']'
  25875. case 'strsearch':
  25876. return '[' + keyRegexp + qlesc(part.key) + '~' + qlesc(strsearch2regexp(part.value)) + ',i]'
  25877. default:
  25878. throw new Error('unknown operator')
  25879. }
  25880. }
  25881. function test (ob, part) {
  25882. if (Array.isArray(part)) {
  25883. return part.every(part => test(ob, part))
  25884. }
  25885. if (part.type) {
  25886. return ob.type === part.type
  25887. }
  25888. if (part.or) {
  25889. return part.or.some(part => test(ob, part))
  25890. }
  25891. if (part.keyRegexp) {
  25892. let regex
  25893. if (part.value) {
  25894. regex = new RegExp(part.value, part.op.match(/i$/) ? 'i' : '')
  25895. }
  25896. for (let k in ob.tags) {
  25897. if (k.match(part.key)) {
  25898. if (regex) {
  25899. if (ob.tags[k].match(regex)) {
  25900. return true
  25901. }
  25902. } else {
  25903. return true
  25904. }
  25905. }
  25906. }
  25907. return false
  25908. }
  25909. switch (part.op) {
  25910. case 'has_key':
  25911. return ob.tags && (part.key in ob.tags)
  25912. case '=':
  25913. return ob.tags && (part.key in ob.tags) && (ob.tags[part.key] === part.value)
  25914. case '!=':
  25915. return ob.tags && (!(part.key in ob.tags) || (ob.tags[part.key] !== part.value))
  25916. case '~':
  25917. return ob.tags && (part.key in ob.tags) && (ob.tags[part.key].match(part.value))
  25918. case '!~':
  25919. return ob.tags && (!(part.key in ob.tags) || (!ob.tags[part.key].match(part.value)))
  25920. case '~i':
  25921. return ob.tags && (part.key in ob.tags) && (ob.tags[part.key].match(new RegExp(part.value, 'i')))
  25922. case '!~i':
  25923. return ob.tags && (!(part.key in ob.tags) || !ob.tags[part.key].match(new RegExp(part.value, 'i')))
  25924. case 'has':
  25925. return ob.tags && (part.key in ob.tags) && (ob.tags[part.key].split(/;/).indexOf(part.value) !== -1)
  25926. case 'strsearch':
  25927. return ob.tags && (part.key in ob.tags) && (ob.tags[part.key].match(new RegExp(strsearch2regexp(part.value), 'i')))
  25928. default:
  25929. return false
  25930. }
  25931. }
  25932. function parseString (str) {
  25933. let result = ''
  25934. let chr = str[0]
  25935. str = str.slice(1)
  25936. while (str.length) {
  25937. let m = str.match('^[^\\\\' + chr + ']+')
  25938. if (m) {
  25939. result += m[0]
  25940. str = str.slice(m[0].length)
  25941. } else if (str[0] === '\\') {
  25942. result += str[1]
  25943. str = str.slice(2)
  25944. } else if (str[0] === chr) {
  25945. str = str.slice(1)
  25946. return [ result, str ]
  25947. } else {
  25948. throw new Error("Can't parse string from query: " + str)
  25949. }
  25950. }
  25951. }
  25952. function parse (def) {
  25953. let result = []
  25954. let mode = 0
  25955. let key
  25956. let value
  25957. let op
  25958. let m
  25959. let keyRegexp = false
  25960. while (def.length) {
  25961. if (mode === 0) {
  25962. m = def.match(/^\s*(node|way|relation|rel|nwr|\()/)
  25963. if (m && m[1] === '(') {
  25964. def = def.slice(m[0].length)
  25965. let parts = []
  25966. do {
  25967. let part
  25968. [ part, def ] = parse(def)
  25969. parts.push(part)
  25970. } while (!def.match(/^\s*\)/))
  25971. return [ { or: parts }, def ]
  25972. } else if (m) {
  25973. if (m[1] === 'rel') {
  25974. result.push({ type: 'relation' })
  25975. } else if (m[1] === 'nwr') {
  25976. // nothing
  25977. } else {
  25978. result.push({ type: m[1] })
  25979. }
  25980. mode = 10
  25981. def = def.slice(m[0].length)
  25982. } else {
  25983. throw new Error("Can't parse query, expected type of object (e.g. 'node'): " + def)
  25984. }
  25985. } else if (mode === 10) {
  25986. let m = def.match(/^\s*(\[|;)/)
  25987. if (m && m[1] === '[') {
  25988. def = def.slice(m[0].length)
  25989. mode = 11
  25990. } else if (m && m[1] === ';') {
  25991. def = def.slice(m[0].length)
  25992. return [ result, def ]
  25993. } else if (!m && def.match(/^\s*$/)) {
  25994. return [ result, '' ]
  25995. } else {
  25996. throw new Error("Can't parse query, expected '[' or ';': " + def)
  25997. }
  25998. } else if (mode === 11) {
  25999. m = def.match(/^(\s*)(~\s*)?([a-zA-Z0-9_]+|"|')/)
  26000. if (m && m[2]) {
  26001. keyRegexp = true
  26002. }
  26003. if (m && (m[3] === '"' || m[3] === "'")) {
  26004. def = def.slice(m[1].length + (m[2] || '').length)
  26005. let x = parseString(def)
  26006. key = x[0]
  26007. def = x[1]
  26008. mode = 12
  26009. } else if (m) {
  26010. key = m[3]
  26011. def = def.slice(m[0].length)
  26012. mode = 12
  26013. } else {
  26014. throw new Error("Can't parse query, expected key: " + def)
  26015. }
  26016. } else if (mode === 12) {
  26017. m = def.match(/^\s*(=|!=|~|!~|\^|]|%)/)
  26018. if (m && m[1] === ']') {
  26019. let entry = { key, op: 'has_key' }
  26020. if (keyRegexp) {
  26021. entry.keyRegexp = true
  26022. }
  26023. result.push(entry)
  26024. def = def.slice(m[0].length)
  26025. mode = 10
  26026. } else if (m) {
  26027. op = m[1] === '^' ? 'has'
  26028. : m[1] === '%' ? 'strsearch'
  26029. : m[1]
  26030. mode = 13
  26031. def = def.slice(m[0].length)
  26032. } else {
  26033. throw new Error("Can't parse query, expected operator or ']': " + def)
  26034. }
  26035. } else if (mode === 13) {
  26036. m = def.match(/^(\s*)([a-zA-Z0-9_]+|"|')/)
  26037. if (m && (m[2] === '"' || m[2] === "'")) {
  26038. def = def.slice(m[1].length)
  26039. let x = parseString(def)
  26040. value = x[0]
  26041. def = x[1]
  26042. mode = 14
  26043. } else if (m) {
  26044. value = m[2]
  26045. def = def.slice(m[0].length)
  26046. mode = 14
  26047. } else {
  26048. throw new Error("Can't parse query, expected value: " + def)
  26049. }
  26050. } else if (mode === 14) {
  26051. m = def.match(/^\s*(,i)?\]/)
  26052. if (m) {
  26053. if (m[1] === ',i') {
  26054. if (op === '~' || op === '!~') {
  26055. op += 'i'
  26056. } else {
  26057. throw new Error("Can't parse query, expected ']': " + def)
  26058. }
  26059. }
  26060. let entry = { key, op, value }
  26061. if (keyRegexp) {
  26062. entry.keyRegexp = true
  26063. }
  26064. result.push(entry)
  26065. mode = 10
  26066. def = def.slice(m[0].length)
  26067. } else {
  26068. throw new Error("Can't parse query, expected ']': " + def)
  26069. }
  26070. }
  26071. }
  26072. return [ result, def ]
  26073. }
  26074. /**
  26075. * A Filter into OSM data. A simplified version of <a href='https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL'>Overpass QL</a>.
  26076. *
  26077. * <p>Either a single query (e.g. <tt>node[amenity=restaurant];</tt>) or a combined query (e.g. <tt>(node[amenity=restaurant];way[amenity=restaurant];);</tt>).<br>
  26078. * A single query statement consists of a type (e.g. 'node', 'way', 'relation', 'nwr' (node, way or relation)) and optional filters:<ul>
  26079. * <li>(Not) Equals (=, !=): <tt>[amenity=restaurant]</tt> or <tt>["amenity"="restaurant"]</tt> resp. <tt>["amenity"!="restaurant"]</tt>.
  26080. * <li>Regular Expression: <tt>[amenity~"^(restaurant|cafe)$"]</tt> resp. negated: <tt>[amenity!~"^(restaurant|cafe)$"]</tt>
  26081. * <li>Key regular expression: <tt>[~"cycleway"~"left"]</tt> (key has to match cycleway and its value match left)
  26082. * <li>Key (not) exists: <tt>[amenity]</tt> or <tt>["amenity"]</tt> resp. <tt>[!amenity]</tt>
  26083. * <li>Array search: <tt>[cuisine^kebap]</tt>: search for cuisine tags which exactly include 'kebap' (semicolon-separated values, e.g. <tt>cuisine=kebap;pizza</tt>).
  26084. * <li>String search: <tt>[name%cafe]</tt>: search for name tags which are similar to cafe, e.g. "café". (see https://github.com/plepe/strsearch2regexp for details).
  26085. * </ul>
  26086. * More advanced queries are not supported.</p>
  26087. *
  26088. * @param {string|object} query
  26089. */
  26090. class Filter {
  26091. constructor (def) {
  26092. if (typeof def === 'string') {
  26093. [ this.def ] = parse(def)
  26094. return
  26095. }
  26096. this.def = def
  26097. }
  26098. /**
  26099. * Check if an object matches this filter
  26100. * @param {OverpassNode|OverpassWay|OverpassRelation} ob an object from Overpass API
  26101. * @return {boolean}
  26102. */
  26103. match (ob, def) {
  26104. if (!def) {
  26105. def = this.def
  26106. }
  26107. if (def.or) {
  26108. return def.or.some(part => this.match(ob, part))
  26109. }
  26110. return def.filter(test.bind(this, ob)).length === def.length
  26111. }
  26112. /**
  26113. * Convert query to a string representation
  26114. * @return {string}
  26115. */
  26116. toString (def) {
  26117. let result = ''
  26118. if (!def) {
  26119. def = this.def
  26120. }
  26121. if (def.or) {
  26122. return '(' + def.or.map(part => this.toString(part)).join(';') + ';)'
  26123. }
  26124. let parts = def.filter(part => part.type)
  26125. switch (parts.length) {
  26126. case 0:
  26127. result = 'nwr'
  26128. break
  26129. case 1:
  26130. result = parts[0].type
  26131. break
  26132. default:
  26133. throw new Error('Filter: only one type query allowed!')
  26134. }
  26135. let queries = filterJoin(def
  26136. .filter(part => !part.type)
  26137. .map(compile))
  26138. if (queries.length > 1) {
  26139. return '(' + queries.map(q => result + q).join(';') + ';)'
  26140. } else {
  26141. return result + queries[0]
  26142. }
  26143. }
  26144. /**
  26145. * Convert query to Overpass QL
  26146. * @param {object} [options] Additional options
  26147. * @param {string} [options.inputSet=''] Specify input set (e.g.'.foo').
  26148. * @return {string}
  26149. */
  26150. toQl (options = {}, def) {
  26151. if (!def) {
  26152. def = this.def
  26153. }
  26154. if (!options.inputSet) {
  26155. options.inputSet = ''
  26156. }
  26157. if (def.or) {
  26158. return '(' + def.or.map(part => {
  26159. let r = this.toQl(options, part)
  26160. return r.slice(1, -1)
  26161. }).join('') + ')'
  26162. }
  26163. let parts = def.filter(part => part.type)
  26164. let types
  26165. switch (parts.length) {
  26166. case 0:
  26167. types = [ 'node', 'way', 'relation' ]
  26168. break
  26169. case 1:
  26170. types = [ parts[0].type ]
  26171. break
  26172. default:
  26173. throw new Error('Filter: only one type query allowed!')
  26174. }
  26175. let queries = filterJoin(def
  26176. .filter(part => !part.type)
  26177. .map(compile))
  26178. if (queries.length > 1) {
  26179. return '(' + queries.map(q => types.map(type => type + options.inputSet + q).join(';')).join(';') + ';)'
  26180. } else {
  26181. return '(' + types.map(type => type + options.inputSet + queries[0]).join(';') + ';)'
  26182. }
  26183. }
  26184. /**
  26185. * Convert query to LokiJS query for local database. If the property 'needMatch' is set on the returned object, an additional match() should be executed for each returned object, as the query can't be fully compiled (and the 'needMatch' property removed).
  26186. * @param {object} [options] Additional options
  26187. * @return {object}
  26188. */
  26189. toLokijs (options = {}, def) {
  26190. if (!def) {
  26191. def = this.def
  26192. }
  26193. if (def.or) {
  26194. let needMatch = false
  26195. let r = { $or:
  26196. def.or.map(part => {
  26197. let r = this.toLokijs(options, part)
  26198. if (r.needMatch) {
  26199. needMatch = true
  26200. }
  26201. delete r.needMatch
  26202. return r
  26203. })
  26204. }
  26205. if (needMatch) {
  26206. r.needMatch = true
  26207. }
  26208. return r
  26209. }
  26210. let query = {}
  26211. let orQueries = []
  26212. if (!Array.isArray(def)) {
  26213. def = [ def ]
  26214. }
  26215. def.forEach(filter => {
  26216. let k, v
  26217. if (filter.keyRegexp) {
  26218. k = 'needMatch'
  26219. v = true
  26220. // can't query for key regexp, skip
  26221. } else if (filter.op === '=') {
  26222. k = 'tags.' + filter.key
  26223. v = { $eq: filter.value }
  26224. } else if (filter.op === '!=') {
  26225. k = 'tags.' + filter.key
  26226. v = { $ne: filter.value }
  26227. } else if (filter.op === 'has_key') {
  26228. k = 'tags.' + filter.key
  26229. v = { $exists: true }
  26230. } else if (filter.op === 'has') {
  26231. k = 'tags.' + filter.key
  26232. v = { $regex: '^(.*;|)' + filter.value + '(|;.*)$' }
  26233. } else if ((filter.op === '~') || (filter.op === '~i')) {
  26234. k = 'tags.' + filter.key
  26235. v = { $regex: new RegExp(filter.value, (filter.op === '~i' ? 'i' : '')) }
  26236. } else if ((filter.op === '!~') || (filter.op === '!~i')) {
  26237. k = 'tags.' + filter.key
  26238. v = { $not: { $regex: new RegExp(filter.value, (filter.op === '!~i' ? 'i' : '')) } }
  26239. } else if (filter.op === 'strsearch') {
  26240. k = 'tags.' + filter.key
  26241. v = { $regex: new RegExp(strsearch2regexp(filter.value), 'i') }
  26242. } else if (filter.type) {
  26243. k = 'type'
  26244. v = { $eq: filter.type }
  26245. } else if (filter.or) {
  26246. orQueries.push(filter.or.map(p => {
  26247. let r = this.toLokijs(options, p)
  26248. if (r.needMatch) {
  26249. query.needMatch = true
  26250. delete r.needMatch
  26251. }
  26252. return r
  26253. }))
  26254. } else {
  26255. console.log('unknown filter', filter)
  26256. }
  26257. if (k && v) {
  26258. if (k === 'needMatch') {
  26259. query.needMatch = true
  26260. } else if (k in query) {
  26261. if (!('$and' in query[k])) {
  26262. query[k] = { $and: [ query[k] ] }
  26263. }
  26264. query[k].$and.push(v)
  26265. } else {
  26266. query[k] = v
  26267. }
  26268. }
  26269. })
  26270. orQueries = orQueries.filter(q => Object.keys(q).length)
  26271. if (orQueries.length === 1) {
  26272. query.$or = orQueries[0]
  26273. } else if (orQueries.length > 1) {
  26274. query.$and = orQueries.map(q => { return { $or: q } })
  26275. }
  26276. return query
  26277. }
  26278. }
  26279. module.exports = Filter
  26280. },{"./filterJoin":194,"strsearch2regexp":205}],180:[function(require,module,exports){
  26281. (function (global){
  26282. const ee = require('event-emitter')
  26283. var async = require('async')
  26284. var weightSort = require('weight-sort')
  26285. var BoundingBox = require('boundingbox')
  26286. const LokiJS = require('lokijs')
  26287. var httpLoad = require('./httpLoad')
  26288. var removeNullEntries = require('./removeNullEntries')
  26289. var OverpassObject = require('./OverpassObject')
  26290. var OverpassNode = require('./OverpassNode')
  26291. var OverpassWay = require('./OverpassWay')
  26292. var OverpassRelation = require('./OverpassRelation')
  26293. var RequestGet = require('./RequestGet')
  26294. var RequestBBox = require('./RequestBBox')
  26295. var defines = require('./defines')
  26296. var loadOsmFile = require('./loadOsmFile')
  26297. var copyOsm3sMetaFrom = require('./copyOsm3sMeta')
  26298. const Filter = require('./Filter')
  26299. /**
  26300. * An error occured
  26301. * @event OverpassFrontend#error
  26302. * @param {Error} error
  26303. */
  26304. /**
  26305. * When a file is specified as URL, this event notifies, that the file has been completely loaded. When a Overpass API is used, every time when data has been received.
  26306. * @event OverpassFrontend#load
  26307. * @param {object} osm3sMeta Meta data (not all properties of meta data might be set)
  26308. * @param {number} osm3sMeta.version OpenStreetMap API version (currently 0.6)
  26309. * @param {string} osm3sMeta.generator Data generator
  26310. * @param {string} osm3sMeta.timestamp_osm_base RFC8601 timestamp of OpenStreetMap data
  26311. * @param {string} osm3sMeta.copyright Copyright statement
  26312. */
  26313. /**
  26314. * When an object is updated (e.g. when loaded; additional information loaded; when a member object got loaded)
  26315. * @event OverpassFrontend#update
  26316. * @param {OverpassNode|OverpassWay|OverpassRelation} object The object which got updated.
  26317. */
  26318. /**
  26319. * A connection to an Overpass API Server or an OpenStreetMap file
  26320. * @param {string} url The URL of the API, e.g. 'https://overpass-api.de/api/'. If you omit the protocol, it will use the protocol which is in use for the current page (or https: on nodejs): '//overpass-api.de/api/'. If the url ends in .json, .osm or .osm.bz2 it will load this OpenStreetMap file and use the data from there.
  26321. * @param {object} options Options
  26322. * @param {number} [options.effortPerRequest=1000] To avoid huge requests to the Overpass API, the request will be split into smaller chunks. This value defines, at which effort the request will be sent.
  26323. * @param {number} [options.effortNode=1] The effort for request a node. Default: 1.
  26324. * @param {number} [options.effortWay=4] The effort for request a way.
  26325. * @param {number} [options.effortRelation=64] The effort for request a relation.
  26326. * @param {number} [options.timeGap=10] A short time gap between two requests to the Overpass API (milliseconds).
  26327. * @param {number} [options.loadChunkSize=1000] When loading a file (instead connecting to an Overpass URL) load elements in chunks of n items.
  26328. */
  26329. class OverpassFrontend {
  26330. constructor (url, options) {
  26331. this.url = url
  26332. this.options = {
  26333. effortPerRequest: 1000,
  26334. effortNode: 1,
  26335. effortWay: 4,
  26336. effortRelation: 64,
  26337. timeGap: 10,
  26338. loadChunkSize: 1000
  26339. }
  26340. for (var k in options) {
  26341. this.options[k] = options[k]
  26342. }
  26343. let db = new LokiJS()
  26344. this.db = db.addCollection('osm', { unique: [ 'id' ] })
  26345. this.clearCache()
  26346. this.requests = []
  26347. this.requestIsActive = false
  26348. this.errorCount = 0
  26349. this.pendingNotifyMemberUpdate = {}
  26350. this.pendingUpdateEmit = {}
  26351. if (this.url.match(/\.(json|osm\.bz2|osm)$/)) {
  26352. this.localOnly = true
  26353. this.ready = false
  26354. this._loadFile()
  26355. } else {
  26356. this.remote = true
  26357. this.ready = true
  26358. }
  26359. }
  26360. /**
  26361. * clear all caches
  26362. */
  26363. clearCache () {
  26364. this.cacheElements = {}
  26365. this.cacheElementsMemberOf = {}
  26366. this.cacheBBoxQueries = {}
  26367. this.db.clear()
  26368. }
  26369. _loadFile () {
  26370. let osm3sMeta
  26371. loadOsmFile(this.url,
  26372. (err, result) => {
  26373. if (err) {
  26374. console.log('Error loading file', err)
  26375. return this.emit('error', err)
  26376. }
  26377. osm3sMeta = copyOsm3sMetaFrom(result)
  26378. let chunks = []
  26379. for (var i = 0; i < result.elements.length; i += this.options.loadChunkSize) {
  26380. chunks.push(result.elements.slice(i, i + this.options.loadChunkSize))
  26381. }
  26382. async.eachLimit(
  26383. chunks,
  26384. 1,
  26385. (chunk, done) => {
  26386. chunk.forEach(
  26387. (element) => {
  26388. let ob = this.createOrUpdateOSMObject(element, {
  26389. osm3sMeta,
  26390. properties: OverpassFrontend.TAGS | OverpassFrontend.META | OverpassFrontend.MEMBERS
  26391. })
  26392. // Set objects to fully known, as no more data can be loaded from the file
  26393. ob.properties |= OverpassFrontend.ALL
  26394. }
  26395. )
  26396. global.setTimeout(done, 0)
  26397. },
  26398. (err) => {
  26399. this.pendingNotifies()
  26400. if (err) {
  26401. console.log('Error loading file', err)
  26402. return this.emit('error', err)
  26403. }
  26404. this.emit('load', osm3sMeta)
  26405. this.ready = true
  26406. this._overpassProcess()
  26407. }
  26408. )
  26409. }
  26410. )
  26411. }
  26412. /**
  26413. * @param {string|string[]} ids - Id or array of Ids of OSM map features, e.g. [ 'n123', 'w2345', 'n123' ]. Illegal IDs will not produce an error but generate a 'null' object.
  26414. * @param {object} options Various options, see below
  26415. * @param {number} [options.priority=0] - Priority for loading these objects. The lower the sooner they will be requested.
  26416. * @param {string|boolean} [options.sort=false] - When set to true or "index", the function featureCallback will be called in order of the "ids" array. When set to false or null, the featureCallback will be called as soon as the object is loaded (e.g. immediately, if it is cached). When set to "BBoxDiagonalLength", the objects are ordered by the length of the diagonal of the bounding box.
  26417. * @param {"asc"|"desc"} [options.sortDir="asc"] Sort direction.
  26418. * @param {function} featureCallback Will be called for each object which is passed in parameter 'ids'. Will be passed: 1. err (if an error occured, otherwise null), 2. the object or null, 3. index of the item in parameter ids.
  26419. * @param {function} finalCallback Will be called after the last feature. Will be passed: 1. err (if an error occured, otherwise null).
  26420. * @return {RequestGet}
  26421. */
  26422. get (ids, options, featureCallback, finalCallback) {
  26423. var request = new RequestGet(this, {
  26424. ids: ids,
  26425. options: options,
  26426. featureCallback: featureCallback,
  26427. finalCallback: finalCallback
  26428. })
  26429. this.requests.push(request)
  26430. this._next()
  26431. return request
  26432. }
  26433. /**
  26434. * return an OSM object, if it is already in the cache
  26435. * @param {string} id - Id of an OSM map feature
  26436. * @param {object} options
  26437. * @param {int} [options.properties] - Which properties have to be known (default: OverpassFrontend.DEFAULT)
  26438. * @return {null|false|OverpassObject} - null: does not exist in the database; false: may exist, but has not been loaded yet (or not enough properties known); OverpassObject: sucessful object
  26439. */
  26440. getCached (id, options) {
  26441. if (typeof options === 'undefined') {
  26442. options = {}
  26443. }
  26444. if (typeof options.properties === 'undefined') {
  26445. options.properties = defines.DEFAULT
  26446. }
  26447. if (!(id in this.cacheElements)) {
  26448. return false
  26449. }
  26450. let ob = this.cacheElements[id]
  26451. if (ob.missingObject) {
  26452. return null
  26453. }
  26454. if ((options.properties & ob.properties) !== options.properties) {
  26455. return false
  26456. }
  26457. return ob
  26458. }
  26459. /**
  26460. * Current request context
  26461. * @typedef {Object} OverpassFrontend#Context
  26462. * @property {string} query - The compiled code of all sub requests
  26463. * @property {Request[]} requests - List of all requests in the context
  26464. * @property {Request#SubRequest[]} subRequests - List of all subRequests in the context
  26465. * @property {BoundingBox} bbox - when there are any BBox requests, add this global bbox
  26466. * @property {int} maxEffort - how many queries can we still add to this context
  26467. * @property {object} todo - list of items which should be loaded via get requests to avoid duplicates
  26468. */
  26469. _overpassProcess () {
  26470. // currently active - we'll come back later :-)
  26471. if (this.requestIsActive || !this.ready) {
  26472. return
  26473. }
  26474. // preprocess all requests
  26475. // e.g. call featureCallback for elements which were received in the
  26476. // meantime
  26477. this.requests.forEach(request => {
  26478. if (request) {
  26479. request.preprocess()
  26480. if (request.mayFinish() || this.localOnly) {
  26481. request.finish()
  26482. }
  26483. }
  26484. })
  26485. this.requests = removeNullEntries(this.requests)
  26486. // nothing todo ...
  26487. if (!this.requests.length) {
  26488. return
  26489. }
  26490. // now order all requests by priority
  26491. this.requests = weightSort(this.requests, 'priority')
  26492. this.requestIsActive = true
  26493. var request
  26494. var j
  26495. var context = {
  26496. bbox: null,
  26497. todo: {},
  26498. requests: [],
  26499. subRequests: [],
  26500. query: '',
  26501. minPriority: this.requests[0].priority,
  26502. minEffort: 0,
  26503. maxEffort: 0
  26504. }
  26505. for (j = 0; j < this.requests.length; j++) {
  26506. request = this.requests[j]
  26507. if (request.priority > context.minPriority &&
  26508. (context.maxEffort === null || context.maxEffort > this.options.effortPerRequest)) {
  26509. break
  26510. }
  26511. if (request.willInclude(context)) {
  26512. let { minEffort, maxEffort } = request.minMaxEffort()
  26513. if (context.minEffort > 0 && context.minEffort + minEffort > this.options.effortPerRequest) {
  26514. continue
  26515. }
  26516. context.minEffort += minEffort
  26517. if (maxEffort === null) {
  26518. context.maxEffort = null
  26519. } else if (context.maxEffort !== null) {
  26520. context.maxEffort += maxEffort
  26521. }
  26522. context.requests.push(request)
  26523. }
  26524. }
  26525. var effortAvailable = this.options.effortPerRequest
  26526. for (j = 0; j < context.requests.length; j++) {
  26527. request = context.requests[j]
  26528. let remainingRequestsAtPriority = context.requests.slice(j).filter(r => r.priority === request.priority)
  26529. context.maxEffort = Math.ceil(effortAvailable / remainingRequestsAtPriority.length)
  26530. var subRequest = request.compileQuery(context)
  26531. if (subRequest.parts.length === 0) {
  26532. console.log('subRequest has no parts! Why was willInclude true?', subRequest)
  26533. continue
  26534. }
  26535. context.subRequests.push(subRequest)
  26536. if (context.query !== '') {
  26537. context.query += '\nout count;\n'
  26538. }
  26539. effortAvailable -= subRequest.effort
  26540. context.query += subRequest.query
  26541. if (effortAvailable <= 0) {
  26542. break
  26543. }
  26544. }
  26545. if (context.query === '') {
  26546. return this._next()
  26547. }
  26548. var query = '[out:json]'
  26549. if (context.bbox) {
  26550. query += '[bbox:' + context.bbox.toLatLonString() + ']'
  26551. }
  26552. query += ';\n' + context.query
  26553. setTimeout(function () {
  26554. httpLoad(
  26555. this.url,
  26556. null,
  26557. query,
  26558. this._handleResult.bind(this, context)
  26559. )
  26560. }.bind(this), this.options.timeGap)
  26561. }
  26562. _handleResult (context, err, results) {
  26563. this.requestIsActive = false
  26564. if (err === null && results.remark) {
  26565. err = results.remark
  26566. }
  26567. if (err !== null) {
  26568. this.errorCount++
  26569. if (this.errorCount <= 3) {
  26570. // retry
  26571. this._overpassProcess()
  26572. } else {
  26573. // abort
  26574. // call finalCallback for the request
  26575. context.subRequests.forEach(function (subRequest) {
  26576. subRequest.request.finish(err)
  26577. })
  26578. }
  26579. return
  26580. } else {
  26581. this.errorCount = 0
  26582. }
  26583. let osm3sMeta = copyOsm3sMetaFrom(results)
  26584. this.emit('load', osm3sMeta)
  26585. var subRequestsIndex = 0
  26586. var partIndex = 0
  26587. var subRequest = context.subRequests[0]
  26588. var request = subRequest.request
  26589. var part = subRequest.parts[0]
  26590. if (!('count' in part)) {
  26591. part.count = 0
  26592. }
  26593. for (var i = 0; i < results.elements.length; i++) {
  26594. var el = results.elements[i]
  26595. if (isSeparator(el)) {
  26596. partIndex++
  26597. if (partIndex >= subRequest.parts.length) {
  26598. request.finishSubRequest(subRequest)
  26599. if (request.mayFinish() && !request.finished) {
  26600. request.finish()
  26601. }
  26602. subRequestsIndex++
  26603. partIndex = 0
  26604. subRequest = context.subRequests[subRequestsIndex]
  26605. request = subRequest.request
  26606. part = subRequest.parts[0]
  26607. if (!('count' in part)) {
  26608. part.count = 0
  26609. }
  26610. } else {
  26611. part = subRequest.parts[partIndex]
  26612. }
  26613. continue
  26614. }
  26615. part.osm3sMeta = osm3sMeta
  26616. var ob = this.createOrUpdateOSMObject(el, part)
  26617. delete context.todo[ob.id]
  26618. var members = this.cacheElements[ob.id].memberIds()
  26619. if (members) {
  26620. for (var j = 0; j < members.length; j++) {
  26621. if (!(members[j] in this.cacheElementsMemberOf)) {
  26622. this.cacheElementsMemberOf[members[j]] = [ this.cacheElements[ob.id] ]
  26623. } else {
  26624. this.cacheElementsMemberOf[members[j]].push(this.cacheElements[ob.id])
  26625. }
  26626. }
  26627. }
  26628. part.count++
  26629. if (part.receiveObject) {
  26630. part.receiveObject(ob)
  26631. }
  26632. if (!request.aborted && !request.finished && part.featureCallback) {
  26633. part.featureCallback(err, ob)
  26634. }
  26635. }
  26636. if (!(subRequestsIndex === context.subRequests.length - 1 || partIndex === context.subRequests[subRequestsIndex].parts.length - 1)) {
  26637. console.log('too many parts!!!!')
  26638. }
  26639. for (var id in context.todo) {
  26640. if (!(id in this.cacheElements)) {
  26641. let ob = new OverpassObject()
  26642. ob.id = id
  26643. ob.type = { n: 'node', w: 'way', r: 'relation' }[id.substr(0, 1)]
  26644. ob.osm_id = id.substr(1)
  26645. ob.properties = OverpassFrontend.ALL
  26646. ob.missingObject = true
  26647. this.cacheElements[id] = ob
  26648. this.db.insert(ob.dbInsert())
  26649. } else {
  26650. let ob = this.cacheElements[id]
  26651. ob.missingObject = true
  26652. this.db.update(ob.dbInsert())
  26653. }
  26654. }
  26655. this.pendingNotifies()
  26656. request.finishSubRequest(subRequest)
  26657. this._next()
  26658. }
  26659. /**
  26660. * @param {string} query - Query for requesting objects from Overpass API, e.g. "node[amenity=restaurant]" or "(node[amenity];way[highway~'^(primary|secondary)$];)". See <a href='Filter.html'>Filter</a> for details.
  26661. * @param {BoundingBox} bounds - A Leaflet Bounds object, e.g. from map.getBounds()
  26662. * @param {object} options
  26663. * @param {number} [options.priority=0] - Priority for loading these objects. The lower the sooner they will be requested.
  26664. * @param {boolean|string} [options.sort=false] - If false, it will be called as soon as the features are availabe (e.g. immediately when cached).
  26665. * @param {bit_array} [options.properties] Which properties of the features should be downloaded: OVERPASS_ID_ONLY, OVERPASS_BBOX, OVERPASS_TAGS, OVERPASS_GEOM, OVERPASS_META. Combine by binary OR: ``OVERPASS_ID | OVERPASS_BBOX``. Default: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.BBOX
  26666. * @param {number} [options.split=0] If more than 'split' elements would be returned, split into several smaller requests, with 'split' elements each. Default: 0 (do not split)
  26667. * @param {boolean} [options.members=false] Query relation members of. Default: false
  26668. * @param {function} [options.memberCallback] For every member, call this callback function. (Requires options.members=true)
  26669. * @param {bit_array} [options.memberProperties] Which properties should be loaded for the members. Default: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.BBOX
  26670. * @param {number} [options.memberSplit=0] If more than 'memberSplit' member elements would be returned, split into smaller requests (see 'split'). 0 = do not split.
  26671. * @param {string|Filter} [options.filter] Additional filter.
  26672. * @param {boolean} [options.noCacheQuery=false] If true, the local cache will not be queried
  26673. * @param {function} featureCallback Will be called for each matching object. Will be passed: 1. err (if an error occured, otherwise null), 2. the object or null.
  26674. * @param {function} finalCallback Will be called after the last feature. Will be passed: 1. err (if an error occured, otherwise null).
  26675. * @return {RequestBBox}
  26676. */
  26677. BBoxQuery (query, bounds, options, featureCallback, finalCallback) {
  26678. bounds = new BoundingBox(bounds)
  26679. var request = new RequestBBox(this, {
  26680. query: query,
  26681. bounds: bounds,
  26682. remainingBounds: bounds,
  26683. options: options,
  26684. doneFeatures: {},
  26685. featureCallback: featureCallback,
  26686. finalCallback: finalCallback
  26687. })
  26688. this.requests.push(request)
  26689. this._next()
  26690. return request
  26691. }
  26692. clearBBoxQuery (query) {
  26693. let filterId = new Filter(query).toString()
  26694. delete this.cacheBBoxQueries[filterId]
  26695. }
  26696. _abortRequest (request) {
  26697. var p = this.requests.indexOf(request)
  26698. if (p === -1) {
  26699. return
  26700. }
  26701. this.requests[p] = null
  26702. }
  26703. _finishRequest (request) {
  26704. this.requests[this.requests.indexOf(request)] = null
  26705. }
  26706. _next () {
  26707. async.setImmediate(function () {
  26708. this._overpassProcess()
  26709. }.bind(this))
  26710. }
  26711. abortAllRequests () {
  26712. for (var j = 0; j < this.requests.length; j++) {
  26713. if (this.requests[j] === null) {
  26714. continue
  26715. }
  26716. this.requests[j].abort()
  26717. }
  26718. this.requests = []
  26719. }
  26720. removeFromCache (ids) {
  26721. if (typeof ids === 'string') {
  26722. ids = [ ids ]
  26723. }
  26724. for (var i = 0; i < ids.length; i++) {
  26725. if (ids[i] in this.cacheElements) {
  26726. let ob = this.cacheElements[ids[i]]
  26727. // remove all memberOf references
  26728. if (ob.members) {
  26729. ob.members.forEach(member => {
  26730. let memberOb = this.cacheElements[member.id]
  26731. memberOb.memberOf = memberOb.memberOf
  26732. .filter(memberOf => memberOf.id !== ob.id)
  26733. })
  26734. }
  26735. let lokiOb = this.cacheElements[ids[i]].dbData
  26736. delete this.cacheElements[ids[i]]
  26737. this.db.remove(lokiOb)
  26738. }
  26739. }
  26740. }
  26741. notifyMemberUpdates () {
  26742. let todo = this.pendingNotifyMemberUpdate
  26743. this.pendingNotifyMemberUpdate = {}
  26744. for (var k in todo) {
  26745. let ob = this.cacheElements[k]
  26746. ob.notifyMemberUpdate(todo[k])
  26747. this.pendingUpdateEmit[ob.id] = ob
  26748. }
  26749. }
  26750. pendingNotifies () {
  26751. this.notifyMemberUpdates()
  26752. let todo = Object.values(this.pendingUpdateEmit)
  26753. this.pendingUpdateEmit = {}
  26754. todo.forEach(ob => {
  26755. ob.emit('update', ob)
  26756. this.db.update(ob.dbInsert())
  26757. })
  26758. }
  26759. createOrUpdateOSMObject (el, options) {
  26760. var id = el.type.substr(0, 1) + el.id
  26761. var ob = null
  26762. let create = true
  26763. if (id in this.cacheElements && !this.cacheElements[id]) {
  26764. console.log('why can this be null?', id)
  26765. }
  26766. if (id in this.cacheElements && this.cacheElements[id]) {
  26767. ob = this.cacheElements[id]
  26768. create = false
  26769. // no new information -> return
  26770. if (~ob.properties & options.properties === 0) {
  26771. return ob
  26772. }
  26773. } else if (el.type === 'relation') {
  26774. ob = new OverpassRelation(id)
  26775. } else if (el.type === 'way') {
  26776. ob = new OverpassWay(id)
  26777. } else if (el.type === 'node') {
  26778. ob = new OverpassNode(id)
  26779. } else {
  26780. ob = new OverpassObject(id)
  26781. }
  26782. ob.overpass = this
  26783. ob.updateData(el, options)
  26784. ob.memberOf.forEach(entry => {
  26785. if (entry.id in this.pendingNotifyMemberUpdate) {
  26786. this.pendingNotifyMemberUpdate[entry.id].push(ob)
  26787. } else {
  26788. this.pendingNotifyMemberUpdate[entry.id] = [ ob ]
  26789. }
  26790. })
  26791. this.pendingUpdateEmit[ob.id] = ob
  26792. if (create) {
  26793. this.db.insert(ob.dbInsert())
  26794. } else {
  26795. this.db.update(ob.dbInsert())
  26796. }
  26797. this.cacheElements[id] = ob
  26798. return ob
  26799. }
  26800. regexpEscape (str) {
  26801. return str.replace('\\', '\\\\')
  26802. .replace('.', '\\.')
  26803. .replace('|', '\\|')
  26804. .replace('[', '\\[')
  26805. .replace(']', '\\]')
  26806. .replace('(', '\\(')
  26807. .replace(')', '\\)')
  26808. .replace('{', '\\{')
  26809. .replace('}', '\\}')
  26810. .replace('?', '\\?')
  26811. .replace('+', '\\+')
  26812. .replace('*', '\\*')
  26813. .replace('^', '\\^')
  26814. .replace('$', '\\$')
  26815. }
  26816. }
  26817. for (var k in defines) {
  26818. OverpassFrontend[k] = defines[k]
  26819. }
  26820. function isSeparator (el) {
  26821. return ('count' in el || ('type' in el && el.type === 'count'))
  26822. }
  26823. ee(OverpassFrontend.prototype)
  26824. OverpassFrontend.Filter = Filter
  26825. module.exports = OverpassFrontend
  26826. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26827. },{"./Filter":179,"./OverpassNode":181,"./OverpassObject":182,"./OverpassRelation":183,"./OverpassWay":184,"./RequestBBox":186,"./RequestGet":188,"./copyOsm3sMeta":192,"./defines":193,"./httpLoad":195,"./loadOsmFile":197,"./removeNullEntries":199,"async":19,"boundingbox":20,"event-emitter":41,"lokijs":172,"weight-sort":208}],181:[function(require,module,exports){
  26828. /* global L:false */
  26829. var OverpassObject = require('./OverpassObject')
  26830. var BoundingBox = require('boundingbox')
  26831. var OverpassFrontend = require('./defines')
  26832. /**
  26833. * A node
  26834. * @extends OverpassObject
  26835. * @property {string} id ID of this object, starting with 'n'.
  26836. * @property {number} osm_id Numeric id.
  26837. * @property {string} type Type: 'node'
  26838. * @property {object} tags OpenStreetMap tags.
  26839. * @property {object} meta OpenStreetMap meta information.
  26840. * @property {Point} geometry of the object
  26841. * @property {object} data Data as loaded from Overpass API.
  26842. * @property {bit_array} properties Which information about this object is known?
  26843. * @property {object[]} memberOf List of ways and relations where this object is member of.
  26844. * @property {string} memberOf.id ID of the way or relation where this way is member of.
  26845. * @property {string} memberOf.role Role of this object in the relation.
  26846. * @property {number} memberOf.sequence This object is the nth member in the way resp. relation.
  26847. * @property {BoundingBox} bounds Bounding box of this object.
  26848. * @property {Point} center Centroid of the bounding box.
  26849. */
  26850. class OverpassNode extends OverpassObject {
  26851. GeoJSON () {
  26852. let result = {
  26853. type: 'Feature',
  26854. id: this.type + '/' + this.osm_id,
  26855. properties: this.GeoJSONProperties()
  26856. }
  26857. if (this.geometry) {
  26858. result.geometry = {
  26859. type: 'Point',
  26860. coordinates: [ this.geometry.lon, this.geometry.lat ]
  26861. }
  26862. }
  26863. return result
  26864. }
  26865. exportOSMXML (options, document, callback) {
  26866. super.exportOSMXML(options, document,
  26867. (err, result) => {
  26868. if (err) {
  26869. return callback(err)
  26870. }
  26871. if (!result) { // already included
  26872. return callback(null)
  26873. }
  26874. result.setAttribute('lat', this.geometry.lat)
  26875. result.setAttribute('lon', this.geometry.lon)
  26876. callback(null, result)
  26877. }
  26878. )
  26879. }
  26880. exportOSMJSON (conf, elements, callback) {
  26881. super.exportOSMJSON(conf, elements,
  26882. (err, result) => {
  26883. if (err) {
  26884. return callback(err)
  26885. }
  26886. if (!result) { // already included
  26887. return callback(null)
  26888. }
  26889. result.lat = this.geometry.lat
  26890. result.lon = this.geometry.lon
  26891. callback(null, result)
  26892. }
  26893. )
  26894. }
  26895. updateData (data, options) {
  26896. super.updateData(data, options)
  26897. if (data.lat) {
  26898. this.geometry = {
  26899. lat: data.lat,
  26900. lon: data.lon
  26901. }
  26902. this.bounds = new BoundingBox(data)
  26903. this.center = this.bounds.getCenter()
  26904. this.properties = this.properties | OverpassFrontend.GEOM | OverpassFrontend.BBOX | OverpassFrontend.CENTER
  26905. }
  26906. }
  26907. /**
  26908. * return a leaflet feature for this object
  26909. * @param {object} [options] options Options will be passed to the leaflet function
  26910. * @param {string} [options.nodeFeature='CircleMarker'] Which type of object should be returned: 'Marker' (L.marker), 'Circle' (L.circle) or 'CircleMarker' (L.circleMarker).
  26911. * @return {L.layer}
  26912. */
  26913. leafletFeature (options) {
  26914. if (!this.geometry) {
  26915. return null
  26916. }
  26917. switch ('nodeFeature' in options ? options.nodeFeature : null) {
  26918. case 'Marker':
  26919. return L.marker(this.geometry, options)
  26920. case 'Circle':
  26921. return L.circle(this.geometry, options.radius, options)
  26922. case 'CircleMarker':
  26923. default:
  26924. return L.circleMarker(this.geometry, options)
  26925. }
  26926. }
  26927. intersects (bbox) {
  26928. if (!this.bounds) {
  26929. return 1
  26930. }
  26931. return bbox.intersects(this.bounds) ? 2 : 0
  26932. }
  26933. }
  26934. module.exports = OverpassNode
  26935. },{"./OverpassObject":182,"./defines":193,"boundingbox":20}],182:[function(require,module,exports){
  26936. const ee = require('event-emitter')
  26937. var BoundingBox = require('boundingbox')
  26938. var OverpassFrontend = require('./defines')
  26939. var turf = {
  26940. difference: require('@turf/difference'),
  26941. intersect: require('@turf/intersect').default
  26942. }
  26943. /**
  26944. * Base class for representing map features.
  26945. * @property {string} id ID of this object.
  26946. * @property {number} osm_id Numeric id.
  26947. * @property {string} type Type: 'node', 'way' or 'relation'.
  26948. * @property {object} tags OpenStreetMap tags.
  26949. * @property {object} meta OpenStreetMap meta information.
  26950. * @property {object} geometry of the object
  26951. * @property {object} data Data as loaded from Overpass API.
  26952. * @property {bit_array} properties Which information about this object is known?
  26953. * @property {object[]} memberOf List of ways and relations where this object is member of.
  26954. * @property {string} memberOf.id ID of the way or relation where this way is member of.
  26955. * @property {string} memberOf.role Role of this object in the relation.
  26956. * @property {number} memberOf.sequence This object is the nth member in the way resp. relation.
  26957. * @property {BoundingBox} bounds Bounding box of this object.
  26958. * @property {Point} center Centroid of the bounding box.
  26959. */
  26960. class OverpassObject {
  26961. constructor () {
  26962. this.data = {}
  26963. this.properties = 0
  26964. this.memberOf = []
  26965. }
  26966. memberIds () {
  26967. return []
  26968. }
  26969. member_ids () { // eslint-disable-line
  26970. console.log('called deprecated OverpassObject.member_ids() function - replace by memberIds()')
  26971. return this.memberIds()
  26972. }
  26973. notifyMemberOf (relation, role, sequence) {
  26974. this.memberOf.push({ id: relation.id, role, sequence })
  26975. }
  26976. updateData (data, options) {
  26977. if (typeof this.id === 'undefined') {
  26978. this.id = data.type.substr(0, 1) + data.id
  26979. this.type = data.type
  26980. this.osm_id = data.id
  26981. }
  26982. this.osm3sMeta = options.osm3sMeta
  26983. for (var k in data) {
  26984. this.data[k] = data[k]
  26985. }
  26986. if (data.bounds) {
  26987. this.bounds = new BoundingBox(data.bounds)
  26988. this.center = this.bounds.getCenter()
  26989. this.diagonalLength = this.bounds.diagonalLength()
  26990. } else if (data.center) {
  26991. this.bounds = new BoundingBox(data.center)
  26992. this.center = this.bounds.getCenter()
  26993. }
  26994. if (options.bbox) {
  26995. if (!this.bounds || options.bbox.intersects(this.bounds)) {
  26996. this.properties = this.properties | options.properties
  26997. } else {
  26998. this.properties = this.properties | OverpassFrontend.BBOX | OverpassFrontend.CENTER
  26999. }
  27000. } else {
  27001. this.properties = this.properties | options.properties
  27002. }
  27003. // result of a request with bbox limitation, where the object was outside
  27004. if (options.bboxNoMatch && this.bounds) {
  27005. // this.boundsPossibleMatch: record unsucessful bbox requests for an object
  27006. if (typeof this.boundsPossibleMatch === 'undefined') {
  27007. this.boundsPossibleMatch = this.bounds.toGeoJSON()
  27008. }
  27009. this.boundsPossibleMatch = turf.difference(this.boundsPossibleMatch, options.bbox.toGeoJSON())
  27010. }
  27011. // geometry is known -> no need for this.boundsPossibleMatch
  27012. if (this.geometry) {
  27013. delete this.boundsPossibleMatch
  27014. }
  27015. if (options.properties & OverpassFrontend.TAGS) {
  27016. if (typeof data.tags === 'undefined') {
  27017. this.tags = {}
  27018. } else {
  27019. this.tags = data.tags
  27020. }
  27021. }
  27022. this.errors = []
  27023. if (data.timestamp) {
  27024. this.meta = {
  27025. timestamp: data.timestamp,
  27026. version: data.version,
  27027. changeset: data.changeset,
  27028. user: data.user,
  27029. uid: data.uid
  27030. }
  27031. }
  27032. if (data.tags) {
  27033. this.tags = data.tags
  27034. }
  27035. }
  27036. notifyMemberUpdate (memberObs) {
  27037. }
  27038. /**
  27039. * Title of of this object (default: name, operator or ref or the id of the object)
  27040. * @return {string}
  27041. */
  27042. title () {
  27043. if (!this.tags) {
  27044. return this.id
  27045. }
  27046. return this.tags.name || this.tags.operator || this.tags.ref || this.id
  27047. }
  27048. /**
  27049. * GeoJSON representation of this object
  27050. * @return {object}
  27051. */
  27052. GeoJSON () {
  27053. return {
  27054. type: 'Feature',
  27055. id: this.type + '/' + this.osm_id,
  27056. geometry: null,
  27057. properties: this.GeoJSONProperties()
  27058. }
  27059. }
  27060. GeoJSONProperties () {
  27061. var ret = {}
  27062. var k
  27063. ret['@id'] = this.type + '/' + this.osm_id
  27064. if (this.tags) {
  27065. for (k in this.tags) {
  27066. ret[k] = this.tags[k]
  27067. }
  27068. }
  27069. if (this.meta) {
  27070. for (k in this.meta) {
  27071. ret['@' + k] = this.meta[k]
  27072. }
  27073. }
  27074. for (k in this.osm3sMeta) {
  27075. ret['@osm3s:' + k] = this.osm3sMeta[k]
  27076. }
  27077. return ret
  27078. }
  27079. /**
  27080. * Export object as GeoJSON. Missing geometry will be loaded.
  27081. * @param object options Options
  27082. * @param function callback Function which will be called with (err, result)
  27083. */
  27084. exportGeoJSON (options, callback) {
  27085. this.overpass.get(
  27086. this.id,
  27087. {
  27088. properties: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META | OverpassFrontend.GEOM
  27089. },
  27090. () => {},
  27091. (err) => {
  27092. if (err) {
  27093. return callback(err)
  27094. }
  27095. callback(null, this.GeoJSON(options))
  27096. }
  27097. )
  27098. }
  27099. /**
  27100. * Export object (and members) as OpenStreetMap XML
  27101. * @param object options Options
  27102. * @param DOMNode parentNode a DOM Node where the object will be appended as child. Depending on object type and options, member objects will also be appended on the same level.
  27103. * @param function callback Function which will be called with (err, dom node)
  27104. */
  27105. exportOSMXML (options, parentNode, callback) {
  27106. if (!parentNode._alreadyIncluded) {
  27107. parentNode._alreadyIncluded = {}
  27108. }
  27109. if (this.id in parentNode._alreadyIncluded) {
  27110. return callback(null)
  27111. }
  27112. parentNode._alreadyIncluded[this.id] = true
  27113. if ((this.properties & (OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META)) !== (OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META)) {
  27114. return this.overpass.get(
  27115. this.id,
  27116. {
  27117. properties: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META
  27118. },
  27119. () => {},
  27120. (err) => {
  27121. if (err) {
  27122. return callback(err)
  27123. }
  27124. this._exportOSMXML(options, parentNode, callback)
  27125. }
  27126. )
  27127. }
  27128. this._exportOSMXML(options, parentNode, callback)
  27129. }
  27130. _exportOSMXML (options, parentNode, callback) {
  27131. let result = parentNode.ownerDocument.createElement(this.type)
  27132. result.setAttribute('id', this.osm_id)
  27133. if (this.meta) {
  27134. result.setAttribute('version', this.meta.version)
  27135. result.setAttribute('timestamp', this.meta.timestamp)
  27136. result.setAttribute('changeset', this.meta.changeset)
  27137. result.setAttribute('uid', this.meta.uid)
  27138. result.setAttribute('user', this.meta.user)
  27139. }
  27140. if (this.tags) {
  27141. for (var k in this.tags) {
  27142. let tag = parentNode.ownerDocument.createElement('tag')
  27143. tag.setAttribute('k', k)
  27144. tag.setAttribute('v', this.tags[k])
  27145. result.appendChild(tag)
  27146. }
  27147. }
  27148. parentNode.appendChild(result)
  27149. callback(null, result)
  27150. }
  27151. /**
  27152. * Export object (and members) as OpenStreetMap JSON
  27153. * @param object options Options
  27154. * @param object elements All exported elements, include member objects. Pass an empty object. If a member element would be exported multiple times it will appear only once. For the final export, to be compatible to Overpass API, you should convert the object to an array via Object.values().
  27155. * @param function callback Function which will be called with (err, result)
  27156. */
  27157. exportOSMJSON (conf, elements, callback) {
  27158. if (this.id in elements) {
  27159. return callback(null)
  27160. }
  27161. elements[this.id] = {}
  27162. if ((this.properties & (OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META)) !== (OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META)) {
  27163. return this.overpass.get(
  27164. this.id,
  27165. {
  27166. properties: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META
  27167. },
  27168. () => {},
  27169. (err) => {
  27170. if (err) {
  27171. return callback(err)
  27172. }
  27173. this._exportOSMJSON(conf, elements, callback)
  27174. }
  27175. )
  27176. }
  27177. this._exportOSMJSON(conf, elements, callback)
  27178. }
  27179. _exportOSMJSON (conf, elements, callback) {
  27180. let result = elements[this.id]
  27181. result.type = this.type
  27182. result.id = this.osm_id
  27183. if (this.meta) {
  27184. result.version = this.meta.version
  27185. result.timestamp = this.meta.timestamp
  27186. result.changeset = this.meta.changeset
  27187. result.uid = this.meta.uid
  27188. result.user = this.meta.user
  27189. }
  27190. if (this.tags && Object.keys(this.tags).length) {
  27191. result.tags = this.tags
  27192. }
  27193. callback(null, result)
  27194. }
  27195. /**
  27196. * Check whether this object intersects (or is within) the specified bounding box. Returns 0 if it does not match; 1 if the exact geometry is not known, but the object's bounding box matches; 2 exact match.
  27197. * @param {boundingbox:BoundingBox} bbox Bounding box
  27198. * @return {number}
  27199. */
  27200. intersects (bbox) {
  27201. if (!this.bounds) {
  27202. return 0
  27203. }
  27204. if (!bbox.intersects(this.bounds)) {
  27205. return 0
  27206. }
  27207. if (this.boundsPossibleMatch) {
  27208. var remaining = turf.intersect(bbox.toGeoJSON(), this.boundsPossibleMatch)
  27209. if (!remaining || remaining.geometry.type !== 'Polygon') {
  27210. // geometry.type != Polygon: bbox matches border of this.boundsPossibleMatch
  27211. return 0
  27212. }
  27213. return 1
  27214. }
  27215. return 1
  27216. }
  27217. /**
  27218. * return a leaflet feature for this object.
  27219. * @param {object} [options] options Options will be passed to the leaflet function
  27220. * @return {L.layer}
  27221. */
  27222. leafletFeature (options) {
  27223. return null
  27224. }
  27225. dbInsert () {
  27226. if (!this.dbData) {
  27227. this.dbData = {}
  27228. }
  27229. this.dbData.tags = this.tags
  27230. this.dbData.osmMeta = this.meta
  27231. this.dbData.id = this.id
  27232. this.dbData.type = this.type
  27233. if (this.bounds && this.bounds.minlat) {
  27234. this.dbData.minlat = this.bounds.minlat
  27235. this.dbData.minlon = this.bounds.minlon
  27236. this.dbData.maxlat = this.bounds.maxlat
  27237. this.dbData.maxlon = this.bounds.maxlon
  27238. }
  27239. return this.dbData
  27240. }
  27241. }
  27242. ee(OverpassObject.prototype)
  27243. module.exports = OverpassObject
  27244. },{"./defines":193,"@turf/difference":9,"@turf/intersect":12,"boundingbox":20,"event-emitter":41}],183:[function(require,module,exports){
  27245. /* global L:false */
  27246. const async = require('async')
  27247. var BoundingBox = require('boundingbox')
  27248. var osmtogeojson = require('osmtogeojson')
  27249. var OverpassObject = require('./OverpassObject')
  27250. var OverpassFrontend = require('./defines')
  27251. var turf = {
  27252. bboxClip: require('@turf/bbox-clip').default
  27253. }
  27254. /**
  27255. * A relation
  27256. * @property {string} id ID of this object, starting with 'r'.
  27257. * @property {number} osm_id Numeric id.
  27258. * @property {string} type Type: 'relation'.
  27259. * @property {object} tags OpenStreetMap tags.
  27260. * @property {object} meta OpenStreetMap meta information.
  27261. * @property {GeoJSON} geometry of the object
  27262. * @property {object} data Data as loaded from Overpass API.
  27263. * @property {bit_array} properties Which information about this object is known?
  27264. * @property {object[]} memberOf List of relations where this object is member of.
  27265. * @property {string} memberOf.id ID of the relation where this object is member of.
  27266. * @property {string} memberOf.role Role of this object in the relation.
  27267. * @property {number} memberOf.sequence This object is the nth member in the relation.
  27268. * @property {null|string} memberOf.connectedPrev null (unknown), 'no' (connected), 'forward' (connected at the front end of this way), 'backward' (connected at the back end of this way)
  27269. * @property {null|string} memberOf.connectedNext null (unknown), 'no' (connected), 'forward' (connected at the back end of this way), 'backward' (connected at the front end of this way)
  27270. * @property {null|string} members.dir null (unknown), 'forward', 'backward'
  27271. * @property {BoundingBox} bounds Bounding box of this object.
  27272. * @property {Point} center Centroid of the bounding box.
  27273. * @property {object[]} members Nodes of the way.
  27274. * @property {string} members.id ID of the member.
  27275. * @property {number} members.ref Numeric ID of the member.
  27276. * @property {string} members.type 'node'.
  27277. * @property {string} members.role Role of the member.
  27278. * @property {null|string} members.connectedPrev null (unknown), 'no' (connected), 'forward' (connected at the front end of this way), 'backward' (connected at the back end of this way)
  27279. * @property {null|string} members.connectedNext null (unknown), 'no' (connected), 'forward' (connected at the back end of this way), 'backward' (connected at the fornt end of this way)
  27280. * @property {null|string} members.dir null (unknown), 'forward', 'backward', 'loop'
  27281. */
  27282. class OverpassRelation extends OverpassObject {
  27283. updateData (data, options) {
  27284. var i
  27285. super.updateData(data, options)
  27286. if ((options.properties & OverpassFrontend.MEMBERS) &&
  27287. data.members) {
  27288. this.members = []
  27289. for (i = 0; i < data.members.length; i++) {
  27290. var member = data.members[i]
  27291. this.members.push(member)
  27292. this.members[i].id = member.type.substr(0, 1) + member.ref
  27293. }
  27294. }
  27295. if (options.properties & OverpassFrontend.MEMBERS) {
  27296. let membersKnown = !!this.memberFeatures
  27297. this.memberFeatures = data.members.map(
  27298. (member, sequence) => {
  27299. let ob = JSON.parse(JSON.stringify(member))
  27300. ob.id = ob.ref
  27301. delete ob.ref
  27302. delete ob.role
  27303. let memberOb = this.overpass.createOrUpdateOSMObject(ob, {
  27304. properties: options.properties & OverpassFrontend.GEOM
  27305. })
  27306. // call notifyMemberOf only once per member
  27307. if (!membersKnown) {
  27308. memberOb.notifyMemberOf(this, member.role, sequence)
  27309. }
  27310. return memberOb
  27311. }
  27312. )
  27313. }
  27314. if ((options.properties & OverpassFrontend.MEMBERS) &&
  27315. (options.properties & OverpassFrontend.GEOM) &&
  27316. data.members) {
  27317. let elements = [ JSON.parse(JSON.stringify(data)) ]
  27318. this.geometry = osmtogeojson({ elements })
  27319. } else if ((options.properties & OverpassFrontend.MEMBERS) &&
  27320. data.members) {
  27321. this.updateGeometry()
  27322. }
  27323. }
  27324. updateGeometry () {
  27325. if (!this.members) {
  27326. return
  27327. }
  27328. let allKnown = true
  27329. let elements = [ {
  27330. type: 'relation',
  27331. id: this.osm_id,
  27332. tags: this.tags,
  27333. members: this.members.map(member => {
  27334. let data = {
  27335. ref: member.ref,
  27336. type: member.type,
  27337. role: member.role
  27338. }
  27339. if (!(member.id in this.overpass.cacheElements)) {
  27340. allKnown = false
  27341. return data
  27342. }
  27343. let ob = this.overpass.cacheElements[member.id]
  27344. if ((ob.properties & OverpassFrontend.GEOM) === 0) {
  27345. allKnown = false
  27346. }
  27347. if (ob.type === 'node') {
  27348. if (ob.geometry) {
  27349. data.lat = ob.geometry.lat
  27350. data.lon = ob.geometry.lon
  27351. }
  27352. } else if (ob.type === 'way') {
  27353. data.geometry = ob.geometry
  27354. }
  27355. return data
  27356. })
  27357. } ]
  27358. this.geometry = osmtogeojson({ elements })
  27359. if (allKnown) {
  27360. this.properties = this.properties | OverpassFrontend.GEOM
  27361. }
  27362. this.members.forEach(
  27363. (member, index) => {
  27364. if (member.type !== 'way') {
  27365. return
  27366. }
  27367. let memberOb = this.overpass.cacheElements[member.id]
  27368. if (!memberOb.members || member.type !== 'way') {
  27369. return
  27370. }
  27371. let firstMemberId = memberOb.members[0].id
  27372. let lastMemberId = memberOb.members[memberOb.members.length - 1].id
  27373. let revMemberOf = memberOb.memberOf.filter(memberOf => memberOf.sequence === index && memberOf.id === this.id)[0]
  27374. if (index > 0) {
  27375. let prevMember = this.overpass.cacheElements[this.members[index - 1].id]
  27376. if (prevMember.type === 'way' && prevMember.members) {
  27377. if (firstMemberId === prevMember.members[0].id || firstMemberId === prevMember.members[prevMember.members.length - 1].id) {
  27378. member.connectedPrev = 'forward'
  27379. } else if (lastMemberId === prevMember.members[0].id || lastMemberId === prevMember.members[prevMember.members.length - 1].id) {
  27380. member.connectedPrev = 'backward'
  27381. } else {
  27382. member.connectedPrev = 'no'
  27383. }
  27384. }
  27385. }
  27386. if (index < this.members.length - 1) {
  27387. let nextMember = this.overpass.cacheElements[this.members[index + 1].id]
  27388. if (nextMember.type === 'way' && nextMember.members) {
  27389. if (firstMemberId === nextMember.members[0].id || firstMemberId === nextMember.members[nextMember.members.length - 1].id) {
  27390. member.connectedNext = 'backward'
  27391. } else if (lastMemberId === nextMember.members[0].id || lastMemberId === nextMember.members[nextMember.members.length - 1].id) {
  27392. member.connectedNext = 'forward'
  27393. } else {
  27394. member.connectedNext = 'no'
  27395. }
  27396. }
  27397. }
  27398. if (!member.connectedPrev || !member.connectedNext) {
  27399. member.dir = member.connectedPrev || member.connectedNext || null
  27400. } else if (member.connectedPrev === member.connectedNext) {
  27401. member.dir = member.connectedPrev || member.connectedNext || null
  27402. } else {
  27403. member.dir = null
  27404. }
  27405. if (revMemberOf) {
  27406. if ('dir' in member) {
  27407. revMemberOf.dir = member.dir
  27408. }
  27409. if ('connectedPrev' in member) {
  27410. revMemberOf.connectedPrev = member.connectedPrev
  27411. }
  27412. if ('connectedNext' in member) {
  27413. revMemberOf.connectedNext = member.connectedNext
  27414. }
  27415. } else {
  27416. console.log('Warning: memberOf reference ' + member.id + ' -> ' + this.id + ' (#' + index + ') does not exist.')
  27417. }
  27418. }
  27419. )
  27420. if (!this.bounds) {
  27421. this.members.forEach(member => {
  27422. let ob = this.overpass.cacheElements[member.id]
  27423. if (ob.bounds) {
  27424. if (this.bounds) {
  27425. this.bounds.extend(ob.bounds)
  27426. } else {
  27427. this.bounds = new BoundingBox(ob.bounds)
  27428. }
  27429. }
  27430. })
  27431. if (this.bounds && allKnown) {
  27432. this.center = this.bounds.getCenter()
  27433. this.properties = this.properties | OverpassFrontend.BBOX | OverpassFrontend.CENTER
  27434. }
  27435. }
  27436. }
  27437. notifyMemberUpdate (memberObs) {
  27438. super.notifyMemberUpdate(memberObs)
  27439. if (!this.members) {
  27440. return
  27441. }
  27442. this.updateGeometry()
  27443. }
  27444. /**
  27445. * Return list of member ids.
  27446. * @return {string[]}
  27447. */
  27448. memberIds () {
  27449. if (this._memberIds) {
  27450. return this._memberIds
  27451. }
  27452. if (typeof this.data.members === 'undefined') {
  27453. return null
  27454. }
  27455. this._memberIds = []
  27456. for (var i = 0; i < this.data.members.length; i++) {
  27457. var member = this.data.members[i]
  27458. this._memberIds.push(member.type.substr(0, 1) + member.ref)
  27459. }
  27460. return this._memberIds
  27461. }
  27462. member_ids () { // eslint-disable-line
  27463. console.log('called deprecated OverpassRelation.member_ids() function - replace by memberIds()')
  27464. return this.memberIds()
  27465. }
  27466. /**
  27467. * return a leaflet feature for this object.
  27468. * @param {object} [options] options Options will be passed to the leaflet function
  27469. * @return {L.layer}
  27470. */
  27471. leafletFeature (options) {
  27472. if (!this.data.members) {
  27473. return null
  27474. }
  27475. // no geometry? use the member features instead
  27476. if (!this.geometry) {
  27477. let feature = L.featureGroup()
  27478. feature._updateCallbacks = []
  27479. return feature
  27480. }
  27481. var feature = L.geoJSON(this.geometry, {
  27482. pointToLayer: function (options, geoJsonPoint, member) {
  27483. let feature
  27484. switch (options.nodeFeature) {
  27485. case 'Marker':
  27486. feature = L.marker(member, options)
  27487. break
  27488. case 'Circle':
  27489. feature = L.circle(member, options.radius, options)
  27490. break
  27491. case 'CircleMarker':
  27492. default:
  27493. feature = L.circleMarker(member, options)
  27494. }
  27495. return feature
  27496. }.bind(this, options)
  27497. })
  27498. feature.setStyle(options)
  27499. // create an event handler on the 'update' event, so that loading member
  27500. // features will update geometry
  27501. this.memberFeatures.forEach(
  27502. (member, index) => {
  27503. if (!(member.properties & OverpassFrontend.GEOM)) {
  27504. let updFun = member => {
  27505. feature.clearLayers()
  27506. feature.addData(this.geometry)
  27507. feature.setStyle(options)
  27508. }
  27509. member.once('update', updFun)
  27510. }
  27511. }
  27512. )
  27513. return feature
  27514. }
  27515. GeoJSON () {
  27516. var ret = {
  27517. type: 'Feature',
  27518. id: this.type + '/' + this.osm_id,
  27519. properties: this.GeoJSONProperties()
  27520. }
  27521. if (this.members) {
  27522. if (this.geometry.features.length === 1) {
  27523. ret.geometry = this.geometry.features[0].geometry
  27524. } else {
  27525. ret.geometry = {
  27526. type: 'GeometryCollection',
  27527. geometries: this.memberFeatures
  27528. .map(member => {
  27529. let geojson = member.GeoJSON()
  27530. if ('geometry' in geojson) {
  27531. return geojson.geometry
  27532. }
  27533. })
  27534. .filter(member => member)
  27535. }
  27536. }
  27537. }
  27538. return ret
  27539. }
  27540. exportOSMXML (options, parentNode, callback) {
  27541. super.exportOSMXML(options, parentNode,
  27542. (err, result) => {
  27543. if (err) {
  27544. return callback(err)
  27545. }
  27546. if (!result) { // already included
  27547. return callback(null)
  27548. }
  27549. if (this.members) {
  27550. async.each(this.members,
  27551. (member, done) => {
  27552. let memberOb = this.overpass.cacheElements[member.id]
  27553. let nd = parentNode.ownerDocument.createElement('member')
  27554. nd.setAttribute('ref', memberOb.osm_id)
  27555. nd.setAttribute('type', memberOb.type)
  27556. nd.setAttribute('role', member.role)
  27557. result.appendChild(nd)
  27558. memberOb.exportOSMXML(options, parentNode, done)
  27559. },
  27560. (err) => {
  27561. callback(err, result)
  27562. }
  27563. )
  27564. } else {
  27565. callback(null, result)
  27566. }
  27567. }
  27568. )
  27569. }
  27570. exportOSMJSON (conf, elements, callback) {
  27571. super.exportOSMJSON(conf, elements,
  27572. (err, result) => {
  27573. if (err) {
  27574. return callback(err)
  27575. }
  27576. if (!result) { // already included
  27577. return callback(null)
  27578. }
  27579. if (this.members) {
  27580. result.members = []
  27581. async.each(this.members,
  27582. (member, done) => {
  27583. let memberOb = this.overpass.cacheElements[member.id]
  27584. result.members.push({
  27585. ref: memberOb.osm_id,
  27586. type: memberOb.type,
  27587. role: member.role
  27588. })
  27589. memberOb.exportOSMJSON(conf, elements, done)
  27590. },
  27591. (err) => {
  27592. callback(err, result)
  27593. }
  27594. )
  27595. } else {
  27596. callback(null, result)
  27597. }
  27598. }
  27599. )
  27600. }
  27601. intersects (bbox) {
  27602. var i
  27603. if (this.bounds) {
  27604. if (!bbox.intersects(this.bounds)) {
  27605. return 0
  27606. }
  27607. }
  27608. if (this.geometry) {
  27609. for (i = 0; i < this.geometry.features.length; i++) {
  27610. var g = this.geometry.features[i]
  27611. if (g.geometry.type === 'Point') {
  27612. if (bbox.intersects(g)) {
  27613. return 2
  27614. }
  27615. continue
  27616. }
  27617. var intersects = turf.bboxClip(g, [ bbox.minlon, bbox.minlat, bbox.maxlon, bbox.maxlat ])
  27618. if (g.geometry.type === 'LineString' || g.geometry.type === 'Polygon') {
  27619. if (intersects.geometry.coordinates.length) {
  27620. return 2
  27621. }
  27622. }
  27623. if (g.geometry.type === 'MultiPolygon' || g.geometry.type === 'MultiLineString') {
  27624. for (var j = 0; j < intersects.geometry.coordinates.length; j++) {
  27625. if (intersects.geometry.coordinates[j].length) {
  27626. return 2
  27627. }
  27628. }
  27629. }
  27630. }
  27631. // if there's a relation member (where Overpass does not return the
  27632. // geometry) we can't know if the geometry intersects -> return 1
  27633. for (i = 0; i < this.data.members.length; i++) {
  27634. if (this.data.members[i].type === 'relation') {
  27635. return 1
  27636. }
  27637. }
  27638. // if there's no relation member we can be sure there's no intersection
  27639. return 0
  27640. } else if (this.members) {
  27641. for (i in this.members) {
  27642. let memberId = this.members[i].id
  27643. let member = this.overpass.cacheElements[memberId]
  27644. if (member) {
  27645. if (member.intersects(bbox) === 2) {
  27646. return 2
  27647. }
  27648. }
  27649. }
  27650. }
  27651. return super.intersects(bbox)
  27652. }
  27653. }
  27654. module.exports = OverpassRelation
  27655. },{"./OverpassObject":182,"./defines":193,"@turf/bbox-clip":3,"async":19,"boundingbox":20,"osmtogeojson":177}],184:[function(require,module,exports){
  27656. /* global L:false */
  27657. const async = require('async')
  27658. var BoundingBox = require('boundingbox')
  27659. var OverpassObject = require('./OverpassObject')
  27660. var OverpassFrontend = require('./defines')
  27661. var turf = {
  27662. bboxClip: require('@turf/bbox-clip').default
  27663. }
  27664. /**
  27665. * A way
  27666. * @property {string} id ID of this object, starting with 'w'.
  27667. * @property {number} osm_id Numeric id.
  27668. * @property {string} type Type: 'way'.
  27669. * @property {object} tags OpenStreetMap tags.
  27670. * @property {object} meta OpenStreetMap meta information.
  27671. * @property {Point[]} geometry of the object
  27672. * @property {object} data Data as loaded from Overpass API.
  27673. * @property {bit_array} properties Which information about this object is known?
  27674. * @property {object[]} memberOf List of relations where this object is member of.
  27675. * @property {string} memberOf.id ID of the relation where this way is member of.
  27676. * @property {string} memberOf.role Role of this object in the relation.
  27677. * @property {number} memberOf.sequence This object is the nth member in the relation.
  27678. * @property {BoundingBox} bounds Bounding box of this object.
  27679. * @property {Point} center Centroid of the bounding box.
  27680. * @property {object[]} members Nodes of the way.
  27681. * @property {string} members.id ID of the member.
  27682. * @property {number} members.ref Numeric ID of the member.
  27683. * @property {string} members.type 'node'.
  27684. */
  27685. class OverpassWay extends OverpassObject {
  27686. updateData (data, options) {
  27687. if (data.nodes) {
  27688. this.nodes = data.nodes
  27689. }
  27690. if (data.geometry) {
  27691. this.geometry = data.geometry
  27692. }
  27693. super.updateData(data, options)
  27694. if (typeof this.data.nodes !== 'undefined') {
  27695. this.members = []
  27696. for (var i = 0; i < this.data.nodes.length; i++) {
  27697. this.members.push({
  27698. id: 'n' + this.data.nodes[i],
  27699. ref: this.data.nodes[i],
  27700. type: 'node'
  27701. })
  27702. let obProperties = OverpassFrontend.ID_ONLY
  27703. let ob = {
  27704. id: this.data.nodes[i],
  27705. type: 'node'
  27706. }
  27707. if (data.geometry) {
  27708. obProperties = obProperties | OverpassFrontend.GEOM
  27709. ob.lat = data.geometry[i].lat
  27710. ob.lon = data.geometry[i].lon
  27711. }
  27712. let memberOb = this.overpass.createOrUpdateOSMObject(ob, {
  27713. properties: obProperties
  27714. })
  27715. memberOb.notifyMemberOf(this, null, i)
  27716. }
  27717. if (!this.geometry) {
  27718. this.geometry = this.members.map(
  27719. member => {
  27720. let node = this.overpass.cacheElements[member.id]
  27721. if (node) {
  27722. return node.geometry
  27723. }
  27724. }
  27725. )
  27726. this.geometry = this.geometry.filter(geom => geom)
  27727. if (!this.geometry.length) {
  27728. delete this.geometry
  27729. }
  27730. }
  27731. }
  27732. if (this.geometry && this.geometry.filter(geom => geom).length === this.geometry.length) {
  27733. this.properties = this.properties | OverpassFrontend.GEOM
  27734. if (!this.bounds) {
  27735. this.bounds = new BoundingBox(this.geometry[0])
  27736. this.geometry.slice(1).forEach(geom => this.bounds.extend(geom))
  27737. this.center = this.bounds.getCenter()
  27738. this.properties = this.properties | OverpassFrontend.BBOX | OverpassFrontend.CENTER
  27739. }
  27740. }
  27741. }
  27742. notifyMemberUpdate (memberObs) {
  27743. super.notifyMemberUpdate(memberObs)
  27744. if (!this.members) {
  27745. return
  27746. }
  27747. memberObs.forEach(memberOb => {
  27748. this.members.forEach((member, index) => {
  27749. if (memberOb.id === member.id) {
  27750. if (memberOb.geometry) {
  27751. if (!this.geometry) {
  27752. this.geometry = new Array(this.members.length)
  27753. }
  27754. this.geometry[index] = memberOb.geometry
  27755. }
  27756. }
  27757. if (this.bounds) {
  27758. this.bounds.extend(memberOb.geometry)
  27759. } else {
  27760. this.bounds = new BoundingBox(memberOb.geometry)
  27761. }
  27762. })
  27763. })
  27764. // all nodes known -> set bbox, geom and center
  27765. if (this.geometry && this.geometry.filter(geom => geom).length === this.geometry.length) {
  27766. this.center = this.bounds.getCenter()
  27767. this.properties = this.properties | OverpassFrontend.BBOX | OverpassFrontend.GEOM | OverpassFrontend.CENTER
  27768. }
  27769. }
  27770. memberIds () {
  27771. if (this._memberIds) {
  27772. return this._memberIds
  27773. }
  27774. if (!this.nodes) {
  27775. return null
  27776. }
  27777. this._memberIds = []
  27778. for (var i = 0; i < this.nodes.length; i++) {
  27779. var member = this.nodes[i]
  27780. this._memberIds.push('n' + member)
  27781. }
  27782. return this._memberIds
  27783. }
  27784. member_ids () { // eslint-disable-line
  27785. console.log('called deprecated OverpassWay.member_ids() function - replace by memberIds()')
  27786. return this.memberIds()
  27787. }
  27788. GeoJSON () {
  27789. var result = {
  27790. type: 'Feature',
  27791. id: this.type + '/' + this.osm_id,
  27792. properties: this.GeoJSONProperties()
  27793. }
  27794. if (this.geometry) {
  27795. let coordinates = this.geometry
  27796. .filter(point => point) // discard non-loaded points
  27797. .map(point => [ point.lon, point.lat ])
  27798. let isClosed = this.members && this.members[0].id === this.members[this.members.length - 1].id
  27799. if (isClosed) {
  27800. result.geometry = {
  27801. type: 'Polygon',
  27802. coordinates: [ coordinates ]
  27803. }
  27804. } else {
  27805. result.geometry = {
  27806. type: 'LineString',
  27807. coordinates: coordinates
  27808. }
  27809. }
  27810. }
  27811. return result
  27812. }
  27813. exportOSMXML (options, parentNode, callback) {
  27814. super.exportOSMXML(options, parentNode,
  27815. (err, result) => {
  27816. if (err) {
  27817. return callback(err)
  27818. }
  27819. if (!result) { // already included
  27820. return callback(null)
  27821. }
  27822. if (this.members) {
  27823. async.each(this.members,
  27824. (member, done) => {
  27825. let memberOb = this.overpass.cacheElements[member.id]
  27826. let nd = parentNode.ownerDocument.createElement('nd')
  27827. nd.setAttribute('ref', memberOb.osm_id)
  27828. result.appendChild(nd)
  27829. memberOb.exportOSMXML(options, parentNode, done)
  27830. },
  27831. (err) => {
  27832. callback(err, result)
  27833. }
  27834. )
  27835. } else {
  27836. callback(null, result)
  27837. }
  27838. }
  27839. )
  27840. }
  27841. exportOSMJSON (conf, elements, callback) {
  27842. super.exportOSMJSON(conf, elements,
  27843. (err, result) => {
  27844. if (err) {
  27845. return callback(err)
  27846. }
  27847. if (!result) { // already included
  27848. return callback(null)
  27849. }
  27850. if (this.members) {
  27851. result.nodes = []
  27852. async.each(this.members,
  27853. (member, done) => {
  27854. let memberOb = this.overpass.cacheElements[member.id]
  27855. result.nodes.push(memberOb.osm_id)
  27856. memberOb.exportOSMJSON(conf, elements, done)
  27857. },
  27858. (err) => {
  27859. callback(err, result)
  27860. }
  27861. )
  27862. } else {
  27863. callback(null, result)
  27864. }
  27865. }
  27866. )
  27867. }
  27868. /**
  27869. * return a leaflet feature for this object. If the ways is closed, a L.polygon will be returned, otherwise a L.polyline.
  27870. * @param {object} [options] options Options will be passed to the leaflet function
  27871. * @return {L.layer}
  27872. */
  27873. leafletFeature (options) {
  27874. if (!this.geometry) {
  27875. return null
  27876. }
  27877. if (this.geometry[this.geometry.length - 1].lat === this.geometry[0].lat &&
  27878. this.geometry[this.geometry.length - 1].lon === this.geometry[0].lon) {
  27879. return L.polygon(this.geometry, options)
  27880. }
  27881. return L.polyline(this.geometry, options)
  27882. }
  27883. intersects (bbox) {
  27884. if (this.bounds) {
  27885. if (!bbox.intersects(this.bounds)) {
  27886. return 0
  27887. }
  27888. }
  27889. if (this.geometry) {
  27890. var intersects = turf.bboxClip(this.GeoJSON(), [ bbox.minlon, bbox.minlat, bbox.maxlon, bbox.maxlat ])
  27891. return intersects.geometry.coordinates.length ? 2 : 0
  27892. }
  27893. return super.intersects(bbox)
  27894. }
  27895. }
  27896. module.exports = OverpassWay
  27897. },{"./OverpassObject":182,"./defines":193,"@turf/bbox-clip":3,"async":19,"boundingbox":20}],185:[function(require,module,exports){
  27898. const ee = require('event-emitter')
  27899. const SortedCallbacks = require('./SortedCallbacks')
  27900. /**
  27901. * A compiled query
  27902. * @typedef {Object} Request#SubRequest
  27903. * @property {string} query - The compiled code
  27904. * @property {object[]} parts - An entry for each part (separated by the 'out count' separator)
  27905. * @property {int} parts[].properties - The properties which each returned map feature has set (TAGS, BBOX, ...)
  27906. * @property {int} effort - Supposed "effort" of this query
  27907. * @property {Request} request - The request this compiled query belongs to
  27908. */
  27909. /**
  27910. * An unspecified request
  27911. * @param {OverpassFrontend} overpass
  27912. * @param {object} options
  27913. */
  27914. class Request {
  27915. constructor (overpass, data) {
  27916. this.overpass = overpass
  27917. for (var k in data) {
  27918. this[k] = data[k]
  27919. }
  27920. if (!this.options) {
  27921. this.options = {}
  27922. }
  27923. this.priority = 'priority' in this.options ? this.options.priority : 0
  27924. var callbacks = new SortedCallbacks(this.options, this.featureCallback, this.finalCallback)
  27925. this.featureCallback = callbacks.next.bind(callbacks)
  27926. this.finalCallback = callbacks.final.bind(callbacks)
  27927. this.callCount = 0
  27928. }
  27929. /**
  27930. * Request got aborted
  27931. * @event Request#abort
  27932. */
  27933. /**
  27934. * abort this request
  27935. */
  27936. abort () {
  27937. this.aborted = true
  27938. this.emit('abort')
  27939. this.overpass._abortRequest(this)
  27940. }
  27941. /**
  27942. * Request is finished
  27943. * @event Request#finish
  27944. * @param {Error|null} - null if no error occured
  27945. */
  27946. /**
  27947. * request is finished
  27948. * @param {Error|null} err - null if no error occured
  27949. */
  27950. finish (err) {
  27951. if (!this.aborted) {
  27952. this.finalCallback(err)
  27953. }
  27954. this.overpass._finishRequest(this)
  27955. this.finished = true
  27956. this.emit('finish', err)
  27957. }
  27958. /**
  27959. * shall this Request be included in the current call?
  27960. * @param {OverpassFrontend#Context} context - Current context
  27961. * @return {boolean} - yes|no
  27962. */
  27963. willInclude (context) {
  27964. return true
  27965. }
  27966. /**
  27967. * @typedef {Object} Request#minMaxEffortResult
  27968. * @property {number} Remaining minimal effort of this request
  27969. * @property {number|null} Remaining maximum effort (or null if unknown)
  27970. */
  27971. /**
  27972. * how much effort can a call to this request use
  27973. * @return {Request#minMaxEffortResult} - minimum and maximum effort
  27974. */
  27975. minMaxEffort () {
  27976. return { minEffort: 0, maxEffort: 0 }
  27977. }
  27978. /**
  27979. * SubRequest got compiled
  27980. * @event Request#subrequest-compiile
  27981. * @param {Request#SubRequest} subRequest - the sub request
  27982. */
  27983. /**
  27984. * compile the query
  27985. * @param {OverpassFrontend#Context} context - Current context
  27986. * @return {Request#SubRequest} - the compiled query
  27987. */
  27988. compileQuery (context) {
  27989. let subRequest = this._compileQuery(context)
  27990. this.emit('subrequest-compile', subRequest)
  27991. this.callCount++
  27992. return subRequest
  27993. }
  27994. /**
  27995. * receive an object from OverpassFronted -> enter to cache, return to caller
  27996. * @param {OverpassObject} ob - Object which has been received
  27997. * @param {Request#SubRequest} subRequest - sub request which is being handled right now
  27998. * @param {int} partIndex - Which part of the subRequest is being received
  27999. */
  28000. receiveObject (ob) {
  28001. }
  28002. /**
  28003. * SubRequest got finished
  28004. * @event Request#subrequest-finished
  28005. * @param {Request#SubRequest} subRequest - the sub request
  28006. */
  28007. /**
  28008. * the current subrequest is finished -> update caches, check whether request is finished
  28009. * @param {Request#SubRequest} subRequest - the current sub request
  28010. */
  28011. finishSubRequest (subRequest) {
  28012. this.emit('subrequest-finish', subRequest)
  28013. }
  28014. }
  28015. ee(Request.prototype)
  28016. module.exports = Request
  28017. },{"./SortedCallbacks":190,"event-emitter":41}],186:[function(require,module,exports){
  28018. const Request = require('./Request')
  28019. const overpassOutOptions = require('./overpassOutOptions')
  28020. const defines = require('./defines')
  28021. const KnownArea = require('./knownArea')
  28022. const RequestBBoxMembers = require('./RequestBBoxMembers')
  28023. const Filter = require('./Filter')
  28024. /**
  28025. * A BBox request
  28026. * @extends Request
  28027. */
  28028. class RequestBBox extends Request {
  28029. /**
  28030. * @param {OverpassFrontend} overpass
  28031. * @param {object} options
  28032. */
  28033. constructor (overpass, data) {
  28034. super(overpass, data)
  28035. this.type = 'BBoxQuery'
  28036. if (typeof this.options.properties === 'undefined') {
  28037. this.options.properties = defines.DEFAULT
  28038. }
  28039. this.options.properties |= defines.BBOX
  28040. this.options.minEffort = this.options.minEffort || 256
  28041. // make sure the request ends with ';'
  28042. if (!this.query.match(/;\s*$/)) {
  28043. this.query += ';'
  28044. }
  28045. if ((typeof this.options.filter !== 'undefined') && !(this.options.filter instanceof Filter)) {
  28046. this.options.filter = new Filter(this.options.filter)
  28047. }
  28048. let filterId = null
  28049. if (this.options.filter) {
  28050. filterId = this.options.filter.toString()
  28051. }
  28052. if (!('noCacheQuery' in this.options) || !this.options.noCacheQuery) {
  28053. this.filterQuery = new Filter(this.query)
  28054. this.lokiQuery = this.filterQuery.toLokijs()
  28055. this.lokiQueryNeedMatch = !!this.lokiQuery.needMatch
  28056. delete this.lokiQuery.needMatch
  28057. if (this.options.filter) {
  28058. let filterLokiQuery = this.options.filter.toLokijs()
  28059. this.lokiQueryFilterNeedMatch = !!filterLokiQuery.needMatch
  28060. delete filterLokiQuery.needMatch
  28061. this.lokiQuery = { $and: [ this.lokiQuery, filterLokiQuery ] }
  28062. }
  28063. this.lokiQuery.minlat = { $lte: this.bounds.maxlat }
  28064. this.lokiQuery.minlon = { $lte: this.bounds.maxlon }
  28065. this.lokiQuery.maxlat = { $gte: this.bounds.minlat }
  28066. this.lokiQuery.maxlon = { $gte: this.bounds.minlon }
  28067. }
  28068. this.loadFinish = false
  28069. this.lastChecked = 0
  28070. if ('members' in this.options) {
  28071. RequestBBoxMembers(this)
  28072. }
  28073. if (this.query in this.overpass.cacheBBoxQueries) {
  28074. this.cache = this.overpass.cacheBBoxQueries[this.query]
  28075. if (filterId) {
  28076. if (!('filter' in this.cache)) {
  28077. this.cache.filter = {}
  28078. }
  28079. if (!(filterId in this.cache.filter)) {
  28080. this.cache.filter[filterId] = new KnownArea()
  28081. }
  28082. this.cacheFilter = this.cache.filter[filterId]
  28083. }
  28084. } else {
  28085. // otherwise initialize cache
  28086. this.overpass.cacheBBoxQueries[this.query] = {}
  28087. this.cache = this.overpass.cacheBBoxQueries[this.query]
  28088. this.cache.requested = new KnownArea()
  28089. this.cache.timestamp = 0
  28090. if (filterId) {
  28091. this.cache.filter = {}
  28092. this.cache.filter[filterId] = new KnownArea()
  28093. this.cacheFilter = this.cache.filter[filterId]
  28094. }
  28095. }
  28096. }
  28097. /**
  28098. * check if there are any map features which can be returned right now
  28099. */
  28100. preprocess () {
  28101. if (this.lastChecked > this.cache.timestamp) {
  28102. if (!this.needLoad()) {
  28103. return
  28104. }
  28105. }
  28106. this.lastChecked = new Date().getTime()
  28107. var items = []
  28108. if (this.lokiQuery) {
  28109. items = this.overpass.db.find(this.lokiQuery)
  28110. }
  28111. for (var i = 0; i < items.length; i++) {
  28112. var id = items[i].id
  28113. if (!(id in this.overpass.cacheElements)) {
  28114. continue
  28115. }
  28116. var ob = this.overpass.cacheElements[id]
  28117. if (id in this.doneFeatures) {
  28118. continue
  28119. }
  28120. // maybe we need an additional check
  28121. if (this.lokiQueryNeedMatch && !this.filterQuery.match(ob)) {
  28122. continue
  28123. }
  28124. if (this.lokiQueryFilterNeedMatch && !this.options.filter.match(ob)) {
  28125. continue
  28126. }
  28127. // also check the object directly if it intersects the bbox - if possible
  28128. if (ob.intersects(this.bounds) < 2) {
  28129. continue
  28130. }
  28131. if ((this.options.properties & ob.properties) === this.options.properties) {
  28132. this.doneFeatures[id] = ob
  28133. this.featureCallback(null, ob)
  28134. }
  28135. }
  28136. }
  28137. /**
  28138. * shall this Request be included in the current call?
  28139. * @param {OverpassFrontend#Context} context - Current context
  28140. * @return {boolean|int[]} - yes|no - or [ minEffort, maxEffort ]
  28141. */
  28142. willInclude (context) {
  28143. if (this.loadFinish) {
  28144. return false
  28145. }
  28146. if (context.bbox && context.bbox.toLatLonString() !== this.bounds.toLatLonString()) {
  28147. return false
  28148. }
  28149. context.bbox = this.bounds
  28150. for (let i in context.requests) {
  28151. let request = context.requests[i]
  28152. if (request instanceof RequestBBox && request.query === this.query) {
  28153. return false
  28154. }
  28155. }
  28156. return true
  28157. }
  28158. /**
  28159. * how much effort can a call to this request use
  28160. * @return {Request#minMaxEffortResult} - minimum and maximum effort
  28161. */
  28162. minMaxEffort () {
  28163. if (this.loadFinish) {
  28164. return { minEffort: 0, maxEffort: 0 }
  28165. }
  28166. return { minEffort: this.options.minEffort, maxEffort: null }
  28167. }
  28168. /**
  28169. * compile the query
  28170. * @param {OverpassFrontend#Context} context - Current context
  28171. * @return {Request#SubRequest|false} - the compiled query or false if the bbox does not match
  28172. */
  28173. _compileQuery (context) {
  28174. if (this.loadFinish || (context.bbox && context.bbox.toLatLonString() !== this.bounds.toLatLonString())) {
  28175. return {
  28176. query: '',
  28177. request: this,
  28178. parts: [],
  28179. effort: 0
  28180. }
  28181. }
  28182. let effortAvailable = Math.max(context.maxEffort, this.options.minEffort)
  28183. // if the context already has a bbox and it differs from this, we can't add
  28184. // ours
  28185. var query = '(' + this.query + ')->.result;\n'
  28186. var queryRemoveDoneFeatures = ''
  28187. var countRemoveDoneFeatures = 0
  28188. for (var id in this.doneFeatures) {
  28189. var ob = this.doneFeatures[id]
  28190. if (countRemoveDoneFeatures % 1000 === 999) {
  28191. query += '(' + queryRemoveDoneFeatures + ')->.done;\n'
  28192. queryRemoveDoneFeatures = '.done;'
  28193. }
  28194. queryRemoveDoneFeatures += ob.type + '(' + ob.osm_id + ');'
  28195. countRemoveDoneFeatures++
  28196. }
  28197. if (countRemoveDoneFeatures) {
  28198. query += '(' + queryRemoveDoneFeatures + ')->.done;\n'
  28199. query += '(.result; - .done;)->.result;\n'
  28200. }
  28201. if (this.options.filter) {
  28202. query += this.options.filter.toQl({
  28203. inputSet: '.result'
  28204. }) + '->.result;\n'
  28205. }
  28206. if (!('split' in this.options)) {
  28207. this.options.effortSplit = Math.ceil(effortAvailable / 4)
  28208. }
  28209. query += '.result out ' + overpassOutOptions(this.options) + ';'
  28210. var subRequest = {
  28211. query,
  28212. request: this,
  28213. parts: [
  28214. {
  28215. properties: this.options.properties,
  28216. receiveObject: this.receiveObject.bind(this),
  28217. featureCallback: this.featureCallback
  28218. }
  28219. ],
  28220. effort: this.options.split ? this.options.split * 4 : effortAvailable // TODO: configure bbox effort
  28221. }
  28222. return subRequest
  28223. }
  28224. /**
  28225. * receive an object from OverpassFronted -> enter to cache, return to caller
  28226. * @param {OverpassObject} ob - Object which has been received
  28227. * @param {Request#SubRequest} subRequest - sub request which is being handled right now
  28228. * @param {int} partIndex - Which part of the subRequest is being received
  28229. */
  28230. receiveObject (ob) {
  28231. this.doneFeatures[ob.id] = ob
  28232. }
  28233. /**
  28234. * the current subrequest is finished -> update caches, check whether request is finished
  28235. * @param {Request#SubRequest} subRequest - the current sub request
  28236. */
  28237. finishSubRequest (subRequest) {
  28238. super.finishSubRequest(subRequest)
  28239. this.cache.timestamp = new Date().getTime()
  28240. if (('effortSplit' in this.options && this.options.effortSplit > subRequest.parts[0].count) ||
  28241. (this.options.split > subRequest.parts[0].count)) {
  28242. this.loadFinish = true
  28243. if (this.options.filter) {
  28244. this.cacheFilter.add(this.remainingBounds)
  28245. } else {
  28246. this.cache.requested.add(this.remainingBounds)
  28247. }
  28248. }
  28249. }
  28250. /**
  28251. * check if we need to call Overpass API. Maybe whole area is cached anyway?
  28252. * @return {boolean} - true, if we need to call Overpass API
  28253. */
  28254. needLoad () {
  28255. if (this.loadFinish) {
  28256. return false
  28257. }
  28258. // check if we need to call Overpass API (whole area known?)
  28259. if (this.options.filter && this.cacheFilter.check(this.bounds)) {
  28260. return false
  28261. }
  28262. return !this.cache.requested.check(this.bounds)
  28263. }
  28264. mayFinish () {
  28265. return !this.needLoad()
  28266. }
  28267. }
  28268. module.exports = RequestBBox
  28269. },{"./Filter":179,"./Request":185,"./RequestBBoxMembers":187,"./defines":193,"./knownArea":196,"./overpassOutOptions":198}],187:[function(require,module,exports){
  28270. const defines = require('./defines')
  28271. const overpassOutOptions = require('./overpassOutOptions')
  28272. const each = require('lodash/forEach')
  28273. const map = require('lodash/map')
  28274. const keys = require('lodash/keys')
  28275. const BoundingBox = require('boundingbox')
  28276. const SortedCallbacks = require('./SortedCallbacks')
  28277. class RequestBBoxMembers {
  28278. constructor (request) {
  28279. this.master = request
  28280. this.options = this.master.options
  28281. this.overpass = this.master.overpass
  28282. this.options.properties |= defines.MEMBERS
  28283. this.options.memberProperties = this.options.memberProperties || defines.DEFAULT
  28284. this.options.memberProperties |= defines.BBOX
  28285. if (this.options.memberBounds) {
  28286. this.bounds = new BoundingBox(this.options.memberBounds)
  28287. }
  28288. this.master._compileQuery = this._compileQuery.bind(this, this.master._compileQuery)
  28289. this.master.needLoad = this.needLoad.bind(this, this.master.needLoad)
  28290. this.master.mayFinish = this.mayFinish.bind(this, this.master.mayFinish)
  28291. this.master.preprocess = this.preprocess.bind(this, this.master.preprocess)
  28292. this.master.willInclude = this.willInclude.bind(this, this.master.willInclude)
  28293. this.master.minMaxEffort = this.minMaxEffort.bind(this, this.master.minMaxEffort)
  28294. this.master.finishSubRequest = this.finishSubRequest.bind(this, this.master.finishSubRequest)
  28295. this.master.featureCallback = this.receiveMasterObject.bind(this, this.master.featureCallback)
  28296. this.doneFeatures = {}
  28297. this.relations = {}
  28298. this.currentRelations = []
  28299. this.todo = {}
  28300. this.loadFinish = true
  28301. var callbacks = new SortedCallbacks(this.options, this.options.memberCallback, this.finalCallback)
  28302. this.options.memberCallback = callbacks.next.bind(callbacks)
  28303. this.finalCallback = callbacks.final.bind(callbacks)
  28304. }
  28305. willInclude (fun, context) {
  28306. let result = fun.call(this.master, context)
  28307. if (!this.loadFinish) {
  28308. return true
  28309. }
  28310. return result
  28311. }
  28312. minMaxEffort (fun) {
  28313. let { minEffort, maxEffort } = fun.call(this.master)
  28314. if (!this.loadFinish) {
  28315. minEffort += 64
  28316. maxEffort = null
  28317. }
  28318. return { minEffort, maxEffort }
  28319. }
  28320. preprocess (fun) {
  28321. fun.call(this.master)
  28322. this.todo = {}
  28323. each(this.relations, ob => {
  28324. each(ob.members, member => {
  28325. if (!(member.id in this.doneFeatures)) {
  28326. this.todo[member.id] = undefined
  28327. }
  28328. })
  28329. })
  28330. each(this.todo, (value, id) => {
  28331. if (id in this.overpass.cacheElements) {
  28332. var ob = this.overpass.cacheElements[id]
  28333. if (this.bounds && !ob.intersects(this.bounds)) {
  28334. return
  28335. }
  28336. if ((this.options.memberProperties & ob.properties) === this.options.memberProperties) {
  28337. this.doneFeatures[id] = ob
  28338. this.options.memberCallback(null, ob)
  28339. }
  28340. }
  28341. })
  28342. return
  28343. }
  28344. _compileQuery (fun, context) {
  28345. var subRequest = fun.call(this.master, context)
  28346. if (keys(this.relations).length === 0) {
  28347. return subRequest
  28348. }
  28349. let query = '(\n'
  28350. query += map(this.relations, ob => {
  28351. if (ob.type === 'relation') {
  28352. return 'relation(' + ob.osm_id + ');\n'
  28353. }
  28354. return ''
  28355. }).join('')
  28356. query += ')->.result;'
  28357. this.currentRelations = keys(this.relations)
  28358. let BBoxString = ''
  28359. if (this.bounds) {
  28360. BBoxString = '(' + this.bounds.toLatLonString() + ')'
  28361. }
  28362. query += '(\n' +
  28363. ' node(r.result)' + BBoxString + ';\n' +
  28364. ' way(r.result)' + BBoxString + ';\n' +
  28365. ' relation(r.result)' + BBoxString + ';\n' +
  28366. ')->.resultMembers;\n'
  28367. var queryRemoveDoneFeatures = ''
  28368. var countRemoveDoneFeatures = 0
  28369. for (var id in this.doneFeatures) {
  28370. var ob = this.doneFeatures[id]
  28371. if (countRemoveDoneFeatures % 1000 === 999) {
  28372. query += '(' + queryRemoveDoneFeatures + ')->.doneMembers;\n'
  28373. queryRemoveDoneFeatures = '.doneMembers;'
  28374. }
  28375. queryRemoveDoneFeatures += ob.type + '(' + ob.osm_id + ');'
  28376. countRemoveDoneFeatures++
  28377. }
  28378. if (countRemoveDoneFeatures) {
  28379. query += '(' + queryRemoveDoneFeatures + ')->.doneMembers;\n'
  28380. query += '(.resultMembers; - .doneMembers;)->.resultMembers;\n'
  28381. }
  28382. this.part = {
  28383. properties: this.options.memberProperties,
  28384. receiveObject: this.receiveObject.bind(this),
  28385. featureCallback: this.options.memberCallback,
  28386. count: 0
  28387. }
  28388. query += '.resultMembers out ' + overpassOutOptions(this.part) + ';'
  28389. this.loadFinish = true
  28390. if (subRequest.parts.length) {
  28391. subRequest.query += '\nout count;\n'
  28392. }
  28393. subRequest.query += query
  28394. subRequest.parts.push(this.part)
  28395. return subRequest
  28396. }
  28397. receiveMasterObject (fun, err, result, index) {
  28398. this.relations[result.id] = result
  28399. this.loadFinish = false
  28400. fun(err, result, index)
  28401. }
  28402. receiveObject (ob) {
  28403. this.doneFeatures[ob.id] = ob
  28404. }
  28405. finishSubRequest (fun, subRequest) {
  28406. fun.call(this.master, subRequest)
  28407. if (keys(this.relations).length !== this.currentRelations.length) {
  28408. this.loadFinish = false
  28409. }
  28410. }
  28411. needLoad (fun) {
  28412. var result = fun.call(this.master)
  28413. if (result === true) {
  28414. return true
  28415. }
  28416. return !this.loadFinish
  28417. }
  28418. mayFinish (fun) {
  28419. var result = fun.call(this.master)
  28420. if (result === false) {
  28421. return false
  28422. }
  28423. return this.loadFinish
  28424. }
  28425. }
  28426. module.exports = function (request) {
  28427. return new RequestBBoxMembers(request)
  28428. }
  28429. },{"./SortedCallbacks":190,"./defines":193,"./overpassOutOptions":198,"boundingbox":20,"lodash/forEach":150,"lodash/keys":164,"lodash/map":165}],188:[function(require,module,exports){
  28430. const Request = require('./Request')
  28431. const defines = require('./defines')
  28432. const BoundingBox = require('boundingbox')
  28433. const overpassOutOptions = require('./overpassOutOptions')
  28434. const RequestGetMembers = require('./RequestGetMembers')
  28435. /**
  28436. * A get request (request list of map features by id)
  28437. * @extends Request
  28438. */
  28439. class RequestGet extends Request {
  28440. /**
  28441. * @param {OverpassFrontend} overpass
  28442. * @param {data} data
  28443. */
  28444. constructor (overpass, data) {
  28445. super(overpass, data)
  28446. this.type = 'get'
  28447. if (typeof this.ids === 'string') {
  28448. this.ids = [ this.ids ]
  28449. } else {
  28450. this.ids = this.ids.concat()
  28451. }
  28452. if (typeof this.options.properties === 'undefined') {
  28453. this.options.properties = defines.DEFAULT
  28454. }
  28455. for (var i = 0; i < this.ids.length; i++) {
  28456. if (this.ids[i] in this.overpass.cacheElements && this.overpass.cacheElements[this.ids[i]] === false) {
  28457. delete this.overpass.cacheElements[this.ids[i]]
  28458. }
  28459. }
  28460. if (this.options.bbox) {
  28461. this.options.bbox = new BoundingBox(this.options.bbox)
  28462. }
  28463. // option 'split' not available for get requests -> use effort instead
  28464. delete this.options.split
  28465. this.done = {}
  28466. if ('members' in this.options) {
  28467. RequestGetMembers(this)
  28468. }
  28469. }
  28470. _effortForId (id) {
  28471. if (!id) {
  28472. return null
  28473. }
  28474. var type = id.substr(0, 1)
  28475. switch (type) {
  28476. case 'n':
  28477. return this.overpass.options.effortNode
  28478. case 'w':
  28479. return this.overpass.options.effortWay
  28480. case 'r':
  28481. return this.overpass.options.effortRelation
  28482. }
  28483. }
  28484. /**
  28485. * how much effort can a call to this request use
  28486. * @return {Request#minMaxEffortResult} - minimum and maximum effort
  28487. */
  28488. minMaxEffort () {
  28489. var todo = this.ids.filter(x => x)
  28490. if (todo.length === 0) {
  28491. return { minEffort: 0, maxEffort: 0 }
  28492. }
  28493. let minEffort = Math.min.apply(this, todo.map(id => this._effortForId(id)))
  28494. let maxEffort = todo.map(id => this._effortForId(id)).reduce((a, b) => a + b)
  28495. return { minEffort, maxEffort }
  28496. }
  28497. /**
  28498. * check if there are any map features which can be returned right now
  28499. */
  28500. preprocess () {
  28501. this.allFound = true
  28502. for (var i = 0; i < this.ids.length; i++) {
  28503. var id = this.ids[i]
  28504. if (id === null) {
  28505. continue
  28506. }
  28507. if (id in this.overpass.cacheElements) {
  28508. var ob = this.overpass.cacheElements[id]
  28509. var ready = true
  28510. // Feature does not exists!
  28511. if (ob.missingObject) {
  28512. this.featureCallback(null, null, i)
  28513. this.ids[i] = null
  28514. continue
  28515. }
  28516. // for bbox option, if object is (partly) loaded, but outside call
  28517. // featureCallback with 'false'
  28518. if (this.options.bbox && !ob.intersects(this.options.bbox)) {
  28519. this.featureCallback(null, false, i)
  28520. this.ids[i] = null
  28521. continue
  28522. }
  28523. // not fully loaded
  28524. if ((ob !== false && ob !== null) && (this.options.properties & ob.properties) !== this.options.properties) {
  28525. ready = false
  28526. }
  28527. // if sort is set in options maybe defer calling featureCallback
  28528. if (ready) {
  28529. this.featureCallback(null, ob, i)
  28530. this.ids[i] = null
  28531. continue
  28532. }
  28533. } else {
  28534. // Illegal ID
  28535. if (id !== null && !id.match(/^[nwr][0-9]+$/)) {
  28536. this.featureCallback(null, null, i)
  28537. this.ids[i] = null
  28538. continue
  28539. }
  28540. }
  28541. this.allFound = false
  28542. }
  28543. }
  28544. /**
  28545. * compile the query
  28546. * @param {OverpassFrontend#Context} context - Current context
  28547. * @return {Request#SubRequest} - the compiled query
  28548. */
  28549. _compileQuery (context) {
  28550. var query = ''
  28551. var nodeQuery = ''
  28552. var wayQuery = ''
  28553. var relationQuery = ''
  28554. var BBoxQuery = ''
  28555. var effort = 0
  28556. if (this.options.bbox) {
  28557. BBoxQuery = '(' + this.options.bbox.toLatLonString() + ')'
  28558. }
  28559. for (var i = 0; i < this.ids.length; i++) {
  28560. var id = this.ids[i]
  28561. var outOptions = overpassOutOptions(this.options)
  28562. if (effort > context.maxEffort) {
  28563. break
  28564. }
  28565. if (id === null) {
  28566. continue
  28567. }
  28568. // don't load objects multiple times in same context
  28569. if (id in context.todo) {
  28570. continue
  28571. }
  28572. if (this.options.bbox) {
  28573. // check if we already know the bbox of the element; if yes, don't try
  28574. // to load object if it does not intersect bounds
  28575. if (id in this.overpass.cacheElements && (this.overpass.cacheElements[id].properties & defines.BBOX)) {
  28576. if (!this.overpass.cacheElements[id].intersects(this.options.bbox)) {
  28577. continue
  28578. }
  28579. }
  28580. }
  28581. switch (id.substr(0, 1)) {
  28582. case 'n':
  28583. nodeQuery += 'node(' + id.substr(1) + ');\n'
  28584. effort += this.overpass.options.effortNode
  28585. break
  28586. case 'w':
  28587. wayQuery += 'way(' + id.substr(1) + ');\n'
  28588. effort += this.overpass.options.effortWay
  28589. break
  28590. case 'r':
  28591. relationQuery += 'relation(' + id.substr(1) + ');\n'
  28592. effort += this.overpass.options.effortRelation
  28593. break
  28594. }
  28595. context.todo[id] = true
  28596. }
  28597. if (nodeQuery !== '') {
  28598. query += '((' + nodeQuery + ');)->.n;\n'
  28599. if (BBoxQuery) {
  28600. query += '(node.n; - node.n' + BBoxQuery + '->.n;);\nout ids bb qt;\n'
  28601. }
  28602. }
  28603. if (wayQuery !== '') {
  28604. query += '((' + wayQuery + ');)->.w;\n'
  28605. if (BBoxQuery) {
  28606. query += '(way.w; - way.w' + BBoxQuery + '->.w;);\nout ids bb qt;\n'
  28607. }
  28608. }
  28609. if (relationQuery !== '') {
  28610. query += '((' + relationQuery + ');)->.r;\n'
  28611. if (BBoxQuery) {
  28612. query += '(relation.r; - relation.r' + BBoxQuery + '->.r;);\nout ids bb qt;\n'
  28613. }
  28614. }
  28615. var requestParts = []
  28616. if (BBoxQuery && (nodeQuery !== '' || wayQuery !== '' || relationQuery !== '')) {
  28617. // additional separator to separate objects outside bbox from inside bbox
  28618. query += 'out count;\n'
  28619. requestParts.push({
  28620. properties: defines.BBOX,
  28621. bbox: this.options.bbox,
  28622. bboxNoMatch: true
  28623. })
  28624. }
  28625. if (nodeQuery !== '') {
  28626. query += '.n out ' + outOptions + ';\n'
  28627. }
  28628. if (wayQuery !== '') {
  28629. query += '.w out ' + outOptions + ';\n'
  28630. }
  28631. if (relationQuery !== '') {
  28632. query += '.r out ' + outOptions + ';\n'
  28633. }
  28634. if (query) {
  28635. requestParts.push({
  28636. properties: this.options.properties,
  28637. receiveObject: this.receiveObject.bind(this),
  28638. featureCallback: this._featureCallback.bind(this, this.featureCallback)
  28639. })
  28640. }
  28641. var subRequest = {
  28642. query,
  28643. effort: effort,
  28644. request: this,
  28645. parts: requestParts
  28646. }
  28647. return subRequest
  28648. }
  28649. _featureCallback (fun, err, ob) {
  28650. var indexes = []
  28651. var p
  28652. while ((p = this.ids.indexOf(ob.id)) !== -1) {
  28653. this.ids[p] = null
  28654. indexes.push(p)
  28655. }
  28656. if (this.options.bbox && !ob.intersects(this.options.bbox)) {
  28657. indexes.forEach(p => fun(null, false, p))
  28658. return
  28659. }
  28660. indexes.forEach(p => fun(null, ob, p))
  28661. }
  28662. needLoad () {
  28663. this.preprocess()
  28664. return this.allFound
  28665. }
  28666. mayFinish () {
  28667. return this.allFound
  28668. }
  28669. }
  28670. module.exports = RequestGet
  28671. },{"./Request":185,"./RequestGetMembers":189,"./defines":193,"./overpassOutOptions":198,"boundingbox":20}],189:[function(require,module,exports){
  28672. const defines = require('./defines')
  28673. const overpassOutOptions = require('./overpassOutOptions')
  28674. const each = require('lodash/forEach')
  28675. const map = require('lodash/map')
  28676. const keys = require('lodash/keys')
  28677. const BoundingBox = require('boundingbox')
  28678. class RequestGetMembers {
  28679. constructor (request) {
  28680. this.master = request
  28681. this.options = this.master.options
  28682. this.overpass = this.master.overpass
  28683. this.options.properties |= defines.MEMBERS
  28684. this.options.memberProperties = this.options.memberProperties || defines.DEFAULT
  28685. this.options.memberProperties |= defines.BBOX
  28686. if (this.options.memberBounds) {
  28687. this.bounds = new BoundingBox(this.options.memberBounds)
  28688. }
  28689. this.master._compileQuery = this._compileQuery.bind(this, this.master._compileQuery)
  28690. this.master.needLoad = this.needLoad.bind(this, this.master.needLoad)
  28691. this.master.mayFinish = this.mayFinish.bind(this, this.master.mayFinish)
  28692. this.master.preprocess = this.preprocess.bind(this, this.master.preprocess)
  28693. this.master.willInclude = this.willInclude.bind(this, this.master.willInclude)
  28694. this.master.minMaxEffort = this.minMaxEffort.bind(this, this.master.minMaxEffort)
  28695. this.master.finishSubRequest = this.finishSubRequest.bind(this, this.master.finishSubRequest)
  28696. this.master.featureCallback = this.receiveMasterObject.bind(this, this.master.featureCallback)
  28697. this.doneFeatures = {}
  28698. this.relations = {}
  28699. this.currentRelations = []
  28700. this.todo = {}
  28701. }
  28702. willInclude (fun, context) {
  28703. let result = fun.call(this.master, context)
  28704. if (this.loadFinish) {
  28705. return false
  28706. }
  28707. if (!result) {
  28708. return false
  28709. }
  28710. if (!('extMembersList' in context)) {
  28711. context.extMembersList = this.relations
  28712. context.extMembersRequests = [ this ]
  28713. context.extMembersPriority = this.master.priority
  28714. return true
  28715. } else if (this.master.priority <= context.extMembersPriority) {
  28716. keys(this.relations).forEach(id => {
  28717. context.extMembersList[id] = this.relations[id]
  28718. })
  28719. context.extMembersRequests.push(this)
  28720. return false
  28721. }
  28722. }
  28723. minMaxEffort (fun) {
  28724. let { minEffort, maxEffort } = fun.call(this.master)
  28725. if (!this.loadFinish) {
  28726. minEffort += 64
  28727. maxEffort = null
  28728. }
  28729. return { minEffort, maxEffort }
  28730. }
  28731. preprocess (fun) {
  28732. fun.call(this.master)
  28733. this.todo = {}
  28734. each(this.relations, ob => {
  28735. each(ob.members, member => {
  28736. if (!(member.id in this.doneFeatures)) {
  28737. this.todo[member.id] = undefined
  28738. }
  28739. })
  28740. })
  28741. each(this.todo, (value, id) => {
  28742. if (id in this.overpass.cacheElements) {
  28743. var ob = this.overpass.cacheElements[id]
  28744. if (this.bounds && !ob.intersects(this.bounds)) {
  28745. return
  28746. }
  28747. if ((this.options.memberProperties & ob.properties) === this.options.memberProperties) {
  28748. this.doneFeatures[id] = ob
  28749. this.options.memberCallback(null, ob)
  28750. }
  28751. }
  28752. })
  28753. return
  28754. }
  28755. _compileQuery (fun, context) {
  28756. var subRequest = fun.call(this.master, context)
  28757. if (keys(this.relations).length === 0) {
  28758. return subRequest
  28759. }
  28760. let query = '(\n'
  28761. query += map(context.extMembersList, ob => {
  28762. if (ob.type === 'relation') {
  28763. return 'relation(' + ob.osm_id + ');\n'
  28764. }
  28765. return ''
  28766. }).join('')
  28767. query += ')->.result;'
  28768. this.currentRelations = keys(this.relations)
  28769. let BBoxString = ''
  28770. if (this.bounds) {
  28771. BBoxString = '(' + this.bounds.toLatLonString() + ')'
  28772. }
  28773. query += '(\n' +
  28774. ' node(r.result)' + BBoxString + ';\n' +
  28775. ' way(r.result)' + BBoxString + ';\n' +
  28776. ' relation(r.result)' + BBoxString + ';\n' +
  28777. ')->.resultMembers;\n'
  28778. var queryRemoveDoneFeatures = ''
  28779. var countRemoveDoneFeatures = 0
  28780. var listedDoneFeatures = {}
  28781. context.extMembersRequests.forEach(request => {
  28782. for (var id in request.doneFeatures) {
  28783. if (id in listedDoneFeatures) {
  28784. continue
  28785. }
  28786. var ob = request.doneFeatures[id]
  28787. if (countRemoveDoneFeatures % 1000 === 999) {
  28788. query += '(' + queryRemoveDoneFeatures + ')->.doneMembers;\n'
  28789. queryRemoveDoneFeatures = '.doneMembers;'
  28790. }
  28791. queryRemoveDoneFeatures += ob.type + '(' + ob.osm_id + ');'
  28792. countRemoveDoneFeatures++
  28793. listedDoneFeatures[id] = true
  28794. }
  28795. request.loadFinish = true
  28796. })
  28797. if (countRemoveDoneFeatures) {
  28798. query += '(' + queryRemoveDoneFeatures + ')->.doneMembers;\n'
  28799. query += '(.resultMembers; - .doneMembers;)->.resultMembers;\n'
  28800. }
  28801. this.part = {
  28802. properties: this.options.memberProperties,
  28803. receiveObject: this.receiveObject.bind(this),
  28804. featureCallback: this.options.memberCallback,
  28805. count: 0
  28806. }
  28807. query += '.resultMembers out ' + overpassOutOptions(this.part) + ';'
  28808. if (subRequest.parts.length) {
  28809. subRequest.query += '\nout count;\n'
  28810. }
  28811. subRequest.query += query
  28812. subRequest.parts.push(this.part)
  28813. return subRequest
  28814. }
  28815. receiveMasterObject (fun, err, result, index) {
  28816. this.relations[result.id] = result
  28817. this.loadFinish = false
  28818. fun(err, result, index)
  28819. }
  28820. receiveObject (ob) {
  28821. this.doneFeatures[ob.id] = ob
  28822. }
  28823. finishSubRequest (fun, subRequest) {
  28824. fun.call(this.master, subRequest)
  28825. if (keys(this.relations).length !== this.currentRelations.length) {
  28826. this.loadFinish = false
  28827. }
  28828. }
  28829. needLoad (fun) {
  28830. var result = fun.call(this.master)
  28831. if (result === true) {
  28832. return true
  28833. }
  28834. return !this.loadFinish
  28835. }
  28836. mayFinish (fun) {
  28837. var result = fun.call(this.master)
  28838. if (result === false) {
  28839. return false
  28840. }
  28841. return this.loadFinish
  28842. }
  28843. }
  28844. module.exports = function (request) {
  28845. return new RequestGetMembers(request)
  28846. }
  28847. },{"./defines":193,"./overpassOutOptions":198,"boundingbox":20,"lodash/forEach":150,"lodash/keys":164,"lodash/map":165}],190:[function(require,module,exports){
  28848. var async = require('async')
  28849. var weightSort = require('weight-sort')
  28850. var OverpassFrontend = require('./defines')
  28851. class SortedCallbacks {
  28852. constructor (options, featureCallback, finalCallback) {
  28853. this.list = []
  28854. this.lastIndex = -1
  28855. this.featureCallback = featureCallback
  28856. this.finalCallback = finalCallback
  28857. this.options = options
  28858. if (!('sort' in this.options) || this.options.sort === false) {
  28859. this.options.sort = null
  28860. }
  28861. if (!('sortDir' in this.options)) {
  28862. this.options.sortDir = 'asc'
  28863. }
  28864. if (this.options.sort === true) {
  28865. this.options.sort = 'index'
  28866. }
  28867. if (this.options.sort === 'BBoxDiagonalLength') {
  28868. this.options.properties |= OverpassFrontend.BBOX
  28869. }
  28870. }
  28871. next (err, feature, index) {
  28872. if (typeof index === 'undefined') {
  28873. index = this.list.length
  28874. }
  28875. this.list[index] = {
  28876. err: err,
  28877. feature: feature,
  28878. index: index
  28879. }
  28880. if ((this.options.sort === null) ||
  28881. (this.options.sort === 'index' && this.options.sortDir === 'asc' && index === this.lastIndex + 1)) {
  28882. async.setImmediate(function () {
  28883. this.featureCallback(this.list[index].err, this.list[index].feature, index)
  28884. }.bind(this))
  28885. this.lastIndex = index
  28886. }
  28887. }
  28888. final (err) {
  28889. if (this.options.sort === 'BBoxDiagonalLength') {
  28890. for (var i = 0; i < this.list.length; i++) {
  28891. var feature = this.list[i].feature
  28892. if (feature && feature.bounds) {
  28893. this.list[i].weight = feature.bounds.diagonalLength()
  28894. }
  28895. }
  28896. this.list = weightSort(this.list)
  28897. }
  28898. if (this.options.sortDir === 'desc') {
  28899. this.list.reverse()
  28900. }
  28901. async.setImmediate(function () {
  28902. if (this.options.sort !== null) {
  28903. for (var i = this.lastIndex + 1; i < this.list.length; i++) {
  28904. // if a request got aborted, the entry in list is missing
  28905. if (this.list[i]) {
  28906. this.featureCallback(this.list[i].err, this.list[i].feature, i)
  28907. }
  28908. }
  28909. }
  28910. this.finalCallback(err)
  28911. }.bind(this))
  28912. }
  28913. }
  28914. module.exports = SortedCallbacks
  28915. },{"./defines":193,"async":19,"weight-sort":208}],191:[function(require,module,exports){
  28916. module.exports = function convertFromXML (xml) {
  28917. let result = {
  28918. version: parseFloat(xml.getAttribute('version')),
  28919. generator: xml.getAttribute('generator'),
  28920. osm3s: {},
  28921. elements: []
  28922. }
  28923. let notes = xml.getElementsByTagName('note')
  28924. if (notes.length) {
  28925. result.osm3s.copyright = notes[0].textContent
  28926. }
  28927. let metas = xml.getElementsByTagName('meta')
  28928. if (metas.length) {
  28929. result.osm3s['timestamp_osm_base'] = metas[0].getAttribute('osm_base')
  28930. if (metas[0].hasAttribute('areas')) {
  28931. result.osm3s['timestamp_areas_base'] = metas[0].getAttribute('areas')
  28932. }
  28933. }
  28934. let current = xml.firstChild
  28935. while (current) {
  28936. let element = {}
  28937. if (current.nodeName === 'node' || current.nodeName === 'way' || current.nodeName === 'relation') {
  28938. element.type = current.nodeName
  28939. element.id = parseInt(current.getAttribute('id'))
  28940. element.changeset = parseInt(current.getAttribute('changeset'))
  28941. element.timestamp = current.getAttribute('timestamp')
  28942. element.user = current.getAttribute('user')
  28943. element.uid = parseInt(current.getAttribute('uid'))
  28944. element.version = parseInt(current.getAttribute('version'))
  28945. if (element.type === 'node') {
  28946. element.lat = parseFloat(current.getAttribute('lat'))
  28947. element.lon = parseFloat(current.getAttribute('lon'))
  28948. } else if (element.type === 'way') {
  28949. element.nodes = []
  28950. } else if (element.type === 'relation') {
  28951. element.members = []
  28952. }
  28953. let child = current.firstChild
  28954. while (child) {
  28955. if (child.nodeName === 'tag') {
  28956. if (!('tags' in element)) {
  28957. element.tags = {}
  28958. }
  28959. element.tags[child.getAttribute('k')] = child.getAttribute('v')
  28960. } else if (child.nodeName === 'member') {
  28961. element.members.push({
  28962. type: child.getAttribute('type'),
  28963. ref: parseInt(child.getAttribute('ref')),
  28964. role: child.getAttribute('role')
  28965. })
  28966. } else if (child.nodeName === 'nd') {
  28967. element.nodes.push(parseInt(child.getAttribute('ref')))
  28968. }
  28969. child = child.nextSibling
  28970. }
  28971. result.elements.push(element)
  28972. }
  28973. current = current.nextSibling
  28974. }
  28975. return result
  28976. }
  28977. },{}],192:[function(require,module,exports){
  28978. module.exports = function copyOsm3sMetaFrom (results) {
  28979. let osm3sMeta = {}
  28980. for (let k in results) {
  28981. if (k !== 'elements' && k !== 'osm3s') {
  28982. osm3sMeta[k] = results[k]
  28983. }
  28984. }
  28985. if (results.osm3s) {
  28986. for (let k in results.osm3s) {
  28987. osm3sMeta[k] = results.osm3s[k]
  28988. }
  28989. }
  28990. return osm3sMeta
  28991. }
  28992. },{}],193:[function(require,module,exports){
  28993. module.exports = {
  28994. 'ID_ONLY': 0,
  28995. 'TAGS': 1,
  28996. 'META': 2,
  28997. 'MEMBERS': 4,
  28998. 'BBOX': 8,
  28999. 'GEOM': 16,
  29000. 'CENTER': 32,
  29001. 'ALL': 63,
  29002. 'DEFAULT': 13
  29003. }
  29004. },{}],194:[function(require,module,exports){
  29005. module.exports = function filterJoin (def) {
  29006. let result = [ '' ]
  29007. if (!Array.isArray(def)) {
  29008. def = [ def ]
  29009. }
  29010. def.forEach(
  29011. d => {
  29012. if (d.or) {
  29013. let sub = d.or.map(e => filterJoin(e))
  29014. let newResult = []
  29015. result.forEach(r => { newResult = newResult.concat(sub.map(s => r + s)) })
  29016. result = newResult
  29017. } else {
  29018. result = result.map(r => r + d)
  29019. }
  29020. }
  29021. )
  29022. return result
  29023. }
  29024. },{}],195:[function(require,module,exports){
  29025. (function (global){
  29026. /* global location:false */
  29027. if (typeof XMLHttpRequest === 'undefined') {
  29028. global.XMLHttpRequest = (typeof window !== "undefined" ? window['XMLHttpRequest'] : typeof global !== "undefined" ? global['XMLHttpRequest'] : null).XMLHttpRequest
  29029. }
  29030. function httpLoad (url, getParam, postParam, callback) {
  29031. var req = new global.XMLHttpRequest()
  29032. req.onreadystatechange = function () {
  29033. var data = null
  29034. var err = null
  29035. if (req.readyState === 4) {
  29036. if (req.status === 200) {
  29037. try {
  29038. data = JSON.parse(req.responseText)
  29039. } catch (err) {
  29040. // err already set
  29041. }
  29042. callback(err, data)
  29043. } else {
  29044. try {
  29045. err = JSON.parse(req.responseText)
  29046. } catch (err) {
  29047. if (req.responseText.search('OSM3S Response') !== -1) {
  29048. var lines = req.responseText.split(/\n/)
  29049. var e = ''
  29050. for (var i = 0; i < lines.length; i++) {
  29051. var m
  29052. if ((m = lines[i].match(/<p><strong style="color:#FF0000">Error<\/strong>: (.*)<\/p>/))) {
  29053. e += m[1] + '\n'
  29054. }
  29055. }
  29056. // Could not parse error message - create alternative
  29057. if (e === '') {
  29058. e = 'Got error ' + req.status
  29059. }
  29060. callback(e, null)
  29061. } else {
  29062. callback(req.responseText, null)
  29063. }
  29064. }
  29065. }
  29066. }
  29067. }
  29068. var reqType = 'GET'
  29069. var postData = null
  29070. if (postParam) {
  29071. reqType = 'POST'
  29072. postData = postParam
  29073. }
  29074. if (url.substr(0, 2) === '//') {
  29075. if (typeof location === 'undefined') {
  29076. url = 'https:' + url
  29077. } else {
  29078. url = location.protocol + url
  29079. }
  29080. }
  29081. req.open(reqType, url, true)
  29082. try {
  29083. req.send(postData)
  29084. } catch (err) {
  29085. callback(err, null)
  29086. }
  29087. }
  29088. module.exports = httpLoad
  29089. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29090. },{}],196:[function(require,module,exports){
  29091. const BoundingBox = require('boundingbox')
  29092. const turf = require('./turf')
  29093. /**
  29094. * When loading area after area of a map, it will be more and more complete.
  29095. * This class manages which area is already known and which not.
  29096. */
  29097. class KnownArea {
  29098. constructor (area = null) {
  29099. this.area = area
  29100. }
  29101. /**
  29102. * make another part of the map known
  29103. */
  29104. add (bbox) {
  29105. bbox = new BoundingBox(bbox).toGeoJSON()
  29106. if (this.area === null) {
  29107. this.area = bbox
  29108. } else {
  29109. this.area = turf.union(bbox, this.area)
  29110. }
  29111. }
  29112. /**
  29113. * is the whole area known?
  29114. */
  29115. check (bbox) {
  29116. if (this.area === null) {
  29117. return false
  29118. }
  29119. bbox = new BoundingBox(bbox).toGeoJSON()
  29120. let remaining = turf.difference(bbox, this.area)
  29121. // console.log(JSON.stringify(this.area), JSON.stringify(bbox), !remaining)
  29122. return !remaining
  29123. }
  29124. /**
  29125. * return area as (multi)polygon
  29126. */
  29127. toGeoJSON () {
  29128. return this.area
  29129. }
  29130. }
  29131. module.exports = KnownArea
  29132. },{"./turf":200,"boundingbox":20}],197:[function(require,module,exports){
  29133. const fs = require('fs')
  29134. const DOMParser = require('xmldom').DOMParser
  29135. const bzip2 = require('bzip2')
  29136. const convertFromXML = require('./convertFromXML')
  29137. module.exports = function loadOsmFile (url, callback) {
  29138. if (typeof location === 'undefined' && !url.match(/^(http:|https:|)\/\//)) {
  29139. fs.readFile(url,
  29140. (err, content) => {
  29141. let data
  29142. if (err) {
  29143. return callback(err)
  29144. }
  29145. if (url.match(/\.osm(\.bz2)?$/)) {
  29146. if (url.match(/\.osm\.bz2$/)) {
  29147. data = bzip2.simple(bzip2.array(content))
  29148. content = ''
  29149. for (let i = 0; i < data.byteLength; i++) {
  29150. content += String.fromCharCode(data[i])
  29151. }
  29152. content = decodeURIComponent(escape(content))
  29153. }
  29154. data = new DOMParser().parseFromString(content.toString(), 'text/xml')
  29155. data = convertFromXML(data.getElementsByTagName('osm')[0])
  29156. } else {
  29157. data = JSON.parse(content)
  29158. }
  29159. callback(null, data)
  29160. }
  29161. )
  29162. return
  29163. }
  29164. let req = new window.XMLHttpRequest()
  29165. req.onreadystatechange = function () {
  29166. if (req.readyState === 4) {
  29167. if (req.status === 200) {
  29168. let data
  29169. if (url.match(/\.osm\.bz2$/)) {
  29170. let content = new Uint8Array(req.response)
  29171. data = bzip2.simple(bzip2.array(content))
  29172. content = ''
  29173. for (let i = 0; i < data.byteLength; i++) {
  29174. content += String.fromCharCode(data[i])
  29175. }
  29176. content = decodeURIComponent(escape(content))
  29177. data = new DOMParser().parseFromString(content.toString(), 'text/xml')
  29178. data = convertFromXML(data.getElementsByTagName('osm')[0])
  29179. } else if (req.responseXML) {
  29180. data = convertFromXML(req.responseXML.firstChild)
  29181. } else {
  29182. data = JSON.parse(req.responseText)
  29183. }
  29184. callback(null, data)
  29185. } else {
  29186. callback(req)
  29187. }
  29188. }
  29189. }
  29190. if (url.substr(0, 2) === '//') {
  29191. if (typeof location === 'undefined') {
  29192. url = 'https:' + url
  29193. } else {
  29194. url = window.location.protocol + url
  29195. }
  29196. }
  29197. if (url.match(/\.osm\.bz2$/)) {
  29198. req.responseType = 'arraybuffer'
  29199. }
  29200. req.open('GET', url)
  29201. req.send()
  29202. }
  29203. },{"./convertFromXML":191,"bzip2":24,"fs":23,"xmldom":210}],198:[function(require,module,exports){
  29204. var defines = require('./defines')
  29205. function overpassOutOptions (options, optionsOverride) {
  29206. var outOptions = ''
  29207. if ('split' in options && options.split > 0) {
  29208. outOptions += options.split + ' '
  29209. } else if ('effortSplit' in options) {
  29210. outOptions += options.effortSplit + ' '
  29211. }
  29212. if (options.properties & defines.META) {
  29213. outOptions += 'meta '
  29214. } else if (options.properties & defines.TAGS) {
  29215. if (options.properties & defines.MEMBERS) {
  29216. outOptions += 'body '
  29217. } else {
  29218. outOptions += 'tags '
  29219. }
  29220. } else if (options.properties & defines.MEMBERS) {
  29221. outOptions += 'skel '
  29222. } else {
  29223. outOptions += 'ids '
  29224. }
  29225. if (options.properties & defines.GEOM) {
  29226. outOptions += 'geom '
  29227. } else if (options.properties & defines.BBOX) {
  29228. outOptions += 'bb '
  29229. } else if (options.properties & defines.CENTER) {
  29230. outOptions += 'center '
  29231. }
  29232. outOptions += 'qt'
  29233. return outOptions
  29234. }
  29235. module.exports = overpassOutOptions
  29236. },{"./defines":193}],199:[function(require,module,exports){
  29237. function removeNullEntries (arr) {
  29238. var p
  29239. while ((p = arr.indexOf(null)) !== -1) {
  29240. arr.splice(p, 1)
  29241. }
  29242. return arr
  29243. }
  29244. module.exports = removeNullEntries
  29245. },{}],200:[function(require,module,exports){
  29246. module.exports = {
  29247. difference: require('@turf/difference'),
  29248. union: require('@turf/union').default
  29249. }
  29250. },{"@turf/difference":9,"@turf/union":18}],201:[function(require,module,exports){
  29251. (function (process){
  29252. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  29253. // backported and transplited with Babel, with backwards-compat fixes
  29254. // Copyright Joyent, Inc. and other Node contributors.
  29255. //
  29256. // Permission is hereby granted, free of charge, to any person obtaining a
  29257. // copy of this software and associated documentation files (the
  29258. // "Software"), to deal in the Software without restriction, including
  29259. // without limitation the rights to use, copy, modify, merge, publish,
  29260. // distribute, sublicense, and/or sell copies of the Software, and to permit
  29261. // persons to whom the Software is furnished to do so, subject to the
  29262. // following conditions:
  29263. //
  29264. // The above copyright notice and this permission notice shall be included
  29265. // in all copies or substantial portions of the Software.
  29266. //
  29267. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  29268. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29269. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  29270. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  29271. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  29272. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  29273. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  29274. // resolves . and .. elements in a path array with directory names there
  29275. // must be no slashes, empty elements, or device names (c:\) in the array
  29276. // (so also no leading and trailing slashes - it does not distinguish
  29277. // relative and absolute paths)
  29278. function normalizeArray(parts, allowAboveRoot) {
  29279. // if the path tries to go above the root, `up` ends up > 0
  29280. var up = 0;
  29281. for (var i = parts.length - 1; i >= 0; i--) {
  29282. var last = parts[i];
  29283. if (last === '.') {
  29284. parts.splice(i, 1);
  29285. } else if (last === '..') {
  29286. parts.splice(i, 1);
  29287. up++;
  29288. } else if (up) {
  29289. parts.splice(i, 1);
  29290. up--;
  29291. }
  29292. }
  29293. // if the path is allowed to go above the root, restore leading ..s
  29294. if (allowAboveRoot) {
  29295. for (; up--; up) {
  29296. parts.unshift('..');
  29297. }
  29298. }
  29299. return parts;
  29300. }
  29301. // path.resolve([from ...], to)
  29302. // posix version
  29303. exports.resolve = function() {
  29304. var resolvedPath = '',
  29305. resolvedAbsolute = false;
  29306. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  29307. var path = (i >= 0) ? arguments[i] : process.cwd();
  29308. // Skip empty and invalid entries
  29309. if (typeof path !== 'string') {
  29310. throw new TypeError('Arguments to path.resolve must be strings');
  29311. } else if (!path) {
  29312. continue;
  29313. }
  29314. resolvedPath = path + '/' + resolvedPath;
  29315. resolvedAbsolute = path.charAt(0) === '/';
  29316. }
  29317. // At this point the path should be resolved to a full absolute path, but
  29318. // handle relative paths to be safe (might happen when process.cwd() fails)
  29319. // Normalize the path
  29320. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  29321. return !!p;
  29322. }), !resolvedAbsolute).join('/');
  29323. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  29324. };
  29325. // path.normalize(path)
  29326. // posix version
  29327. exports.normalize = function(path) {
  29328. var isAbsolute = exports.isAbsolute(path),
  29329. trailingSlash = substr(path, -1) === '/';
  29330. // Normalize the path
  29331. path = normalizeArray(filter(path.split('/'), function(p) {
  29332. return !!p;
  29333. }), !isAbsolute).join('/');
  29334. if (!path && !isAbsolute) {
  29335. path = '.';
  29336. }
  29337. if (path && trailingSlash) {
  29338. path += '/';
  29339. }
  29340. return (isAbsolute ? '/' : '') + path;
  29341. };
  29342. // posix version
  29343. exports.isAbsolute = function(path) {
  29344. return path.charAt(0) === '/';
  29345. };
  29346. // posix version
  29347. exports.join = function() {
  29348. var paths = Array.prototype.slice.call(arguments, 0);
  29349. return exports.normalize(filter(paths, function(p, index) {
  29350. if (typeof p !== 'string') {
  29351. throw new TypeError('Arguments to path.join must be strings');
  29352. }
  29353. return p;
  29354. }).join('/'));
  29355. };
  29356. // path.relative(from, to)
  29357. // posix version
  29358. exports.relative = function(from, to) {
  29359. from = exports.resolve(from).substr(1);
  29360. to = exports.resolve(to).substr(1);
  29361. function trim(arr) {
  29362. var start = 0;
  29363. for (; start < arr.length; start++) {
  29364. if (arr[start] !== '') break;
  29365. }
  29366. var end = arr.length - 1;
  29367. for (; end >= 0; end--) {
  29368. if (arr[end] !== '') break;
  29369. }
  29370. if (start > end) return [];
  29371. return arr.slice(start, end - start + 1);
  29372. }
  29373. var fromParts = trim(from.split('/'));
  29374. var toParts = trim(to.split('/'));
  29375. var length = Math.min(fromParts.length, toParts.length);
  29376. var samePartsLength = length;
  29377. for (var i = 0; i < length; i++) {
  29378. if (fromParts[i] !== toParts[i]) {
  29379. samePartsLength = i;
  29380. break;
  29381. }
  29382. }
  29383. var outputParts = [];
  29384. for (var i = samePartsLength; i < fromParts.length; i++) {
  29385. outputParts.push('..');
  29386. }
  29387. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  29388. return outputParts.join('/');
  29389. };
  29390. exports.sep = '/';
  29391. exports.delimiter = ':';
  29392. exports.dirname = function (path) {
  29393. if (typeof path !== 'string') path = path + '';
  29394. if (path.length === 0) return '.';
  29395. var code = path.charCodeAt(0);
  29396. var hasRoot = code === 47 /*/*/;
  29397. var end = -1;
  29398. var matchedSlash = true;
  29399. for (var i = path.length - 1; i >= 1; --i) {
  29400. code = path.charCodeAt(i);
  29401. if (code === 47 /*/*/) {
  29402. if (!matchedSlash) {
  29403. end = i;
  29404. break;
  29405. }
  29406. } else {
  29407. // We saw the first non-path separator
  29408. matchedSlash = false;
  29409. }
  29410. }
  29411. if (end === -1) return hasRoot ? '/' : '.';
  29412. if (hasRoot && end === 1) {
  29413. // return '//';
  29414. // Backwards-compat fix:
  29415. return '/';
  29416. }
  29417. return path.slice(0, end);
  29418. };
  29419. function basename(path) {
  29420. if (typeof path !== 'string') path = path + '';
  29421. var start = 0;
  29422. var end = -1;
  29423. var matchedSlash = true;
  29424. var i;
  29425. for (i = path.length - 1; i >= 0; --i) {
  29426. if (path.charCodeAt(i) === 47 /*/*/) {
  29427. // If we reached a path separator that was not part of a set of path
  29428. // separators at the end of the string, stop now
  29429. if (!matchedSlash) {
  29430. start = i + 1;
  29431. break;
  29432. }
  29433. } else if (end === -1) {
  29434. // We saw the first non-path separator, mark this as the end of our
  29435. // path component
  29436. matchedSlash = false;
  29437. end = i + 1;
  29438. }
  29439. }
  29440. if (end === -1) return '';
  29441. return path.slice(start, end);
  29442. }
  29443. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  29444. // in new Node.js versions, so only basename() above is backported here
  29445. exports.basename = function (path, ext) {
  29446. var f = basename(path);
  29447. if (ext && f.substr(-1 * ext.length) === ext) {
  29448. f = f.substr(0, f.length - ext.length);
  29449. }
  29450. return f;
  29451. };
  29452. exports.extname = function (path) {
  29453. if (typeof path !== 'string') path = path + '';
  29454. var startDot = -1;
  29455. var startPart = 0;
  29456. var end = -1;
  29457. var matchedSlash = true;
  29458. // Track the state of characters (if any) we see before our first dot and
  29459. // after any path separator we find
  29460. var preDotState = 0;
  29461. for (var i = path.length - 1; i >= 0; --i) {
  29462. var code = path.charCodeAt(i);
  29463. if (code === 47 /*/*/) {
  29464. // If we reached a path separator that was not part of a set of path
  29465. // separators at the end of the string, stop now
  29466. if (!matchedSlash) {
  29467. startPart = i + 1;
  29468. break;
  29469. }
  29470. continue;
  29471. }
  29472. if (end === -1) {
  29473. // We saw the first non-path separator, mark this as the end of our
  29474. // extension
  29475. matchedSlash = false;
  29476. end = i + 1;
  29477. }
  29478. if (code === 46 /*.*/) {
  29479. // If this is our first dot, mark it as the start of our extension
  29480. if (startDot === -1)
  29481. startDot = i;
  29482. else if (preDotState !== 1)
  29483. preDotState = 1;
  29484. } else if (startDot !== -1) {
  29485. // We saw a non-dot and non-path separator before our dot, so we should
  29486. // have a good chance at having a non-empty extension
  29487. preDotState = -1;
  29488. }
  29489. }
  29490. if (startDot === -1 || end === -1 ||
  29491. // We saw a non-dot character immediately before the dot
  29492. preDotState === 0 ||
  29493. // The (right-most) trimmed path component is exactly '..'
  29494. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  29495. return '';
  29496. }
  29497. return path.slice(startDot, end);
  29498. };
  29499. function filter (xs, f) {
  29500. if (xs.filter) return xs.filter(f);
  29501. var res = [];
  29502. for (var i = 0; i < xs.length; i++) {
  29503. if (f(xs[i], i, xs)) res.push(xs[i]);
  29504. }
  29505. return res;
  29506. }
  29507. // String.prototype.substr - negative index don't work in IE8
  29508. var substr = 'ab'.substr(-1) === 'b'
  29509. ? function (str, start, len) { return str.substr(start, len) }
  29510. : function (str, start, len) {
  29511. if (start < 0) start = str.length + start;
  29512. return str.substr(start, len);
  29513. }
  29514. ;
  29515. }).call(this,require('_process'))
  29516. },{"_process":202}],202:[function(require,module,exports){
  29517. // shim for using process in browser
  29518. var process = module.exports = {};
  29519. // cached from whatever global is present so that test runners that stub it
  29520. // don't break things. But we need to wrap it in a try catch in case it is
  29521. // wrapped in strict mode code which doesn't define any globals. It's inside a
  29522. // function because try/catches deoptimize in certain engines.
  29523. var cachedSetTimeout;
  29524. var cachedClearTimeout;
  29525. function defaultSetTimout() {
  29526. throw new Error('setTimeout has not been defined');
  29527. }
  29528. function defaultClearTimeout () {
  29529. throw new Error('clearTimeout has not been defined');
  29530. }
  29531. (function () {
  29532. try {
  29533. if (typeof setTimeout === 'function') {
  29534. cachedSetTimeout = setTimeout;
  29535. } else {
  29536. cachedSetTimeout = defaultSetTimout;
  29537. }
  29538. } catch (e) {
  29539. cachedSetTimeout = defaultSetTimout;
  29540. }
  29541. try {
  29542. if (typeof clearTimeout === 'function') {
  29543. cachedClearTimeout = clearTimeout;
  29544. } else {
  29545. cachedClearTimeout = defaultClearTimeout;
  29546. }
  29547. } catch (e) {
  29548. cachedClearTimeout = defaultClearTimeout;
  29549. }
  29550. } ())
  29551. function runTimeout(fun) {
  29552. if (cachedSetTimeout === setTimeout) {
  29553. //normal enviroments in sane situations
  29554. return setTimeout(fun, 0);
  29555. }
  29556. // if setTimeout wasn't available but was latter defined
  29557. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  29558. cachedSetTimeout = setTimeout;
  29559. return setTimeout(fun, 0);
  29560. }
  29561. try {
  29562. // when when somebody has screwed with setTimeout but no I.E. maddness
  29563. return cachedSetTimeout(fun, 0);
  29564. } catch(e){
  29565. try {
  29566. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  29567. return cachedSetTimeout.call(null, fun, 0);
  29568. } catch(e){
  29569. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  29570. return cachedSetTimeout.call(this, fun, 0);
  29571. }
  29572. }
  29573. }
  29574. function runClearTimeout(marker) {
  29575. if (cachedClearTimeout === clearTimeout) {
  29576. //normal enviroments in sane situations
  29577. return clearTimeout(marker);
  29578. }
  29579. // if clearTimeout wasn't available but was latter defined
  29580. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  29581. cachedClearTimeout = clearTimeout;
  29582. return clearTimeout(marker);
  29583. }
  29584. try {
  29585. // when when somebody has screwed with setTimeout but no I.E. maddness
  29586. return cachedClearTimeout(marker);
  29587. } catch (e){
  29588. try {
  29589. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  29590. return cachedClearTimeout.call(null, marker);
  29591. } catch (e){
  29592. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  29593. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  29594. return cachedClearTimeout.call(this, marker);
  29595. }
  29596. }
  29597. }
  29598. var queue = [];
  29599. var draining = false;
  29600. var currentQueue;
  29601. var queueIndex = -1;
  29602. function cleanUpNextTick() {
  29603. if (!draining || !currentQueue) {
  29604. return;
  29605. }
  29606. draining = false;
  29607. if (currentQueue.length) {
  29608. queue = currentQueue.concat(queue);
  29609. } else {
  29610. queueIndex = -1;
  29611. }
  29612. if (queue.length) {
  29613. drainQueue();
  29614. }
  29615. }
  29616. function drainQueue() {
  29617. if (draining) {
  29618. return;
  29619. }
  29620. var timeout = runTimeout(cleanUpNextTick);
  29621. draining = true;
  29622. var len = queue.length;
  29623. while(len) {
  29624. currentQueue = queue;
  29625. queue = [];
  29626. while (++queueIndex < len) {
  29627. if (currentQueue) {
  29628. currentQueue[queueIndex].run();
  29629. }
  29630. }
  29631. queueIndex = -1;
  29632. len = queue.length;
  29633. }
  29634. currentQueue = null;
  29635. draining = false;
  29636. runClearTimeout(timeout);
  29637. }
  29638. process.nextTick = function (fun) {
  29639. var args = new Array(arguments.length - 1);
  29640. if (arguments.length > 1) {
  29641. for (var i = 1; i < arguments.length; i++) {
  29642. args[i - 1] = arguments[i];
  29643. }
  29644. }
  29645. queue.push(new Item(fun, args));
  29646. if (queue.length === 1 && !draining) {
  29647. runTimeout(drainQueue);
  29648. }
  29649. };
  29650. // v8 likes predictible objects
  29651. function Item(fun, array) {
  29652. this.fun = fun;
  29653. this.array = array;
  29654. }
  29655. Item.prototype.run = function () {
  29656. this.fun.apply(null, this.array);
  29657. };
  29658. process.title = 'browser';
  29659. process.browser = true;
  29660. process.env = {};
  29661. process.argv = [];
  29662. process.version = ''; // empty string to avoid regexp issues
  29663. process.versions = {};
  29664. function noop() {}
  29665. process.on = noop;
  29666. process.addListener = noop;
  29667. process.once = noop;
  29668. process.off = noop;
  29669. process.removeListener = noop;
  29670. process.removeAllListeners = noop;
  29671. process.emit = noop;
  29672. process.prependListener = noop;
  29673. process.prependOnceListener = noop;
  29674. process.listeners = function (name) { return [] }
  29675. process.binding = function (name) {
  29676. throw new Error('process.binding is not supported');
  29677. };
  29678. process.cwd = function () { return '/' };
  29679. process.chdir = function (dir) {
  29680. throw new Error('process.chdir is not supported');
  29681. };
  29682. process.umask = function() { return 0; };
  29683. },{}],203:[function(require,module,exports){
  29684. (function (global, factory) {
  29685. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  29686. typeof define === 'function' && define.amd ? define(factory) :
  29687. (global.quickselect = factory());
  29688. }(this, (function () { 'use strict';
  29689. function quickselect(arr, k, left, right, compare) {
  29690. quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
  29691. }
  29692. function quickselectStep(arr, k, left, right, compare) {
  29693. while (right > left) {
  29694. if (right - left > 600) {
  29695. var n = right - left + 1;
  29696. var m = k - left + 1;
  29697. var z = Math.log(n);
  29698. var s = 0.5 * Math.exp(2 * z / 3);
  29699. var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
  29700. var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
  29701. var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
  29702. quickselectStep(arr, k, newLeft, newRight, compare);
  29703. }
  29704. var t = arr[k];
  29705. var i = left;
  29706. var j = right;
  29707. swap(arr, left, k);
  29708. if (compare(arr[right], t) > 0) swap(arr, left, right);
  29709. while (i < j) {
  29710. swap(arr, i, j);
  29711. i++;
  29712. j--;
  29713. while (compare(arr[i], t) < 0) i++;
  29714. while (compare(arr[j], t) > 0) j--;
  29715. }
  29716. if (compare(arr[left], t) === 0) swap(arr, left, j);
  29717. else {
  29718. j++;
  29719. swap(arr, j, right);
  29720. }
  29721. if (j <= k) left = j + 1;
  29722. if (k <= j) right = j - 1;
  29723. }
  29724. }
  29725. function swap(arr, i, j) {
  29726. var tmp = arr[i];
  29727. arr[i] = arr[j];
  29728. arr[j] = tmp;
  29729. }
  29730. function defaultCompare(a, b) {
  29731. return a < b ? -1 : a > b ? 1 : 0;
  29732. }
  29733. return quickselect;
  29734. })));
  29735. },{}],204:[function(require,module,exports){
  29736. 'use strict';
  29737. module.exports = rbush;
  29738. module.exports.default = rbush;
  29739. var quickselect = require('quickselect');
  29740. function rbush(maxEntries, format) {
  29741. if (!(this instanceof rbush)) return new rbush(maxEntries, format);
  29742. // max entries in a node is 9 by default; min node fill is 40% for best performance
  29743. this._maxEntries = Math.max(4, maxEntries || 9);
  29744. this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
  29745. if (format) {
  29746. this._initFormat(format);
  29747. }
  29748. this.clear();
  29749. }
  29750. rbush.prototype = {
  29751. all: function () {
  29752. return this._all(this.data, []);
  29753. },
  29754. search: function (bbox) {
  29755. var node = this.data,
  29756. result = [],
  29757. toBBox = this.toBBox;
  29758. if (!intersects(bbox, node)) return result;
  29759. var nodesToSearch = [],
  29760. i, len, child, childBBox;
  29761. while (node) {
  29762. for (i = 0, len = node.children.length; i < len; i++) {
  29763. child = node.children[i];
  29764. childBBox = node.leaf ? toBBox(child) : child;
  29765. if (intersects(bbox, childBBox)) {
  29766. if (node.leaf) result.push(child);
  29767. else if (contains(bbox, childBBox)) this._all(child, result);
  29768. else nodesToSearch.push(child);
  29769. }
  29770. }
  29771. node = nodesToSearch.pop();
  29772. }
  29773. return result;
  29774. },
  29775. collides: function (bbox) {
  29776. var node = this.data,
  29777. toBBox = this.toBBox;
  29778. if (!intersects(bbox, node)) return false;
  29779. var nodesToSearch = [],
  29780. i, len, child, childBBox;
  29781. while (node) {
  29782. for (i = 0, len = node.children.length; i < len; i++) {
  29783. child = node.children[i];
  29784. childBBox = node.leaf ? toBBox(child) : child;
  29785. if (intersects(bbox, childBBox)) {
  29786. if (node.leaf || contains(bbox, childBBox)) return true;
  29787. nodesToSearch.push(child);
  29788. }
  29789. }
  29790. node = nodesToSearch.pop();
  29791. }
  29792. return false;
  29793. },
  29794. load: function (data) {
  29795. if (!(data && data.length)) return this;
  29796. if (data.length < this._minEntries) {
  29797. for (var i = 0, len = data.length; i < len; i++) {
  29798. this.insert(data[i]);
  29799. }
  29800. return this;
  29801. }
  29802. // recursively build the tree with the given data from scratch using OMT algorithm
  29803. var node = this._build(data.slice(), 0, data.length - 1, 0);
  29804. if (!this.data.children.length) {
  29805. // save as is if tree is empty
  29806. this.data = node;
  29807. } else if (this.data.height === node.height) {
  29808. // split root if trees have the same height
  29809. this._splitRoot(this.data, node);
  29810. } else {
  29811. if (this.data.height < node.height) {
  29812. // swap trees if inserted one is bigger
  29813. var tmpNode = this.data;
  29814. this.data = node;
  29815. node = tmpNode;
  29816. }
  29817. // insert the small tree into the large tree at appropriate level
  29818. this._insert(node, this.data.height - node.height - 1, true);
  29819. }
  29820. return this;
  29821. },
  29822. insert: function (item) {
  29823. if (item) this._insert(item, this.data.height - 1);
  29824. return this;
  29825. },
  29826. clear: function () {
  29827. this.data = createNode([]);
  29828. return this;
  29829. },
  29830. remove: function (item, equalsFn) {
  29831. if (!item) return this;
  29832. var node = this.data,
  29833. bbox = this.toBBox(item),
  29834. path = [],
  29835. indexes = [],
  29836. i, parent, index, goingUp;
  29837. // depth-first iterative tree traversal
  29838. while (node || path.length) {
  29839. if (!node) { // go up
  29840. node = path.pop();
  29841. parent = path[path.length - 1];
  29842. i = indexes.pop();
  29843. goingUp = true;
  29844. }
  29845. if (node.leaf) { // check current node
  29846. index = findItem(item, node.children, equalsFn);
  29847. if (index !== -1) {
  29848. // item found, remove the item and condense tree upwards
  29849. node.children.splice(index, 1);
  29850. path.push(node);
  29851. this._condense(path);
  29852. return this;
  29853. }
  29854. }
  29855. if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
  29856. path.push(node);
  29857. indexes.push(i);
  29858. i = 0;
  29859. parent = node;
  29860. node = node.children[0];
  29861. } else if (parent) { // go right
  29862. i++;
  29863. node = parent.children[i];
  29864. goingUp = false;
  29865. } else node = null; // nothing found
  29866. }
  29867. return this;
  29868. },
  29869. toBBox: function (item) { return item; },
  29870. compareMinX: compareNodeMinX,
  29871. compareMinY: compareNodeMinY,
  29872. toJSON: function () { return this.data; },
  29873. fromJSON: function (data) {
  29874. this.data = data;
  29875. return this;
  29876. },
  29877. _all: function (node, result) {
  29878. var nodesToSearch = [];
  29879. while (node) {
  29880. if (node.leaf) result.push.apply(result, node.children);
  29881. else nodesToSearch.push.apply(nodesToSearch, node.children);
  29882. node = nodesToSearch.pop();
  29883. }
  29884. return result;
  29885. },
  29886. _build: function (items, left, right, height) {
  29887. var N = right - left + 1,
  29888. M = this._maxEntries,
  29889. node;
  29890. if (N <= M) {
  29891. // reached leaf level; return leaf
  29892. node = createNode(items.slice(left, right + 1));
  29893. calcBBox(node, this.toBBox);
  29894. return node;
  29895. }
  29896. if (!height) {
  29897. // target height of the bulk-loaded tree
  29898. height = Math.ceil(Math.log(N) / Math.log(M));
  29899. // target number of root entries to maximize storage utilization
  29900. M = Math.ceil(N / Math.pow(M, height - 1));
  29901. }
  29902. node = createNode([]);
  29903. node.leaf = false;
  29904. node.height = height;
  29905. // split the items into M mostly square tiles
  29906. var N2 = Math.ceil(N / M),
  29907. N1 = N2 * Math.ceil(Math.sqrt(M)),
  29908. i, j, right2, right3;
  29909. multiSelect(items, left, right, N1, this.compareMinX);
  29910. for (i = left; i <= right; i += N1) {
  29911. right2 = Math.min(i + N1 - 1, right);
  29912. multiSelect(items, i, right2, N2, this.compareMinY);
  29913. for (j = i; j <= right2; j += N2) {
  29914. right3 = Math.min(j + N2 - 1, right2);
  29915. // pack each entry recursively
  29916. node.children.push(this._build(items, j, right3, height - 1));
  29917. }
  29918. }
  29919. calcBBox(node, this.toBBox);
  29920. return node;
  29921. },
  29922. _chooseSubtree: function (bbox, node, level, path) {
  29923. var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
  29924. while (true) {
  29925. path.push(node);
  29926. if (node.leaf || path.length - 1 === level) break;
  29927. minArea = minEnlargement = Infinity;
  29928. for (i = 0, len = node.children.length; i < len; i++) {
  29929. child = node.children[i];
  29930. area = bboxArea(child);
  29931. enlargement = enlargedArea(bbox, child) - area;
  29932. // choose entry with the least area enlargement
  29933. if (enlargement < minEnlargement) {
  29934. minEnlargement = enlargement;
  29935. minArea = area < minArea ? area : minArea;
  29936. targetNode = child;
  29937. } else if (enlargement === minEnlargement) {
  29938. // otherwise choose one with the smallest area
  29939. if (area < minArea) {
  29940. minArea = area;
  29941. targetNode = child;
  29942. }
  29943. }
  29944. }
  29945. node = targetNode || node.children[0];
  29946. }
  29947. return node;
  29948. },
  29949. _insert: function (item, level, isNode) {
  29950. var toBBox = this.toBBox,
  29951. bbox = isNode ? item : toBBox(item),
  29952. insertPath = [];
  29953. // find the best node for accommodating the item, saving all nodes along the path too
  29954. var node = this._chooseSubtree(bbox, this.data, level, insertPath);
  29955. // put the item into the node
  29956. node.children.push(item);
  29957. extend(node, bbox);
  29958. // split on node overflow; propagate upwards if necessary
  29959. while (level >= 0) {
  29960. if (insertPath[level].children.length > this._maxEntries) {
  29961. this._split(insertPath, level);
  29962. level--;
  29963. } else break;
  29964. }
  29965. // adjust bboxes along the insertion path
  29966. this._adjustParentBBoxes(bbox, insertPath, level);
  29967. },
  29968. // split overflowed node into two
  29969. _split: function (insertPath, level) {
  29970. var node = insertPath[level],
  29971. M = node.children.length,
  29972. m = this._minEntries;
  29973. this._chooseSplitAxis(node, m, M);
  29974. var splitIndex = this._chooseSplitIndex(node, m, M);
  29975. var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
  29976. newNode.height = node.height;
  29977. newNode.leaf = node.leaf;
  29978. calcBBox(node, this.toBBox);
  29979. calcBBox(newNode, this.toBBox);
  29980. if (level) insertPath[level - 1].children.push(newNode);
  29981. else this._splitRoot(node, newNode);
  29982. },
  29983. _splitRoot: function (node, newNode) {
  29984. // split root node
  29985. this.data = createNode([node, newNode]);
  29986. this.data.height = node.height + 1;
  29987. this.data.leaf = false;
  29988. calcBBox(this.data, this.toBBox);
  29989. },
  29990. _chooseSplitIndex: function (node, m, M) {
  29991. var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
  29992. minOverlap = minArea = Infinity;
  29993. for (i = m; i <= M - m; i++) {
  29994. bbox1 = distBBox(node, 0, i, this.toBBox);
  29995. bbox2 = distBBox(node, i, M, this.toBBox);
  29996. overlap = intersectionArea(bbox1, bbox2);
  29997. area = bboxArea(bbox1) + bboxArea(bbox2);
  29998. // choose distribution with minimum overlap
  29999. if (overlap < minOverlap) {
  30000. minOverlap = overlap;
  30001. index = i;
  30002. minArea = area < minArea ? area : minArea;
  30003. } else if (overlap === minOverlap) {
  30004. // otherwise choose distribution with minimum area
  30005. if (area < minArea) {
  30006. minArea = area;
  30007. index = i;
  30008. }
  30009. }
  30010. }
  30011. return index;
  30012. },
  30013. // sorts node children by the best axis for split
  30014. _chooseSplitAxis: function (node, m, M) {
  30015. var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
  30016. compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
  30017. xMargin = this._allDistMargin(node, m, M, compareMinX),
  30018. yMargin = this._allDistMargin(node, m, M, compareMinY);
  30019. // if total distributions margin value is minimal for x, sort by minX,
  30020. // otherwise it's already sorted by minY
  30021. if (xMargin < yMargin) node.children.sort(compareMinX);
  30022. },
  30023. // total margin of all possible split distributions where each node is at least m full
  30024. _allDistMargin: function (node, m, M, compare) {
  30025. node.children.sort(compare);
  30026. var toBBox = this.toBBox,
  30027. leftBBox = distBBox(node, 0, m, toBBox),
  30028. rightBBox = distBBox(node, M - m, M, toBBox),
  30029. margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
  30030. i, child;
  30031. for (i = m; i < M - m; i++) {
  30032. child = node.children[i];
  30033. extend(leftBBox, node.leaf ? toBBox(child) : child);
  30034. margin += bboxMargin(leftBBox);
  30035. }
  30036. for (i = M - m - 1; i >= m; i--) {
  30037. child = node.children[i];
  30038. extend(rightBBox, node.leaf ? toBBox(child) : child);
  30039. margin += bboxMargin(rightBBox);
  30040. }
  30041. return margin;
  30042. },
  30043. _adjustParentBBoxes: function (bbox, path, level) {
  30044. // adjust bboxes along the given tree path
  30045. for (var i = level; i >= 0; i--) {
  30046. extend(path[i], bbox);
  30047. }
  30048. },
  30049. _condense: function (path) {
  30050. // go through the path, removing empty nodes and updating bboxes
  30051. for (var i = path.length - 1, siblings; i >= 0; i--) {
  30052. if (path[i].children.length === 0) {
  30053. if (i > 0) {
  30054. siblings = path[i - 1].children;
  30055. siblings.splice(siblings.indexOf(path[i]), 1);
  30056. } else this.clear();
  30057. } else calcBBox(path[i], this.toBBox);
  30058. }
  30059. },
  30060. _initFormat: function (format) {
  30061. // data format (minX, minY, maxX, maxY accessors)
  30062. // uses eval-type function compilation instead of just accepting a toBBox function
  30063. // because the algorithms are very sensitive to sorting functions performance,
  30064. // so they should be dead simple and without inner calls
  30065. var compareArr = ['return a', ' - b', ';'];
  30066. this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
  30067. this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
  30068. this.toBBox = new Function('a',
  30069. 'return {minX: a' + format[0] +
  30070. ', minY: a' + format[1] +
  30071. ', maxX: a' + format[2] +
  30072. ', maxY: a' + format[3] + '};');
  30073. }
  30074. };
  30075. function findItem(item, items, equalsFn) {
  30076. if (!equalsFn) return items.indexOf(item);
  30077. for (var i = 0; i < items.length; i++) {
  30078. if (equalsFn(item, items[i])) return i;
  30079. }
  30080. return -1;
  30081. }
  30082. // calculate node's bbox from bboxes of its children
  30083. function calcBBox(node, toBBox) {
  30084. distBBox(node, 0, node.children.length, toBBox, node);
  30085. }
  30086. // min bounding rectangle of node children from k to p-1
  30087. function distBBox(node, k, p, toBBox, destNode) {
  30088. if (!destNode) destNode = createNode(null);
  30089. destNode.minX = Infinity;
  30090. destNode.minY = Infinity;
  30091. destNode.maxX = -Infinity;
  30092. destNode.maxY = -Infinity;
  30093. for (var i = k, child; i < p; i++) {
  30094. child = node.children[i];
  30095. extend(destNode, node.leaf ? toBBox(child) : child);
  30096. }
  30097. return destNode;
  30098. }
  30099. function extend(a, b) {
  30100. a.minX = Math.min(a.minX, b.minX);
  30101. a.minY = Math.min(a.minY, b.minY);
  30102. a.maxX = Math.max(a.maxX, b.maxX);
  30103. a.maxY = Math.max(a.maxY, b.maxY);
  30104. return a;
  30105. }
  30106. function compareNodeMinX(a, b) { return a.minX - b.minX; }
  30107. function compareNodeMinY(a, b) { return a.minY - b.minY; }
  30108. function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
  30109. function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
  30110. function enlargedArea(a, b) {
  30111. return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
  30112. (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
  30113. }
  30114. function intersectionArea(a, b) {
  30115. var minX = Math.max(a.minX, b.minX),
  30116. minY = Math.max(a.minY, b.minY),
  30117. maxX = Math.min(a.maxX, b.maxX),
  30118. maxY = Math.min(a.maxY, b.maxY);
  30119. return Math.max(0, maxX - minX) *
  30120. Math.max(0, maxY - minY);
  30121. }
  30122. function contains(a, b) {
  30123. return a.minX <= b.minX &&
  30124. a.minY <= b.minY &&
  30125. b.maxX <= a.maxX &&
  30126. b.maxY <= a.maxY;
  30127. }
  30128. function intersects(a, b) {
  30129. return b.minX <= a.maxX &&
  30130. b.minY <= a.maxY &&
  30131. b.maxX >= a.minX &&
  30132. b.maxY >= a.minY;
  30133. }
  30134. function createNode(children) {
  30135. return {
  30136. children: children,
  30137. height: 1,
  30138. leaf: true,
  30139. minX: Infinity,
  30140. minY: Infinity,
  30141. maxX: -Infinity,
  30142. maxY: -Infinity
  30143. };
  30144. }
  30145. // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
  30146. // combines selection algorithm with binary divide & conquer approach
  30147. function multiSelect(arr, left, right, n, compare) {
  30148. var stack = [left, right],
  30149. mid;
  30150. while (stack.length) {
  30151. right = stack.pop();
  30152. left = stack.pop();
  30153. if (right - left <= n) continue;
  30154. mid = left + Math.ceil((right - left) / n / 2) * n;
  30155. quickselect(arr, mid, left, right, compare);
  30156. stack.push(left, mid, mid, right);
  30157. }
  30158. }
  30159. },{"quickselect":203}],205:[function(require,module,exports){
  30160. module.exports = function strsearch2regexp (str) {
  30161. return str
  30162. .replace('.', '\\.')
  30163. .replace(' ', '.*')
  30164. .replace('a', '[aàáâãäå]')
  30165. .replace('A', '[AÀÁÂÃÄÅ]')
  30166. .replace('C', '[CÇ]')
  30167. .replace('c', '[cç]')
  30168. .replace('E', '[EÉÊË]')
  30169. .replace('I', '[IÌÍÎÏ]')
  30170. .replace('D', '[DÐ]')
  30171. .replace('N', '[NÑ]')
  30172. .replace('O', '[OÒÓÔÕÖØ]')
  30173. .replace('X', '[X×]')
  30174. .replace('U', '[UÙÚÛÜ]')
  30175. .replace('Y', '[YÝ]')
  30176. .replace('s', '[sß]')
  30177. .replace('e', '[eèeéêëė]')
  30178. .replace('i', '[iìíîï]')
  30179. .replace('d', '[dð]')
  30180. .replace('n', '[nñ]')
  30181. .replace('o', '[oòóôõöø]')
  30182. .replace('u', '[uùúûü]')
  30183. .replace('y', '[yýÿ]')
  30184. }
  30185. },{}],206:[function(require,module,exports){
  30186. (function (setImmediate,clearImmediate){
  30187. var nextTick = require('process/browser.js').nextTick;
  30188. var apply = Function.prototype.apply;
  30189. var slice = Array.prototype.slice;
  30190. var immediateIds = {};
  30191. var nextImmediateId = 0;
  30192. // DOM APIs, for completeness
  30193. exports.setTimeout = function() {
  30194. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  30195. };
  30196. exports.setInterval = function() {
  30197. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  30198. };
  30199. exports.clearTimeout =
  30200. exports.clearInterval = function(timeout) { timeout.close(); };
  30201. function Timeout(id, clearFn) {
  30202. this._id = id;
  30203. this._clearFn = clearFn;
  30204. }
  30205. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  30206. Timeout.prototype.close = function() {
  30207. this._clearFn.call(window, this._id);
  30208. };
  30209. // Does not start the time, just sets up the members needed.
  30210. exports.enroll = function(item, msecs) {
  30211. clearTimeout(item._idleTimeoutId);
  30212. item._idleTimeout = msecs;
  30213. };
  30214. exports.unenroll = function(item) {
  30215. clearTimeout(item._idleTimeoutId);
  30216. item._idleTimeout = -1;
  30217. };
  30218. exports._unrefActive = exports.active = function(item) {
  30219. clearTimeout(item._idleTimeoutId);
  30220. var msecs = item._idleTimeout;
  30221. if (msecs >= 0) {
  30222. item._idleTimeoutId = setTimeout(function onTimeout() {
  30223. if (item._onTimeout)
  30224. item._onTimeout();
  30225. }, msecs);
  30226. }
  30227. };
  30228. // That's not how node.js implements it but the exposed api is the same.
  30229. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  30230. var id = nextImmediateId++;
  30231. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  30232. immediateIds[id] = true;
  30233. nextTick(function onNextTick() {
  30234. if (immediateIds[id]) {
  30235. // fn.call() is faster so we optimize for the common use-case
  30236. // @see http://jsperf.com/call-apply-segu
  30237. if (args) {
  30238. fn.apply(null, args);
  30239. } else {
  30240. fn.call(null);
  30241. }
  30242. // Prevent ids from leaking
  30243. exports.clearImmediate(id);
  30244. }
  30245. });
  30246. return id;
  30247. };
  30248. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  30249. delete immediateIds[id];
  30250. };
  30251. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  30252. },{"process/browser.js":202,"timers":206}],207:[function(require,module,exports){
  30253. (function (global,__dirname){
  30254. !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Twig=t():e.Twig=t()}(global,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:n})},r.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=27)}([function(e,t){e.exports=require("path")},function(e,t,r){"use strict";e.exports=function(){var e=arguments,t=0,r=function(e,t,r,n){r||(r=" ");var o=e.length>=t?"":new Array(1+t-e.length>>>0).join(r);return n?e+o:o+e},n=function(e,t,n,o,i,s){var a=o-e.length;return a>0&&(e=n||!i?r(e,o,s,n):[e.slice(0,t.length),r("",a,"0",!0),e.slice(t.length)].join("")),e},o=function(e,t,o,i,s,a,p){var c=e>>>0;return e=(o=o&&c&&{2:"0b",8:"0",16:"0x"}[t]||"")+r(c.toString(t),a||0,"0",!1),n(e,o,i,s,p)},i=function(e,t,r,o,i,s){return null!==o&&void 0!==o&&(e=e.slice(0,o)),n(e,"",t,r,i,s)};return e[t++].replace(/%%|%(\d+\$)?([-+'#0 ]*)(\*\d+\$|\*|\d+)?(?:\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g,function(s,a,p,c,l,u){var f,h,y,d,g;if("%%"===s)return"%";var m,x=!1,v="",b=!1,w=!1,k=" ",_=p.length;for(m=0;m<_;m++)switch(p.charAt(m)){case" ":v=" ";break;case"+":v="+";break;case"-":x=!0;break;case"'":k=p.charAt(m+1);break;case"0":b=!0,k="0";break;case"#":w=!0}if((c=c?"*"===c?+e[t++]:"*"===c.charAt(0)?+e[c.slice(1,-1)]:+c:0)<0&&(c=-c,x=!0),!isFinite(c))throw new Error("sprintf: (minimum-)width must be finite");switch(l=l?"*"===l?+e[t++]:"*"===l.charAt(0)?+e[l.slice(1,-1)]:+l:"fFeE".indexOf(u)>-1?6:"d"===u?0:void 0,g=a?e[a.slice(0,-1)]:e[t++],u){case"s":return i(g+"",x,c,l,b,k);case"c":return i(String.fromCharCode(+g),x,c,l,b);case"b":return o(g,2,w,x,c,l,b);case"o":return o(g,8,w,x,c,l,b);case"x":return o(g,16,w,x,c,l,b);case"X":return o(g,16,w,x,c,l,b).toUpperCase();case"u":return o(g,10,w,x,c,l,b);case"i":case"d":return f=+g||0,g=(h=(f=Math.round(f-f%1))<0?"-":v)+r(String(Math.abs(f)),l,"0",!1),n(g,h,x,c,b);case"e":case"E":case"f":case"F":case"g":case"G":return h=(f=+g)<0?"-":v,y=["toExponential","toFixed","toPrecision"]["efg".indexOf(u.toLowerCase())],d=["toString","toUpperCase"]["eEfFgG".indexOf(u)%2],g=h+Math.abs(f)[y](l),n(g,h,x,c,b)[d]();default:return s}})}},function(e,t){e.exports=function(e){"use strict";return e.exports={VERSION:e.VERSION},e.exports.twig=function(t){var r=t.id,n={strict_variables:t.strict_variables||!1,autoescape:null!=t.autoescape&&t.autoescape||!1,allowInlineIncludes:t.allowInlineIncludes||!1,rethrow:t.rethrow||!1,namespaces:t.namespaces};if(e.cache&&r&&e.validateId(r),void 0!==t.debug&&(e.debug=t.debug),void 0!==t.trace&&(e.trace=t.trace),void 0!==t.data)return e.Templates.parsers.twig({data:t.data,path:t.hasOwnProperty("path")?t.path:void 0,module:t.module,id:r,options:n});if(void 0!==t.ref){if(void 0!==t.id)throw new e.Error("Both ref and id cannot be set on a twig.js template.");return e.Templates.load(t.ref)}if(void 0!==t.method){if(!e.Templates.isRegisteredLoader(t.method))throw new e.Error('Loader for "'+t.method+'" is not defined.');return e.Templates.loadRemote(t.name||t.href||t.path||r||void 0,{id:r,method:t.method,parser:t.parser||"twig",base:t.base,module:t.module,precompiled:t.precompiled,async:t.async,options:n},t.load,t.error)}return void 0!==t.href?e.Templates.loadRemote(t.href,{id:r,method:"ajax",parser:t.parser||"twig",base:t.base,module:t.module,precompiled:t.precompiled,async:t.async,options:n},t.load,t.error):void 0!==t.path?e.Templates.loadRemote(t.path,{id:r,method:"fs",parser:t.parser||"twig",base:t.base,module:t.module,precompiled:t.precompiled,async:t.async,options:n},t.load,t.error):void 0},e.exports.extendFilter=function(t,r){e.filter.extend(t,r)},e.exports.extendFunction=function(t,r){e._function.extend(t,r)},e.exports.extendTest=function(t,r){e.test.extend(t,r)},e.exports.extendTag=function(t){e.logic.extend(t)},e.exports.extend=function(t){t(e)},e.exports.compile=function(t,r){var n,o=r.filename,i=r.filename;return n=new e.Template({data:t,path:i,id:o,options:r.settings["twig options"]}),function(e){return n.render(e)}},e.exports.renderFile=function(t,r,n){"function"==typeof r&&(n=r,r={});var o=(r=r||{}).settings||{},i={path:t,base:o.views,load:function(e){n(null,""+e.render(r))}},s=o["twig options"];if(s)for(var a in s)s.hasOwnProperty(a)&&(i[a]=s[a]);e.exports.twig(i)},e.exports.__express=e.exports.renderFile,e.exports.cache=function(t){e.cache=t},e.exports.path=e.path,e.exports.filters=e.filters,e.exports.Promise=e.Promise,e}},function(e,t){e.exports=function(e){"use strict";var t=1,r=2;return e.parseAsync=function(t,r){return e.parse.call(this,t,r,!0)},e.expression.parseAsync=function(t,r,n){return e.expression.parse.call(this,t,r,n,!0)},e.logic.parseAsync=function(t,r,n){return e.logic.parse.call(this,t,r,n,!0)},e.Template.prototype.renderAsync=function(e,t){return this.render(e,t,!0)},e.async={},e.isPromise=function(e){return e&&e.then&&"function"==typeof e.then},e.async.potentiallyAsync=function(t,r,n){return r?e.Promise.resolve(n.call(t)):function(t,r,n){var o=n.call(t),i=null,s=!0;if(!e.isPromise(o))return o;if(o.then(function(e){o=e,s=!1}).catch(function(e){i=e}),null!==i)throw i;if(s)throw new e.Error("You are using Twig.js in sync mode in combination with async extensions.");return o}(t,0,n)},e.Thenable=function(e,t,r){this.then=e,this._value=r?t:null,this._state=r||0},e.Thenable.prototype.catch=function(e){return this._state==t?this:this.then(null,e)},e.Thenable.resolvedThen=function(t){try{return e.Promise.resolve(t(this._value))}catch(t){return e.Promise.reject(t)}},e.Thenable.rejectedThen=function(t,r){if(!r||"function"!=typeof r)return this;var n=this._value,o=e.attempt(function(){return r(n)},e.Promise.reject);return e.Promise.resolve(o)},e.Promise=function(n){var o=0,i=null,s=function(e,t){o=e,i=t};return function(e,t,r){try{e(t,r)}catch(e){r(e)}}(n,function(e){s(t,e)},function(e){s(r,e)}),o===t?e.Promise.resolve(i):o===r?e.Promise.reject(i):(s=e.FullPromise()).promise},e.FullPromise=function(){var r=null;function n(e){e(a._value)}function o(e,t){t(a._value)}var i=function(e,t){r=function(e,t,r){var n=[t,r,-2];return e?-2==e[2]?e=[e,n]:e.push(n):e=n,e}(r,e,t)};function s(s,p){a._state||(a._value=p,a._state=s,i=s==t?n:o,r&&(-2===r[2]&&(i(r[0],r[1]),r=null),e.forEach(r,function(e){i(e[0],e[1])}),r=null))}var a=new e.Thenable(function(r,n){var o="function"==typeof r;if(a._state==t&&!o)return e.Promise.resolve(a._value);if(a._state===t)return e.attempt(function(){return e.Promise.resolve(r(a._value))},e.Promise.reject);var s="function"==typeof n;return e.Promise(function(t,a){i(o?function(n){e.attempt(function(){t(r(n))},a)}:t,s?function(r){e.attempt(function(){t(n(r))},a)}:a)})});return s.promise=a,s},e.Promise.defaultResolved=new e.Thenable(e.Thenable.resolvedThen,void 0,t),e.Promise.emptyStringResolved=new e.Thenable(e.Thenable.resolvedThen,"",t),e.Promise.resolve=function(r){return arguments.length<1||void 0===r?e.Promise.defaultResolved:e.isPromise(r)?r:""===r?e.Promise.emptyStringResolved:new e.Thenable(e.Thenable.resolvedThen,r,t)},e.Promise.reject=function(t){return new e.Thenable(e.Thenable.rejectedThen,t,r)},e.Promise.all=function(r){var n=new Array(r.length);return e.async.forEach(r,function(r,o){if(e.isPromise(r)){if(r._state!=t)return r.then(function(e){n[o]=e});n[o]=r._value}else n[o]=r}).then(function(){return n})},e.async.forEach=function(r,n){var o=r.length,i=0;return function s(){var a=null;do{if(i==o)return e.Promise.resolve();a=n(r[i],i),i++}while(!a||!e.isPromise(a)||a._state==t);return a.then(s)}()},e}},function(e,t){e.exports=function(e){"use strict";return e.tests={empty:function(e){if(null===e||void 0===e)return!0;if("number"==typeof e)return!1;if(e.length&&e.length>0)return!1;for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},odd:function(e){return e%2==1},even:function(e){return e%2==0},divisibleby:function(e,t){return e%t[0]==0},defined:function(e){return void 0!==e},none:function(e){return null===e},null:function(e){return this.none(e)},"same as":function(e,t){return e===t[0]},sameas:function(t,r){return console.warn("`sameas` is deprecated use `same as`"),e.tests["same as"](t,r)},iterable:function(t){return t&&(e.lib.is("Array",t)||e.lib.is("Object",t))}},e.test=function(t,r,n){if(!e.tests[t])throw"Test "+t+" is not defined.";return e.tests[t](r,n)},e.test.extend=function(t,r){e.tests[t]=r},e}},function(e,t,r){e.exports=function(e){"use strict";e.path={};var t=/.::/,n=/@/;return e.path.parsePath=function(r,o){var i=null,s=r.options.namespaces,a=o||"";if(s&&"object"==typeof s){for(i in s)t.test(a)?a=a.replace(i+"::",s[i]):n.test(a)&&(a=a.replace("@"+i,s[i]));return a}return e.path.relativePath(r,a)},e.path.relativePath=function(t,n){var o,i,s,a="/",p=[];n=n||"";if(t.url)o=void 0!==t.base?t.base+("/"===t.base.charAt(t.base.length-1)?"":"/"):t.url;else if(t.path){var c=r(0),l=c.sep||a,u=new RegExp("^\\.{1,2}"+l.replace("\\","\\\\"));n=n.replace(/\//g,l),void 0!==t.base&&null==n.match(u)?(n=n.replace(t.base,""),o=t.base+l):o=c.normalize(t.path),o=o.replace(l+l,l),a=l}else{if(!t.name&&!t.id||!t.method||"fs"===t.method||"ajax"===t.method)throw new e.Error("Cannot extend an inline template.");o=t.base||t.name||t.id}for((i=o.split(a)).pop(),i=i.concat(n.split(a));i.length>0;)"."==(s=i.shift())||(".."==s&&p.length>0&&".."!=p[p.length-1]?p.pop():p.push(s));return p.join(a)},e}},function(e,t){e.exports=function(e){"use strict";e.Templates.registerParser("twig",function(t){return new e.Template(t)})}},function(e,t){e.exports=function(e){"use strict";e.Templates.registerParser("source",function(e){return e.data||""})}},function(e,t){e.exports=function(e){"use strict";for(e.logic={},e.logic.type={if_:"Twig.logic.type.if",endif:"Twig.logic.type.endif",for_:"Twig.logic.type.for",endfor:"Twig.logic.type.endfor",else_:"Twig.logic.type.else",elseif:"Twig.logic.type.elseif",set:"Twig.logic.type.set",setcapture:"Twig.logic.type.setcapture",endset:"Twig.logic.type.endset",filter:"Twig.logic.type.filter",endfilter:"Twig.logic.type.endfilter",shortblock:"Twig.logic.type.shortblock",block:"Twig.logic.type.block",endblock:"Twig.logic.type.endblock",extends_:"Twig.logic.type.extends",use:"Twig.logic.type.use",include:"Twig.logic.type.include",spaceless:"Twig.logic.type.spaceless",endspaceless:"Twig.logic.type.endspaceless",macro:"Twig.logic.type.macro",endmacro:"Twig.logic.type.endmacro",import_:"Twig.logic.type.import",from:"Twig.logic.type.from",embed:"Twig.logic.type.embed",endembed:"Twig.logic.type.endembed",with:"Twig.logic.type.with",endwith:"Twig.logic.type.endwith"},e.logic.definitions=[{type:e.logic.type.if_,regex:/^if\s+([\s\S]+)$/,next:[e.logic.type.else_,e.logic.type.elseif,e.logic.type.endif],open:!0,compile:function(t){var r=t.match[1];return t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,delete t.match,t},parse:function(t,r,n){var o=this;return e.expression.parseAsync.call(this,t.stack,r).then(function(i){return n=!0,e.lib.boolval(i)?(n=!1,e.parseAsync.call(o,t.output,r)):""}).then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.elseif,regex:/^elseif\s+([^\s].*)$/,next:[e.logic.type.else_,e.logic.type.elseif,e.logic.type.endif],open:!1,compile:function(t){var r=t.match[1];return t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,delete t.match,t},parse:function(t,r,n){var o=this;return e.expression.parseAsync.call(this,t.stack,r).then(function(i){return n&&e.lib.boolval(i)?(n=!1,e.parseAsync.call(o,t.output,r)):""}).then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.else_,regex:/^else$/,next:[e.logic.type.endif,e.logic.type.endfor],open:!1,parse:function(t,r,n){var o=e.Promise.resolve("");return n&&(o=e.parseAsync.call(this,t.output,r)),o.then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.endif,regex:/^endif$/,next:[],open:!1},{type:e.logic.type.for_,regex:/^for\s+([a-zA-Z0-9_,\s]+)\s+in\s+([^\s].*?)(?:\s+if\s+([^\s].*))?$/,next:[e.logic.type.else_,e.logic.type.endfor],open:!0,compile:function(t){var r=t.match[1],n=t.match[2],o=t.match[3],i=null;if(t.key_var=null,t.value_var=null,r.indexOf(",")>=0){if(2!==(i=r.split(",")).length)throw new e.Error("Invalid expression in for loop: "+r);t.key_var=i[0].trim(),t.value_var=i[1].trim()}else t.value_var=r;return t.expression=e.expression.compile.call(this,{type:e.expression.type.expression,value:n}).stack,o&&(t.conditional=e.expression.compile.call(this,{type:e.expression.type.expression,value:o}).stack),delete t.match,t},parse:function(t,r,n){var o,i,s=[],a=0,p=this,c=t.conditional,l=function(n,i){var l=e.ChildContext(r);return l[t.value_var]=i,t.key_var&&(l[t.key_var]=n),l.loop=function(e,t){var n=void 0!==c;return{index:e+1,index0:e,revindex:n?void 0:t-e,revindex0:n?void 0:t-e-1,first:0===e,last:n?void 0:e===t-1,length:n?void 0:t,parent:r}}(a,o),(void 0===c?e.Promise.resolve(!0):e.expression.parseAsync.call(p,c,l)).then(function(r){if(r)return e.parseAsync.call(p,t.output,l).then(function(e){s.push(e),a+=1})}).then(function(){delete l.loop,delete l[t.value_var],delete l[t.key_var],e.merge(r,l,!0)})};return e.expression.parseAsync.call(this,t.expression,r).then(function(t){return e.lib.isArray(t)?(o=t.length,e.async.forEach(t,function(e){return l(a,e)})):e.lib.is("Object",t)?(i=void 0!==t._keys?t._keys:Object.keys(t),o=i.length,e.async.forEach(i,function(e){if("_keys"!==e)return l(e,t[e])})):void 0}).then(function(){return{chain:0===s.length,output:e.output.call(p,s)}})}},{type:e.logic.type.endfor,regex:/^endfor$/,next:[],open:!1},{type:e.logic.type.set,regex:/^set\s+([a-zA-Z0-9_,\s]+)\s*=\s*([\s\S]+)$/,next:[],open:!0,compile:function(t){var r=t.match[1].trim(),n=t.match[2],o=e.expression.compile.call(this,{type:e.expression.type.expression,value:n}).stack;return t.key=r,t.expression=o,delete t.match,t},parse:function(t,r,n){var o=t.key;return e.expression.parseAsync.call(this,t.expression,r).then(function(t){return t===r&&(t=e.lib.copy(t)),r[o]=t,{chain:n,context:r}})}},{type:e.logic.type.setcapture,regex:/^set\s+([a-zA-Z0-9_,\s]+)$/,next:[e.logic.type.endset],open:!0,compile:function(e){var t=e.match[1].trim();return e.key=t,delete e.match,e},parse:function(t,r,n){var o=this,i=t.key;return e.parseAsync.call(this,t.output,r).then(function(e){return o.context[i]=e,r[i]=e,{chain:n,context:r}})}},{type:e.logic.type.endset,regex:/^endset$/,next:[],open:!1},{type:e.logic.type.filter,regex:/^filter\s+(.+)$/,next:[e.logic.type.endfilter],open:!0,compile:function(t){var r="|"+t.match[1].trim();return t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,delete t.match,t},parse:function(t,r,n){var o=this;return e.parseAsync.call(this,t.output,r).then(function(n){var i=[{type:e.expression.type.string,value:n}].concat(t.stack);return e.expression.parseAsync.call(o,i,r)}).then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.endfilter,regex:/^endfilter$/,next:[],open:!1},{type:e.logic.type.block,regex:/^block\s+([a-zA-Z0-9_]+)$/,next:[e.logic.type.endblock],open:!0,compile:function(e){return e.block=e.match[1].trim(),delete e.match,e},parse:function(t,r,n){var o,i=this,s=e.Promise.resolve(),a=e.indexOf(this.importedBlocks,t.block)>-1,p=this.blocks[t.block]&&e.indexOf(this.blocks[t.block],e.placeholders.parent)>-1;return e.forEach(this.parseStack,function(r){r.type==e.logic.type.for_&&(t.overwrite=!0)}),(void 0===this.blocks[t.block]||a||p||t.overwrite)&&(s=(s=t.expression?e.expression.parseAsync.call(this,t.output,r).then(function(t){return e.expression.parseAsync.call(i,{type:e.expression.type.string,value:t},r)}):e.parseAsync.call(this,t.output,r).then(function(t){return e.expression.parseAsync.call(i,{type:e.expression.type.string,value:t},r)})).then(function(r){a&&i.importedBlocks.splice(i.importedBlocks.indexOf(t.block),1),i.blocks[t.block]=p?e.Markup(i.blocks[t.block].replace(e.placeholders.parent,r)):r,i.originalBlockTokens[t.block]={type:t.type,block:t.block,output:t.output,overwrite:!0}})),s.then(function(){return o=i.child.blocks[t.block]?i.child.blocks[t.block]:i.blocks[t.block],{chain:n,output:o}})}},{type:e.logic.type.shortblock,regex:/^block\s+([a-zA-Z0-9_]+)\s+(.+)$/,next:[],open:!0,compile:function(t){return t.expression=t.match[2].trim(),t.output=e.expression.compile({type:e.expression.type.expression,value:t.expression}).stack,t.block=t.match[1].trim(),delete t.match,t},parse:function(t,r,n){for(var o=new Array(arguments.length),i=arguments.length;i-- >0;)o[i]=arguments[i];return e.logic.handler[e.logic.type.block].parse.apply(this,o)}},{type:e.logic.type.endblock,regex:/^endblock(?:\s+([a-zA-Z0-9_]+))?$/,next:[],open:!1},{type:e.logic.type.extends_,regex:/^extends\s+(.+)$/,next:[],open:!0,compile:function(t){var r=t.match[1].trim();return delete t.match,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,t},parse:function(t,r,n){var o=this,i=e.ChildContext(r);return e.expression.parseAsync.call(this,t.stack,r).then(function(t){return o.extend=t,(t instanceof e.Template?t:o.importFile(t)).renderAsync(i)}).then(function(){return e.lib.extend(r,i),{chain:n,output:""}})}},{type:e.logic.type.use,regex:/^use\s+(.+)$/,next:[],open:!0,compile:function(t){var r=t.match[1].trim();return delete t.match,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,t},parse:function(t,r,n){var o=this;return e.expression.parseAsync.call(this,t.stack,r).then(function(e){return o.importBlocks(e),{chain:n,output:""}})}},{type:e.logic.type.include,regex:/^include\s+(.+?)(?:\s|$)(ignore missing(?:\s|$))?(?:with\s+([\S\s]+?))?(?:\s|$)(only)?$/,next:[],open:!0,compile:function(t){var r=t.match,n=r[1].trim(),o=void 0!==r[2],i=r[3],s=void 0!==r[4]&&r[4].length;return delete t.match,t.only=s,t.ignoreMissing=o,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:n}).stack,void 0!==i&&(t.withStack=e.expression.compile.call(this,{type:e.expression.type.expression,value:i.trim()}).stack),t},parse:function(t,r,n){var o=t.only?{}:e.ChildContext(r),i=t.ignoreMissing,s=this,a={chain:n,output:""};return(void 0!==t.withStack?e.expression.parseAsync.call(this,t.withStack,r).then(function(t){e.lib.extend(o,t)}):e.Promise.resolve()).then(function(){return e.expression.parseAsync.call(s,t.stack,r)}).then(function(t){if(t instanceof e.Template)return t.renderAsync(o);try{return s.importFile(t).renderAsync(o)}catch(e){if(i)return"";throw e}}).then(function(e){return""!==e&&(a.output=e),a})}},{type:e.logic.type.spaceless,regex:/^spaceless$/,next:[e.logic.type.endspaceless],open:!0,parse:function(t,r,n){return e.parseAsync.call(this,t.output,r).then(function(t){var r=t.replace(/>\s+</g,"><").trim();return r=e.Markup(r),{chain:n,output:r}})}},{type:e.logic.type.endspaceless,regex:/^endspaceless$/,next:[],open:!1},{type:e.logic.type.macro,regex:/^macro\s+([a-zA-Z0-9_]+)\s*\(\s*((?:[a-zA-Z0-9_]+(?:\s*=\s*([\s\S]+))?(?:,\s*)?)*)\s*\)$/,next:[e.logic.type.endmacro],open:!0,compile:function(t){var r=t.match[1],n=t.match[2].split(/\s*,\s*/),o=n.map(function(e){return e.split(/\s*=\s*/)[0]}),i=o.length;if(i>1)for(var s={},a=0;a<i;a++){var p=o[a];if(s[p])throw new e.Error("Duplicate arguments for parameter: "+p);s[p]=1}return t.macroName=r,t.parameters=o,t.defaults=n.reduce(function(t,r){var n=r.split(/\s*=\s*/),o=n[0],i=n[1];return t[o]=i?e.expression.compile.call(this,{type:e.expression.type.expression,value:i}).stack:void 0,t},{}),delete t.match,t},parse:function(t,r,n){var o=this;return this.macros[t.macroName]=function(){var n={_self:o.macros},i=Array.prototype.slice.call(arguments);return e.async.forEach(t.parameters,function(o,s){return void 0!==i[s]?(n[o]=i[s],!0):void 0!==t.defaults[o]?e.expression.parseAsync.call(this,t.defaults[o],r).then(function(t){return n[o]=t,e.Promise.resolve()}):(n[o]=void 0,!0)}).then(function(){return e.parseAsync.call(o,t.output,n)})},{chain:n,output:""}}},{type:e.logic.type.endmacro,regex:/^endmacro$/,next:[],open:!1},{type:e.logic.type.import_,regex:/^import\s+(.+)\s+as\s+([a-zA-Z0-9_]+)$/,next:[],open:!0,compile:function(t){var r=t.match[1].trim(),n=t.match[2].trim();return delete t.match,t.expression=r,t.contextName=n,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,t},parse:function(t,r,n){var o=this,i={chain:n,output:""};return"_self"===t.expression?(r[t.contextName]=this.macros,e.Promise.resolve(i)):e.expression.parseAsync.call(this,t.stack,r).then(function(e){return o.importFile(e||t.expression)}).then(function(e){return r[t.contextName]=e.renderAsync({},{output:"macros"}),i})}},{type:e.logic.type.from,regex:/^from\s+(.+)\s+import\s+([a-zA-Z0-9_, ]+)$/,next:[],open:!0,compile:function(t){for(var r=t.match[1].trim(),n=t.match[2].trim().split(/\s*,\s*/),o={},i=0;i<n.length;i++){var s=n[i],a=s.match(/^([a-zA-Z0-9_]+)\s+as\s+([a-zA-Z0-9_]+)$/);a?o[a[1].trim()]=a[2].trim():s.match(/^([a-zA-Z0-9_]+)$/)&&(o[s]=s)}return delete t.match,t.expression=r,t.macroNames=o,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,t},parse:function(t,r,n){var o=this,i=e.Promise.resolve(this.macros);return"_self"!==t.expression&&(i=e.expression.parseAsync.call(this,t.stack,r).then(function(e){return o.importFile(e||t.expression)}).then(function(e){return e.renderAsync({},{output:"macros"})})),i.then(function(e){for(var o in t.macroNames)e.hasOwnProperty(o)&&(r[t.macroNames[o]]=e[o]);return{chain:n,output:""}})}},{type:e.logic.type.embed,regex:/^embed\s+(.+?)(?:\s+(ignore missing))?(?:\s+with\s+([\S\s]+?))?(?:\s+(only))?$/,next:[e.logic.type.endembed],open:!0,compile:function(t){var r=t.match,n=r[1].trim(),o=void 0!==r[2],i=r[3],s=void 0!==r[4]&&r[4].length;return delete t.match,t.only=s,t.ignoreMissing=o,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:n}).stack,void 0!==i&&(t.withStack=e.expression.compile.call(this,{type:e.expression.type.expression,value:i.trim()}).stack),t},parse:function(t,r,n){var o,i,s={},a=this,p=e.Promise.resolve();if(!t.only)for(o in r)r.hasOwnProperty(o)&&(s[o]=r[o]);return void 0!==t.withStack&&(p=e.expression.parseAsync.call(this,t.withStack,r).then(function(e){for(o in e)e.hasOwnProperty(o)&&(s[o]=e[o])})),p.then(function(){return p=null,e.expression.parseAsync.call(a,t.stack,s)}).then(function(r){if(r instanceof e.Template)i=r;else try{i=a.importFile(r)}catch(e){if(t.ignoreMissing)return"";throw a=null,e}return a._blocks=e.lib.copy(a.blocks),a.blocks={},e.parseAsync.call(a,t.output,s).then(function(){return i.renderAsync(s,{blocks:a.blocks})})}).then(function(t){return a.blocks=e.lib.copy(a._blocks),{chain:n,output:t}})}},{type:e.logic.type.endembed,regex:/^endembed$/,next:[],open:!1},{type:e.logic.type.with,regex:/^(?:with\s+([\S\s]+?))(?:\s|$)(only)?$/,next:[e.logic.type.endwith],open:!0,compile:function(t){var r=t.match,n=r[1],o=void 0!==r[2]&&r[2].length;return delete t.match,t.only=o,void 0!==n&&(t.withStack=e.expression.compile.call(this,{type:e.expression.type.expression,value:n.trim()}).stack),t},parse:function(t,r,n){var o,i={},s=this,a=e.Promise.resolve();return t.only||(i=e.ChildContext(r)),void 0!==t.withStack&&(a=e.expression.parseAsync.call(this,t.withStack,r).then(function(e){for(o in e)e.hasOwnProperty(o)&&(i[o]=e[o])})),a.then(function(){return e.parseAsync.call(s,t.output,i)}).then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.endwith,regex:/^endwith$/,next:[],open:!1}],e.logic.handler={},e.logic.extendType=function(t,r){r=r||"Twig.logic.type"+t,e.logic.type[t]=r},e.logic.extend=function(t){if(!t.type)throw new e.Error("Unable to extend logic definition. No type provided for "+t);e.logic.extendType(t.type),e.logic.handler[t.type]=t};e.logic.definitions.length>0;)e.logic.extend(e.logic.definitions.shift());return e.logic.compile=function(t){var r=t.value.trim(),n=e.logic.tokenize.call(this,r),o=e.logic.handler[n.type];return o.compile&&(n=o.compile.call(this,n),e.log.trace("Twig.logic.compile: ","Compiled logic token to ",n)),n},e.logic.tokenize=function(t){var r=null,n=null,o=null,i=null,s=null,a=null,p=null;for(r in t=t.trim(),e.logic.handler)for(n=e.logic.handler[r].type,i=o=e.logic.handler[r].regex,e.lib.isArray(o)||(i=[o]),s=i.length,a=0;a<s;a++)if(null!==(p=i[a].exec(t)))return e.log.trace("Twig.logic.tokenize: ","Matched a ",n," regular expression of ",p),{type:n,match:p};throw new e.Error("Unable to parse '"+t.trim()+"'")},e.logic.parse=function(t,r,n,o){return e.async.potentiallyAsync(this,o,function(){e.log.debug("Twig.logic.parse: ","Parsing logic token ",t);var o,i=e.logic.handler[t.type],s=this;return i.parse?(s.parseStack.unshift(t),o=i.parse.call(s,t,r||{},n),e.isPromise(o)?o=o.then(function(e){return s.parseStack.shift(),e}):s.parseStack.shift(),o):""})},e}},function(e,t){e.exports=require("fs")},function(e,t,r){e.exports=function(e){"use strict";var t,n;try{t=r(9),n=r(0)}catch(e){}e.Templates.registerLoader("fs",function(r,o,i,s){var a,p=null,c=o.precompiled,l=this.parsers[o.parser]||this.parser.twig;if(!t||!n)throw new e.Error('Unsupported platform: Unable to load from file because there is no "fs" or "path" implementation');var u=function(e,t){e?"function"==typeof s&&s(e):(!0===c&&(t=JSON.parse(t)),o.data=t,o.path=o.path||r,a=l.call(this,o),"function"==typeof i&&i(a))};if(o.path=o.path||r,o.async)return t.stat(o.path,function(r,n){!r&&n.isFile()?t.readFile(o.path,"utf8",u):"function"==typeof s&&s(new e.Error("Unable to find template file "+o.path))}),!0;try{if(!t.statSync(o.path).isFile())throw new e.Error("Unable to find template file "+o.path)}catch(t){throw new e.Error("Unable to find template file "+o.path)}return p=t.readFileSync(o.path,"utf8"),u(void 0,p),a})}},function(e,t){e.exports=function(e){"use strict";e.Templates.registerLoader("ajax",function(t,r,n,o){var i,s,a=r.precompiled,p=this.parsers[r.parser]||this.parser.twig;if("undefined"==typeof XMLHttpRequest)throw new e.Error('Unsupported platform: Unable to do ajax requests because there is no "XMLHTTPRequest" implementation');return(s=new XMLHttpRequest).onreadystatechange=function(){var c=null;4===s.readyState&&(200===s.status||window.cordova&&0==s.status?(e.log.debug("Got template ",s.responseText),c=!0===a?JSON.parse(s.responseText):s.responseText,r.url=t,r.data=c,i=p.call(this,r),"function"==typeof n&&n(i)):"function"==typeof o&&o(s))},s.open("GET",t,!!r.async),s.send(),!!r.async||i})}},function(e,t,r){"use strict";e.exports=function(e){return!1!==e&&(0!==e&&0!==e&&(""!==e&&"0"!==e&&((!Array.isArray(e)||0!==e.length)&&(null!==e&&void 0!==e))))}},function(e,t,r){"use strict";e.exports=function(e,t){var r,n,o=["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur","January","February","March","April","May","June","July","August","September","October","November","December"],i=/\\?(.?)/gi,s=function(e,t){return n[e]?n[e]():t},a=function(e,t){for(e=String(e);e.length<t;)e="0"+e;return e};n={d:function(){return a(n.j(),2)},D:function(){return n.l().slice(0,3)},j:function(){return r.getDate()},l:function(){return o[n.w()]+"day"},N:function(){return n.w()||7},S:function(){var e=n.j(),t=e%10;return t<=3&&1===parseInt(e%100/10,10)&&(t=0),["st","nd","rd"][t-1]||"th"},w:function(){return r.getDay()},z:function(){var e=new Date(n.Y(),n.n()-1,n.j()),t=new Date(n.Y(),0,1);return Math.round((e-t)/864e5)},W:function(){var e=new Date(n.Y(),n.n()-1,n.j()-n.N()+3),t=new Date(e.getFullYear(),0,4);return a(1+Math.round((e-t)/864e5/7),2)},F:function(){return o[6+n.n()]},m:function(){return a(n.n(),2)},M:function(){return n.F().slice(0,3)},n:function(){return r.getMonth()+1},t:function(){return new Date(n.Y(),n.n(),0).getDate()},L:function(){var e=n.Y();return e%4==0&e%100!=0|e%400==0},o:function(){var e=n.n(),t=n.W();return n.Y()+(12===e&&t<9?1:1===e&&t>9?-1:0)},Y:function(){return r.getFullYear()},y:function(){return n.Y().toString().slice(-2)},a:function(){return r.getHours()>11?"pm":"am"},A:function(){return n.a().toUpperCase()},B:function(){var e=3600*r.getUTCHours(),t=60*r.getUTCMinutes(),n=r.getUTCSeconds();return a(Math.floor((e+t+n+3600)/86.4)%1e3,3)},g:function(){return n.G()%12||12},G:function(){return r.getHours()},h:function(){return a(n.g(),2)},H:function(){return a(n.G(),2)},i:function(){return a(r.getMinutes(),2)},s:function(){return a(r.getSeconds(),2)},u:function(){return a(1e3*r.getMilliseconds(),6)},e:function(){throw new Error("Not supported (see source code of date() for timezone on how to add support)")},I:function(){return new Date(n.Y(),0)-Date.UTC(n.Y(),0)!=new Date(n.Y(),6)-Date.UTC(n.Y(),6)?1:0},O:function(){var e=r.getTimezoneOffset(),t=Math.abs(e);return(e>0?"-":"+")+a(100*Math.floor(t/60)+t%60,4)},P:function(){var e=n.O();return e.substr(0,3)+":"+e.substr(3,2)},T:function(){return"UTC"},Z:function(){return 60*-r.getTimezoneOffset()},c:function(){return"Y-m-d\\TH:i:sP".replace(i,s)},r:function(){return"D, d M Y H:i:s O".replace(i,s)},U:function(){return r/1e3|0}};return function(e,t){return r=void 0===t?new Date:t instanceof Date?new Date(t):new Date(1e3*t),e.replace(i,s)}(e,t)}},function(e,t,r){"use strict";e.exports=function(e,t){var r,n,o,i,s,a,p,c,l,u,f;if(!e)return!1;e=e.replace(/^\s+|\s+$/g,"").replace(/\s{2,}/g," ").replace(/[\t\r\n]/g,"").toLowerCase();var h=new RegExp(["^(\\d{1,4})","([\\-\\.\\/:])","(\\d{1,2})","([\\-\\.\\/:])","(\\d{1,4})","(?:\\s(\\d{1,2}):(\\d{2})?:?(\\d{2})?)?","(?:\\s([A-Z]+)?)?$"].join(""));if((n=e.match(h))&&n[2]===n[4])if(n[1]>1901)switch(n[2]){case"-":return!(n[3]>12||n[5]>31)&&new Date(n[1],parseInt(n[3],10)-1,n[5],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3;case".":return!1;case"/":return!(n[3]>12||n[5]>31)&&new Date(n[1],parseInt(n[3],10)-1,n[5],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3}else if(n[5]>1901)switch(n[2]){case"-":case".":return!(n[3]>12||n[1]>31)&&new Date(n[5],parseInt(n[3],10)-1,n[1],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3;case"/":return!(n[1]>12||n[3]>31)&&new Date(n[5],parseInt(n[1],10)-1,n[3],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3}else switch(n[2]){case"-":return!(n[3]>12||n[5]>31||n[1]<70&&n[1]>38)&&(i=n[1]>=0&&n[1]<=38?+n[1]+2e3:n[1],new Date(i,parseInt(n[3],10)-1,n[5],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3);case".":return n[5]>=70?!(n[3]>12||n[1]>31)&&new Date(n[5],parseInt(n[3],10)-1,n[1],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3:n[5]<60&&!n[6]&&(!(n[1]>23||n[3]>59)&&(o=new Date,new Date(o.getFullYear(),o.getMonth(),o.getDate(),n[1]||0,n[3]||0,n[5]||0,n[9]||0)/1e3));case"/":return!(n[1]>12||n[3]>31||n[5]<70&&n[5]>38)&&(i=n[5]>=0&&n[5]<=38?+n[5]+2e3:n[5],new Date(i,parseInt(n[1],10)-1,n[3],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3);case":":return!(n[1]>23||n[3]>59||n[5]>59)&&(o=new Date,new Date(o.getFullYear(),o.getMonth(),o.getDate(),n[1]||0,n[3]||0,n[5]||0)/1e3)}if("now"===e)return null===t||isNaN(t)?(new Date).getTime()/1e3|0:0|t;if(!isNaN(r=Date.parse(e)))return r/1e3|0;if(h=new RegExp(["^([0-9]{4}-[0-9]{2}-[0-9]{2})","[ t]","([0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?)","([\\+-][0-9]{2}(:[0-9]{2})?|z)"].join("")),(n=e.match(h))&&("z"===n[4]?n[4]="Z":n[4].match(/^([+-][0-9]{2})$/)&&(n[4]=n[4]+":00"),!isNaN(r=Date.parse(n[1]+"T"+n[2]+n[4]))))return r/1e3|0;function y(e){var t=e.split(" "),r=t[0],n=t[1].substring(0,3),o=/\d+/.test(r),i="ago"===t[2],c=("last"===r?-1:1)*(i?-1:1);if(o&&(c*=parseInt(r,10)),p.hasOwnProperty(n)&&!t[1].match(/^mon(day|\.)?$/i))return s["set"+p[n]](s["get"+p[n]]()+c);if("wee"===n)return s.setDate(s.getDate()+7*c);if("next"===r||"last"===r)!function(e,t,r){var n,o=a[t];void 0!==o&&(0==(n=o-s.getDay())?n=7*r:n>0&&"last"===e?n-=7:n<0&&"next"===e&&(n+=7),s.setDate(s.getDate()+n))}(r,n,c);else if(!o)return!1;return!0}if(s=t?new Date(1e3*t):new Date,a={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6},p={yea:"FullYear",mon:"Month",day:"Date",hou:"Hours",min:"Minutes",sec:"Seconds"},u="([+-]?\\d+\\s"+(l="(years?|months?|weeks?|days?|hours?|minutes?|min|seconds?|sec|sunday|sun\\.?|monday|mon\\.?|tuesday|tue\\.?|wednesday|wed\\.?|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?)")+"|(last|next)\\s"+l+")(\\sago)?",!(n=e.match(new RegExp(u,"gi"))))return!1;for(f=0,c=n.length;f<c;f++)if(!y(n[f]))return!1;return s.getTime()/1e3}},function(e,t,r){"use strict";e.exports=function(e,t){t=(((t||"")+"").toLowerCase().match(/<[a-z][a-z0-9]*>/g)||[]).join("");return e.replace(/<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi,"").replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,function(e,r){return t.indexOf("<"+r.toLowerCase()+">")>-1?e:""})}},function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.exports=function(){var e,t,r,o=0,i=arguments,s=i.length,a=function(e){if("[object Array]"===Object.prototype.toString.call(e))return e;var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t},p=function e(t,r){var o=0,i=0,s=0,p=0,c=0;if(t===r)return 0;if("object"===(void 0===t?"undefined":n(t))){if("object"===(void 0===r?"undefined":n(r))){if(t=a(t),r=a(r),c=t.length,(p=r.length)>c)return 1;if(p<c)return-1;for(o=0,i=c;o<i;++o){if(1===(s=e(t[o],r[o])))return 1;if(-1===s)return-1}return 0}return-1}return"object"===(void 0===r?"undefined":n(r))?1:isNaN(r)&&!isNaN(t)?0===t?0:t<0?1:-1:isNaN(t)&&!isNaN(r)?0===r?0:r>0?1:-1:r===t?0:r>t?1:-1};if(0===s)throw new Error("At least one value should be passed to min()");if(1===s){if("object"!==n(i[0]))throw new Error("Wrong parameter count for min()");if(0===(e=a(i[0])).length)throw new Error("Array must contain at least one element for min()")}else e=i;for(t=e[0],o=1,r=e.length;o<r;++o)-1===p(t,e[o])&&(t=e[o]);return t}},function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.exports=function(){var e,t,r,o=0,i=arguments,s=i.length,a=function(e){if("[object Array]"===Object.prototype.toString.call(e))return e;var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t},p=function e(t,r){var o=0,i=0,s=0,p=0,c=0;if(t===r)return 0;if("object"===(void 0===t?"undefined":n(t))){if("object"===(void 0===r?"undefined":n(r))){if(t=a(t),r=a(r),c=t.length,(p=r.length)>c)return 1;if(p<c)return-1;for(o=0,i=c;o<i;++o){if(1===(s=e(t[o],r[o])))return 1;if(-1===s)return-1}return 0}return-1}return"object"===(void 0===r?"undefined":n(r))?1:isNaN(r)&&!isNaN(t)?0===t?0:t<0?1:-1:isNaN(t)&&!isNaN(r)?0===r?0:r>0?1:-1:r===t?0:r>t?1:-1};if(0===s)throw new Error("At least one value should be passed to max()");if(1===s){if("object"!==n(i[0]))throw new Error("Wrong parameter count for max()");if(0===(e=a(i[0])).length)throw new Error("Array must contain at least one element for max()")}else e=i;for(t=e[0],o=1,r=e.length;o<r;++o)1===p(t,e[o])&&(t=e[o]);return t}},function(e,t,r){"use strict";e.exports=function(e,t,r){var n,o,i,s;if(t|=0,i=(e*=n=Math.pow(10,t))%1==.5*(s=e>0|-(e<0)),o=Math.floor(e),i)switch(r){case"PHP_ROUND_HALF_DOWN":e=o+(s<0);break;case"PHP_ROUND_HALF_EVEN":e=o+o%2*s;break;case"PHP_ROUND_HALF_ODD":e=o+!(o%2);break;default:e=o+(s>0)}return(i?e:Math.round(e))/n}},function(e,t,r){"use strict";e.exports=function(e,t){return r(1).apply(this,[e].concat(t))}},function(e,t,r){e.exports=function(e){e.lib={},e.lib.sprintf=r(1),e.lib.vsprintf=r(19),e.lib.round=r(18),e.lib.max=r(17),e.lib.min=r(16),e.lib.strip_tags=r(15),e.lib.strtotime=r(14),e.lib.date=r(13),e.lib.boolval=r(12);var t=Object.prototype.toString;return e.lib.is=function(e,r){return void 0!==r&&null!==r&&("Array"===e&&Array.isArray?Array.isArray(r):t.call(r).slice(8,-1)===e)},e.lib.isArray=Array.isArray||function(e){return"Array"===t.call(e).slice(8,-1)},e.lib.copy=function(e){var t,r={};for(t in e)r[t]=e[t];return r},e.lib.extend=function(e,t){var r,n=Object.keys(t);for(r=n.length;r--;)e[n[r]]=t[n[r]];return e},e.lib.replaceAll=function(e,t,r){return e.split(t).join(r)},e.lib.chunkArray=function(t,r){var n=[],o=0,i=t.length;if(r<1||!e.lib.is("Array",t))return[];for(;o<i;)n.push(t.slice(o,o+=r));return n},e}},function(e,t){e.exports=function(t){return t.functions={range:function(e,t,r){var n,o,i=[],s=r||1,a=!1;if(isNaN(e)||isNaN(t)?isNaN(e)&&isNaN(t)?(a=!0,n=e.charCodeAt(0),o=t.charCodeAt(0)):(n=isNaN(e)?0:e,o=isNaN(t)?0:t):(n=parseInt(e,10),o=parseInt(t,10)),!(n>o))for(;n<=o;)i.push(a?String.fromCharCode(n):n),n+=s;else for(;n>=o;)i.push(a?String.fromCharCode(n):n),n-=s;return i},cycle:function(e,t){return e[t%e.length]},dump:function(){var e=arguments.length;for(args=new Array(e);e-- >0;)args[e]=arguments[e];var r=0,n="",o=function(e){for(var t="";e>0;)e--,t+=" ";return t},i=function(e){n+=o(r),"object"==typeof e?s(e):"function"==typeof e?n+="function()\n":"string"==typeof e?n+="string("+e.length+') "'+e+'"\n':"number"==typeof e?n+="number("+e+")\n":"boolean"==typeof e&&(n+="bool("+e+")\n")},s=function(e){var t;if(null===e)n+="NULL\n";else if(void 0===e)n+="undefined\n";else if("object"==typeof e){for(t in n+=o(r)+typeof e,r++,n+="("+function(e){var t,r=0;for(t in e)e.hasOwnProperty(t)&&r++;return r}(e)+") {\n",e)n+=o(r)+"["+t+"]=> \n",i(e[t]);n+=o(--r)+"}\n"}else i(e)};return 0==args.length&&args.push(this.context),t.forEach(args,function(e){s(e)}),n},date:function(e,r){var n;if(void 0===e||null===e||""===e)n=new Date;else if(t.lib.is("Date",e))n=e;else if(t.lib.is("String",e))n=e.match(/^[0-9]+$/)?new Date(1e3*e):new Date(1e3*t.lib.strtotime(e));else{if(!t.lib.is("Number",e))throw new t.Error("Unable to parse date "+e);n=new Date(1e3*e)}return n},block:function(e){return this.originalBlockTokens[e]?t.logic.parse.call(this,this.originalBlockTokens[e],this.context).output:this.blocks[e]},parent:function(){return t.placeholders.parent},attribute:function(e,r,n){return t.lib.is("Object",e)&&e.hasOwnProperty(r)?"function"==typeof e[r]?e[r].apply(void 0,n):e[r]:e[r]||void 0},max:function(e){return t.lib.is("Object",e)?(delete e._keys,t.lib.max(e)):t.lib.max.apply(null,arguments)},min:function(e){return t.lib.is("Object",e)?(delete e._keys,t.lib.min(e)):t.lib.min.apply(null,arguments)},template_from_string:function(e){return void 0===e&&(e=""),t.Templates.parsers.twig({options:this.options,data:e})},random:function(e){var r=2147483648;function n(e){var t=Math.floor(Math.random()*r),n=Math.min.call(null,0,e),o=Math.max.call(null,0,e);return n+Math.floor((o-n+1)*t/r)}if(t.lib.is("Number",e))return n(e);if(t.lib.is("String",e))return e.charAt(n(e.length-1));if(t.lib.is("Array",e))return e[n(e.length-1)];if(t.lib.is("Object",e)){var o=Object.keys(e);return e[o[n(o.length-1)]]}return n(r-1)},source:function(r,n){var o,i,s,a=!1;void 0!==e&&void 0!==e.exports&&"undefined"==typeof window?(i="fs",s=__dirname+"/"+r):(i="ajax",s=r);var p={id:r,path:s,method:i,parser:"source",async:!1,fetchTemplateSource:!0};void 0===n&&(n=!1);try{void 0===(o=t.Templates.loadRemote(r,p))||null===o?o="":a=!0}catch(e){t.log.debug("Twig.functions.source: ","Problem loading template ",e)}return a||n?o:'Template "{name}" is not defined.'.replace("{name}",r)}},t._function=function(e,r,n){if(!t.functions[e])throw"Unable to find function "+e;return t.functions[e](r,n)},t._function.extend=function(e,r){t.functions[e]=r},t}},function(e,t){e.exports=function(e){function t(e,t){var r=Object.prototype.toString.call(t).slice(8,-1);return void 0!==t&&null!==t&&r===e}return e.filters={upper:function(e){return"string"!=typeof e?e:e.toUpperCase()},lower:function(e){return"string"!=typeof e?e:e.toLowerCase()},capitalize:function(e){return"string"!=typeof e?e:e.substr(0,1).toUpperCase()+e.toLowerCase().substr(1)},title:function(e){return"string"!=typeof e?e:e.toLowerCase().replace(/(^|\s)([a-z])/g,function(e,t,r){return t+r.toUpperCase()})},length:function(t){return e.lib.is("Array",t)||"string"==typeof t?t.length:e.lib.is("Object",t)?void 0===t._keys?Object.keys(t).length:t._keys.length:0},reverse:function(e){if(t("Array",e))return e.reverse();if(t("String",e))return e.split("").reverse().join("");if(t("Object",e)){var r=e._keys||Object.keys(e).reverse();return e._keys=r,e}},sort:function(e){if(t("Array",e))return e.sort();if(t("Object",e)){delete e._keys;var r=Object.keys(e).sort(function(t,r){var n;return e[t]>e[r]==!(e[t]<=e[r])?e[t]>e[r]?1:e[t]<e[r]?-1:0:isNaN(n=parseFloat(e[t]))||isNaN(b1=parseFloat(e[r]))?"string"==typeof e[t]?e[t]>e[r].toString()?1:e[t]<e[r].toString()?-1:0:"string"==typeof e[r]?e[t].toString()>e[r]?1:e[t].toString()<e[r]?-1:0:null:n>b1?1:n<b1?-1:0});return e._keys=r,e}},keys:function(t){if(void 0!==t&&null!==t){var r=t._keys||Object.keys(t),n=[];return e.forEach(r,function(e){"_keys"!==e&&t.hasOwnProperty(e)&&n.push(e)}),n}},url_encode:function(e){if(void 0!==e&&null!==e){var t=encodeURIComponent(e);return t=t.replace("'","%27")}},join:function(r,n){if(void 0!==r&&null!==r){var o="",i=[],s=null;return n&&n[0]&&(o=n[0]),t("Array",r)?i=r:(s=r._keys||Object.keys(r),e.forEach(s,function(e){"_keys"!==e&&r.hasOwnProperty(e)&&i.push(r[e])})),i.join(o)}},default:function(t,r){if(void 0!==r&&r.length>1)throw new e.Error("default filter expects one argument");return void 0===t||null===t||""===t?void 0===r?"":r[0]:t},json_encode:function(r){if(void 0===r||null===r)return"null";if("object"==typeof r&&t("Array",r))return o=[],e.forEach(r,function(t){o.push(e.filters.json_encode(t))}),"["+o.join(",")+"]";if("object"==typeof r&&t("Date",r))return'"'+r.toISOString()+'"';if("object"==typeof r){var n=r._keys||Object.keys(r),o=[];return e.forEach(n,function(t){o.push(JSON.stringify(t)+":"+e.filters.json_encode(r[t]))}),"{"+o.join(",")+"}"}return JSON.stringify(r)},merge:function(r,n){var o=[],i=0,s=[];if(t("Array",r)?e.forEach(n,function(e){t("Array",e)||(o={})}):o={},t("Array",o)||(o._keys=[]),t("Array",r)?e.forEach(r,function(e){o._keys&&o._keys.push(i),o[i]=e,i++}):(s=r._keys||Object.keys(r),e.forEach(s,function(e){o[e]=r[e],o._keys.push(e);var t=parseInt(e,10);!isNaN(t)&&t>=i&&(i=t+1)})),e.forEach(n,function(r){t("Array",r)?e.forEach(r,function(e){o._keys&&o._keys.push(i),o[i]=e,i++}):(s=r._keys||Object.keys(r),e.forEach(s,function(e){o[e]||o._keys.push(e),o[e]=r[e];var t=parseInt(e,10);!isNaN(t)&&t>=i&&(i=t+1)}))}),0===n.length)throw new e.Error("Filter merge expects at least one parameter");return o},date:function(t,r){var n=e.functions.date(t),o=r&&r.length?r[0]:"F j, Y H:i";return e.lib.date(o,n)},date_modify:function(t,r){if(void 0!==t&&null!==t){if(void 0===r||1!==r.length)throw new e.Error("date_modify filter expects 1 argument");var n,o=r[0];return e.lib.is("Date",t)&&(n=e.lib.strtotime(o,t.getTime()/1e3)),e.lib.is("String",t)&&(n=e.lib.strtotime(o,e.lib.strtotime(t))),e.lib.is("Number",t)&&(n=e.lib.strtotime(o,t)),new Date(1e3*n)}},replace:function(t,r){if(void 0!==t&&null!==t){var n,o=r[0];for(n in o)o.hasOwnProperty(n)&&"_keys"!==n&&(t=e.lib.replaceAll(t,n,o[n]));return t}},format:function(t,r){if(void 0!==t&&null!==t)return e.lib.vsprintf(t,r)},striptags:function(t,r){if(void 0!==t&&null!==t)return e.lib.strip_tags(t,r)},escape:function(t,r){if(void 0!==t&&null!==t){var n="html";if(r&&r.length&&!0!==r[0]&&(n=r[0]),"html"==n){var o=t.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;");return e.Markup(o,"html")}if("js"==n){o=t.toString();for(var i="",s=0;s<o.length;s++){if(o[s].match(/^[a-zA-Z0-9,\._]$/))i+=o[s];else i+=(a=o.charCodeAt(s))<128?"\\x"+a.toString(16).toUpperCase():e.lib.sprintf("\\u%04s",a.toString(16).toUpperCase())}return e.Markup(i,"js")}if("css"==n){for(o=t.toString(),i="",s=0;s<o.length;s++){if(o[s].match(/^[a-zA-Z0-9]$/))i+=o[s];else i+="\\"+(a=o.charCodeAt(s)).toString(16).toUpperCase()+" "}return e.Markup(i,"css")}if("url"==n){i=e.filters.url_encode(t);return e.Markup(i,"url")}if("html_attr"==n){for(o=t.toString(),i="",s=0;s<o.length;s++)if(o[s].match(/^[a-zA-Z0-9,\.\-_]$/))i+=o[s];else if(o[s].match(/^[&<>"]$/))i+=o[s].replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");else{var a;i+=(a=o.charCodeAt(s))<=31&&9!=a&&10!=a&&13!=a?"&#xFFFD;":a<128?e.lib.sprintf("&#x%02s;",a.toString(16).toUpperCase()):e.lib.sprintf("&#x%04s;",a.toString(16).toUpperCase())}return e.Markup(i,"html_attr")}throw new e.Error("escape strategy unsupported")}},e:function(t,r){return e.filters.escape(t,r)},nl2br:function(t){if(void 0!==t&&null!==t){var r="<br />BACKSLASH_n_replace";return t=e.filters.escape(t).replace(/\r\n/g,r).replace(/\r/g,r).replace(/\n/g,r),t=e.lib.replaceAll(t,"BACKSLASH_n_replace","\n"),e.Markup(t)}},number_format:function(e,t){var r=e,n=t&&t[0]?t[0]:void 0,o=t&&void 0!==t[1]?t[1]:".",i=t&&void 0!==t[2]?t[2]:",";r=(r+"").replace(/[^0-9+\-Ee.]/g,"");var s=isFinite(+r)?+r:0,a=isFinite(+n)?Math.abs(n):0,p="";return(p=(a?function(e,t){var r=Math.pow(10,t);return""+Math.round(e*r)/r}(s,a):""+Math.round(s)).split("."))[0].length>3&&(p[0]=p[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,i)),(p[1]||"").length<a&&(p[1]=p[1]||"",p[1]+=new Array(a-p[1].length+1).join("0")),p.join(o)},trim:function(e,t){if(void 0!==e&&null!==e){var r,n=""+e;r=t&&t[0]?""+t[0]:" \n\r\t\f\v            ​\u2028\u2029 ";for(var o=0;o<n.length;o++)if(-1===r.indexOf(n.charAt(o))){n=n.substring(o);break}for(o=n.length-1;o>=0;o--)if(-1===r.indexOf(n.charAt(o))){n=n.substring(0,o+1);break}return-1===r.indexOf(n.charAt(0))?n:""}},truncate:function(e,t){var r=30,n=!1,o="...";if(e+="",t&&(t[0]&&(r=t[0]),t[1]&&(n=t[1]),t[2]&&(o=t[2])),e.length>r){if(n&&-1===(r=e.indexOf(" ",r)))return e;e=e.substr(0,r)+o}return e},slice:function(t,r){if(void 0!==t&&null!==t){if(void 0===r||r.length<1)throw new e.Error("slice filter expects at least 1 argument");var n=r[0]||0,o=r.length>1?r[1]:t.length,i=n>=0?n:Math.max(t.length+n,0);if(e.lib.is("Array",t)){for(var s=[],a=i;a<i+o&&a<t.length;a++)s.push(t[a]);return s}if(e.lib.is("String",t))return t.substr(i,o);throw new e.Error("slice filter expects value to be an array or string")}},abs:function(e){if(void 0!==e&&null!==e)return Math.abs(e)},first:function(e){if(t("Array",e))return e[0];if(t("Object",e)){if("_keys"in e)return e[e._keys[0]]}else if("string"==typeof e)return e.substr(0,1)},split:function(t,r){if(void 0!==t&&null!==t){if(void 0===r||r.length<1||r.length>2)throw new e.Error("split filter expects 1 or 2 argument");if(e.lib.is("String",t)){var n=r[0],o=r[1],i=t.split(n);if(void 0===o)return i;if(o<0)return t.split(n,i.length+o);var s=[];if(""==n)for(;i.length>0;){for(var a="",p=0;p<o&&i.length>0;p++)a+=i.shift();s.push(a)}else{for(p=0;p<o-1&&i.length>0;p++)s.push(i.shift());i.length>0&&s.push(i.join(n))}return s}throw new e.Error("split filter expects value to be a string")}},last:function(t){var r;return e.lib.is("Object",t)?t[(r=void 0===t._keys?Object.keys(t):t._keys)[r.length-1]]:t[t.length-1]},raw:function(t){return e.Markup(t)},batch:function(t,r){var n,o,i,s=r.shift(),a=r.shift();if(!e.lib.is("Array",t))throw new e.Error("batch filter expects items to be an array");if(!e.lib.is("Number",s))throw new e.Error("batch filter expects size to be a number");if(s=Math.ceil(s),n=e.lib.chunkArray(t,s),a&&t.length%s!=0){for(i=s-(o=n.pop()).length;i--;)o.push(a);n.push(o)}return n},round:function(t,r){var n=(r=r||[]).length>0?r[0]:0,o=r.length>1?r[1]:"common";if(t=parseFloat(t),n&&!e.lib.is("Number",n))throw new e.Error("round filter expects precision to be a number");if("common"===o)return e.lib.round(t,n);if(!e.lib.is("Function",Math[o]))throw new e.Error("round filter expects method to be 'floor', 'ceil', or 'common'");return Math[o](t*Math.pow(10,n))/Math.pow(10,n)}},e.filter=function(t,r,n){if(!e.filters[t])throw"Unable to find filter "+t;return e.filters[t].call(this,r,n)},e.filter.extend=function(t,r){e.filters[t]=r},e}},function(e,t){e.exports=function(e){"use strict";e.expression.operator={leftToRight:"leftToRight",rightToLeft:"rightToLeft"};var t=function(e,t){if(void 0===t||null===t)return null;if(void 0!==t.indexOf)return e===t||""!==e&&t.indexOf(e)>-1;var r;for(r in t)if(t.hasOwnProperty(r)&&t[r]===e)return!0;return!1};return e.expression.operator.lookup=function(t,r){switch(t){case"..":r.precidence=20,r.associativity=e.expression.operator.leftToRight;break;case",":r.precidence=18,r.associativity=e.expression.operator.leftToRight;break;case"?:":case"?":case":":r.precidence=16,r.associativity=e.expression.operator.rightToLeft;break;case"or":r.precidence=14,r.associativity=e.expression.operator.leftToRight;break;case"and":r.precidence=13,r.associativity=e.expression.operator.leftToRight;break;case"b-or":r.precidence=12,r.associativity=e.expression.operator.leftToRight;break;case"b-xor":r.precidence=11,r.associativity=e.expression.operator.leftToRight;break;case"b-and":r.precidence=10,r.associativity=e.expression.operator.leftToRight;break;case"==":case"!=":r.precidence=9,r.associativity=e.expression.operator.leftToRight;break;case"<":case"<=":case">":case">=":case"not in":case"in":r.precidence=8,r.associativity=e.expression.operator.leftToRight;break;case"~":case"+":case"-":r.precidence=6,r.associativity=e.expression.operator.leftToRight;break;case"//":case"**":case"*":case"/":case"%":r.precidence=5,r.associativity=e.expression.operator.leftToRight;break;case"not":r.precidence=3,r.associativity=e.expression.operator.rightToLeft;break;default:throw new e.Error("Failed to lookup operator: "+t+" is an unknown operator.")}return r.operator=t,r},e.expression.operator.parse=function(r,n){var o,i,s;switch(e.log.trace("Twig.expression.operator.parse: ","Handling ",r),"?"===r&&(s=n.pop()),i=n.pop(),"not"!==r&&(o=n.pop()),"in"!==r&&"not in"!==r&&(o&&Array.isArray(o)&&(o=o.length),i&&Array.isArray(i)&&(i=i.length)),r){case":":break;case"?:":e.lib.boolval(o)?n.push(o):n.push(i);break;case"?":void 0===o&&(o=i,i=s,s=void 0),e.lib.boolval(o)?n.push(i):n.push(s);break;case"+":i=parseFloat(i),o=parseFloat(o),n.push(o+i);break;case"-":i=parseFloat(i),o=parseFloat(o),n.push(o-i);break;case"*":i=parseFloat(i),o=parseFloat(o),n.push(o*i);break;case"/":i=parseFloat(i),o=parseFloat(o),n.push(o/i);break;case"//":i=parseFloat(i),o=parseFloat(o),n.push(Math.floor(o/i));break;case"%":i=parseFloat(i),o=parseFloat(o),n.push(o%i);break;case"~":n.push((null!=o?o.toString():"")+(null!=i?i.toString():""));break;case"not":case"!":n.push(!e.lib.boolval(i));break;case"<":n.push(o<i);break;case"<=":n.push(o<=i);break;case">":n.push(o>i);break;case">=":n.push(o>=i);break;case"===":n.push(o===i);break;case"==":n.push(o==i);break;case"!==":n.push(o!==i);break;case"!=":n.push(o!=i);break;case"or":n.push(e.lib.boolval(o)||e.lib.boolval(i));break;case"b-or":n.push(o|i);break;case"b-xor":n.push(o^i);break;case"and":n.push(e.lib.boolval(o)&&e.lib.boolval(i));break;case"b-and":n.push(o&i);break;case"**":n.push(Math.pow(o,i));break;case"not in":n.push(!t(o,i));break;case"in":n.push(t(o,i));break;case"..":n.push(e.functions.range(o,i));break;default:throw new e.Error("Failed to parse operator: "+r+" is an unknown operator.")}},e}},function(e,t,r){e.exports=function(e){"use strict";function t(t,r,n){return r?e.expression.parseAsync.call(t,r,n):e.Promise.resolve(!1)}for(e.expression={},r(23)(e),e.expression.reservedWords=["true","false","null","TRUE","FALSE","NULL","_context","and","b-and","or","b-or","b-xor","in","not in","if"],e.expression.type={comma:"Twig.expression.type.comma",operator:{unary:"Twig.expression.type.operator.unary",binary:"Twig.expression.type.operator.binary"},string:"Twig.expression.type.string",bool:"Twig.expression.type.bool",slice:"Twig.expression.type.slice",array:{start:"Twig.expression.type.array.start",end:"Twig.expression.type.array.end"},object:{start:"Twig.expression.type.object.start",end:"Twig.expression.type.object.end"},parameter:{start:"Twig.expression.type.parameter.start",end:"Twig.expression.type.parameter.end"},subexpression:{start:"Twig.expression.type.subexpression.start",end:"Twig.expression.type.subexpression.end"},key:{period:"Twig.expression.type.key.period",brackets:"Twig.expression.type.key.brackets"},filter:"Twig.expression.type.filter",_function:"Twig.expression.type._function",variable:"Twig.expression.type.variable",number:"Twig.expression.type.number",_null:"Twig.expression.type.null",context:"Twig.expression.type.context",test:"Twig.expression.type.test"},e.expression.set={operations:[e.expression.type.filter,e.expression.type.operator.unary,e.expression.type.operator.binary,e.expression.type.array.end,e.expression.type.object.end,e.expression.type.parameter.end,e.expression.type.subexpression.end,e.expression.type.comma,e.expression.type.test],expressions:[e.expression.type._function,e.expression.type.bool,e.expression.type.string,e.expression.type.variable,e.expression.type.number,e.expression.type._null,e.expression.type.context,e.expression.type.parameter.start,e.expression.type.array.start,e.expression.type.object.start,e.expression.type.subexpression.start,e.expression.type.operator.unary]},e.expression.set.operations_extended=e.expression.set.operations.concat([e.expression.type.key.period,e.expression.type.key.brackets,e.expression.type.slice]),e.expression.fn={compile:{push:function(e,t,r){r.push(e)},push_both:function(e,t,r){r.push(e),t.push(e)}},parse:{push:function(e,t,r){t.push(e)},push_value:function(e,t,r){t.push(e.value)}}},e.expression.definitions=[{type:e.expression.type.test,regex:/^is\s+(not)?\s*([a-zA-Z_][a-zA-Z0-9_]*(\s?as)?)/,next:e.expression.set.operations.concat([e.expression.type.parameter.start]),compile:function(e,t,r){e.filter=e.match[2],e.modifier=e.match[1],delete e.match,delete e.value,r.push(e)},parse:function(r,n,o){var i=n.pop();return t(this,r.params,o).then(function(t){var o=e.test(r.filter,i,t);"not"==r.modifier?n.push(!o):n.push(o)})}},{type:e.expression.type.comma,regex:/^,/,next:e.expression.set.expressions.concat([e.expression.type.array.end,e.expression.type.object.end]),compile:function(t,r,n){var o,i=r.length-1;for(delete t.match,delete t.value;i>=0;i--){if((o=r.pop()).type===e.expression.type.object.start||o.type===e.expression.type.parameter.start||o.type===e.expression.type.array.start){r.push(o);break}n.push(o)}n.push(t)}},{type:e.expression.type.number,regex:/^\-?\d+(\.\d+)?/,next:e.expression.set.operations,compile:function(e,t,r){e.value=Number(e.value),r.push(e)},parse:e.expression.fn.parse.push_value},{type:e.expression.type.operator.binary,regex:/(^\?\:|^(b\-and)|^(b\-or)|^(b\-xor)|^[\+\-~%\?]|^[\:](?!\d\])|^[!=]==?|^[!<>]=?|^\*\*?|^\/\/?|^(and)[\(|\s+]|^(or)[\(|\s+]|^(in)[\(|\s+]|^(not in)[\(|\s+]|^\.\.)/,next:e.expression.set.expressions,transform:function(e,t){switch(e[0]){case"and(":case"or(":case"in(":case"not in(":return t[t.length-1].value=e[2],e[0];default:return""}},compile:function(t,r,n){delete t.match,t.value=t.value.trim();var o=t.value,i=e.expression.operator.lookup(o,t);for(e.log.trace("Twig.expression.compile: ","Operator: ",i," from ",o);r.length>0&&(r[r.length-1].type==e.expression.type.operator.unary||r[r.length-1].type==e.expression.type.operator.binary)&&(i.associativity===e.expression.operator.leftToRight&&i.precidence>=r[r.length-1].precidence||i.associativity===e.expression.operator.rightToLeft&&i.precidence>r[r.length-1].precidence);){var s=r.pop();n.push(s)}if(":"===o){if(!r[r.length-1]||"?"!==r[r.length-1].value){var a=n.pop();if(a.type===e.expression.type.string||a.type===e.expression.type.variable)t.key=a.value;else if(a.type===e.expression.type.number)t.key=a.value.toString();else{if(!a.expression||a.type!==e.expression.type.parameter.end&&a.type!=e.expression.type.subexpression.end)throw new e.Error("Unexpected value before ':' of "+a.type+" = "+a.value);t.params=a.params}return void n.push(t)}}else r.push(i)},parse:function(t,r,n){if(t.key)r.push(t);else{if(t.params)return e.expression.parseAsync.call(this,t.params,n).then(function(e){t.key=e,r.push(t),n.loop||delete t.params});e.expression.operator.parse(t.value,r)}}},{type:e.expression.type.operator.unary,regex:/(^not\s+)/,next:e.expression.set.expressions,compile:function(t,r,n){delete t.match,t.value=t.value.trim();var o=t.value,i=e.expression.operator.lookup(o,t);for(e.log.trace("Twig.expression.compile: ","Operator: ",i," from ",o);r.length>0&&(r[r.length-1].type==e.expression.type.operator.unary||r[r.length-1].type==e.expression.type.operator.binary)&&(i.associativity===e.expression.operator.leftToRight&&i.precidence>=r[r.length-1].precidence||i.associativity===e.expression.operator.rightToLeft&&i.precidence>r[r.length-1].precidence);){var s=r.pop();n.push(s)}r.push(i)},parse:function(t,r,n){e.expression.operator.parse(t.value,r)}},{type:e.expression.type.string,regex:/^(["'])(?:(?=(\\?))\2[\s\S])*?\1/,next:e.expression.set.operations_extended,compile:function(t,r,n){var o=t.value;delete t.match,o='"'===o.substring(0,1)?o.replace('\\"','"'):o.replace("\\'","'"),t.value=o.substring(1,o.length-1).replace(/\\n/g,"\n").replace(/\\r/g,"\r"),e.log.trace("Twig.expression.compile: ","String value: ",t.value),n.push(t)},parse:e.expression.fn.parse.push_value},{type:e.expression.type.subexpression.start,regex:/^\(/,next:e.expression.set.expressions.concat([e.expression.type.subexpression.end]),compile:function(e,t,r){e.value="(",r.push(e),t.push(e)},parse:e.expression.fn.parse.push},{type:e.expression.type.subexpression.end,regex:/^\)/,next:e.expression.set.operations_extended,validate:function(t,r){for(var n=r.length-1,o=!1,i=!1,s=0;!o&&n>=0;){var a=r[n];(o=a.type===e.expression.type.subexpression.start)&&i&&(i=!1,o=!1),a.type===e.expression.type.parameter.start?s++:a.type===e.expression.type.parameter.end?s--:a.type===e.expression.type.subexpression.end&&(i=!0),n--}return o&&0===s},compile:function(t,r,n){var o,i=t;for(o=r.pop();r.length>0&&o.type!=e.expression.type.subexpression.start;)n.push(o),o=r.pop();for(var s=[];t.type!==e.expression.type.subexpression.start;)s.unshift(t),t=n.pop();s.unshift(t);void 0===(o=r[r.length-1])||o.type!==e.expression.type._function&&o.type!==e.expression.type.filter&&o.type!==e.expression.type.test&&o.type!==e.expression.type.key.brackets?(i.expression=!0,s.pop(),s.shift(),i.params=s,n.push(i)):(i.expression=!1,o.params=s)},parse:function(t,r,n){if(t.expression)return e.expression.parseAsync.call(this,t.params,n).then(function(e){r.push(e)});throw new e.Error("Unexpected subexpression end when token is not marked as an expression")}},{type:e.expression.type.parameter.start,regex:/^\(/,next:e.expression.set.expressions.concat([e.expression.type.parameter.end]),validate:function(t,r){var n=r[r.length-1];return n&&e.indexOf(e.expression.reservedWords,n.value.trim())<0},compile:e.expression.fn.compile.push_both,parse:e.expression.fn.parse.push},{type:e.expression.type.parameter.end,regex:/^\)/,next:e.expression.set.operations_extended,compile:function(t,r,n){var o,i=t;for(o=r.pop();r.length>0&&o.type!=e.expression.type.parameter.start;)n.push(o),o=r.pop();for(var s=[];t.type!==e.expression.type.parameter.start;)s.unshift(t),t=n.pop();s.unshift(t);void 0===(t=n[n.length-1])||t.type!==e.expression.type._function&&t.type!==e.expression.type.filter&&t.type!==e.expression.type.test&&t.type!==e.expression.type.key.brackets?(i.expression=!0,s.pop(),s.shift(),i.params=s,n.push(i)):(i.expression=!1,t.params=s)},parse:function(t,r,n){var o=[],i=!1,s=null;if(t.expression)return e.expression.parseAsync.call(this,t.params,n).then(function(e){r.push(e)});for(;r.length>0;){if((s=r.pop())&&s.type&&s.type==e.expression.type.parameter.start){i=!0;break}o.unshift(s)}if(!i)throw new e.Error("Expected end of parameter set.");r.push(o)}},{type:e.expression.type.slice,regex:/^\[(\d*\:\d*)\]/,next:e.expression.set.operations_extended,compile:function(e,t,r){var n=e.match[1].split(":"),o=n[0]?parseInt(n[0]):void 0,i=n[1]?parseInt(n[1]):void 0;e.value="slice",e.params=[o,i],i||(e.params=[o]),r.push(e)},parse:function(t,r,n){var o=r.pop(),i=t.params;r.push(e.filter.call(this,t.value,o,i))}},{type:e.expression.type.array.start,regex:/^\[/,next:e.expression.set.expressions.concat([e.expression.type.array.end]),compile:e.expression.fn.compile.push_both,parse:e.expression.fn.parse.push},{type:e.expression.type.array.end,regex:/^\]/,next:e.expression.set.operations_extended,compile:function(t,r,n){for(var o,i=r.length-1;i>=0&&(o=r.pop()).type!==e.expression.type.array.start;i--)n.push(o);n.push(t)},parse:function(t,r,n){for(var o=[],i=!1,s=null;r.length>0;){if((s=r.pop()).type&&s.type==e.expression.type.array.start){i=!0;break}o.unshift(s)}if(!i)throw new e.Error("Expected end of array.");r.push(o)}},{type:e.expression.type.object.start,regex:/^\{/,next:e.expression.set.expressions.concat([e.expression.type.object.end]),compile:e.expression.fn.compile.push_both,parse:e.expression.fn.parse.push},{type:e.expression.type.object.end,regex:/^\}/,next:e.expression.set.operations_extended,compile:function(t,r,n){for(var o,i=r.length-1;i>=0&&(!(o=r.pop())||o.type!==e.expression.type.object.start);i--)n.push(o);n.push(t)},parse:function(t,r,n){for(var o={},i=!1,s=null,a=!1,p=null;r.length>0;){if((s=r.pop())&&s.type&&s.type===e.expression.type.object.start){i=!0;break}if(s&&s.type&&(s.type===e.expression.type.operator.binary||s.type===e.expression.type.operator.unary)&&s.key){if(!a)throw new e.Error("Missing value for key '"+s.key+"' in object definition.");o[s.key]=p,void 0===o._keys&&(o._keys=[]),o._keys.unshift(s.key),p=null,a=!1}else a=!0,p=s}if(!i)throw new e.Error("Unexpected end of object.");r.push(o)}},{type:e.expression.type.filter,regex:/^\|\s?([a-zA-Z_][a-zA-Z0-9_\-]*)/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:function(e,t,r){e.value=e.match[1],r.push(e)},parse:function(r,n,o){var i=this,s=n.pop();return t(this,r.params,o).then(function(t){return e.filter.call(i,r.value,s,t)}).then(function(e){n.push(e)})}},{type:e.expression.type._function,regex:/^([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/,next:e.expression.type.parameter.start,validate:function(t,r){return t[1]&&e.indexOf(e.expression.reservedWords,t[1])<0},transform:function(e,t){return"("},compile:function(e,t,r){var n=e.match[1];e.fn=n,delete e.match,delete e.value,r.push(e)},parse:function(r,n,o){var i,s=this,a=r.fn;return t(this,r.params,o).then(function(t){if(e.functions[a])i=e.functions[a].apply(s,t);else{if("function"!=typeof o[a])throw new e.Error(a+" function does not exist and is not defined in the context");i=o[a].apply(o,t)}return i}).then(function(e){n.push(e)})}},{type:e.expression.type.variable,regex:/^[a-zA-Z_][a-zA-Z0-9_]*/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:e.expression.fn.compile.push,validate:function(t,r){return e.indexOf(e.expression.reservedWords,t[0])<0},parse:function(t,r,n){return e.expression.resolveAsync.call(this,n[t.value],n).then(function(e){r.push(e)})}},{type:e.expression.type.key.period,regex:/^\.([a-zA-Z0-9_]+)/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:function(e,t,r){e.key=e.match[1],delete e.match,delete e.value,r.push(e)},parse:function(r,n,o,i){var s,a=this,p=r.key,c=n.pop();return t(this,r.params,o).then(function(t){if(null===c||void 0===c){if(a.options.strict_variables)throw new e.Error("Can't access a key "+p+" on an null or undefined object.");s=void 0}else{var r=function(e){return e.substr(0,1).toUpperCase()+e.substr(1)};s="object"==typeof c&&p in c?c[p]:void 0!==c["get"+r(p)]?c["get"+r(p)]:void 0!==c["is"+r(p)]?c["is"+r(p)]:void 0}return e.expression.resolveAsync.call(a,s,o,t,i,c)}).then(function(e){n.push(e)})}},{type:e.expression.type.key.brackets,regex:/^\[([^\]\:]*)\]/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:function(t,r,n){var o=t.match[1];delete t.value,delete t.match,t.stack=e.expression.compile({value:o}).stack,n.push(t)},parse:function(r,n,o,i){var s,a,p=this,c=null;return t(this,r.params,o).then(function(t){return c=t,e.expression.parseAsync.call(p,r.stack,o)}).then(function(t){if(null===(s=n.pop())||void 0===s){if(p.options.strict_variables)throw new e.Error("Can't access a key "+t+" on an null or undefined object.");return null}return a="object"==typeof s&&t in s?s[t]:null,e.expression.resolveAsync.call(p,a,s,c,i)}).then(function(e){n.push(e)})}},{type:e.expression.type._null,regex:/^(null|NULL|none|NONE)/,next:e.expression.set.operations,compile:function(e,t,r){delete e.match,e.value=null,r.push(e)},parse:e.expression.fn.parse.push_value},{type:e.expression.type.context,regex:/^_context/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:e.expression.fn.compile.push,parse:function(e,t,r){t.push(r)}},{type:e.expression.type.bool,regex:/^(true|TRUE|false|FALSE)/,next:e.expression.set.operations,compile:function(e,t,r){e.value="true"===e.match[0].toLowerCase(),delete e.match,r.push(e)},parse:e.expression.fn.parse.push_value}],e.expression.resolveAsync=function(t,r,n,o,i){if("function"!=typeof t)return e.Promise.resolve(t);var s=e.Promise.resolve(n);if(o&&o.type===e.expression.type.parameter.end){s=s.then(function(){return o.params&&e.expression.parseAsync.call(this,o.params,r,!0)}).then(function(e){return o.cleanup=!0,e})}return s.then(function(e){return t.apply(i||r,e||[])})},e.expression.resolve=function(t,r,n,o,i){return e.async.potentiallyAsync(this,!1,function(){return e.expression.resolveAsync.call(this,t,r,n,o,i)})},e.expression.handler={},e.expression.extendType=function(t){e.expression.type[t]="Twig.expression.type."+t},e.expression.extend=function(t){if(!t.type)throw new e.Error("Unable to extend logic definition. No type provided for "+t);e.expression.handler[t.type]=t};e.expression.definitions.length>0;)e.expression.extend(e.expression.definitions.shift());return e.expression.tokenize=function(t){var r,n,o,i,s,a,p=[],c=0,l=null,u=[];for(a=function(){for(var t=arguments.length-2,n=new Array(t);t-- >0;)n[t]=arguments[t];if(e.log.trace("Twig.expression.tokenize","Matched a ",r," regular expression of ",n),l&&e.indexOf(l,r)<0)return u.push(r+" cannot follow a "+p[p.length-1].type+" at template:"+c+" near '"+n[0].substring(0,20)+"...'"),n[0];var o=e.expression.handler[r];return o.validate&&!o.validate(n,p)?n[0]:(u=[],p.push({type:r,value:n[0],match:n}),s=!0,l=i,c+=n[0].length,o.transform?o.transform(n,p):"")},e.log.debug("Twig.expression.tokenize","Tokenizing expression ",t);t.length>0;){for(r in t=t.trim(),e.expression.handler){if(i=e.expression.handler[r].next,n=e.expression.handler[r].regex,e.log.trace("Checking type ",r," on ",t),s=!1,e.lib.isArray(n))for(o=n.length;o-- >0;)t=t.replace(n[o],a);else t=t.replace(n,a);if(s)break}if(!s)throw u.length>0?new e.Error(u.join(" OR ")):new e.Error("Unable to parse '"+t+"' at template position"+c)}return e.log.trace("Twig.expression.tokenize","Tokenized to ",p),p},e.expression.compile=function(t){var r=t.value,n=e.expression.tokenize(r),o=null,i=[],s=[],a=null;for(e.log.trace("Twig.expression.compile: ","Compiling ",r);n.length>0;)o=n.shift(),a=e.expression.handler[o.type],e.log.trace("Twig.expression.compile: ","Compiling ",o),a.compile&&a.compile(o,s,i),e.log.trace("Twig.expression.compile: ","Stack is",s),e.log.trace("Twig.expression.compile: ","Output is",i);for(;s.length>0;)i.push(s.pop());return e.log.trace("Twig.expression.compile: ","Final output is",i),t.stack=i,delete t.value,t},e.expression.parse=function(t,r,n,o){var i=this;e.lib.isArray(t)||(t=[t]);var s=[],a=[],p=e.expression.type.operator.binary;return e.async.potentiallyAsync(this,o,function(){return e.async.forEach(t,function(n,o){var c,l=null,u=null;if(!n.cleanup)return t.length>o+1&&(u=t[o+1]),(l=e.expression.handler[n.type]).parse&&(c=l.parse.call(i,n,s,r,u)),n.type===p&&r.loop&&a.push(n),c}).then(function(){for(var e=a.length,t=null;e-- >0;)(t=a[e]).params&&t.key&&delete t.key;if(n){var r=s.splice(0);s.push(r)}return s.pop()})})},e}},function(e,t){e.exports=function(e){return e.compiler={module:{}},e.compiler.compile=function(t,r){var n,o=JSON.stringify(t.tokens),i=t.id;if(r.module){if(void 0===e.compiler.module[r.module])throw new e.Error("Unable to find module type "+r.module);n=e.compiler.module[r.module](i,o,r.twig)}else n=e.compiler.wrap(i,o);return n},e.compiler.module={amd:function(t,r,n){return'define(["'+n+'"], function (Twig) {\n\tvar twig, templates;\ntwig = Twig.twig;\ntemplates = '+e.compiler.wrap(t,r)+"\n\treturn templates;\n});"},node:function(t,r){return'var twig = require("twig").twig;\nexports.template = '+e.compiler.wrap(t,r)},cjs2:function(t,r,n){return'module.declare([{ twig: "'+n+'" }], function (require, exports, module) {\n\tvar twig = require("twig").twig;\n\texports.template = '+e.compiler.wrap(t,r)+"\n});"}},e.compiler.wrap=function(e,t){return'twig({id:"'+e.replace('"','\\"')+'", data:'+t+", precompiled: true});\n"},e}},function(e,t){e.exports=function(e){"use strict";function t(t,r){if(t.options.rethrow)throw"string"==typeof r&&(r=new e.Error(r)),"TwigException"!=r.type||r.file||(r.file=t.id),r;if(e.log.error("Error parsing twig template "+t.id+": "),r.stack?e.log.error(r.stack):e.log.error(r.toString()),e.debug)return r.toString()}return e.trace=!1,e.debug=!1,e.cache=!0,e.noop=function(){},e.placeholders={parent:"{{|PARENT|}}"},e.hasIndexOf=Array.prototype.hasOwnProperty("indexOf"),e.indexOf=function(t,r){if(e.hasIndexOf)return t.indexOf(r);if(void 0===t||null===t)throw new TypeError;var n=Object(t),o=n.length>>>0;if(0===o)return-1;var i=0;if(arguments.length>0&&((i=Number(arguments[1]))!=i?i=0:0!==i&&i!==1/0&&i!==-1/0&&(i=(i>0||-1)*Math.floor(Math.abs(i)))),i>=o)return-1;for(var s=i>=0?i:Math.max(o-Math.abs(i),0);s<o;s++)if(s in n&&n[s]===r)return s;return t==r?0:-1},e.forEach=function(e,t,r){if(Array.prototype.forEach)return e.forEach(t,r);var n,o;if(null==e)throw new TypeError(" this is null or not defined");var i=Object(e),s=i.length>>>0;if("[object Function]"!={}.toString.call(t))throw new TypeError(t+" is not a function");for(r&&(n=r),o=0;o<s;){var a;o in i&&(a=i[o],t.call(n,a,o,i)),o++}},e.merge=function(t,r,n){return e.forEach(Object.keys(r),function(e){(!n||e in t)&&(t[e]=r[e])}),t},e.attempt=function(e,t){try{return e()}catch(e){return t(e)}},e.Error=function(e,t){this.message=e,this.name="TwigException",this.type="TwigException",this.file=t},e.Error.prototype.toString=function(){return this.name+": "+this.message},e.log={trace:function(){e.trace&&console&&console.log(Array.prototype.slice.call(arguments))},debug:function(){e.debug&&console&&console.log(Array.prototype.slice.call(arguments))}},"undefined"!=typeof console?void 0!==console.error?e.log.error=function(){console.error.apply(console,arguments)}:void 0!==console.log&&(e.log.error=function(){console.log.apply(console,arguments)}):e.log.error=function(){},e.ChildContext=function(t){return e.lib.copy(t)},e.token={},e.token.type={output:"output",logic:"logic",comment:"comment",raw:"raw",output_whitespace_pre:"output_whitespace_pre",output_whitespace_post:"output_whitespace_post",output_whitespace_both:"output_whitespace_both",logic_whitespace_pre:"logic_whitespace_pre",logic_whitespace_post:"logic_whitespace_post",logic_whitespace_both:"logic_whitespace_both"},e.token.definitions=[{type:e.token.type.raw,open:"{% raw %}",close:"{% endraw %}"},{type:e.token.type.raw,open:"{% verbatim %}",close:"{% endverbatim %}"},{type:e.token.type.output_whitespace_pre,open:"{{-",close:"}}"},{type:e.token.type.output_whitespace_post,open:"{{",close:"-}}"},{type:e.token.type.output_whitespace_both,open:"{{-",close:"-}}"},{type:e.token.type.logic_whitespace_pre,open:"{%-",close:"%}"},{type:e.token.type.logic_whitespace_post,open:"{%",close:"-%}"},{type:e.token.type.logic_whitespace_both,open:"{%-",close:"-%}"},{type:e.token.type.output,open:"{{",close:"}}"},{type:e.token.type.logic,open:"{%",close:"%}"},{type:e.token.type.comment,open:"{#",close:"#}"}],e.token.strings=['"',"'"],e.token.findStart=function(t){var r,n,o,i,s={position:null,def:null},a=null,p=e.token.definitions.length;for(r=0;r<p;r++)n=e.token.definitions[r],o=t.indexOf(n.open),i=t.indexOf(n.close),e.log.trace("Twig.token.findStart: ","Searching for ",n.open," found at ",o),o>=0&&n.open.length!==n.close.length&&i<0||(o>=0&&(null===s.position||o<s.position)?(s.position=o,s.def=n,a=i):o>=0&&null!==s.position&&o===s.position&&(n.open.length>s.def.open.length?(s.position=o,s.def=n,a=i):n.open.length===s.def.open.length&&(n.close.length,s.def.close.length,i>=0&&i<a&&(s.position=o,s.def=n,a=i))));return s},e.token.findEnd=function(t,r,n){for(var o,i,s=null,a=!1,p=0,c=null,l=null,u=null,f=null,h=null,y=null;!a;){if(c=null,l=null,!((u=t.indexOf(r.close,p))>=0))throw new e.Error("Unable to find closing bracket '"+r.close+"' opened near template position "+n);if(s=u,a=!0,r.type===e.token.type.comment)break;if(r.type===e.token.type.raw)break;for(i=e.token.strings.length,o=0;o<i;o+=1)(h=t.indexOf(e.token.strings[o],p))>0&&h<u&&(null===c||h<c)&&(c=h,l=e.token.strings[o]);if(null!==c)for(f=c+1,s=null,a=!1;;){if((y=t.indexOf(l,f))<0)throw"Unclosed string in template";if("\\"!==t.substr(y-1,1)){p=y+1;break}f=y+1}}return s},e.tokenize=function(t){for(var r=[],n=0,o=null,i=null;t.length>0;)if(o=e.token.findStart(t),e.log.trace("Twig.tokenize: ","Found token: ",o),null!==o.position){if(o.position>0&&r.push({type:e.token.type.raw,value:t.substring(0,o.position)}),t=t.substr(o.position+o.def.open.length),n+=o.position+o.def.open.length,i=e.token.findEnd(t,o.def,n),e.log.trace("Twig.tokenize: ","Token ends at ",i),r.push({type:o.def.type,value:t.substring(0,i).trim()}),"\n"===t.substr(i+o.def.close.length,1))switch(o.def.type){case"logic_whitespace_pre":case"logic_whitespace_post":case"logic_whitespace_both":case"logic":i+=1}t=t.substr(i+o.def.close.length),n+=i+o.def.close.length}else r.push({type:e.token.type.raw,value:t}),t="";return r},e.compile=function(t){var r=this;return e.attempt(function(){for(var n=[],o=[],i=[],s=null,a=null,p=null,c=null,l=null,u=null,f=null,h=null,y=null,d=null,g=null,m=null,x=function(t){e.expression.compile.call(r,t),o.length>0?i.push(t):n.push(t)},v=function(t){if(a=e.logic.compile.call(r,t),d=a.type,g=e.logic.handler[d].open,m=e.logic.handler[d].next,e.log.trace("Twig.compile: ","Compiled logic token to ",a," next is: ",m," open is : ",g),void 0!==g&&!g){if(c=o.pop(),f=e.logic.handler[c.type],e.indexOf(f.next,d)<0)throw new Error(d+" not expected after a "+c.type);c.output=c.output||[],c.output=c.output.concat(i),i=[],y={type:e.token.type.logic,token:c},o.length>0?i.push(y):n.push(y)}void 0!==m&&m.length>0?(e.log.trace("Twig.compile: ","Pushing ",a," to logic stack."),o.length>0&&((c=o.pop()).output=c.output||[],c.output=c.output.concat(i),o.push(c),i=[]),o.push(a)):void 0!==g&&g&&(y={type:e.token.type.logic,token:a},o.length>0?i.push(y):n.push(y))};t.length>0;){switch(s=t.shift(),l=n[n.length-1],u=i[i.length-1],h=t[0],e.log.trace("Compiling token ",s),s.type){case e.token.type.raw:o.length>0?i.push(s):n.push(s);break;case e.token.type.logic:v.call(r,s);break;case e.token.type.comment:break;case e.token.type.output:x.call(r,s);break;case e.token.type.logic_whitespace_pre:case e.token.type.logic_whitespace_post:case e.token.type.logic_whitespace_both:case e.token.type.output_whitespace_pre:case e.token.type.output_whitespace_post:case e.token.type.output_whitespace_both:switch(s.type!==e.token.type.output_whitespace_post&&s.type!==e.token.type.logic_whitespace_post&&(l&&l.type===e.token.type.raw&&(n.pop(),null===l.value.match(/^\s*$/)&&(l.value=l.value.trim(),n.push(l))),u&&u.type===e.token.type.raw&&(i.pop(),null===u.value.match(/^\s*$/)&&(u.value=u.value.trim(),i.push(u)))),s.type){case e.token.type.output_whitespace_pre:case e.token.type.output_whitespace_post:case e.token.type.output_whitespace_both:x.call(r,s);break;case e.token.type.logic_whitespace_pre:case e.token.type.logic_whitespace_post:case e.token.type.logic_whitespace_both:v.call(r,s)}s.type!==e.token.type.output_whitespace_pre&&s.type!==e.token.type.logic_whitespace_pre&&h&&h.type===e.token.type.raw&&(t.shift(),null===h.value.match(/^\s*$/)&&(h.value=h.value.trim(),t.unshift(h)))}e.log.trace("Twig.compile: "," Output: ",n," Logic Stack: ",o," Pending Output: ",i)}if(o.length>0)throw p=o.pop(),new Error("Unable to find an end tag for "+p.type+", expecting one of "+p.next);return n},function(t){if(r.options.rethrow)throw"TwigException"!=t.type||t.file||(t.file=r.id),t;e.log.error("Error compiling twig template "+r.id+": "),t.stack?e.log.error(t.stack):e.log.error(t.toString())})},e.parse=function(r,n,o){var i,s=this,a=[],p=null,c=!0,l=!0;function u(e){a.push(e)}function f(e){void 0!==e.chain&&(l=e.chain),void 0!==e.context&&(n=e.context),void 0!==e.output&&a.push(e.output)}if(i=e.async.forEach(r,function(t){switch(e.log.debug("Twig.parse: ","Parsing token: ",t),t.type){case e.token.type.raw:a.push(e.filters.raw(t.value));break;case e.token.type.logic:return e.logic.parseAsync.call(s,t.token,n,l).then(f);case e.token.type.comment:break;case e.token.type.output_whitespace_pre:case e.token.type.output_whitespace_post:case e.token.type.output_whitespace_both:case e.token.type.output:return e.log.debug("Twig.parse: ","Output token: ",t.stack),e.expression.parseAsync.call(s,t.stack,n).then(u)}}).then(function(){return a=e.output.call(s,a),c=!1,a}).catch(function(e){o&&t(s,e),p=e}),o)return i;if(null!==p)return t(this,p);if(c)throw new e.Error("You are using Twig.js in sync mode in combination with async extensions.");return a},e.prepare=function(t){var r,n;return e.log.debug("Twig.prepare: ","Tokenizing ",t),n=e.tokenize.call(this,t),e.log.debug("Twig.prepare: ","Compiling ",n),r=e.compile.call(this,n),e.log.debug("Twig.prepare: ","Compiled ",r),r},e.output=function(t){var r=this.options.autoescape;if(!r)return t.join("");var n="string"==typeof r?r:"html",o=0,i=t.length,s="",a=new Array(i);for(o=0;o<i;o++)(s=t[o])&&!0!==s.twig_markup&&s.twig_markup!=n&&(s=e.filters.escape(s,[n])),a[o]=s;return a.length<1?"":e.Markup(a.join(""),!0)},e.Templates={loaders:{},parsers:{},registry:{}},e.validateId=function(t){if("prototype"===t)throw new e.Error(t+" is not a valid twig identifier");if(e.cache&&e.Templates.registry.hasOwnProperty(t))throw new e.Error("There is already a template with the ID "+t);return!0},e.Templates.registerLoader=function(t,r,n){if("function"!=typeof r)throw new e.Error("Unable to add loader for "+t+": Invalid function reference given.");n&&(r=r.bind(n)),this.loaders[t]=r},e.Templates.unRegisterLoader=function(e){this.isRegisteredLoader(e)&&delete this.loaders[e]},e.Templates.isRegisteredLoader=function(e){return this.loaders.hasOwnProperty(e)},e.Templates.registerParser=function(t,r,n){if("function"!=typeof r)throw new e.Error("Unable to add parser for "+t+": Invalid function regerence given.");n&&(r=r.bind(n)),this.parsers[t]=r},e.Templates.unRegisterParser=function(e){this.isRegisteredParser(e)&&delete this.parsers[e]},e.Templates.isRegisteredParser=function(e){return this.parsers.hasOwnProperty(e)},e.Templates.save=function(t){if(void 0===t.id)throw new e.Error("Unable to save template with no id");e.Templates.registry[t.id]=t},e.Templates.load=function(t){return e.Templates.registry.hasOwnProperty(t)?e.Templates.registry[t]:null},e.Templates.loadRemote=function(t,r,n,o){var i=void 0===r.id?t:r.id,s=e.Templates.registry[i];return e.cache&&void 0!==s?("function"==typeof n&&n(s),s):(r.parser=r.parser||"twig",r.id=i,void 0===r.async&&(r.async=!0),(this.loaders[r.method]||this.loaders.fs).call(this,t,r,n,o))},e.Template=function(t){var r,n,o,i=t.data,s=t.id,a=t.blocks,p=t.macros||{},c=t.base,l=t.path,u=t.url,f=t.name,h=t.method,y=t.options;this.id=s,this.method=h,this.base=c,this.path=l,this.url=u,this.name=f,this.macros=p,this.options=y,this.reset(a),r="String",n=i,o=Object.prototype.toString.call(n).slice(8,-1),this.tokens=void 0!==n&&null!==n&&o===r?e.prepare.call(this,i):i,void 0!==s&&e.Templates.save(this)},e.Template.prototype.reset=function(t){e.log.debug("Twig.Template.reset","Reseting template "+this.id),this.blocks={},this.importedBlocks=[],this.originalBlockTokens={},this.child={blocks:t||{}},this.extend=null,this.parseStack=[]},e.Template.prototype.render=function(t,r,n){var o=this;return this.context=t||{},this.reset(),r&&r.blocks&&(this.blocks=r.blocks),r&&r.macros&&(this.macros=r.macros),e.async.potentiallyAsync(this,n,function(){return e.parseAsync.call(this,this.tokens,this.context).then(function(t){var n,i;return o.extend?(o.options.allowInlineIncludes&&(n=e.Templates.load(o.extend))&&(n.options=o.options),n||(i=e.path.parsePath(o,o.extend),n=e.Templates.loadRemote(i,{method:o.getLoaderMethod(),base:o.base,async:!1,id:i,options:o.options})),o.parent=n,o.parent.renderAsync(o.context,{blocks:o.blocks})):r?"blocks"==r.output?o.blocks:"macros"==r.output?o.macros:t:t})})},e.Template.prototype.importFile=function(t){var r,n;if(!this.url&&this.options.allowInlineIncludes){if(t=this.path?e.path.parsePath(this,t):t,!(n=e.Templates.load(t))&&!(n=e.Templates.loadRemote(r,{id:t,method:this.getLoaderMethod(),async:!1,path:t,options:this.options})))throw new e.Error("Unable to find the template "+t);return n.options=this.options,n}return r=e.path.parsePath(this,t),n=e.Templates.loadRemote(r,{method:this.getLoaderMethod(),base:this.base,async:!1,options:this.options,id:r})},e.Template.prototype.importBlocks=function(t,r){var n=this.importFile(t),o=this.context,i=this;r=r||!1,n.render(o),e.forEach(Object.keys(n.blocks),function(e){(r||void 0===i.blocks[e])&&(i.blocks[e]=n.blocks[e],i.importedBlocks.push(e))})},e.Template.prototype.importMacros=function(t){var r=e.path.parsePath(this,t);return e.Templates.loadRemote(r,{method:this.getLoaderMethod(),async:!1,id:r})},e.Template.prototype.getLoaderMethod=function(){return this.path?"fs":this.url?"ajax":this.method||"fs"},e.Template.prototype.compile=function(t){return e.compiler.compile(this,t)},e.Markup=function(e,t){if("string"!=typeof e||e.length<1)return e;var r=new String(e);return r.twig_markup=void 0===t||t,r},e}},function(e,t,r){
  30255. /**
  30256. * Twig.js
  30257. *
  30258. * @copyright 2011-2016 John Roepke and the Twig.js Contributors
  30259. * @license Available under the BSD 2-Clause License
  30260. * @link https://github.com/twigjs/twig.js
  30261. */
  30262. var n={VERSION:"1.11.1"};r(26)(n),r(25)(n),r(24)(n),r(22)(n),r(21)(n),r(20)(n),r(11)(n),r(10)(n),r(8)(n),r(7)(n),r(6)(n),r(5)(n),r(4)(n),r(3)(n),r(2)(n),e.exports=n.exports}])});
  30263. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/node_modules/twig")
  30264. },{"fs":21,"path":201}],208:[function(require,module,exports){
  30265. // weightSort(arr, [options | weightKey])
  30266. // Parameters:
  30267. // arr ... an array of form [ [ weight, var], ... ]
  30268. // [ [ -3, A ], [ -1, B ], [ 5, C ], [ -1, D ] ]
  30269. // OR
  30270. // an array of form [ { 'weight': value, other key/values } ]
  30271. // [ { 'weight': -3, k: A ], { 'weight': -1, v: B }, [ 5, C ] ]
  30272. // OR
  30273. // an object of form { 'index': {'weight': value, other key/values }, ... }
  30274. // (please note that numerical indexes won't work)
  30275. //
  30276. // weightKey ... name of the key which holds each element's weight (default:
  30277. // 'weight')
  30278. //
  30279. // as the last item shows, you can even mix the forms
  30280. //
  30281. // Returns:
  30282. // if the first form is used, only the 'var' will be returned; with the
  30283. // second form the elements are untouched, only their position changed.
  30284. //
  30285. // Notes:
  30286. // Entries in the source array with the same weight are returned in the
  30287. // same order
  30288. // * weight might be a function closure
  30289. function weightSort (arr, options) {
  30290. // source: http://stackoverflow.com/a/9716515/4832631
  30291. function isNumber (n) {
  30292. return !isNaN(parseFloat(n)) && isFinite(n)
  30293. }
  30294. function cmp (a, b) {
  30295. if (a === b) {
  30296. return 0
  30297. }
  30298. if (isNumber(a) && isNumber(b)) {
  30299. return parseFloat(a) < parseFloat(b) ? -1 : 1
  30300. } else {
  30301. return a < b ? -1 : 1
  30302. }
  30303. }
  30304. var i
  30305. var j
  30306. var ret1 = {}
  30307. if (typeof options === 'string') {
  30308. options = {
  30309. key: options
  30310. }
  30311. } else if (!options) {
  30312. options = {
  30313. key: 'weight'
  30314. }
  30315. }
  30316. if (!('key' in options)) {
  30317. options.key = 'weight'
  30318. }
  30319. if (!('compareFunction' in options)) {
  30320. options.compareFunction = cmp
  30321. }
  30322. // check if input array is an object, convert to array
  30323. var isObject = false
  30324. if (typeof arr.length === 'undefined') {
  30325. var newArr = []
  30326. isObject = true
  30327. for (i in arr) {
  30328. arr[i].__weightSort_index = i
  30329. newArr.push(arr[i])
  30330. }
  30331. arr = newArr
  30332. }
  30333. // first put all elements into an assoc. array
  30334. for (i = 0; i < arr.length; i++) {
  30335. var cur = arr[i]
  30336. var wgt
  30337. var data
  30338. if (cur.length) {
  30339. wgt = cur[0]
  30340. data = cur[1]
  30341. } else {
  30342. wgt = cur[options.key]
  30343. data = cur
  30344. }
  30345. if (typeof wgt === 'function') {
  30346. wgt = wgt()
  30347. }
  30348. if (!wgt) {
  30349. wgt = 0
  30350. }
  30351. if (!ret1[wgt]) {
  30352. ret1[wgt] = []
  30353. }
  30354. ret1[wgt].push(data)
  30355. }
  30356. // get the keys, convert to value, order them
  30357. var keys1 = []
  30358. for (var k in ret1) {
  30359. keys1.push(k)
  30360. }
  30361. keys1.sort(options.compareFunction)
  30362. if (options.reverse) {
  30363. keys1.reverse()
  30364. }
  30365. var ret2 = []
  30366. // iterate through array and compile final return value
  30367. for (i = 0; i < keys1.length; i++) {
  30368. for (j = 0; j < ret1[keys1[i]].length; j++) {
  30369. ret2.push(ret1[keys1[i]][j])
  30370. }
  30371. }
  30372. // rebuild object if necessary
  30373. if (isObject) {
  30374. newArr = {}
  30375. for (i = 0; i < ret2.length; i++) {
  30376. var ob = ret2[i]
  30377. var index = ob.__weightSort_index
  30378. delete ob.__weightSort_index
  30379. newArr[index] = ob
  30380. }
  30381. ret2 = newArr
  30382. }
  30383. return ret2
  30384. }
  30385. if (typeof module !== 'undefined' && module.exports) {
  30386. module.exports = weightSort
  30387. }
  30388. if (typeof window !== 'undefined') {
  30389. window.weightSort = weightSort
  30390. window.weight_sort = weightSort // legacy
  30391. }
  30392. },{}],209:[function(require,module,exports){
  30393. module.exports.RADIUS = 6378137;
  30394. module.exports.FLATTENING = 1/298.257223563;
  30395. module.exports.POLAR_RADIUS = 6356752.3142;
  30396. },{}],210:[function(require,module,exports){
  30397. function DOMParser(options){
  30398. this.options = options ||{locator:{}};
  30399. }
  30400. DOMParser.prototype.parseFromString = function(source,mimeType){
  30401. var options = this.options;
  30402. var sax = new XMLReader();
  30403. var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
  30404. var errorHandler = options.errorHandler;
  30405. var locator = options.locator;
  30406. var defaultNSMap = options.xmlns||{};
  30407. var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}
  30408. if(locator){
  30409. domBuilder.setDocumentLocator(locator)
  30410. }
  30411. sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
  30412. sax.domBuilder = options.domBuilder || domBuilder;
  30413. if(/\/x?html?$/.test(mimeType)){
  30414. entityMap.nbsp = '\xa0';
  30415. entityMap.copy = '\xa9';
  30416. defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
  30417. }
  30418. defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
  30419. if(source){
  30420. sax.parse(source,defaultNSMap,entityMap);
  30421. }else{
  30422. sax.errorHandler.error("invalid doc source");
  30423. }
  30424. return domBuilder.doc;
  30425. }
  30426. function buildErrorHandler(errorImpl,domBuilder,locator){
  30427. if(!errorImpl){
  30428. if(domBuilder instanceof DOMHandler){
  30429. return domBuilder;
  30430. }
  30431. errorImpl = domBuilder ;
  30432. }
  30433. var errorHandler = {}
  30434. var isCallback = errorImpl instanceof Function;
  30435. locator = locator||{}
  30436. function build(key){
  30437. var fn = errorImpl[key];
  30438. if(!fn && isCallback){
  30439. fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
  30440. }
  30441. errorHandler[key] = fn && function(msg){
  30442. fn('[xmldom '+key+']\t'+msg+_locator(locator));
  30443. }||function(){};
  30444. }
  30445. build('warning');
  30446. build('error');
  30447. build('fatalError');
  30448. return errorHandler;
  30449. }
  30450. //console.log('#\n\n\n\n\n\n\n####')
  30451. /**
  30452. * +ContentHandler+ErrorHandler
  30453. * +LexicalHandler+EntityResolver2
  30454. * -DeclHandler-DTDHandler
  30455. *
  30456. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  30457. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  30458. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  30459. */
  30460. function DOMHandler() {
  30461. this.cdata = false;
  30462. }
  30463. function position(locator,node){
  30464. node.lineNumber = locator.lineNumber;
  30465. node.columnNumber = locator.columnNumber;
  30466. }
  30467. /**
  30468. * @see org.xml.sax.ContentHandler#startDocument
  30469. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  30470. */
  30471. DOMHandler.prototype = {
  30472. startDocument : function() {
  30473. this.doc = new DOMImplementation().createDocument(null, null, null);
  30474. if (this.locator) {
  30475. this.doc.documentURI = this.locator.systemId;
  30476. }
  30477. },
  30478. startElement:function(namespaceURI, localName, qName, attrs) {
  30479. var doc = this.doc;
  30480. var el = doc.createElementNS(namespaceURI, qName||localName);
  30481. var len = attrs.length;
  30482. appendElement(this, el);
  30483. this.currentElement = el;
  30484. this.locator && position(this.locator,el)
  30485. for (var i = 0 ; i < len; i++) {
  30486. var namespaceURI = attrs.getURI(i);
  30487. var value = attrs.getValue(i);
  30488. var qName = attrs.getQName(i);
  30489. var attr = doc.createAttributeNS(namespaceURI, qName);
  30490. this.locator &&position(attrs.getLocator(i),attr);
  30491. attr.value = attr.nodeValue = value;
  30492. el.setAttributeNode(attr)
  30493. }
  30494. },
  30495. endElement:function(namespaceURI, localName, qName) {
  30496. var current = this.currentElement
  30497. var tagName = current.tagName;
  30498. this.currentElement = current.parentNode;
  30499. },
  30500. startPrefixMapping:function(prefix, uri) {
  30501. },
  30502. endPrefixMapping:function(prefix) {
  30503. },
  30504. processingInstruction:function(target, data) {
  30505. var ins = this.doc.createProcessingInstruction(target, data);
  30506. this.locator && position(this.locator,ins)
  30507. appendElement(this, ins);
  30508. },
  30509. ignorableWhitespace:function(ch, start, length) {
  30510. },
  30511. characters:function(chars, start, length) {
  30512. chars = _toString.apply(this,arguments)
  30513. //console.log(chars)
  30514. if(chars){
  30515. if (this.cdata) {
  30516. var charNode = this.doc.createCDATASection(chars);
  30517. } else {
  30518. var charNode = this.doc.createTextNode(chars);
  30519. }
  30520. if(this.currentElement){
  30521. this.currentElement.appendChild(charNode);
  30522. }else if(/^\s*$/.test(chars)){
  30523. this.doc.appendChild(charNode);
  30524. //process xml
  30525. }
  30526. this.locator && position(this.locator,charNode)
  30527. }
  30528. },
  30529. skippedEntity:function(name) {
  30530. },
  30531. endDocument:function() {
  30532. this.doc.normalize();
  30533. },
  30534. setDocumentLocator:function (locator) {
  30535. if(this.locator = locator){// && !('lineNumber' in locator)){
  30536. locator.lineNumber = 0;
  30537. }
  30538. },
  30539. //LexicalHandler
  30540. comment:function(chars, start, length) {
  30541. chars = _toString.apply(this,arguments)
  30542. var comm = this.doc.createComment(chars);
  30543. this.locator && position(this.locator,comm)
  30544. appendElement(this, comm);
  30545. },
  30546. startCDATA:function() {
  30547. //used in characters() methods
  30548. this.cdata = true;
  30549. },
  30550. endCDATA:function() {
  30551. this.cdata = false;
  30552. },
  30553. startDTD:function(name, publicId, systemId) {
  30554. var impl = this.doc.implementation;
  30555. if (impl && impl.createDocumentType) {
  30556. var dt = impl.createDocumentType(name, publicId, systemId);
  30557. this.locator && position(this.locator,dt)
  30558. appendElement(this, dt);
  30559. }
  30560. },
  30561. /**
  30562. * @see org.xml.sax.ErrorHandler
  30563. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  30564. */
  30565. warning:function(error) {
  30566. console.warn('[xmldom warning]\t'+error,_locator(this.locator));
  30567. },
  30568. error:function(error) {
  30569. console.error('[xmldom error]\t'+error,_locator(this.locator));
  30570. },
  30571. fatalError:function(error) {
  30572. console.error('[xmldom fatalError]\t'+error,_locator(this.locator));
  30573. throw error;
  30574. }
  30575. }
  30576. function _locator(l){
  30577. if(l){
  30578. return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
  30579. }
  30580. }
  30581. function _toString(chars,start,length){
  30582. if(typeof chars == 'string'){
  30583. return chars.substr(start,length)
  30584. }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  30585. if(chars.length >= start+length || start){
  30586. return new java.lang.String(chars,start,length)+'';
  30587. }
  30588. return chars;
  30589. }
  30590. }
  30591. /*
  30592. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  30593. * used method of org.xml.sax.ext.LexicalHandler:
  30594. * #comment(chars, start, length)
  30595. * #startCDATA()
  30596. * #endCDATA()
  30597. * #startDTD(name, publicId, systemId)
  30598. *
  30599. *
  30600. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  30601. * #endDTD()
  30602. * #startEntity(name)
  30603. * #endEntity(name)
  30604. *
  30605. *
  30606. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  30607. * IGNORED method of org.xml.sax.ext.DeclHandler
  30608. * #attributeDecl(eName, aName, type, mode, value)
  30609. * #elementDecl(name, model)
  30610. * #externalEntityDecl(name, publicId, systemId)
  30611. * #internalEntityDecl(name, value)
  30612. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  30613. * IGNORED method of org.xml.sax.EntityResolver2
  30614. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  30615. * #resolveEntity(publicId, systemId)
  30616. * #getExternalSubset(name, baseURI)
  30617. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  30618. * IGNORED method of org.xml.sax.DTDHandler
  30619. * #notationDecl(name, publicId, systemId) {};
  30620. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  30621. */
  30622. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
  30623. DOMHandler.prototype[key] = function(){return null}
  30624. })
  30625. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  30626. function appendElement (hander,node) {
  30627. if (!hander.currentElement) {
  30628. hander.doc.appendChild(node);
  30629. } else {
  30630. hander.currentElement.appendChild(node);
  30631. }
  30632. }//appendChild and setAttributeNS are preformance key
  30633. //if(typeof require == 'function'){
  30634. var XMLReader = require('./sax').XMLReader;
  30635. var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
  30636. exports.XMLSerializer = require('./dom').XMLSerializer ;
  30637. exports.DOMParser = DOMParser;
  30638. //}
  30639. },{"./dom":211,"./sax":212}],211:[function(require,module,exports){
  30640. /*
  30641. * DOM Level 2
  30642. * Object DOMException
  30643. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  30644. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  30645. */
  30646. function copy(src,dest){
  30647. for(var p in src){
  30648. dest[p] = src[p];
  30649. }
  30650. }
  30651. /**
  30652. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  30653. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  30654. */
  30655. function _extends(Class,Super){
  30656. var pt = Class.prototype;
  30657. if(Object.create){
  30658. var ppt = Object.create(Super.prototype)
  30659. pt.__proto__ = ppt;
  30660. }
  30661. if(!(pt instanceof Super)){
  30662. function t(){};
  30663. t.prototype = Super.prototype;
  30664. t = new t();
  30665. copy(pt,t);
  30666. Class.prototype = pt = t;
  30667. }
  30668. if(pt.constructor != Class){
  30669. if(typeof Class != 'function'){
  30670. console.error("unknow Class:"+Class)
  30671. }
  30672. pt.constructor = Class
  30673. }
  30674. }
  30675. var htmlns = 'http://www.w3.org/1999/xhtml' ;
  30676. // Node Types
  30677. var NodeType = {}
  30678. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  30679. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  30680. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  30681. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  30682. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  30683. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  30684. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  30685. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  30686. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  30687. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  30688. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  30689. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  30690. // ExceptionCode
  30691. var ExceptionCode = {}
  30692. var ExceptionMessage = {};
  30693. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
  30694. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
  30695. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
  30696. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
  30697. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
  30698. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
  30699. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
  30700. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
  30701. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
  30702. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
  30703. //level2
  30704. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
  30705. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
  30706. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
  30707. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
  30708. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
  30709. function DOMException(code, message) {
  30710. if(message instanceof Error){
  30711. var error = message;
  30712. }else{
  30713. error = this;
  30714. Error.call(this, ExceptionMessage[code]);
  30715. this.message = ExceptionMessage[code];
  30716. if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  30717. }
  30718. error.code = code;
  30719. if(message) this.message = this.message + ": " + message;
  30720. return error;
  30721. };
  30722. DOMException.prototype = Error.prototype;
  30723. copy(ExceptionCode,DOMException)
  30724. /**
  30725. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  30726. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  30727. * The items in the NodeList are accessible via an integral index, starting from 0.
  30728. */
  30729. function NodeList() {
  30730. };
  30731. NodeList.prototype = {
  30732. /**
  30733. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  30734. * @standard level1
  30735. */
  30736. length:0,
  30737. /**
  30738. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  30739. * @standard level1
  30740. * @param index unsigned long
  30741. * Index into the collection.
  30742. * @return Node
  30743. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  30744. */
  30745. item: function(index) {
  30746. return this[index] || null;
  30747. },
  30748. toString:function(isHTML,nodeFilter){
  30749. for(var buf = [], i = 0;i<this.length;i++){
  30750. serializeToString(this[i],buf,isHTML,nodeFilter);
  30751. }
  30752. return buf.join('');
  30753. }
  30754. };
  30755. function LiveNodeList(node,refresh){
  30756. this._node = node;
  30757. this._refresh = refresh
  30758. _updateLiveList(this);
  30759. }
  30760. function _updateLiveList(list){
  30761. var inc = list._node._inc || list._node.ownerDocument._inc;
  30762. if(list._inc != inc){
  30763. var ls = list._refresh(list._node);
  30764. //console.log(ls.length)
  30765. __set__(list,'length',ls.length);
  30766. copy(ls,list);
  30767. list._inc = inc;
  30768. }
  30769. }
  30770. LiveNodeList.prototype.item = function(i){
  30771. _updateLiveList(this);
  30772. return this[i];
  30773. }
  30774. _extends(LiveNodeList,NodeList);
  30775. /**
  30776. *
  30777. * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
  30778. * NamedNodeMap objects in the DOM are live.
  30779. * used for attributes or DocumentType entities
  30780. */
  30781. function NamedNodeMap() {
  30782. };
  30783. function _findNodeIndex(list,node){
  30784. var i = list.length;
  30785. while(i--){
  30786. if(list[i] === node){return i}
  30787. }
  30788. }
  30789. function _addNamedNode(el,list,newAttr,oldAttr){
  30790. if(oldAttr){
  30791. list[_findNodeIndex(list,oldAttr)] = newAttr;
  30792. }else{
  30793. list[list.length++] = newAttr;
  30794. }
  30795. if(el){
  30796. newAttr.ownerElement = el;
  30797. var doc = el.ownerDocument;
  30798. if(doc){
  30799. oldAttr && _onRemoveAttribute(doc,el,oldAttr);
  30800. _onAddAttribute(doc,el,newAttr);
  30801. }
  30802. }
  30803. }
  30804. function _removeNamedNode(el,list,attr){
  30805. //console.log('remove attr:'+attr)
  30806. var i = _findNodeIndex(list,attr);
  30807. if(i>=0){
  30808. var lastIndex = list.length-1
  30809. while(i<lastIndex){
  30810. list[i] = list[++i]
  30811. }
  30812. list.length = lastIndex;
  30813. if(el){
  30814. var doc = el.ownerDocument;
  30815. if(doc){
  30816. _onRemoveAttribute(doc,el,attr);
  30817. attr.ownerElement = null;
  30818. }
  30819. }
  30820. }else{
  30821. throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
  30822. }
  30823. }
  30824. NamedNodeMap.prototype = {
  30825. length:0,
  30826. item:NodeList.prototype.item,
  30827. getNamedItem: function(key) {
  30828. // if(key.indexOf(':')>0 || key == 'xmlns'){
  30829. // return null;
  30830. // }
  30831. //console.log()
  30832. var i = this.length;
  30833. while(i--){
  30834. var attr = this[i];
  30835. //console.log(attr.nodeName,key)
  30836. if(attr.nodeName == key){
  30837. return attr;
  30838. }
  30839. }
  30840. },
  30841. setNamedItem: function(attr) {
  30842. var el = attr.ownerElement;
  30843. if(el && el!=this._ownerElement){
  30844. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  30845. }
  30846. var oldAttr = this.getNamedItem(attr.nodeName);
  30847. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  30848. return oldAttr;
  30849. },
  30850. /* returns Node */
  30851. setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  30852. var el = attr.ownerElement, oldAttr;
  30853. if(el && el!=this._ownerElement){
  30854. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  30855. }
  30856. oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
  30857. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  30858. return oldAttr;
  30859. },
  30860. /* returns Node */
  30861. removeNamedItem: function(key) {
  30862. var attr = this.getNamedItem(key);
  30863. _removeNamedNode(this._ownerElement,this,attr);
  30864. return attr;
  30865. },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  30866. //for level2
  30867. removeNamedItemNS:function(namespaceURI,localName){
  30868. var attr = this.getNamedItemNS(namespaceURI,localName);
  30869. _removeNamedNode(this._ownerElement,this,attr);
  30870. return attr;
  30871. },
  30872. getNamedItemNS: function(namespaceURI, localName) {
  30873. var i = this.length;
  30874. while(i--){
  30875. var node = this[i];
  30876. if(node.localName == localName && node.namespaceURI == namespaceURI){
  30877. return node;
  30878. }
  30879. }
  30880. return null;
  30881. }
  30882. };
  30883. /**
  30884. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
  30885. */
  30886. function DOMImplementation(/* Object */ features) {
  30887. this._features = {};
  30888. if (features) {
  30889. for (var feature in features) {
  30890. this._features = features[feature];
  30891. }
  30892. }
  30893. };
  30894. DOMImplementation.prototype = {
  30895. hasFeature: function(/* string */ feature, /* string */ version) {
  30896. var versions = this._features[feature.toLowerCase()];
  30897. if (versions && (!version || version in versions)) {
  30898. return true;
  30899. } else {
  30900. return false;
  30901. }
  30902. },
  30903. // Introduced in DOM Level 2:
  30904. createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
  30905. var doc = new Document();
  30906. doc.implementation = this;
  30907. doc.childNodes = new NodeList();
  30908. doc.doctype = doctype;
  30909. if(doctype){
  30910. doc.appendChild(doctype);
  30911. }
  30912. if(qualifiedName){
  30913. var root = doc.createElementNS(namespaceURI,qualifiedName);
  30914. doc.appendChild(root);
  30915. }
  30916. return doc;
  30917. },
  30918. // Introduced in DOM Level 2:
  30919. createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
  30920. var node = new DocumentType();
  30921. node.name = qualifiedName;
  30922. node.nodeName = qualifiedName;
  30923. node.publicId = publicId;
  30924. node.systemId = systemId;
  30925. // Introduced in DOM Level 2:
  30926. //readonly attribute DOMString internalSubset;
  30927. //TODO:..
  30928. // readonly attribute NamedNodeMap entities;
  30929. // readonly attribute NamedNodeMap notations;
  30930. return node;
  30931. }
  30932. };
  30933. /**
  30934. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  30935. */
  30936. function Node() {
  30937. };
  30938. Node.prototype = {
  30939. firstChild : null,
  30940. lastChild : null,
  30941. previousSibling : null,
  30942. nextSibling : null,
  30943. attributes : null,
  30944. parentNode : null,
  30945. childNodes : null,
  30946. ownerDocument : null,
  30947. nodeValue : null,
  30948. namespaceURI : null,
  30949. prefix : null,
  30950. localName : null,
  30951. // Modified in DOM Level 2:
  30952. insertBefore:function(newChild, refChild){//raises
  30953. return _insertBefore(this,newChild,refChild);
  30954. },
  30955. replaceChild:function(newChild, oldChild){//raises
  30956. this.insertBefore(newChild,oldChild);
  30957. if(oldChild){
  30958. this.removeChild(oldChild);
  30959. }
  30960. },
  30961. removeChild:function(oldChild){
  30962. return _removeChild(this,oldChild);
  30963. },
  30964. appendChild:function(newChild){
  30965. return this.insertBefore(newChild,null);
  30966. },
  30967. hasChildNodes:function(){
  30968. return this.firstChild != null;
  30969. },
  30970. cloneNode:function(deep){
  30971. return cloneNode(this.ownerDocument||this,this,deep);
  30972. },
  30973. // Modified in DOM Level 2:
  30974. normalize:function(){
  30975. var child = this.firstChild;
  30976. while(child){
  30977. var next = child.nextSibling;
  30978. if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
  30979. this.removeChild(next);
  30980. child.appendData(next.data);
  30981. }else{
  30982. child.normalize();
  30983. child = next;
  30984. }
  30985. }
  30986. },
  30987. // Introduced in DOM Level 2:
  30988. isSupported:function(feature, version){
  30989. return this.ownerDocument.implementation.hasFeature(feature,version);
  30990. },
  30991. // Introduced in DOM Level 2:
  30992. hasAttributes:function(){
  30993. return this.attributes.length>0;
  30994. },
  30995. lookupPrefix:function(namespaceURI){
  30996. var el = this;
  30997. while(el){
  30998. var map = el._nsMap;
  30999. //console.dir(map)
  31000. if(map){
  31001. for(var n in map){
  31002. if(map[n] == namespaceURI){
  31003. return n;
  31004. }
  31005. }
  31006. }
  31007. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  31008. }
  31009. return null;
  31010. },
  31011. // Introduced in DOM Level 3:
  31012. lookupNamespaceURI:function(prefix){
  31013. var el = this;
  31014. while(el){
  31015. var map = el._nsMap;
  31016. //console.dir(map)
  31017. if(map){
  31018. if(prefix in map){
  31019. return map[prefix] ;
  31020. }
  31021. }
  31022. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  31023. }
  31024. return null;
  31025. },
  31026. // Introduced in DOM Level 3:
  31027. isDefaultNamespace:function(namespaceURI){
  31028. var prefix = this.lookupPrefix(namespaceURI);
  31029. return prefix == null;
  31030. }
  31031. };
  31032. function _xmlEncoder(c){
  31033. return c == '<' && '&lt;' ||
  31034. c == '>' && '&gt;' ||
  31035. c == '&' && '&amp;' ||
  31036. c == '"' && '&quot;' ||
  31037. '&#'+c.charCodeAt()+';'
  31038. }
  31039. copy(NodeType,Node);
  31040. copy(NodeType,Node.prototype);
  31041. /**
  31042. * @param callback return true for continue,false for break
  31043. * @return boolean true: break visit;
  31044. */
  31045. function _visitNode(node,callback){
  31046. if(callback(node)){
  31047. return true;
  31048. }
  31049. if(node = node.firstChild){
  31050. do{
  31051. if(_visitNode(node,callback)){return true}
  31052. }while(node=node.nextSibling)
  31053. }
  31054. }
  31055. function Document(){
  31056. }
  31057. function _onAddAttribute(doc,el,newAttr){
  31058. doc && doc._inc++;
  31059. var ns = newAttr.namespaceURI ;
  31060. if(ns == 'http://www.w3.org/2000/xmlns/'){
  31061. //update namespace
  31062. el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
  31063. }
  31064. }
  31065. function _onRemoveAttribute(doc,el,newAttr,remove){
  31066. doc && doc._inc++;
  31067. var ns = newAttr.namespaceURI ;
  31068. if(ns == 'http://www.w3.org/2000/xmlns/'){
  31069. //update namespace
  31070. delete el._nsMap[newAttr.prefix?newAttr.localName:'']
  31071. }
  31072. }
  31073. function _onUpdateChild(doc,el,newChild){
  31074. if(doc && doc._inc){
  31075. doc._inc++;
  31076. //update childNodes
  31077. var cs = el.childNodes;
  31078. if(newChild){
  31079. cs[cs.length++] = newChild;
  31080. }else{
  31081. //console.log(1)
  31082. var child = el.firstChild;
  31083. var i = 0;
  31084. while(child){
  31085. cs[i++] = child;
  31086. child =child.nextSibling;
  31087. }
  31088. cs.length = i;
  31089. }
  31090. }
  31091. }
  31092. /**
  31093. * attributes;
  31094. * children;
  31095. *
  31096. * writeable properties:
  31097. * nodeValue,Attr:value,CharacterData:data
  31098. * prefix
  31099. */
  31100. function _removeChild(parentNode,child){
  31101. var previous = child.previousSibling;
  31102. var next = child.nextSibling;
  31103. if(previous){
  31104. previous.nextSibling = next;
  31105. }else{
  31106. parentNode.firstChild = next
  31107. }
  31108. if(next){
  31109. next.previousSibling = previous;
  31110. }else{
  31111. parentNode.lastChild = previous;
  31112. }
  31113. _onUpdateChild(parentNode.ownerDocument,parentNode);
  31114. return child;
  31115. }
  31116. /**
  31117. * preformance key(refChild == null)
  31118. */
  31119. function _insertBefore(parentNode,newChild,nextChild){
  31120. var cp = newChild.parentNode;
  31121. if(cp){
  31122. cp.removeChild(newChild);//remove and update
  31123. }
  31124. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  31125. var newFirst = newChild.firstChild;
  31126. if (newFirst == null) {
  31127. return newChild;
  31128. }
  31129. var newLast = newChild.lastChild;
  31130. }else{
  31131. newFirst = newLast = newChild;
  31132. }
  31133. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  31134. newFirst.previousSibling = pre;
  31135. newLast.nextSibling = nextChild;
  31136. if(pre){
  31137. pre.nextSibling = newFirst;
  31138. }else{
  31139. parentNode.firstChild = newFirst;
  31140. }
  31141. if(nextChild == null){
  31142. parentNode.lastChild = newLast;
  31143. }else{
  31144. nextChild.previousSibling = newLast;
  31145. }
  31146. do{
  31147. newFirst.parentNode = parentNode;
  31148. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  31149. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  31150. //console.log(parentNode.lastChild.nextSibling == null)
  31151. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  31152. newChild.firstChild = newChild.lastChild = null;
  31153. }
  31154. return newChild;
  31155. }
  31156. function _appendSingleChild(parentNode,newChild){
  31157. var cp = newChild.parentNode;
  31158. if(cp){
  31159. var pre = parentNode.lastChild;
  31160. cp.removeChild(newChild);//remove and update
  31161. var pre = parentNode.lastChild;
  31162. }
  31163. var pre = parentNode.lastChild;
  31164. newChild.parentNode = parentNode;
  31165. newChild.previousSibling = pre;
  31166. newChild.nextSibling = null;
  31167. if(pre){
  31168. pre.nextSibling = newChild;
  31169. }else{
  31170. parentNode.firstChild = newChild;
  31171. }
  31172. parentNode.lastChild = newChild;
  31173. _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
  31174. return newChild;
  31175. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  31176. }
  31177. Document.prototype = {
  31178. //implementation : null,
  31179. nodeName : '#document',
  31180. nodeType : DOCUMENT_NODE,
  31181. doctype : null,
  31182. documentElement : null,
  31183. _inc : 1,
  31184. insertBefore : function(newChild, refChild){//raises
  31185. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  31186. var child = newChild.firstChild;
  31187. while(child){
  31188. var next = child.nextSibling;
  31189. this.insertBefore(child,refChild);
  31190. child = next;
  31191. }
  31192. return newChild;
  31193. }
  31194. if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
  31195. this.documentElement = newChild;
  31196. }
  31197. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  31198. },
  31199. removeChild : function(oldChild){
  31200. if(this.documentElement == oldChild){
  31201. this.documentElement = null;
  31202. }
  31203. return _removeChild(this,oldChild);
  31204. },
  31205. // Introduced in DOM Level 2:
  31206. importNode : function(importedNode,deep){
  31207. return importNode(this,importedNode,deep);
  31208. },
  31209. // Introduced in DOM Level 2:
  31210. getElementById : function(id){
  31211. var rtv = null;
  31212. _visitNode(this.documentElement,function(node){
  31213. if(node.nodeType == ELEMENT_NODE){
  31214. if(node.getAttribute('id') == id){
  31215. rtv = node;
  31216. return true;
  31217. }
  31218. }
  31219. })
  31220. return rtv;
  31221. },
  31222. //document factory method:
  31223. createElement : function(tagName){
  31224. var node = new Element();
  31225. node.ownerDocument = this;
  31226. node.nodeName = tagName;
  31227. node.tagName = tagName;
  31228. node.childNodes = new NodeList();
  31229. var attrs = node.attributes = new NamedNodeMap();
  31230. attrs._ownerElement = node;
  31231. return node;
  31232. },
  31233. createDocumentFragment : function(){
  31234. var node = new DocumentFragment();
  31235. node.ownerDocument = this;
  31236. node.childNodes = new NodeList();
  31237. return node;
  31238. },
  31239. createTextNode : function(data){
  31240. var node = new Text();
  31241. node.ownerDocument = this;
  31242. node.appendData(data)
  31243. return node;
  31244. },
  31245. createComment : function(data){
  31246. var node = new Comment();
  31247. node.ownerDocument = this;
  31248. node.appendData(data)
  31249. return node;
  31250. },
  31251. createCDATASection : function(data){
  31252. var node = new CDATASection();
  31253. node.ownerDocument = this;
  31254. node.appendData(data)
  31255. return node;
  31256. },
  31257. createProcessingInstruction : function(target,data){
  31258. var node = new ProcessingInstruction();
  31259. node.ownerDocument = this;
  31260. node.tagName = node.target = target;
  31261. node.nodeValue= node.data = data;
  31262. return node;
  31263. },
  31264. createAttribute : function(name){
  31265. var node = new Attr();
  31266. node.ownerDocument = this;
  31267. node.name = name;
  31268. node.nodeName = name;
  31269. node.localName = name;
  31270. node.specified = true;
  31271. return node;
  31272. },
  31273. createEntityReference : function(name){
  31274. var node = new EntityReference();
  31275. node.ownerDocument = this;
  31276. node.nodeName = name;
  31277. return node;
  31278. },
  31279. // Introduced in DOM Level 2:
  31280. createElementNS : function(namespaceURI,qualifiedName){
  31281. var node = new Element();
  31282. var pl = qualifiedName.split(':');
  31283. var attrs = node.attributes = new NamedNodeMap();
  31284. node.childNodes = new NodeList();
  31285. node.ownerDocument = this;
  31286. node.nodeName = qualifiedName;
  31287. node.tagName = qualifiedName;
  31288. node.namespaceURI = namespaceURI;
  31289. if(pl.length == 2){
  31290. node.prefix = pl[0];
  31291. node.localName = pl[1];
  31292. }else{
  31293. //el.prefix = null;
  31294. node.localName = qualifiedName;
  31295. }
  31296. attrs._ownerElement = node;
  31297. return node;
  31298. },
  31299. // Introduced in DOM Level 2:
  31300. createAttributeNS : function(namespaceURI,qualifiedName){
  31301. var node = new Attr();
  31302. var pl = qualifiedName.split(':');
  31303. node.ownerDocument = this;
  31304. node.nodeName = qualifiedName;
  31305. node.name = qualifiedName;
  31306. node.namespaceURI = namespaceURI;
  31307. node.specified = true;
  31308. if(pl.length == 2){
  31309. node.prefix = pl[0];
  31310. node.localName = pl[1];
  31311. }else{
  31312. //el.prefix = null;
  31313. node.localName = qualifiedName;
  31314. }
  31315. return node;
  31316. }
  31317. };
  31318. _extends(Document,Node);
  31319. function Element() {
  31320. this._nsMap = {};
  31321. };
  31322. Element.prototype = {
  31323. nodeType : ELEMENT_NODE,
  31324. hasAttribute : function(name){
  31325. return this.getAttributeNode(name)!=null;
  31326. },
  31327. getAttribute : function(name){
  31328. var attr = this.getAttributeNode(name);
  31329. return attr && attr.value || '';
  31330. },
  31331. getAttributeNode : function(name){
  31332. return this.attributes.getNamedItem(name);
  31333. },
  31334. setAttribute : function(name, value){
  31335. var attr = this.ownerDocument.createAttribute(name);
  31336. attr.value = attr.nodeValue = "" + value;
  31337. this.setAttributeNode(attr)
  31338. },
  31339. removeAttribute : function(name){
  31340. var attr = this.getAttributeNode(name)
  31341. attr && this.removeAttributeNode(attr);
  31342. },
  31343. //four real opeartion method
  31344. appendChild:function(newChild){
  31345. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  31346. return this.insertBefore(newChild,null);
  31347. }else{
  31348. return _appendSingleChild(this,newChild);
  31349. }
  31350. },
  31351. setAttributeNode : function(newAttr){
  31352. return this.attributes.setNamedItem(newAttr);
  31353. },
  31354. setAttributeNodeNS : function(newAttr){
  31355. return this.attributes.setNamedItemNS(newAttr);
  31356. },
  31357. removeAttributeNode : function(oldAttr){
  31358. //console.log(this == oldAttr.ownerElement)
  31359. return this.attributes.removeNamedItem(oldAttr.nodeName);
  31360. },
  31361. //get real attribute name,and remove it by removeAttributeNode
  31362. removeAttributeNS : function(namespaceURI, localName){
  31363. var old = this.getAttributeNodeNS(namespaceURI, localName);
  31364. old && this.removeAttributeNode(old);
  31365. },
  31366. hasAttributeNS : function(namespaceURI, localName){
  31367. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  31368. },
  31369. getAttributeNS : function(namespaceURI, localName){
  31370. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  31371. return attr && attr.value || '';
  31372. },
  31373. setAttributeNS : function(namespaceURI, qualifiedName, value){
  31374. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  31375. attr.value = attr.nodeValue = "" + value;
  31376. this.setAttributeNode(attr)
  31377. },
  31378. getAttributeNodeNS : function(namespaceURI, localName){
  31379. return this.attributes.getNamedItemNS(namespaceURI, localName);
  31380. },
  31381. getElementsByTagName : function(tagName){
  31382. return new LiveNodeList(this,function(base){
  31383. var ls = [];
  31384. _visitNode(base,function(node){
  31385. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  31386. ls.push(node);
  31387. }
  31388. });
  31389. return ls;
  31390. });
  31391. },
  31392. getElementsByTagNameNS : function(namespaceURI, localName){
  31393. return new LiveNodeList(this,function(base){
  31394. var ls = [];
  31395. _visitNode(base,function(node){
  31396. if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
  31397. ls.push(node);
  31398. }
  31399. });
  31400. return ls;
  31401. });
  31402. }
  31403. };
  31404. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  31405. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  31406. _extends(Element,Node);
  31407. function Attr() {
  31408. };
  31409. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  31410. _extends(Attr,Node);
  31411. function CharacterData() {
  31412. };
  31413. CharacterData.prototype = {
  31414. data : '',
  31415. substringData : function(offset, count) {
  31416. return this.data.substring(offset, offset+count);
  31417. },
  31418. appendData: function(text) {
  31419. text = this.data+text;
  31420. this.nodeValue = this.data = text;
  31421. this.length = text.length;
  31422. },
  31423. insertData: function(offset,text) {
  31424. this.replaceData(offset,0,text);
  31425. },
  31426. appendChild:function(newChild){
  31427. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
  31428. },
  31429. deleteData: function(offset, count) {
  31430. this.replaceData(offset,count,"");
  31431. },
  31432. replaceData: function(offset, count, text) {
  31433. var start = this.data.substring(0,offset);
  31434. var end = this.data.substring(offset+count);
  31435. text = start + text + end;
  31436. this.nodeValue = this.data = text;
  31437. this.length = text.length;
  31438. }
  31439. }
  31440. _extends(CharacterData,Node);
  31441. function Text() {
  31442. };
  31443. Text.prototype = {
  31444. nodeName : "#text",
  31445. nodeType : TEXT_NODE,
  31446. splitText : function(offset) {
  31447. var text = this.data;
  31448. var newText = text.substring(offset);
  31449. text = text.substring(0, offset);
  31450. this.data = this.nodeValue = text;
  31451. this.length = text.length;
  31452. var newNode = this.ownerDocument.createTextNode(newText);
  31453. if(this.parentNode){
  31454. this.parentNode.insertBefore(newNode, this.nextSibling);
  31455. }
  31456. return newNode;
  31457. }
  31458. }
  31459. _extends(Text,CharacterData);
  31460. function Comment() {
  31461. };
  31462. Comment.prototype = {
  31463. nodeName : "#comment",
  31464. nodeType : COMMENT_NODE
  31465. }
  31466. _extends(Comment,CharacterData);
  31467. function CDATASection() {
  31468. };
  31469. CDATASection.prototype = {
  31470. nodeName : "#cdata-section",
  31471. nodeType : CDATA_SECTION_NODE
  31472. }
  31473. _extends(CDATASection,CharacterData);
  31474. function DocumentType() {
  31475. };
  31476. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  31477. _extends(DocumentType,Node);
  31478. function Notation() {
  31479. };
  31480. Notation.prototype.nodeType = NOTATION_NODE;
  31481. _extends(Notation,Node);
  31482. function Entity() {
  31483. };
  31484. Entity.prototype.nodeType = ENTITY_NODE;
  31485. _extends(Entity,Node);
  31486. function EntityReference() {
  31487. };
  31488. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  31489. _extends(EntityReference,Node);
  31490. function DocumentFragment() {
  31491. };
  31492. DocumentFragment.prototype.nodeName = "#document-fragment";
  31493. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  31494. _extends(DocumentFragment,Node);
  31495. function ProcessingInstruction() {
  31496. }
  31497. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  31498. _extends(ProcessingInstruction,Node);
  31499. function XMLSerializer(){}
  31500. XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
  31501. return nodeSerializeToString.call(node,isHtml,nodeFilter);
  31502. }
  31503. Node.prototype.toString = nodeSerializeToString;
  31504. function nodeSerializeToString(isHtml,nodeFilter){
  31505. var buf = [];
  31506. var refNode = this.nodeType == 9?this.documentElement:this;
  31507. var prefix = refNode.prefix;
  31508. var uri = refNode.namespaceURI;
  31509. if(uri && prefix == null){
  31510. //console.log(prefix)
  31511. var prefix = refNode.lookupPrefix(uri);
  31512. if(prefix == null){
  31513. //isHTML = true;
  31514. var visibleNamespaces=[
  31515. {namespace:uri,prefix:null}
  31516. //{namespace:uri,prefix:''}
  31517. ]
  31518. }
  31519. }
  31520. serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
  31521. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  31522. return buf.join('');
  31523. }
  31524. function needNamespaceDefine(node,isHTML, visibleNamespaces) {
  31525. var prefix = node.prefix||'';
  31526. var uri = node.namespaceURI;
  31527. if (!prefix && !uri){
  31528. return false;
  31529. }
  31530. if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
  31531. || uri == 'http://www.w3.org/2000/xmlns/'){
  31532. return false;
  31533. }
  31534. var i = visibleNamespaces.length
  31535. //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
  31536. while (i--) {
  31537. var ns = visibleNamespaces[i];
  31538. // get namespace prefix
  31539. //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
  31540. if (ns.prefix == prefix){
  31541. return ns.namespace != uri;
  31542. }
  31543. }
  31544. //console.log(isHTML,uri,prefix=='')
  31545. //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
  31546. // return false;
  31547. //}
  31548. //node.flag = '11111'
  31549. //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
  31550. return true;
  31551. }
  31552. function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
  31553. if(nodeFilter){
  31554. node = nodeFilter(node);
  31555. if(node){
  31556. if(typeof node == 'string'){
  31557. buf.push(node);
  31558. return;
  31559. }
  31560. }else{
  31561. return;
  31562. }
  31563. //buf.sort.apply(attrs, attributeSorter);
  31564. }
  31565. switch(node.nodeType){
  31566. case ELEMENT_NODE:
  31567. if (!visibleNamespaces) visibleNamespaces = [];
  31568. var startVisibleNamespaces = visibleNamespaces.length;
  31569. var attrs = node.attributes;
  31570. var len = attrs.length;
  31571. var child = node.firstChild;
  31572. var nodeName = node.tagName;
  31573. isHTML = (htmlns === node.namespaceURI) ||isHTML
  31574. buf.push('<',nodeName);
  31575. for(var i=0;i<len;i++){
  31576. // add namespaces for attributes
  31577. var attr = attrs.item(i);
  31578. if (attr.prefix == 'xmlns') {
  31579. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  31580. }else if(attr.nodeName == 'xmlns'){
  31581. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  31582. }
  31583. }
  31584. for(var i=0;i<len;i++){
  31585. var attr = attrs.item(i);
  31586. if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
  31587. var prefix = attr.prefix||'';
  31588. var uri = attr.namespaceURI;
  31589. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  31590. buf.push(ns, '="' , uri , '"');
  31591. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  31592. }
  31593. serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
  31594. }
  31595. // add namespace for current node
  31596. if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
  31597. var prefix = node.prefix||'';
  31598. var uri = node.namespaceURI;
  31599. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  31600. buf.push(ns, '="' , uri , '"');
  31601. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  31602. }
  31603. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  31604. buf.push('>');
  31605. //if is cdata child node
  31606. if(isHTML && /^script$/i.test(nodeName)){
  31607. while(child){
  31608. if(child.data){
  31609. buf.push(child.data);
  31610. }else{
  31611. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  31612. }
  31613. child = child.nextSibling;
  31614. }
  31615. }else
  31616. {
  31617. while(child){
  31618. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  31619. child = child.nextSibling;
  31620. }
  31621. }
  31622. buf.push('</',nodeName,'>');
  31623. }else{
  31624. buf.push('/>');
  31625. }
  31626. // remove added visible namespaces
  31627. //visibleNamespaces.length = startVisibleNamespaces;
  31628. return;
  31629. case DOCUMENT_NODE:
  31630. case DOCUMENT_FRAGMENT_NODE:
  31631. var child = node.firstChild;
  31632. while(child){
  31633. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  31634. child = child.nextSibling;
  31635. }
  31636. return;
  31637. case ATTRIBUTE_NODE:
  31638. return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
  31639. case TEXT_NODE:
  31640. return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
  31641. case CDATA_SECTION_NODE:
  31642. return buf.push( '<![CDATA[',node.data,']]>');
  31643. case COMMENT_NODE:
  31644. return buf.push( "<!--",node.data,"-->");
  31645. case DOCUMENT_TYPE_NODE:
  31646. var pubid = node.publicId;
  31647. var sysid = node.systemId;
  31648. buf.push('<!DOCTYPE ',node.name);
  31649. if(pubid){
  31650. buf.push(' PUBLIC "',pubid);
  31651. if (sysid && sysid!='.') {
  31652. buf.push( '" "',sysid);
  31653. }
  31654. buf.push('">');
  31655. }else if(sysid && sysid!='.'){
  31656. buf.push(' SYSTEM "',sysid,'">');
  31657. }else{
  31658. var sub = node.internalSubset;
  31659. if(sub){
  31660. buf.push(" [",sub,"]");
  31661. }
  31662. buf.push(">");
  31663. }
  31664. return;
  31665. case PROCESSING_INSTRUCTION_NODE:
  31666. return buf.push( "<?",node.target," ",node.data,"?>");
  31667. case ENTITY_REFERENCE_NODE:
  31668. return buf.push( '&',node.nodeName,';');
  31669. //case ENTITY_NODE:
  31670. //case NOTATION_NODE:
  31671. default:
  31672. buf.push('??',node.nodeName);
  31673. }
  31674. }
  31675. function importNode(doc,node,deep){
  31676. var node2;
  31677. switch (node.nodeType) {
  31678. case ELEMENT_NODE:
  31679. node2 = node.cloneNode(false);
  31680. node2.ownerDocument = doc;
  31681. //var attrs = node2.attributes;
  31682. //var len = attrs.length;
  31683. //for(var i=0;i<len;i++){
  31684. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  31685. //}
  31686. case DOCUMENT_FRAGMENT_NODE:
  31687. break;
  31688. case ATTRIBUTE_NODE:
  31689. deep = true;
  31690. break;
  31691. //case ENTITY_REFERENCE_NODE:
  31692. //case PROCESSING_INSTRUCTION_NODE:
  31693. ////case TEXT_NODE:
  31694. //case CDATA_SECTION_NODE:
  31695. //case COMMENT_NODE:
  31696. // deep = false;
  31697. // break;
  31698. //case DOCUMENT_NODE:
  31699. //case DOCUMENT_TYPE_NODE:
  31700. //cannot be imported.
  31701. //case ENTITY_NODE:
  31702. //case NOTATION_NODE:
  31703. //can not hit in level3
  31704. //default:throw e;
  31705. }
  31706. if(!node2){
  31707. node2 = node.cloneNode(false);//false
  31708. }
  31709. node2.ownerDocument = doc;
  31710. node2.parentNode = null;
  31711. if(deep){
  31712. var child = node.firstChild;
  31713. while(child){
  31714. node2.appendChild(importNode(doc,child,deep));
  31715. child = child.nextSibling;
  31716. }
  31717. }
  31718. return node2;
  31719. }
  31720. //
  31721. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  31722. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  31723. function cloneNode(doc,node,deep){
  31724. var node2 = new node.constructor();
  31725. for(var n in node){
  31726. var v = node[n];
  31727. if(typeof v != 'object' ){
  31728. if(v != node2[n]){
  31729. node2[n] = v;
  31730. }
  31731. }
  31732. }
  31733. if(node.childNodes){
  31734. node2.childNodes = new NodeList();
  31735. }
  31736. node2.ownerDocument = doc;
  31737. switch (node2.nodeType) {
  31738. case ELEMENT_NODE:
  31739. var attrs = node.attributes;
  31740. var attrs2 = node2.attributes = new NamedNodeMap();
  31741. var len = attrs.length
  31742. attrs2._ownerElement = node2;
  31743. for(var i=0;i<len;i++){
  31744. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  31745. }
  31746. break;;
  31747. case ATTRIBUTE_NODE:
  31748. deep = true;
  31749. }
  31750. if(deep){
  31751. var child = node.firstChild;
  31752. while(child){
  31753. node2.appendChild(cloneNode(doc,child,deep));
  31754. child = child.nextSibling;
  31755. }
  31756. }
  31757. return node2;
  31758. }
  31759. function __set__(object,key,value){
  31760. object[key] = value
  31761. }
  31762. //do dynamic
  31763. try{
  31764. if(Object.defineProperty){
  31765. Object.defineProperty(LiveNodeList.prototype,'length',{
  31766. get:function(){
  31767. _updateLiveList(this);
  31768. return this.$$length;
  31769. }
  31770. });
  31771. Object.defineProperty(Node.prototype,'textContent',{
  31772. get:function(){
  31773. return getTextContent(this);
  31774. },
  31775. set:function(data){
  31776. switch(this.nodeType){
  31777. case ELEMENT_NODE:
  31778. case DOCUMENT_FRAGMENT_NODE:
  31779. while(this.firstChild){
  31780. this.removeChild(this.firstChild);
  31781. }
  31782. if(data || String(data)){
  31783. this.appendChild(this.ownerDocument.createTextNode(data));
  31784. }
  31785. break;
  31786. default:
  31787. //TODO:
  31788. this.data = data;
  31789. this.value = data;
  31790. this.nodeValue = data;
  31791. }
  31792. }
  31793. })
  31794. function getTextContent(node){
  31795. switch(node.nodeType){
  31796. case ELEMENT_NODE:
  31797. case DOCUMENT_FRAGMENT_NODE:
  31798. var buf = [];
  31799. node = node.firstChild;
  31800. while(node){
  31801. if(node.nodeType!==7 && node.nodeType !==8){
  31802. buf.push(getTextContent(node));
  31803. }
  31804. node = node.nextSibling;
  31805. }
  31806. return buf.join('');
  31807. default:
  31808. return node.nodeValue;
  31809. }
  31810. }
  31811. __set__ = function(object,key,value){
  31812. //console.log(value)
  31813. object['$$'+key] = value
  31814. }
  31815. }
  31816. }catch(e){//ie8
  31817. }
  31818. //if(typeof require == 'function'){
  31819. exports.DOMImplementation = DOMImplementation;
  31820. exports.XMLSerializer = XMLSerializer;
  31821. //}
  31822. },{}],212:[function(require,module,exports){
  31823. //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  31824. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  31825. //[5] Name ::= NameStartChar (NameChar)*
  31826. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
  31827. var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  31828. var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
  31829. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  31830. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  31831. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  31832. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  31833. var S_TAG = 0;//tag name offerring
  31834. var S_ATTR = 1;//attr name offerring
  31835. var S_ATTR_SPACE=2;//attr name end and space offer
  31836. var S_EQ = 3;//=space?
  31837. var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
  31838. var S_ATTR_END = 5;//attr value end and no space(quot end)
  31839. var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
  31840. var S_TAG_CLOSE = 7;//closed el<el />
  31841. function XMLReader(){
  31842. }
  31843. XMLReader.prototype = {
  31844. parse:function(source,defaultNSMap,entityMap){
  31845. var domBuilder = this.domBuilder;
  31846. domBuilder.startDocument();
  31847. _copy(defaultNSMap ,defaultNSMap = {})
  31848. parse(source,defaultNSMap,entityMap,
  31849. domBuilder,this.errorHandler);
  31850. domBuilder.endDocument();
  31851. }
  31852. }
  31853. function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
  31854. function fixedFromCharCode(code) {
  31855. // String.prototype.fromCharCode does not supports
  31856. // > 2 bytes unicode chars directly
  31857. if (code > 0xffff) {
  31858. code -= 0x10000;
  31859. var surrogate1 = 0xd800 + (code >> 10)
  31860. , surrogate2 = 0xdc00 + (code & 0x3ff);
  31861. return String.fromCharCode(surrogate1, surrogate2);
  31862. } else {
  31863. return String.fromCharCode(code);
  31864. }
  31865. }
  31866. function entityReplacer(a){
  31867. var k = a.slice(1,-1);
  31868. if(k in entityMap){
  31869. return entityMap[k];
  31870. }else if(k.charAt(0) === '#'){
  31871. return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
  31872. }else{
  31873. errorHandler.error('entity not found:'+a);
  31874. return a;
  31875. }
  31876. }
  31877. function appendText(end){//has some bugs
  31878. if(end>start){
  31879. var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
  31880. locator&&position(start);
  31881. domBuilder.characters(xt,0,end-start);
  31882. start = end
  31883. }
  31884. }
  31885. function position(p,m){
  31886. while(p>=lineEnd && (m = linePattern.exec(source))){
  31887. lineStart = m.index;
  31888. lineEnd = lineStart + m[0].length;
  31889. locator.lineNumber++;
  31890. //console.log('line++:',locator,startPos,endPos)
  31891. }
  31892. locator.columnNumber = p-lineStart+1;
  31893. }
  31894. var lineStart = 0;
  31895. var lineEnd = 0;
  31896. var linePattern = /.*(?:\r\n?|\n)|.*$/g
  31897. var locator = domBuilder.locator;
  31898. var parseStack = [{currentNSMap:defaultNSMapCopy}]
  31899. var closeMap = {};
  31900. var start = 0;
  31901. while(true){
  31902. try{
  31903. var tagStart = source.indexOf('<',start);
  31904. if(tagStart<0){
  31905. if(!source.substr(start).match(/^\s*$/)){
  31906. var doc = domBuilder.doc;
  31907. var text = doc.createTextNode(source.substr(start));
  31908. doc.appendChild(text);
  31909. domBuilder.currentElement = text;
  31910. }
  31911. return;
  31912. }
  31913. if(tagStart>start){
  31914. appendText(tagStart);
  31915. }
  31916. switch(source.charAt(tagStart+1)){
  31917. case '/':
  31918. var end = source.indexOf('>',tagStart+3);
  31919. var tagName = source.substring(tagStart+2,end);
  31920. var config = parseStack.pop();
  31921. if(end<0){
  31922. tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
  31923. //console.error('#@@@@@@'+tagName)
  31924. errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
  31925. end = tagStart+1+tagName.length;
  31926. }else if(tagName.match(/\s</)){
  31927. tagName = tagName.replace(/[\s<].*/,'');
  31928. errorHandler.error("end tag name: "+tagName+' maybe not complete');
  31929. end = tagStart+1+tagName.length;
  31930. }
  31931. //console.error(parseStack.length,parseStack)
  31932. //console.error(config);
  31933. var localNSMap = config.localNSMap;
  31934. var endMatch = config.tagName == tagName;
  31935. var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
  31936. if(endIgnoreCaseMach){
  31937. domBuilder.endElement(config.uri,config.localName,tagName);
  31938. if(localNSMap){
  31939. for(var prefix in localNSMap){
  31940. domBuilder.endPrefixMapping(prefix) ;
  31941. }
  31942. }
  31943. if(!endMatch){
  31944. errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
  31945. }
  31946. }else{
  31947. parseStack.push(config)
  31948. }
  31949. end++;
  31950. break;
  31951. // end elment
  31952. case '?':// <?...?>
  31953. locator&&position(tagStart);
  31954. end = parseInstruction(source,tagStart,domBuilder);
  31955. break;
  31956. case '!':// <!doctype,<![CDATA,<!--
  31957. locator&&position(tagStart);
  31958. end = parseDCC(source,tagStart,domBuilder,errorHandler);
  31959. break;
  31960. default:
  31961. locator&&position(tagStart);
  31962. var el = new ElementAttributes();
  31963. var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  31964. //elStartEnd
  31965. var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
  31966. var len = el.length;
  31967. if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
  31968. el.closed = true;
  31969. if(!entityMap.nbsp){
  31970. errorHandler.warning('unclosed xml attribute');
  31971. }
  31972. }
  31973. if(locator && len){
  31974. var locator2 = copyLocator(locator,{});
  31975. //try{//attribute position fixed
  31976. for(var i = 0;i<len;i++){
  31977. var a = el[i];
  31978. position(a.offset);
  31979. a.locator = copyLocator(locator,{});
  31980. }
  31981. //}catch(e){console.error('@@@@@'+e)}
  31982. domBuilder.locator = locator2
  31983. if(appendElement(el,domBuilder,currentNSMap)){
  31984. parseStack.push(el)
  31985. }
  31986. domBuilder.locator = locator;
  31987. }else{
  31988. if(appendElement(el,domBuilder,currentNSMap)){
  31989. parseStack.push(el)
  31990. }
  31991. }
  31992. if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
  31993. end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
  31994. }else{
  31995. end++;
  31996. }
  31997. }
  31998. }catch(e){
  31999. errorHandler.error('element parse error: '+e)
  32000. //errorHandler.error('element parse error: '+e);
  32001. end = -1;
  32002. //throw e;
  32003. }
  32004. if(end>start){
  32005. start = end;
  32006. }else{
  32007. //TODO: 这里有可能sax回退,有位置错误风险
  32008. appendText(Math.max(tagStart,start)+1);
  32009. }
  32010. }
  32011. }
  32012. function copyLocator(f,t){
  32013. t.lineNumber = f.lineNumber;
  32014. t.columnNumber = f.columnNumber;
  32015. return t;
  32016. }
  32017. /**
  32018. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  32019. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  32020. */
  32021. function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
  32022. var attrName;
  32023. var value;
  32024. var p = ++start;
  32025. var s = S_TAG;//status
  32026. while(true){
  32027. var c = source.charAt(p);
  32028. switch(c){
  32029. case '=':
  32030. if(s === S_ATTR){//attrName
  32031. attrName = source.slice(start,p);
  32032. s = S_EQ;
  32033. }else if(s === S_ATTR_SPACE){
  32034. s = S_EQ;
  32035. }else{
  32036. //fatalError: equal must after attrName or space after attrName
  32037. throw new Error('attribute equal must after attrName');
  32038. }
  32039. break;
  32040. case '\'':
  32041. case '"':
  32042. if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  32043. ){//equal
  32044. if(s === S_ATTR){
  32045. errorHandler.warning('attribute value must after "="')
  32046. attrName = source.slice(start,p)
  32047. }
  32048. start = p+1;
  32049. p = source.indexOf(c,start)
  32050. if(p>0){
  32051. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  32052. el.add(attrName,value,start-1);
  32053. s = S_ATTR_END;
  32054. }else{
  32055. //fatalError: no end quot match
  32056. throw new Error('attribute value no end \''+c+'\' match');
  32057. }
  32058. }else if(s == S_ATTR_NOQUOT_VALUE){
  32059. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  32060. //console.log(attrName,value,start,p)
  32061. el.add(attrName,value,start);
  32062. //console.dir(el)
  32063. errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
  32064. start = p+1;
  32065. s = S_ATTR_END
  32066. }else{
  32067. //fatalError: no equal before
  32068. throw new Error('attribute value must after "="');
  32069. }
  32070. break;
  32071. case '/':
  32072. switch(s){
  32073. case S_TAG:
  32074. el.setTagName(source.slice(start,p));
  32075. case S_ATTR_END:
  32076. case S_TAG_SPACE:
  32077. case S_TAG_CLOSE:
  32078. s =S_TAG_CLOSE;
  32079. el.closed = true;
  32080. case S_ATTR_NOQUOT_VALUE:
  32081. case S_ATTR:
  32082. case S_ATTR_SPACE:
  32083. break;
  32084. //case S_EQ:
  32085. default:
  32086. throw new Error("attribute invalid close char('/')")
  32087. }
  32088. break;
  32089. case ''://end document
  32090. //throw new Error('unexpected end of input')
  32091. errorHandler.error('unexpected end of input');
  32092. if(s == S_TAG){
  32093. el.setTagName(source.slice(start,p));
  32094. }
  32095. return p;
  32096. case '>':
  32097. switch(s){
  32098. case S_TAG:
  32099. el.setTagName(source.slice(start,p));
  32100. case S_ATTR_END:
  32101. case S_TAG_SPACE:
  32102. case S_TAG_CLOSE:
  32103. break;//normal
  32104. case S_ATTR_NOQUOT_VALUE://Compatible state
  32105. case S_ATTR:
  32106. value = source.slice(start,p);
  32107. if(value.slice(-1) === '/'){
  32108. el.closed = true;
  32109. value = value.slice(0,-1)
  32110. }
  32111. case S_ATTR_SPACE:
  32112. if(s === S_ATTR_SPACE){
  32113. value = attrName;
  32114. }
  32115. if(s == S_ATTR_NOQUOT_VALUE){
  32116. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  32117. el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
  32118. }else{
  32119. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
  32120. errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
  32121. }
  32122. el.add(value,value,start)
  32123. }
  32124. break;
  32125. case S_EQ:
  32126. throw new Error('attribute value missed!!');
  32127. }
  32128. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  32129. return p;
  32130. /*xml space '\x20' | #x9 | #xD | #xA; */
  32131. case '\u0080':
  32132. c = ' ';
  32133. default:
  32134. if(c<= ' '){//space
  32135. switch(s){
  32136. case S_TAG:
  32137. el.setTagName(source.slice(start,p));//tagName
  32138. s = S_TAG_SPACE;
  32139. break;
  32140. case S_ATTR:
  32141. attrName = source.slice(start,p)
  32142. s = S_ATTR_SPACE;
  32143. break;
  32144. case S_ATTR_NOQUOT_VALUE:
  32145. var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  32146. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  32147. el.add(attrName,value,start)
  32148. case S_ATTR_END:
  32149. s = S_TAG_SPACE;
  32150. break;
  32151. //case S_TAG_SPACE:
  32152. //case S_EQ:
  32153. //case S_ATTR_SPACE:
  32154. // void();break;
  32155. //case S_TAG_CLOSE:
  32156. //ignore warning
  32157. }
  32158. }else{//not space
  32159. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  32160. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  32161. switch(s){
  32162. //case S_TAG:void();break;
  32163. //case S_ATTR:void();break;
  32164. //case S_ATTR_NOQUOT_VALUE:void();break;
  32165. case S_ATTR_SPACE:
  32166. var tagName = el.tagName;
  32167. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
  32168. errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
  32169. }
  32170. el.add(attrName,attrName,start);
  32171. start = p;
  32172. s = S_ATTR;
  32173. break;
  32174. case S_ATTR_END:
  32175. errorHandler.warning('attribute space is required"'+attrName+'"!!')
  32176. case S_TAG_SPACE:
  32177. s = S_ATTR;
  32178. start = p;
  32179. break;
  32180. case S_EQ:
  32181. s = S_ATTR_NOQUOT_VALUE;
  32182. start = p;
  32183. break;
  32184. case S_TAG_CLOSE:
  32185. throw new Error("elements closed character '/' and '>' must be connected to");
  32186. }
  32187. }
  32188. }//end outer switch
  32189. //console.log('p++',p)
  32190. p++;
  32191. }
  32192. }
  32193. /**
  32194. * @return true if has new namespace define
  32195. */
  32196. function appendElement(el,domBuilder,currentNSMap){
  32197. var tagName = el.tagName;
  32198. var localNSMap = null;
  32199. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  32200. var i = el.length;
  32201. while(i--){
  32202. var a = el[i];
  32203. var qName = a.qName;
  32204. var value = a.value;
  32205. var nsp = qName.indexOf(':');
  32206. if(nsp>0){
  32207. var prefix = a.prefix = qName.slice(0,nsp);
  32208. var localName = qName.slice(nsp+1);
  32209. var nsPrefix = prefix === 'xmlns' && localName
  32210. }else{
  32211. localName = qName;
  32212. prefix = null
  32213. nsPrefix = qName === 'xmlns' && ''
  32214. }
  32215. //can not set prefix,because prefix !== ''
  32216. a.localName = localName ;
  32217. //prefix == null for no ns prefix attribute
  32218. if(nsPrefix !== false){//hack!!
  32219. if(localNSMap == null){
  32220. localNSMap = {}
  32221. //console.log(currentNSMap,0)
  32222. _copy(currentNSMap,currentNSMap={})
  32223. //console.log(currentNSMap,1)
  32224. }
  32225. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  32226. a.uri = 'http://www.w3.org/2000/xmlns/'
  32227. domBuilder.startPrefixMapping(nsPrefix, value)
  32228. }
  32229. }
  32230. var i = el.length;
  32231. while(i--){
  32232. a = el[i];
  32233. var prefix = a.prefix;
  32234. if(prefix){//no prefix attribute has no namespace
  32235. if(prefix === 'xml'){
  32236. a.uri = 'http://www.w3.org/XML/1998/namespace';
  32237. }if(prefix !== 'xmlns'){
  32238. a.uri = currentNSMap[prefix || '']
  32239. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  32240. }
  32241. }
  32242. }
  32243. var nsp = tagName.indexOf(':');
  32244. if(nsp>0){
  32245. prefix = el.prefix = tagName.slice(0,nsp);
  32246. localName = el.localName = tagName.slice(nsp+1);
  32247. }else{
  32248. prefix = null;//important!!
  32249. localName = el.localName = tagName;
  32250. }
  32251. //no prefix element has default namespace
  32252. var ns = el.uri = currentNSMap[prefix || ''];
  32253. domBuilder.startElement(ns,localName,tagName,el);
  32254. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  32255. //localNSMap = null
  32256. if(el.closed){
  32257. domBuilder.endElement(ns,localName,tagName);
  32258. if(localNSMap){
  32259. for(prefix in localNSMap){
  32260. domBuilder.endPrefixMapping(prefix)
  32261. }
  32262. }
  32263. }else{
  32264. el.currentNSMap = currentNSMap;
  32265. el.localNSMap = localNSMap;
  32266. //parseStack.push(el);
  32267. return true;
  32268. }
  32269. }
  32270. function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
  32271. if(/^(?:script|textarea)$/i.test(tagName)){
  32272. var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
  32273. var text = source.substring(elStartEnd+1,elEndStart);
  32274. if(/[&<]/.test(text)){
  32275. if(/^script$/i.test(tagName)){
  32276. //if(!/\]\]>/.test(text)){
  32277. //lexHandler.startCDATA();
  32278. domBuilder.characters(text,0,text.length);
  32279. //lexHandler.endCDATA();
  32280. return elEndStart;
  32281. //}
  32282. }//}else{//text area
  32283. text = text.replace(/&#?\w+;/g,entityReplacer);
  32284. domBuilder.characters(text,0,text.length);
  32285. return elEndStart;
  32286. //}
  32287. }
  32288. }
  32289. return elStartEnd+1;
  32290. }
  32291. function fixSelfClosed(source,elStartEnd,tagName,closeMap){
  32292. //if(tagName in closeMap){
  32293. var pos = closeMap[tagName];
  32294. if(pos == null){
  32295. //console.log(tagName)
  32296. pos = source.lastIndexOf('</'+tagName+'>')
  32297. if(pos<elStartEnd){//忘记闭合
  32298. pos = source.lastIndexOf('</'+tagName)
  32299. }
  32300. closeMap[tagName] =pos
  32301. }
  32302. return pos<elStartEnd;
  32303. //}
  32304. }
  32305. function _copy(source,target){
  32306. for(var n in source){target[n] = source[n]}
  32307. }
  32308. function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
  32309. var next= source.charAt(start+2)
  32310. switch(next){
  32311. case '-':
  32312. if(source.charAt(start + 3) === '-'){
  32313. var end = source.indexOf('-->',start+4);
  32314. //append comment source.substring(4,end)//<!--
  32315. if(end>start){
  32316. domBuilder.comment(source,start+4,end-start-4);
  32317. return end+3;
  32318. }else{
  32319. errorHandler.error("Unclosed comment");
  32320. return -1;
  32321. }
  32322. }else{
  32323. //error
  32324. return -1;
  32325. }
  32326. default:
  32327. if(source.substr(start+3,6) == 'CDATA['){
  32328. var end = source.indexOf(']]>',start+9);
  32329. domBuilder.startCDATA();
  32330. domBuilder.characters(source,start+9,end-start-9);
  32331. domBuilder.endCDATA()
  32332. return end+3;
  32333. }
  32334. //<!DOCTYPE
  32335. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  32336. var matchs = split(source,start);
  32337. var len = matchs.length;
  32338. if(len>1 && /!doctype/i.test(matchs[0][0])){
  32339. var name = matchs[1][0];
  32340. var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0]
  32341. var sysid = len>4 && matchs[4][0];
  32342. var lastMatch = matchs[len-1]
  32343. domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
  32344. sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
  32345. domBuilder.endDTD();
  32346. return lastMatch.index+lastMatch[0].length
  32347. }
  32348. }
  32349. return -1;
  32350. }
  32351. function parseInstruction(source,start,domBuilder){
  32352. var end = source.indexOf('?>',start);
  32353. if(end){
  32354. var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  32355. if(match){
  32356. var len = match[0].length;
  32357. domBuilder.processingInstruction(match[1], match[2]) ;
  32358. return end+2;
  32359. }else{//error
  32360. return -1;
  32361. }
  32362. }
  32363. return -1;
  32364. }
  32365. /**
  32366. * @param source
  32367. */
  32368. function ElementAttributes(source){
  32369. }
  32370. ElementAttributes.prototype = {
  32371. setTagName:function(tagName){
  32372. if(!tagNamePattern.test(tagName)){
  32373. throw new Error('invalid tagName:'+tagName)
  32374. }
  32375. this.tagName = tagName
  32376. },
  32377. add:function(qName,value,offset){
  32378. if(!tagNamePattern.test(qName)){
  32379. throw new Error('invalid attribute:'+qName)
  32380. }
  32381. this[this.length++] = {qName:qName,value:value,offset:offset}
  32382. },
  32383. length:0,
  32384. getLocalName:function(i){return this[i].localName},
  32385. getLocator:function(i){return this[i].locator},
  32386. getQName:function(i){return this[i].qName},
  32387. getURI:function(i){return this[i].uri},
  32388. getValue:function(i){return this[i].value}
  32389. // ,getIndex:function(uri, localName)){
  32390. // if(localName){
  32391. //
  32392. // }else{
  32393. // var qName = uri
  32394. // }
  32395. // },
  32396. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  32397. // getType:function(uri,localName){}
  32398. // getType:function(i){},
  32399. }
  32400. function _set_proto_(thiz,parent){
  32401. thiz.__proto__ = parent;
  32402. return thiz;
  32403. }
  32404. if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){
  32405. _set_proto_ = function(thiz,parent){
  32406. function p(){};
  32407. p.prototype = parent;
  32408. p = new p();
  32409. for(parent in thiz){
  32410. p[parent] = thiz[parent];
  32411. }
  32412. return p;
  32413. }
  32414. }
  32415. function split(source,start){
  32416. var match;
  32417. var buf = [];
  32418. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  32419. reg.lastIndex = start;
  32420. reg.exec(source);//skip <
  32421. while(match = reg.exec(source)){
  32422. buf.push(match);
  32423. if(match[1])return buf;
  32424. }
  32425. }
  32426. exports.XMLReader = XMLReader;
  32427. },{}],213:[function(require,module,exports){
  32428. /* global L */
  32429. const isTrue = require('./isTrue')
  32430. const styleToLeaflet = require('./styleToLeaflet')
  32431. class DecoratorPattern {
  32432. constructor (layer) {
  32433. this.layer = layer
  32434. this.layer.on('update', this.processObject.bind(this))
  32435. this.layer.on('remove', this.removeObject.bind(this))
  32436. }
  32437. parseType (key, value) {
  32438. switch (key) {
  32439. case 'polygon':
  32440. case 'rotate':
  32441. return isTrue(value)
  32442. case 'angleCorrection':
  32443. case 'pixelSize':
  32444. case 'headAngle':
  32445. return parseFloat(value)
  32446. default:
  32447. return value
  32448. }
  32449. }
  32450. processObject (object, data) {
  32451. if (!data.patternFeatures) {
  32452. data.patternFeatures = {}
  32453. }
  32454. for (var k in data.features) {
  32455. let def = k === 'default' ? data.data.style : data.data['style:' + k]
  32456. if (def.pattern && data.styles.includes(k)) {
  32457. let symbol
  32458. let symbolOptions = {}
  32459. let options = {}
  32460. for (let k in def) {
  32461. let m1 = k.match(/^pattern-path-(.*)$/)
  32462. let m2 = k.match(/^pattern-(.*)$/)
  32463. if (m1) {
  32464. symbolOptions[m1[1]] = def[k]
  32465. } else if (m2) {
  32466. options[m2[1]] = this.parseType(m2[1], def[k])
  32467. }
  32468. }
  32469. symbolOptions = styleToLeaflet(symbolOptions)
  32470. switch (def.pattern.toString()) {
  32471. case 'dash':
  32472. options.pathOptions = symbolOptions
  32473. symbol = L.Symbol.dash(options)
  32474. break
  32475. case 'arrowHead':
  32476. options.pathOptions = symbolOptions
  32477. symbol = L.Symbol.arrowHead(options)
  32478. break
  32479. case 'marker':
  32480. options.markerOptions = symbolOptions
  32481. symbol = L.Symbol.marker(options)
  32482. break
  32483. default:
  32484. // TODO
  32485. }
  32486. options.symbol = symbol
  32487. if (!data.patternFeatures[k]) {
  32488. data.patternFeatures[k] = L.polylineDecorator(data.features[k])
  32489. data.patternFeatures[k].addTo(this.layer.map)
  32490. }
  32491. data.patternFeatures[k].setPatterns([ options ])
  32492. if (this.layer._shallBindPopupToStyle(k)) {
  32493. data.patternFeatures[k].bindPopup(data.popup)
  32494. }
  32495. } else {
  32496. if (data.patternFeatures[k]) {
  32497. this.layer.map.removeLayer(data.patternFeatures[k])
  32498. delete data.patternFeatures[k]
  32499. }
  32500. }
  32501. }
  32502. }
  32503. removeObject (object, data) {
  32504. if (!data.patternFeatures) {
  32505. return
  32506. }
  32507. for (var k in data.features) {
  32508. if (data.patternFeatures[k]) {
  32509. this.layer.map.removeLayer(data.patternFeatures[k])
  32510. delete data.patternFeatures[k]
  32511. }
  32512. }
  32513. }
  32514. }
  32515. module.exports = DecoratorPattern
  32516. },{"./isTrue":222,"./styleToLeaflet":224}],214:[function(require,module,exports){
  32517. const Sublayer = require('./Sublayer')
  32518. class Memberlayer extends Sublayer {
  32519. constructor (master, options) {
  32520. super(master, options)
  32521. this.masterlayer = this.master.mainlayer
  32522. this.masterlayer.on('add', this.featureOnMainModified.bind(this))
  32523. this.masterlayer.on('remove', this.featureOnMainModified.bind(this))
  32524. this.masterlayer.on('update', this.featureOnMainModified.bind(this))
  32525. this.on('add', this.featureMemberModified.bind(this))
  32526. this.on('remove', this.featureMemberModified.bind(this))
  32527. }
  32528. featureMemberModified (feature, data) {
  32529. feature.memberOf.forEach(master => {
  32530. this.masterlayer.scheduleReprocess(master.id)
  32531. })
  32532. }
  32533. featureOnMainModified (feature) {
  32534. if (!feature.members) {
  32535. return
  32536. }
  32537. feature.members.forEach(member => {
  32538. if (member.id in this.visibleFeatures) {
  32539. this.scheduleReprocess(member.id)
  32540. }
  32541. })
  32542. }
  32543. twigData (ob, data) {
  32544. let result = super.twigData(ob, data)
  32545. for (var k in this.masterlayer.visibleFeatures) {
  32546. let feature = this.masterlayer.visibleFeatures[k]
  32547. if (feature.object.members) {
  32548. feature.object.members.forEach((member, sequence) => {
  32549. if (member.id === ob.id) {
  32550. if (!('masters' in result)) {
  32551. result.masters = []
  32552. }
  32553. result.masters.push({
  32554. id: feature.id,
  32555. type: feature.object.type,
  32556. osm_id: feature.object.osm_id,
  32557. tags: feature.object.tags,
  32558. meta: feature.object.meta,
  32559. role: member.role,
  32560. dir: member.dir,
  32561. connectedPrev: member.connectedPrev,
  32562. connectedNext: member.connectedNext,
  32563. flags: feature.flags,
  32564. sequence
  32565. })
  32566. }
  32567. })
  32568. }
  32569. }
  32570. return result
  32571. }
  32572. }
  32573. module.exports = Memberlayer
  32574. },{"./Sublayer":219}],215:[function(require,module,exports){
  32575. var css = ".leaflet-popup-content {\n max-height: 250px;\n overflow: auto;\n}\n.leaflet-popup-content pre {\n font-size: 8px;\n}\n.overpass-layer-icon > img,\n.overpass-layer-icon > svg {\n display: block;\n}\n.overpass-layer-icon div.sign {\n position: relative;\n font-size: 12px;\n text-align: center;\n transform: translate(-50%, -50%);\n display: flex;\n justify-content: center;\n}\n/* top: -37px; */\n"; (require("browserify-css").createStyle(css, { "href": "src/OverpassLayer.css" }, { "insertAt": "bottom" })); module.exports = css;
  32576. },{"browserify-css":22}],216:[function(require,module,exports){
  32577. /* global overpassFrontend:false */
  32578. /* eslint camelcase: 0 */
  32579. require('./OverpassLayer.css')
  32580. const ee = require('event-emitter')
  32581. const BoundingBox = require('boundingbox')
  32582. const twig = require('twig')
  32583. const OverpassFrontend = require('overpass-frontend')
  32584. const escapeHtml = require('html-escape')
  32585. const Sublayer = require('./Sublayer')
  32586. const Memberlayer = require('./Memberlayer')
  32587. const compileFeature = require('./compileFeature')
  32588. class OverpassLayer {
  32589. constructor (options) {
  32590. if (!options) {
  32591. options = {}
  32592. }
  32593. this.options = options
  32594. this.overpassFrontend = 'overpassFrontend' in this.options ? this.options.overpassFrontend : overpassFrontend
  32595. this.options.minZoom = 'minZoom' in this.options ? this.options.minZoom : 16
  32596. this.options.maxZoom = 'maxZoom' in this.options ? this.options.maxZoom : null
  32597. this.options.feature = 'feature' in this.options ? this.options.feature : {}
  32598. this.options.feature.style = 'style' in this.options.feature ? this.options.feature.style : {}
  32599. this.options.feature.title = 'title' in this.options.feature ? this.options.feature.title : function (ob) { return escapeHtml(ob.tags.name || ob.tags.operator || ob.tags.ref || ob.id) }
  32600. this.options.feature.body = 'body' in this.options.feature ? this.options.feature.body : ''
  32601. this.options.feature.markerSymbol = 'markerSymbol' in this.options.feature ? this.options.feature.markerSymbol : '<img anchorX="13" anchorY="42" width="25" height="42" signAnchorX="0" signAnchorY="-30" src="img/map_pointer.png">'
  32602. this.options.feature.markerSign = 'markerSign' in this.options.feature ? this.options.feature.markerSign : null
  32603. this.options.queryOptions = 'queryOptions' in this.options ? this.options.queryOptions : {}
  32604. if (!('properties' in this.options.queryOptions)) {
  32605. this.options.queryOptions.properties = OverpassFrontend.ALL
  32606. }
  32607. this.options.styleNoBindPopup = this.options.styleNoBindPopup || []
  32608. this.options.stylesNoAutoShow = this.options.stylesNoAutoShow || []
  32609. compileFeature(this.options.feature, twig)
  32610. this.currentRequest = null
  32611. this.lastZoom = null
  32612. this.mainlayer = new Sublayer(this, options)
  32613. this.subLayers = {
  32614. main: this.mainlayer
  32615. }
  32616. if (this.options.members) {
  32617. this.options.queryOptions.properties = OverpassFrontend.TAGS | OverpassFrontend.META | OverpassFrontend.MEMBERS | OverpassFrontend.BBOX
  32618. this.options.queryOptions.memberProperties = OverpassFrontend.ALL
  32619. this.options.queryOptions.members = true
  32620. let memberOptions = {
  32621. id: this.options.id,
  32622. sublayer_id: 'member',
  32623. minZoom: this.options.minZoom,
  32624. maxZoom: this.options.maxZoom,
  32625. feature: this.options.memberFeature,
  32626. styleNoBindPopup: this.options.styleNoBindPopup || [],
  32627. stylesNoAutoShow: this.options.stylesNoAutoShow || [],
  32628. const: this.options.const
  32629. }
  32630. if (this.options.updateAssets) {
  32631. memberOptions.updateAssets = this.options.updateAssets
  32632. }
  32633. compileFeature(memberOptions.feature, twig)
  32634. this.memberlayer = new Memberlayer(this, memberOptions)
  32635. this.subLayers.member = this.memberlayer
  32636. }
  32637. }
  32638. addTo (map) {
  32639. this.map = map
  32640. this.map.on('moveend', this.check_update_map, this)
  32641. for (let k in this.subLayers) {
  32642. this.subLayers[k].addTo(map)
  32643. }
  32644. this.check_update_map()
  32645. this.map.createPane('hover')
  32646. this.map.getPane('hover').style.zIndex = 499
  32647. }
  32648. remove () {
  32649. for (let k in this.subLayers) {
  32650. this.subLayers[k].hideAll(true)
  32651. this.subLayers[k].remove()
  32652. }
  32653. this.abortRequest()
  32654. this.map.off('moveend', this.check_update_map, this)
  32655. this.map = null
  32656. }
  32657. abortRequest () {
  32658. if (this.currentRequest) {
  32659. if (this.onLoadEnd) {
  32660. this.onLoadEnd({
  32661. request: this.currentRequest,
  32662. error: null
  32663. })
  32664. }
  32665. this.currentRequest.abort()
  32666. this.currentRequest = null
  32667. }
  32668. }
  32669. check_update_map () {
  32670. var bounds = new BoundingBox(this.map.getBounds())
  32671. if (this.map.getZoom() < this.options.minZoom ||
  32672. (this.options.maxZoom !== null && this.map.getZoom() > this.options.maxZoom)) {
  32673. for (let k in this.subLayers) {
  32674. this.subLayers[k].hideAll()
  32675. }
  32676. // abort remaining request
  32677. this.abortRequest()
  32678. return
  32679. }
  32680. for (let k in this.subLayers) {
  32681. this.subLayers[k].hideNonVisible(bounds)
  32682. }
  32683. let query = this.options.query
  32684. if (typeof query === 'object') {
  32685. query = query[Object.keys(query).filter(function (x) { return x <= this.map.getZoom() }.bind(this)).reverse()[0]]
  32686. }
  32687. if (query !== this.lastQuery) {
  32688. let filter = new OverpassFrontend.Filter(query)
  32689. this.mainlayer.hideNonVisibleFilter(filter)
  32690. this.lastQuery = query
  32691. }
  32692. // When zoom level changed, update visible objects
  32693. if (this.lastZoom !== this.map.getZoom()) {
  32694. for (let k in this.subLayers) {
  32695. this.subLayers[k].zoomChange()
  32696. }
  32697. this.lastZoom = this.map.getZoom()
  32698. }
  32699. // Abort current requests (in case they are long-lasting - we don't need them
  32700. // anyway). Data which is being submitted will still be loaded to the cache.
  32701. this.abortRequest()
  32702. if (!query) {
  32703. return
  32704. }
  32705. for (let k in this.subLayers) {
  32706. this.subLayers[k].startAdding()
  32707. }
  32708. if (this.options.members) {
  32709. this.options.queryOptions.memberBounds = bounds
  32710. this.options.queryOptions.memberCallback = (err, ob) => {
  32711. if (err) {
  32712. return console.error('unexpected error', err)
  32713. }
  32714. this.memberlayer.add(ob)
  32715. }
  32716. }
  32717. this.currentRequest = this.overpassFrontend.BBoxQuery(query, bounds,
  32718. this.options.queryOptions,
  32719. (err, ob) => {
  32720. if (err) {
  32721. console.log('unexpected error', err)
  32722. }
  32723. this.mainlayer.add(ob)
  32724. },
  32725. function (err) {
  32726. if (this.onLoadEnd) {
  32727. this.onLoadEnd({
  32728. request: this.currentRequest,
  32729. error: err
  32730. })
  32731. }
  32732. for (let k in this.subLayers) {
  32733. this.subLayers[k].finishAdding()
  32734. }
  32735. this.currentRequest = null
  32736. }.bind(this)
  32737. )
  32738. if (this.onLoadStart) {
  32739. this.onLoadStart({
  32740. request: this.currentRequest
  32741. })
  32742. }
  32743. }
  32744. recalc () {
  32745. for (let k in this.subLayers) {
  32746. this.subLayers[k].recalc()
  32747. }
  32748. }
  32749. scheduleReprocess (id) {
  32750. for (let k in this.subLayers) {
  32751. this.subLayers[k].scheduleReprocess(id)
  32752. }
  32753. }
  32754. updateAssets (div, objectData) {
  32755. for (let k in this.subLayers) {
  32756. this.subLayers[k].updateAssets(div, objectData)
  32757. }
  32758. }
  32759. get (id, callback) {
  32760. var done = false
  32761. this.overpassFrontend.get(id,
  32762. {
  32763. properties: OverpassFrontend.ALL
  32764. },
  32765. (err, ob) => {
  32766. if (err === null) {
  32767. callback(err, ob)
  32768. }
  32769. done = true
  32770. },
  32771. (err) => {
  32772. if (!done) {
  32773. callback(err, null)
  32774. }
  32775. }
  32776. )
  32777. }
  32778. show (id, options, callback) {
  32779. let sublayer = this.mainlayer
  32780. if (options.sublayer_id) {
  32781. sublayer = this.subLayers[options.sublayer_id]
  32782. }
  32783. let request = sublayer.show(id, options, callback)
  32784. let result = {
  32785. id: id,
  32786. sublayer_id: options.sublayer_id,
  32787. options: options,
  32788. hide: request.hide
  32789. }
  32790. return result
  32791. }
  32792. hide (id) {
  32793. this.mainlayer.hide(id)
  32794. }
  32795. openPopupOnObject (ob, sublayer = 'main') {
  32796. this.subLayers[sublayer].openPopupOnObject(ob)
  32797. }
  32798. }
  32799. ee(OverpassLayer.prototype)
  32800. // to enable extending twig
  32801. OverpassLayer.twig = twig
  32802. module.exports = OverpassLayer
  32803. },{"./Memberlayer":214,"./OverpassLayer.css":215,"./Sublayer":219,"./compileFeature":221,"boundingbox":20,"event-emitter":41,"html-escape":46,"overpass-frontend":180,"twig":207}],217:[function(require,module,exports){
  32804. var css = "ul.overpass-layer-list {\n margin-top: 0;\n margin-bottom: 0;\n}\nul.overpass-layer-list > li {\n position: relative;\n list-style: none;\n min-height: 30px;\n}\nul.overpass-layer-list > li > .markerParent {\n position: absolute;\n margin-left: -35px;\n width: 30px;\n height: 30px;\n text-align: center;\n display: block;\n color: black;\n text-decoration: none;\n}\n\nul.overpass-layer-list > li > .markerParent > .icon {\n text-align: center;\n position: absolute;\n top: 3px;\n font-size: 15px;\n left: 0;\n right: 0;\n z-index: 1;\n display: inline-block;\n}\nul.overpass-layer-list > li > a.title {\n display: inline-block;\n color: black;\n text-decoration: none;\n}\nul.overpass-layer-list > li > a.title:hover,\nul.overpass-layer-list > li > a.title:active {\n text-decoration: underline;\n}\nul.overpass-layer-list > li > div.description {\n font-style: italic;\n color: #707070;\n float: right;\n text-align: right;\n}\nul.overpass-layer-list > li:after {\n content: '';\n display: table;\n clear: both;\n}\n.hoverable {\n cursor: pointer;\n}\n"; (require("browserify-css").createStyle(css, { "href": "src/OverpassLayerList.css" }, { "insertAt": "bottom" })); module.exports = css;
  32805. },{"browserify-css":22}],218:[function(require,module,exports){
  32806. /* eslint camelcase: 0 */
  32807. require('./OverpassLayerList.css')
  32808. const isTrue = require('./isTrue')
  32809. class OverpassLayerList {
  32810. constructor (layer, options) {
  32811. // compatibility <1.0
  32812. let parentDom
  32813. if (arguments.length > 1 && arguments[1].constructor.name === 'OverpassLayer') {
  32814. parentDom = arguments[0]
  32815. layer = arguments[1]
  32816. console.error('overpass-layer: class OverpassLayerList() accepts only one parameter, "layer"')
  32817. }
  32818. // end
  32819. this.dom = document.createElement('ul')
  32820. this.dom.className = 'overpass-layer-list'
  32821. this.layer = layer
  32822. this.options = options || {}
  32823. this.options.prefix = this.options.prefix || 'list'
  32824. this.layer.on('add', (ob, data) => this.addObject(data))
  32825. this.layer.on('update', (ob, data) => this.updateObject(data))
  32826. this.layer.on('remove', (ob, data) => this.delObject(data))
  32827. this.items = {}
  32828. if (parentDom) {
  32829. this.addTo(parentDom)
  32830. }
  32831. }
  32832. addTo (parentDom) {
  32833. parentDom.appendChild(this.dom)
  32834. }
  32835. _getMarker (ob) {
  32836. var a
  32837. if (ob.data[this.options.prefix + 'MarkerSymbol']) {
  32838. a = document.createElement('div')
  32839. a.className = 'marker'
  32840. a.innerHTML = ob.data[this.options.prefix + 'MarkerSymbol']
  32841. } else if (ob.data.markerSymbol) {
  32842. a = document.createElement('div')
  32843. a.className = 'marker'
  32844. a.innerHTML = ob.data.markerSymbol
  32845. } else if (ob.data.marker && ob.data.marker.iconUrl) {
  32846. a = document.createElement('img')
  32847. a.className = 'marker'
  32848. a.src = ob.data.marker.iconUrl
  32849. }
  32850. return a
  32851. }
  32852. addObject (ob) {
  32853. if (isTrue(ob.data[this.options.prefix + 'Exclude'])) {
  32854. return
  32855. }
  32856. if (ob.id in this.items) { // already added
  32857. return
  32858. }
  32859. var div = document.createElement('li')
  32860. var a
  32861. this.items[ob.id] = div
  32862. ob[this.options.prefix + 'Item'] = div
  32863. // MARKER&ICON PARENT
  32864. var p = document.createElement('a')
  32865. p.className = 'markerParent'
  32866. p.href = 'appUrl' in ob.data ? ob.data.appUrl : '#'
  32867. p.onclick = function (ob) {
  32868. this.layer.openPopupOnObject(ob)
  32869. return false
  32870. }.bind(this, ob)
  32871. div.appendChild(p)
  32872. // MARKER
  32873. a = this._getMarker(ob)
  32874. if (a) {
  32875. p.appendChild(a)
  32876. }
  32877. // ICON
  32878. a = document.createElement('div')
  32879. a.className = 'icon'
  32880. let html = ob.data[this.options.prefix + 'MarkerSign'] || ob.data.markerSign || ''
  32881. a.innerHTML = html
  32882. a.currentHTML = html
  32883. p.appendChild(a)
  32884. // TITLE
  32885. a = document.createElement('a')
  32886. a.className = 'title'
  32887. a.href = 'appUrl' in ob.data ? ob.data.appUrl : '#'
  32888. a.onclick = function (ob) {
  32889. this.layer.openPopupOnObject(ob)
  32890. return false
  32891. }.bind(this, ob)
  32892. html = ob.data[this.options.prefix + 'Title'] || ob.data.title
  32893. a.innerHTML = html
  32894. a.currentHTML = html
  32895. div.appendChild(a)
  32896. let title = a
  32897. // DESCRIPTION
  32898. a = document.createElement('div')
  32899. a.className = 'description'
  32900. html = ob.data[this.options.prefix + 'Description'] || ob.data.description || ''
  32901. a.innerHTML = html
  32902. a.currentHTML = html
  32903. div.appendChild(a)
  32904. div.priority = 'priority' in ob.data ? parseFloat(ob.data.priority) : 0
  32905. var current = this.dom.firstChild
  32906. while (current && current.priority <= div.priority) {
  32907. current = current.nextSibling
  32908. }
  32909. if (current) {
  32910. this.dom.insertBefore(div, current)
  32911. } else {
  32912. this.dom.appendChild(div)
  32913. }
  32914. ob.sublayer.updateAssets(div, ob.data)
  32915. title.onmouseover = function (id, sublayer_id) {
  32916. if (this.currentHover) {
  32917. this.currentHover.hide()
  32918. }
  32919. this.currentHover = this.layer.show(id,
  32920. {
  32921. styles: [ 'hover' ],
  32922. flags: [ 'hover' ],
  32923. sublayer_id
  32924. },
  32925. () => {}
  32926. )
  32927. }.bind(this, ob.id, ob.sublayer_id)
  32928. title.onmouseout = function (id, sublayer_id) {
  32929. if (this.currentHover) {
  32930. this.currentHover.hide()
  32931. }
  32932. this.currentHover = null
  32933. }.bind(this, ob.id, ob.sublayer_id)
  32934. }
  32935. updateObject (ob) {
  32936. var listExclude = isTrue(ob.data[this.options.prefix + 'Exclude'])
  32937. if (!(ob.id in this.items) && !listExclude) {
  32938. return
  32939. }
  32940. if (listExclude) {
  32941. return this.delObject(ob)
  32942. }
  32943. var div = this.items[ob.id]
  32944. var p = div.firstChild
  32945. while (p) {
  32946. if (p.className === 'markerParent') {
  32947. var a = p.firstChild
  32948. while (a) {
  32949. // MARKER
  32950. if (a.className === 'marker') {
  32951. while (p.lastChild) {
  32952. p.removeChild(p.lastChild)
  32953. }
  32954. a = this._getMarker(ob)
  32955. p.appendChild(a)
  32956. }
  32957. // ICON
  32958. a = document.createElement('div')
  32959. a.className = 'icon'
  32960. a.innerHTML = ob.data[this.options.prefix + 'MarkerSign'] || ob.data.markerSign || ''
  32961. p.appendChild(a)
  32962. a = a.nextSibling
  32963. }
  32964. }
  32965. // TITLE
  32966. if (p.className === 'title') {
  32967. let html = ob.data[this.options.prefix + 'Title'] || ob.data.title || ''
  32968. if (p.currentHTML !== html) {
  32969. p.innerHTML = html
  32970. ob.sublayer.updateAssets(div, ob.data)
  32971. }
  32972. }
  32973. // TITLE
  32974. if (p.className === 'description') {
  32975. let html = ob.data[this.options.prefix + 'Description'] || ob.data.description || ''
  32976. if (p.currentHTML !== html) {
  32977. p.innerHTML = html
  32978. ob.sublayer.updateAssets(div, ob.data)
  32979. }
  32980. }
  32981. p = p.nextSibling
  32982. }
  32983. }
  32984. delObject (ob) {
  32985. var div = this.items[ob.id]
  32986. if (div) {
  32987. this.dom.removeChild(div)
  32988. }
  32989. delete this.items[ob.id]
  32990. delete ob[this.options.prefix + 'Item']
  32991. }
  32992. remove () {
  32993. while (this.dom.firstChild) {
  32994. this.dom.removeChild(this.dom.lastChild)
  32995. }
  32996. for (var k in this.items) {
  32997. delete this.items[k][this.options.prefix + 'Item']
  32998. }
  32999. this.items = {}
  33000. }
  33001. }
  33002. module.exports = OverpassLayerList
  33003. },{"./OverpassLayerList.css":217,"./isTrue":222}],219:[function(require,module,exports){
  33004. /* global L */
  33005. const ee = require('event-emitter')
  33006. const OverpassFrontend = require('overpass-frontend')
  33007. const nearestPointOnGeometry = require('nearest-point-on-geometry')
  33008. const BoundingBox = require('boundingbox')
  33009. const styleToLeaflet = require('./styleToLeaflet')
  33010. const strToStyle = require('./strToStyle')
  33011. const SublayerFeature = require('./SublayerFeature')
  33012. // Extensions:
  33013. const decorators = [
  33014. require('./DecoratorPattern')
  33015. ]
  33016. class Sublayer {
  33017. constructor (master, options) {
  33018. this.master = master
  33019. options.sublayer_id = options.sublayer_id || 'main'
  33020. this.options = options
  33021. this.visibleFeatures = {}
  33022. this.shownFeatures = {} // features which are forcibly shown
  33023. this.shownFeatureOptions = {}
  33024. this.lastZoom = null
  33025. this._scheduledReprocesses = {}
  33026. if (!options.feature['style:hover']) {
  33027. options.feature['style:hover'] = {
  33028. color: 'black',
  33029. width: 3,
  33030. opacity: 1,
  33031. radius: 12,
  33032. pane: 'hover'
  33033. }
  33034. }
  33035. if (options.styleNoBindPopup) {
  33036. options.styleNoBindPopup.push('hover')
  33037. } else {
  33038. options.styleNoBindPopup = [ 'hover' ]
  33039. }
  33040. if (options.stylesNoAutoShow) {
  33041. options.stylesNoAutoShow.push('hover')
  33042. } else {
  33043. options.stylesNoAutoShow = [ 'hover' ]
  33044. }
  33045. decorators.forEach(Ext => new Ext(this))
  33046. }
  33047. addTo (map) {
  33048. this.map = map
  33049. this.map.on('popupopen', this._popupOpen.bind(this))
  33050. }
  33051. _popupOpen (e) {
  33052. if (e.popup.sublayer === this) {
  33053. this.updateAssets(e.popup._contentNode)
  33054. }
  33055. }
  33056. domUpdateHooks (node) {
  33057. if (node.getAttribute) {
  33058. let id = node.getAttribute('data-object')
  33059. if (id) {
  33060. let sublayerId = node.getAttribute('data-sublayer') || 'main'
  33061. node.classList.add('hoverable')
  33062. // check if referenced object is loaded - if not, request load
  33063. let ofOptions = {
  33064. properties: OverpassFrontend.ALL
  33065. }
  33066. let subObject = this.master.overpassFrontend.getCached(id, ofOptions)
  33067. if (!subObject) {
  33068. this.master.overpassFrontend.get(id, ofOptions,
  33069. () => {},
  33070. () => {}
  33071. )
  33072. }
  33073. node.onmouseover = () => {
  33074. if (this.currentHover) {
  33075. this.currentHover.hide()
  33076. }
  33077. this.currentHover = this.master.subLayers[sublayerId].show(id, { styles: [ 'hover' ] }, function () {})
  33078. }
  33079. node.onmouseout = () => {
  33080. if (this.currentHover) {
  33081. this.currentHover.hide()
  33082. }
  33083. this.currentHover = null
  33084. }
  33085. node.onclick = () => {
  33086. if (this.currentHover) {
  33087. this.currentHover.hide()
  33088. }
  33089. this.master.subLayers[sublayerId].openPopupOnObject(id)
  33090. }
  33091. }
  33092. }
  33093. let child = node.firstChild
  33094. while (child) {
  33095. this.domUpdateHooks(child)
  33096. child = child.nextSibling
  33097. }
  33098. }
  33099. remove () {
  33100. this.map.off('popupopen', this._popupOpen.bind(this))
  33101. this.map = null
  33102. }
  33103. startAdding () {
  33104. this.currentRequestFeatures = {}
  33105. }
  33106. add (ob) {
  33107. this.currentRequestFeatures[ob.id] = true
  33108. if (!(ob.id in this.visibleFeatures)) {
  33109. var data = new SublayerFeature(ob, this)
  33110. if (ob.id in this.shownFeatures) {
  33111. data = this.shownFeatures[ob.id]
  33112. } else {
  33113. this._processObject(data)
  33114. this._show(data)
  33115. }
  33116. this.visibleFeatures[ob.id] = data
  33117. if (this.master.onAppear) {
  33118. this.master.onAppear(data)
  33119. }
  33120. this.master.emit('add', ob, data)
  33121. this.emit('add', ob, data)
  33122. }
  33123. }
  33124. finishAdding () {
  33125. for (var k in this.visibleFeatures) {
  33126. if (!(k in this.currentRequestFeatures)) {
  33127. if (!(k in this.shownFeatures)) {
  33128. this._hide(this.visibleFeatures[k])
  33129. }
  33130. delete this.visibleFeatures[k]
  33131. }
  33132. }
  33133. }
  33134. hideAll (force) {
  33135. for (let k in this.visibleFeatures) {
  33136. let ob = this.visibleFeatures[k]
  33137. if (force || !(ob.id in this.shownFeatures)) {
  33138. this._hide(ob)
  33139. }
  33140. }
  33141. this.visibleFeatures = {}
  33142. }
  33143. // Hide loaded but non-visible objects
  33144. hideNonVisible (bounds) {
  33145. for (let k in this.visibleFeatures) {
  33146. let ob = this.visibleFeatures[k]
  33147. if (!ob.object.intersects(bounds)) {
  33148. if (!(ob.id in this.shownFeatures)) {
  33149. this._hide(ob)
  33150. }
  33151. delete this.visibleFeatures[k]
  33152. }
  33153. }
  33154. }
  33155. /**
  33156. * Hide all objects which do not satisfy the filter
  33157. * @param {OverpassFrontend.Filter} filter A filter, e.g. new OverpassFrontend.Filter('nwr[amenity=restaurant]')
  33158. */
  33159. hideNonVisibleFilter (filter) {
  33160. for (let k in this.visibleFeatures) {
  33161. let ob = this.visibleFeatures[k]
  33162. if (!filter.match(ob.object)) {
  33163. if (!(ob.id in this.shownFeatures)) {
  33164. this._hide(ob)
  33165. }
  33166. delete this.visibleFeatures[k]
  33167. }
  33168. }
  33169. }
  33170. get (id, options, callback) {
  33171. let isAborted = false
  33172. let isDone = false
  33173. let result = {
  33174. id,
  33175. options,
  33176. abort: () => {
  33177. if (isDone) {
  33178. console.log('abort called, although done')
  33179. return
  33180. }
  33181. isAborted = true
  33182. isDone = true
  33183. if (result.request) {
  33184. result.request.abort()
  33185. }
  33186. }
  33187. }
  33188. if (id in this.visibleFeatures) {
  33189. window.setTimeout(() => {
  33190. isDone = true
  33191. if (!isAborted) {
  33192. callback(null, this.visibleFeatures[id])
  33193. }
  33194. }, 0)
  33195. return result
  33196. }
  33197. if (id in this.shownFeatures) {
  33198. window.setTimeout(() => {
  33199. isDone = true
  33200. if (!isAborted) {
  33201. callback(null, this.shownFeatures[id])
  33202. }
  33203. }, 0)
  33204. return result
  33205. }
  33206. result.request = this.master.get(id, (err, ob) => {
  33207. isDone = true
  33208. if (err) {
  33209. return callback(err)
  33210. }
  33211. if (isAborted) {
  33212. return
  33213. }
  33214. if (ob === null) {
  33215. return console.log('object does not exist', id)
  33216. }
  33217. let data
  33218. if (id in this.visibleFeatures) {
  33219. data = this.visibleFeatures[id]
  33220. } else if (id in this.shownFeatures) {
  33221. data = this.shownFeatures[id]
  33222. } else {
  33223. data = new SublayerFeature(ob, this)
  33224. }
  33225. callback(null, data)
  33226. })
  33227. return result
  33228. }
  33229. show (data, options, callback) {
  33230. let show1 = () => {
  33231. id = data.id
  33232. result.id = id
  33233. this.shownFeatures[id] = data
  33234. if (!(id in this.shownFeatureOptions)) {
  33235. this.shownFeatureOptions[id] = []
  33236. }
  33237. this.shownFeatureOptions[id].push(options)
  33238. data.isShown = true
  33239. data.updateFlags()
  33240. this._processObject(data)
  33241. this._show(data)
  33242. callback(null, data.object, data)
  33243. }
  33244. let id = typeof data === 'string' ? data : data.id
  33245. let isHidden = false
  33246. let result = {
  33247. options,
  33248. hide: () => {
  33249. if (isHidden) {
  33250. console.log('already hidden')
  33251. }
  33252. isHidden = true
  33253. if (result.request) {
  33254. result.request.abort()
  33255. delete result.request
  33256. return
  33257. }
  33258. if (id in this.shownFeatures) {
  33259. var i = this.shownFeatureOptions[id].indexOf(options)
  33260. if (i !== -1) {
  33261. this.shownFeatureOptions[id].splice(i, 1)
  33262. }
  33263. data.updateFlags()
  33264. if (this.shownFeatureOptions[id].length === 0) {
  33265. this.hide(data)
  33266. } else {
  33267. this._processObject(this.shownFeatures[id])
  33268. }
  33269. }
  33270. }
  33271. }
  33272. options.priority = -1
  33273. options.properties = OverpassFrontend.ALL
  33274. if (typeof data === 'string') {
  33275. result.request = this.get(data, options, (err, _data) => {
  33276. delete result.request
  33277. if (isHidden) {
  33278. return
  33279. }
  33280. if (err) {
  33281. callback(err)
  33282. return
  33283. }
  33284. data = _data
  33285. show1()
  33286. })
  33287. } else {
  33288. show1()
  33289. }
  33290. return result
  33291. }
  33292. hide (id) {
  33293. if (typeof id === 'object') {
  33294. id = id.id
  33295. }
  33296. if (id in this.shownFeatures) {
  33297. let data = this.shownFeatures[id]
  33298. delete this.shownFeatures[id]
  33299. delete this.shownFeatureOptions[id]
  33300. if (id in this.visibleFeatures) {
  33301. this._processObject(data)
  33302. } else {
  33303. this._hide(data)
  33304. }
  33305. }
  33306. }
  33307. zoomChange () {
  33308. this.recalc()
  33309. for (let k in this.visibleFeatures) {
  33310. let data = this.visibleFeatures[k]
  33311. this.master.emit('zoomChange', data.object, data)
  33312. this.emit('zoomChange', data.object, data)
  33313. if (this.master.onZoomChange) {
  33314. this.master.onZoomChange(data)
  33315. }
  33316. }
  33317. this.lastZoom = this.map.getZoom()
  33318. }
  33319. recalc () {
  33320. for (var k in this.visibleFeatures) {
  33321. this._processObject(this.visibleFeatures[k])
  33322. }
  33323. }
  33324. _processObject (data) {
  33325. var k
  33326. var ob = data.object
  33327. var showOptions = {
  33328. styles: []
  33329. }
  33330. if (ob.id in this.shownFeatureOptions) {
  33331. this.shownFeatureOptions[ob.id].forEach(function (opt) {
  33332. if ('styles' in opt) {
  33333. showOptions.styles = showOptions.styles.concat(opt.styles)
  33334. }
  33335. })
  33336. }
  33337. var objectData = this.evaluate(data)
  33338. if (!data.feature) {
  33339. data.feature = ob.leafletFeature({
  33340. weight: 0,
  33341. opacity: 0,
  33342. fillOpacity: 0,
  33343. radius: 0
  33344. })
  33345. }
  33346. for (k in objectData) {
  33347. var m = k.match(/^style(|:(.*))$/)
  33348. if (m) {
  33349. var styleId = typeof m[2] === 'undefined' ? 'default' : m[2]
  33350. var style = styleToLeaflet(objectData[k])
  33351. if (data.features[styleId]) {
  33352. data.features[styleId].setStyle(style)
  33353. } else {
  33354. data.features[styleId] = ob.leafletFeature(style)
  33355. }
  33356. if ('text' in style && 'setText' in data.features[styleId]) {
  33357. data.features[styleId].setText(null)
  33358. data.features[styleId].setText(style.text, {
  33359. repeat: style.textRepeat,
  33360. offset: style.textOffset,
  33361. below: style.textBelow,
  33362. attributes: {
  33363. 'fill': style.textFill,
  33364. 'fill-opacity': style.textFillOpacity,
  33365. 'font-weight': style.textFontWeight,
  33366. 'font-size': style.textFontSize,
  33367. 'letter-spacing': style.textLetterSpacing
  33368. }
  33369. })
  33370. }
  33371. if ('offset' in style && 'setOffset' in data.features[styleId]) {
  33372. data.features[styleId].setOffset(style.offset)
  33373. }
  33374. }
  33375. }
  33376. if ('styles' in showOptions) {
  33377. objectData.styles = objectData.styles.concat(showOptions.styles)
  33378. }
  33379. objectData.marker = {
  33380. html: '',
  33381. iconAnchor: [ 0, 0 ],
  33382. iconSize: [ 0, 0 ],
  33383. signAnchor: [ 0, 0 ],
  33384. popupAnchor: [ 0, 0 ]
  33385. }
  33386. if (objectData.markerSymbol) {
  33387. objectData.marker.html += objectData.markerSymbol
  33388. var div = document.createElement('div')
  33389. div.innerHTML = objectData.markerSymbol
  33390. if (div.firstChild) {
  33391. var c = div.firstChild
  33392. objectData.marker.iconSize = [ c.offsetWidth, c.offsetHeight ]
  33393. if (c.hasAttribute('width')) {
  33394. objectData.marker.iconSize[0] = parseFloat(c.getAttribute('width'))
  33395. }
  33396. if (c.hasAttribute('height')) {
  33397. objectData.marker.iconSize[1] = parseFloat(c.getAttribute('height'))
  33398. }
  33399. objectData.marker.iconAnchor = [ objectData.marker.iconSize[0] / 2, objectData.marker.iconSize[1] / 2 ]
  33400. if (c.hasAttribute('anchorx')) {
  33401. objectData.marker.iconAnchor[0] = parseFloat(c.getAttribute('anchorx'))
  33402. }
  33403. if (c.hasAttribute('anchory')) {
  33404. objectData.marker.iconAnchor[1] = parseFloat(c.getAttribute('anchory'))
  33405. }
  33406. if (c.hasAttribute('signanchorx')) {
  33407. objectData.marker.signAnchor[0] = parseFloat(c.getAttribute('signanchorx'))
  33408. }
  33409. if (c.hasAttribute('signanchory')) {
  33410. objectData.marker.signAnchor[1] = parseFloat(c.getAttribute('signanchory'))
  33411. }
  33412. if (c.hasAttribute('popupanchory')) {
  33413. objectData.marker.popupAnchor[0] = parseFloat(c.getAttribute('popupanchorx'))
  33414. }
  33415. if (c.hasAttribute('popupanchory')) {
  33416. objectData.marker.popupAnchor[1] = parseFloat(c.getAttribute('popupanchory'))
  33417. }
  33418. }
  33419. this.updateAssets(div, objectData)
  33420. }
  33421. if (objectData.markerSign) {
  33422. let x = objectData.marker.iconAnchor[0] + objectData.marker.signAnchor[0]
  33423. let y = -objectData.marker.iconSize[1] + objectData.marker.iconAnchor[1] + objectData.marker.signAnchor[1]
  33424. objectData.marker.html += '<div class="sign" style="margin-left: ' + x + 'px; margin-top: ' + y + 'px;">' + objectData.markerSign + '</div>'
  33425. }
  33426. if (objectData.marker.html) {
  33427. objectData.marker.className = 'overpass-layer-icon'
  33428. var icon = L.divIcon(objectData.marker)
  33429. if (data.featureMarker) {
  33430. data.featureMarker.setIcon(icon)
  33431. if (data.featureMarker._icon) {
  33432. this.updateAssets(data.featureMarker._icon, objectData)
  33433. }
  33434. } else {
  33435. data.featureMarker = L.marker(ob.center, { icon: icon })
  33436. }
  33437. }
  33438. if (data.isShown) {
  33439. for (k in data.features) {
  33440. data.feature.addTo(this.map)
  33441. if (objectData.styles && objectData.styles.indexOf(k) !== -1 && data.styles && data.styles.indexOf(k) === -1) {
  33442. data.features[k].addTo(this.map)
  33443. }
  33444. if (objectData.styles && objectData.styles.indexOf(k) === -1 && data.styles && data.styles.indexOf(k) !== -1) {
  33445. this.map.removeLayer(data.features[k])
  33446. }
  33447. }
  33448. }
  33449. data.styles = objectData.styles
  33450. var popupContent = ''
  33451. popupContent += '<h1>' + objectData.title + '</h1>'
  33452. var popupDescription = objectData.popupDescription || objectData.description
  33453. if (popupDescription) {
  33454. popupContent += '<div class="description">' + popupDescription + '</div>'
  33455. }
  33456. if (objectData.body) {
  33457. popupContent += '<div class="body">' + objectData.body + '</div>'
  33458. }
  33459. if (data.popup) {
  33460. if (data.popup._contentNode) {
  33461. if (data.popup.currentHTML !== popupContent) {
  33462. data.popup._contentNode.innerHTML = popupContent
  33463. this.updateAssets(data.popup._contentNode, objectData)
  33464. }
  33465. } else {
  33466. data.popup.setContent(popupContent)
  33467. }
  33468. data.popup.currentHTML = popupContent
  33469. } else {
  33470. data.popup = L.popup().setContent(popupContent)
  33471. data.popup.object = data
  33472. data.popup.sublayer = this
  33473. data.feature.bindPopup(data.popup)
  33474. for (k in data.features) {
  33475. if (this._shallBindPopupToStyle(k)) {
  33476. data.features[k].bindPopup(data.popup)
  33477. }
  33478. }
  33479. if (data.featureMarker) {
  33480. data.featureMarker.bindPopup(data.popup)
  33481. }
  33482. }
  33483. data.id = ob.id
  33484. data.layer_id = this.options.id
  33485. data.sublayer_id = this.options.sublayer_id
  33486. data.data = objectData
  33487. if (this.master.onUpdate) {
  33488. this.master.onUpdate(data)
  33489. }
  33490. this.master.emit('update', data.object, data)
  33491. this.emit('update', data.object, data)
  33492. }
  33493. evaluate (data) {
  33494. var k
  33495. var ob = data.object
  33496. data.twigData = this.twigData(ob, data)
  33497. var objectData = {}
  33498. for (k in this.options.feature) {
  33499. if (typeof this.options.feature[k] === 'function') {
  33500. objectData[k] = this.options.feature[k](data.twigData)
  33501. } else {
  33502. objectData[k] = this.options.feature[k]
  33503. }
  33504. }
  33505. var styleIds = []
  33506. for (k in objectData) {
  33507. var m = k.match(/^style(|:(.*))$/)
  33508. if (m) {
  33509. var style = objectData[k]
  33510. var styleId = typeof m[2] === 'undefined' ? 'default' : m[2]
  33511. if (typeof style === 'string' || 'twig_markup' in style) {
  33512. objectData[k] = strToStyle(style)
  33513. }
  33514. if (this.options.stylesNoAutoShow.indexOf(styleId) === -1) {
  33515. styleIds.push(styleId)
  33516. }
  33517. }
  33518. }
  33519. if (!('features' in data)) {
  33520. data.features = {}
  33521. }
  33522. objectData.styles =
  33523. 'styles' in objectData ? objectData.styles
  33524. : 'styles' in this.options ? this.options.styles
  33525. : styleIds
  33526. if (typeof objectData.styles === 'string' || 'twig_markup' in objectData.styles) {
  33527. var styles = objectData.styles.trim()
  33528. if (styles === '') {
  33529. objectData.styles = []
  33530. } else {
  33531. objectData.styles = styles.split(/,/)
  33532. }
  33533. }
  33534. return objectData
  33535. }
  33536. twigData (ob, data) {
  33537. var result = {
  33538. id: ob.id,
  33539. sublayer_id: this.options.sublayer_id,
  33540. osm_id: ob.osm_id,
  33541. type: ob.type,
  33542. tags: ob.tags,
  33543. meta: ob.meta,
  33544. flags: data.flags,
  33545. members: [],
  33546. 'const': this.options.const
  33547. }
  33548. if (ob.memberFeatures) {
  33549. ob.memberFeatures.forEach((member, sequence) => {
  33550. let r = {
  33551. id: member.id,
  33552. sequence,
  33553. type: member.type,
  33554. osm_id: member.osm_id,
  33555. role: ob.members[sequence].role,
  33556. tags: member.tags,
  33557. meta: member.meta,
  33558. dir: member.dir,
  33559. connectedPrev: member.connectedPrev,
  33560. connectedNext: member.connectedNext
  33561. }
  33562. result.members.push(r)
  33563. })
  33564. }
  33565. if (this.map) {
  33566. result.map = {
  33567. zoom: this.map.getZoom()
  33568. }
  33569. }
  33570. this.emit('twigData', ob, data, result)
  33571. this.master.emit('twigData', ob, data, result)
  33572. return result
  33573. }
  33574. _shallBindPopupToStyle (styleId) {
  33575. return this.options.styleNoBindPopup.indexOf(styleId) === -1
  33576. }
  33577. _show (data) {
  33578. if (!this.map) {
  33579. return
  33580. }
  33581. data.feature.addTo(this.map)
  33582. for (var i = 0; i < data.styles.length; i++) {
  33583. var k = data.styles[i]
  33584. if (k in data.features) {
  33585. data.features[k].addTo(this.map)
  33586. }
  33587. }
  33588. if (data.featureMarker) {
  33589. data.featureMarker.addTo(this.map)
  33590. this.updateAssets(data.featureMarker._icon, data)
  33591. }
  33592. data.object.on('update', this.scheduleReprocess.bind(this, data.id))
  33593. data.isShown = true
  33594. }
  33595. _hide (data) {
  33596. this.master.emit('remove', data.object, data)
  33597. this.emit('remove', data.object, data)
  33598. this.map.removeLayer(data.feature)
  33599. for (var k in data.features) {
  33600. this.map.removeLayer(data.features[k])
  33601. }
  33602. if (data.featureMarker) {
  33603. this.map.removeLayer(data.featureMarker)
  33604. }
  33605. if (this.master.onDisappear) {
  33606. this.master.onDisappear(data)
  33607. }
  33608. data.object.off('update', this.scheduleReprocess.bind(this, data.id))
  33609. data.isShown = false
  33610. }
  33611. scheduleReprocess (id) {
  33612. if (!(id in this._scheduledReprocesses)) {
  33613. this._scheduledReprocesses[id] = window.setTimeout(() => {
  33614. delete this._scheduledReprocesses[id]
  33615. if (id in this.visibleFeatures) {
  33616. this._processObject(this.visibleFeatures[id])
  33617. }
  33618. }, 0)
  33619. }
  33620. }
  33621. updateAssets (div, objectData) {
  33622. this.domUpdateHooks(div)
  33623. if (this.options.updateAssets) {
  33624. this.options.updateAssets(div, objectData, this)
  33625. }
  33626. }
  33627. openPopupOnObject (ob, options) {
  33628. if (typeof ob === 'string') {
  33629. return this.get(ob, options, (err, ob) => {
  33630. if (err) {
  33631. return console.log(err)
  33632. }
  33633. this._processObject(ob)
  33634. this._show(ob)
  33635. this.openPopupOnObject(ob, options)
  33636. })
  33637. }
  33638. // When object is quite smaller than current view, show popup on feature
  33639. let viewBounds = new BoundingBox(this.map.getBounds())
  33640. let obBounds = new BoundingBox(ob.object.bounds)
  33641. if (obBounds.diagonalLength() * 0.75 < viewBounds.diagonalLength()) {
  33642. return ob.feature.openPopup()
  33643. }
  33644. // otherwise, try to find point on geometry closest to center of view
  33645. let pt = this.map.getCenter()
  33646. let geom = ob.object.GeoJSON()
  33647. let pos = nearestPointOnGeometry(geom, { type: 'Feature', geometry: { type: 'Point', coordinates: [ pt.lng, pt.lat ] } })
  33648. if (pos) {
  33649. pos = pos.geometry.coordinates
  33650. return ob.feature.openPopup([pos[1], pos[0]])
  33651. }
  33652. // no point found? use normal object popup open then ...
  33653. ob.feature.openPopup()
  33654. }
  33655. }
  33656. ee(Sublayer.prototype)
  33657. module.exports = Sublayer
  33658. },{"./DecoratorPattern":213,"./SublayerFeature":220,"./strToStyle":223,"./styleToLeaflet":224,"boundingbox":20,"event-emitter":41,"nearest-point-on-geometry":174,"overpass-frontend":180}],220:[function(require,module,exports){
  33659. class SublayerFeature {
  33660. constructor (object, sublayer) {
  33661. this.object = object
  33662. this.id = object.id
  33663. this.sublayer = sublayer
  33664. this.isShown = false
  33665. this.flags = {}
  33666. }
  33667. updateFlags () {
  33668. let shownFeatureOptions = this.sublayer.shownFeatureOptions[this.id]
  33669. this.flags = {}
  33670. shownFeatureOptions.forEach(options => {
  33671. if (options.flags) {
  33672. options.flags.forEach(flag => {
  33673. this.flags[flag] = true
  33674. })
  33675. }
  33676. })
  33677. }
  33678. }
  33679. module.exports = SublayerFeature
  33680. },{}],221:[function(require,module,exports){
  33681. function compileFeature (feature, twig) {
  33682. for (var k in feature) {
  33683. if (typeof feature[k] === 'string' && feature[k].search('{') !== -1) {
  33684. let template
  33685. try {
  33686. template = twig.twig({ data: feature[k], autoescape: true })
  33687. } catch (err) {
  33688. console.log('Error compiling twig template ' + this.id + '/' + k + ':', err)
  33689. break
  33690. }
  33691. feature[k] = function (template, k, ob) {
  33692. try {
  33693. return template.render(ob)
  33694. } catch (err) {
  33695. console.log('Error rendering twig template ' + this.id + '/' + k + ': ', err)
  33696. }
  33697. return null
  33698. }.bind(this, template, k)
  33699. } else if (typeof feature[k] === 'object' && (['style'].indexOf(k) !== -1 || k.match(/^style:/))) {
  33700. var templates = {}
  33701. for (var k1 in feature[k]) {
  33702. if (typeof feature[k][k1] === 'string' && feature[k][k1].search('{') !== -1) {
  33703. templates[k1] = twig.twig({ data: feature[k][k1], autoescape: true })
  33704. } else {
  33705. templates[k1] = feature[k][k1]
  33706. }
  33707. }
  33708. feature[k] = function (templates, ob) {
  33709. var ret = {}
  33710. for (var k1 in templates) {
  33711. if (typeof templates[k1] === 'object' && templates[k1] !== null && 'render' in templates[k1]) {
  33712. ret[k1] = templates[k1].render(ob)
  33713. } else {
  33714. ret[k1] = templates[k1]
  33715. }
  33716. }
  33717. return ret
  33718. }.bind(this, templates)
  33719. }
  33720. }
  33721. return feature
  33722. }
  33723. module.exports = compileFeature
  33724. },{}],222:[function(require,module,exports){
  33725. function isTrue (value) {
  33726. if (value === null || typeof value === 'undefined') {
  33727. return false
  33728. }
  33729. if (typeof value === 'boolean') {
  33730. return value
  33731. }
  33732. if ((typeof value === 'string') ||
  33733. (typeof value === 'object' && 'twig_markup' in value)) {
  33734. if (value.trim() === 'false') {
  33735. return false
  33736. }
  33737. if (value.trim() === 'true') {
  33738. return true
  33739. }
  33740. }
  33741. if (value === 0 || value.toString() === '0' || value.toString() === '') {
  33742. return false
  33743. }
  33744. return true
  33745. }
  33746. window.isTrue = isTrue
  33747. module.exports = isTrue
  33748. },{}],223:[function(require,module,exports){
  33749. function strToStyle (style) {
  33750. var str = style.split('\n')
  33751. style = {}
  33752. for (var i = 0; i < str.length; i++) {
  33753. var m
  33754. if ((m = str[i].match(/^\s*([a-zA-Z0-9_]+)\s*:\s*(.*)\s*$/))) {
  33755. var v = m[2].trim()
  33756. if (v.match(/^-?[0-9]+(\.[0-9]+)?/)) {
  33757. v = parseFloat(v)
  33758. }
  33759. style[m[1]] = v
  33760. }
  33761. }
  33762. return style
  33763. }
  33764. module.exports = strToStyle
  33765. },{}],224:[function(require,module,exports){
  33766. const isTrue = require('./isTrue')
  33767. const transforms = {
  33768. stroke: {
  33769. type: 'boolean'
  33770. },
  33771. fill: {
  33772. type: 'boolean'
  33773. },
  33774. textRepeat: {
  33775. type: 'boolean'
  33776. },
  33777. textBelow: {
  33778. type: 'boolean'
  33779. },
  33780. noClip: {
  33781. type: 'boolean'
  33782. },
  33783. width: {
  33784. rename: 'weight',
  33785. type: 'float'
  33786. },
  33787. opacity: {
  33788. type: 'float'
  33789. },
  33790. fillOpacity: {
  33791. type: 'float'
  33792. }
  33793. }
  33794. function styleToLeaflet (style) {
  33795. let ret = JSON.parse(JSON.stringify(style))
  33796. for (let k in ret) {
  33797. let value = ret[k]
  33798. if (k in transforms) {
  33799. let transform = transforms[k]
  33800. switch (transform.type) {
  33801. case 'boolean':
  33802. value = isTrue(ret[k])
  33803. break
  33804. case 'float':
  33805. value = parseFloat(ret[k])
  33806. break
  33807. }
  33808. if (transform.rename) {
  33809. delete ret[k]
  33810. k = transform.rename
  33811. }
  33812. }
  33813. ret[k] = value
  33814. }
  33815. return ret
  33816. }
  33817. module.exports = styleToLeaflet
  33818. },{"./isTrue":222}]},{},[1]);