You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lib-jitsi-meet.js 398KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JitsiMeetJS=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var xmpp = require("./modules/xmpp/xmpp");
  3. /**
  4. * Creates a JitsiConference object with the given name and properties.
  5. * Note: this constructor is not a part of the public API (objects should be
  6. * created using JitsiConnection.createConference).
  7. * @param options.config properties / settings related to the conference that will be created.
  8. * @param options.name the name of the conference
  9. * @param options.connection the JitsiConnection object for this JitsiConference.
  10. * @constructor
  11. */
  12. function JitsiConference(options) {
  13. this.options = options;
  14. }
  15. /**
  16. * Joins the conference.
  17. */
  18. JitsiConference.prototype.join = function () {
  19. xmpp.joinRoom(this.options.name, null, null);
  20. }
  21. /**
  22. * Leaves the conference.
  23. */
  24. JitsiConference.prototype.leave = function () {
  25. xmpp.l
  26. }
  27. /**
  28. * Creates the media tracks and returns them via the callback.
  29. * @param options Object with properties / settings specifying the tracks which should be created.
  30. * should be created or some additional configurations about resolution for example.
  31. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  32. * or a JitsiConferenceError if rejected.
  33. */
  34. JitsiConference.prototype.createLocalTracks = function (options) {
  35. }
  36. /**
  37. * Returns the local tracks.
  38. */
  39. JitsiConference.prototype.getLocalTracks = function () {
  40. };
  41. /**
  42. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  43. * in JitsiConferenceEvents.
  44. * @param eventId the event ID.
  45. * @param handler handler for the event.
  46. *
  47. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  48. */
  49. JitsiConference.prototype.on = function (eventId, handler) {
  50. }
  51. /**
  52. * Removes event listener
  53. * @param eventId the event ID.
  54. * @param [handler] optional, the specific handler to unbind
  55. *
  56. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  57. */
  58. JitsiConference.prototype.off = function (eventId, handler) {
  59. }
  60. // Common aliases for event emitter
  61. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  62. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  63. /**
  64. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  65. * @param command {String} the name of the command
  66. * @param handler {Function} handler for the command
  67. */
  68. JitsiConference.prototype.addCommandListener = function (command, handler) {
  69. }
  70. /**
  71. * Removes command listener
  72. * @param command {String} the name of the command
  73. */
  74. JitsiConference.prototype.removeCommandListener = function (command) {
  75. }
  76. /**
  77. * Sends text message to the other participants in the conference
  78. * @param message the text message.
  79. */
  80. JitsiConference.prototype.sendTextMessage = function (message) {
  81. }
  82. /**
  83. * Send presence command.
  84. * @param name the name of the command.
  85. * @param values Object with keys and values that will be send.
  86. * @param persistent if false the command will be sent only one time
  87. * @param successCallback will be called when the command is successfully send.
  88. * @param errorCallback will be called when the command is not sent successfully.
  89. * @returns {Promise.<{void}, JitsiConferenceError>} A promise that returns an array of created streams if resolved,
  90. * or an JitsiConferenceError if rejected.
  91. */
  92. JitsiConference.prototype.sendCommand = function (name, values, persistent) {
  93. }
  94. /**
  95. * Sets the display name for this conference.
  96. * @param name the display name to set
  97. */
  98. JitsiConference.prototype.setDisplayName = function(name) {
  99. }
  100. /**
  101. * Elects the participant with the given id to be the selected participant or the speaker.
  102. * @param id the identifier of the participant
  103. */
  104. JitsiConference.prototype.selectParticipant = function(participantId) {
  105. }
  106. /**
  107. * Returns the list of participants for this conference.
  108. * @return Object a list of participant identifiers containing all conference participants.
  109. */
  110. JitsiConference.prototype.getParticipants = function() {
  111. }
  112. module.exports = JitsiConference;
  113. },{"./modules/xmpp/xmpp":21}],2:[function(require,module,exports){
  114. /**
  115. * Enumeration with the errors for the conference.
  116. * @type {{string: string}}
  117. */
  118. var JitsiConferenceErrors = {
  119. /**
  120. * Indicates that a password is required in order to join the conference.
  121. */
  122. PASSWORD_REQUIRED: "conference.passwordRequired",
  123. /**
  124. * Indicates that a connection error occurred when trying to join a conference.
  125. */
  126. CONNECTION_ERROR: "conference.connectionError",
  127. /**
  128. * Indicates that there is no available videobridge.
  129. */
  130. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  131. /**
  132. * Many more errors TBD here.
  133. */
  134. };
  135. module.exports = JitsiConferenceErrors;
  136. },{}],3:[function(require,module,exports){
  137. /**
  138. * Enumeration with the events for the conference.
  139. * @type {{string: string}}
  140. */
  141. var JitsiConferenceEvents = {
  142. /**
  143. * A new media track was added to the conference.
  144. */
  145. TRACK_ADDED: "conference.trackAdded",
  146. /**
  147. * The media track was removed to the conference.
  148. */
  149. TRACK_REMOVED: "conference.trackRemoved",
  150. /**
  151. * The active speaker was changed.
  152. */
  153. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  154. /**
  155. * A new user joinned the conference.
  156. */
  157. USER_JOINED: "conference.userJoined",
  158. /**
  159. * A user has left the conference.
  160. */
  161. USER_LEFT: "conference.userLeft",
  162. /**
  163. * New text message was received.
  164. */
  165. MESSAGE_RECEIVED: "conference.messageReceived",
  166. /**
  167. * A user has changed it display name
  168. */
  169. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  170. /**
  171. * A participant avatar has changed.
  172. */
  173. AVATAR_CHANGED: "conference.avatarChanged",
  174. /**
  175. * New connection statistics are received.
  176. */
  177. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  178. /**
  179. * The Last N set is changed.
  180. */
  181. LAST_N_CHANGED: "conference.lastNChanged",
  182. /**
  183. * A media track was muted.
  184. */
  185. TRACK_MUTED: "conference.trackMuted",
  186. /**
  187. * A media track was unmuted.
  188. */
  189. TRACK_UNMUTED: "conference.trackUnmuted",
  190. /**
  191. * Audio levels of a media track was changed.
  192. */
  193. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  194. /**
  195. * Indicates that the connection to the conference has been interrupted for some reason.
  196. */
  197. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  198. /**
  199. * Indicates that the connection to the conference has been restored.
  200. */
  201. CONNECTION_ESTABLISHED: "conference.connecionEstablished"
  202. };
  203. module.exports = JitsiConferenceEvents;
  204. },{}],4:[function(require,module,exports){
  205. var JitsiConference = require("./JitsiConference");
  206. var XMPP = require("./modules/xmpp/xmpp");
  207. /**
  208. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  209. * JitsiConference interface.
  210. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  211. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  212. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  213. * @param options Object with properties / settings related to connection with the server.
  214. * @constructor
  215. */
  216. function JitsiConnection(appID, token, options) {
  217. this.appID = appID;
  218. this.token = token;
  219. this.options = options;
  220. this.xmpp = new XMPP(options);
  221. }
  222. /**
  223. * Connect the client with the server.
  224. * @param options {object} connecting options (for example authentications parameters).
  225. */
  226. JitsiConnection.prototype.connect = function (options) {
  227. if(!options)
  228. options = {};
  229. this.xmpp.connect(options.id, options.password);
  230. }
  231. /**
  232. * Disconnect the client from the server.
  233. */
  234. JitsiConnection.prototype.disconnect = function () {
  235. this.xmpp.disconnect();
  236. }
  237. /**
  238. * This method allows renewal of the tokens if they are expiring.
  239. * @param token the new token.
  240. */
  241. JitsiConnection.prototype.setToken = function (token) {
  242. this.token = token;
  243. }
  244. /**
  245. * Creates and joins new conference.
  246. * @param name the name of the conference; if null - a generated name will be provided from the api
  247. * @param options Object with properties / settings related to the conference that will be created.
  248. * @returns {JitsiConference} returns the new conference object.
  249. */
  250. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  251. return new JitsiConference({name: name, config: options, connection: this});
  252. }
  253. /**
  254. * Subscribes the passed listener to the event.
  255. * @param event {JitsiConnectionEvents} the connection event.
  256. * @param listener {Function} the function that will receive the event
  257. */
  258. JitsiConnection.prototype.addListener = function (event, listener) {
  259. this.xmpp.addListener(event, listener);
  260. }
  261. /**
  262. * Unsubscribes the passed handler.
  263. * @param event {JitsiConnectionEvents} the connection event.
  264. * @param listener {Function} the function that will receive the event
  265. */
  266. JitsiConnection.prototype.removeListener = function (event, listener) {
  267. this.xmpp.removeListener(event, listener);
  268. }
  269. module.exports = JitsiConnection;
  270. },{"./JitsiConference":1,"./modules/xmpp/xmpp":21}],5:[function(require,module,exports){
  271. /**
  272. * Enumeration with the errors for the connection.
  273. * @type {{string: string}}
  274. */
  275. var JitsiConnectionErrors = {
  276. /**
  277. * Indicates that a password is required in order to join the conference.
  278. */
  279. PASSWORD_REQUIRED: "connection.passwordRequired",
  280. /**
  281. * Indicates that a connection error occurred when trying to join a conference.
  282. */
  283. CONNECTION_ERROR: "connection.connectionError",
  284. /**
  285. * Not specified errors.
  286. */
  287. OTHER_ERROR: "connection.otherError"
  288. };
  289. module.exports = JitsiConnectionErrors;
  290. },{}],6:[function(require,module,exports){
  291. /**
  292. * Enumeration with the events for the connection.
  293. * @type {{string: string}}
  294. */
  295. var JitsiConnnectionEvents = {
  296. /**
  297. * Indicates that the connection has been failed for some reason.
  298. */
  299. CONNECTION_FAILED: "connection.connecionFailed",
  300. /**
  301. * Indicates that the connection has been established.
  302. */
  303. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  304. /**
  305. * Indicates that the connection has been disconnected.
  306. */
  307. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  308. /**
  309. * Indicates that the perfomed action cannot be executed because the
  310. * connection is not in the correct state(connected, disconnected, etc.)
  311. */
  312. WRONG_STATE: "connection.wrongState"
  313. };
  314. module.exports = JitsiConnnectionEvents;
  315. },{}],7:[function(require,module,exports){
  316. var JitsiConnection = require("./JitsiConnection");
  317. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  318. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  319. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  320. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  321. /**
  322. * Namespace for the interface of Jitsi Meet Library.
  323. */
  324. var LibJitsiMeet = {
  325. JitsiConnection: JitsiConnection,
  326. events: {
  327. conference: JitsiConferenceEvents,
  328. connection: JitsiConnectionEvents
  329. },
  330. errors: {
  331. conference: JitsiConferenceErrors,
  332. connection: JitsiConnectionErrors
  333. }
  334. }
  335. //Setups the promise object.
  336. require("es6-promise").polyfill();
  337. module.exports = LibJitsiMeet;
  338. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"es6-promise":22}],8:[function(require,module,exports){
  339. /* global config, APP, Strophe */
  340. // cache datachannels to avoid garbage collection
  341. // https://code.google.com/p/chromium/issues/detail?id=405545
  342. var RTCEvents = require("../../service/RTC/RTCEvents");
  343. var _dataChannels = [];
  344. var eventEmitter = null;
  345. var DataChannels = {
  346. /**
  347. * Callback triggered by PeerConnection when new data channel is opened
  348. * on the bridge.
  349. * @param event the event info object.
  350. */
  351. onDataChannel: function (event) {
  352. var dataChannel = event.channel;
  353. dataChannel.onopen = function () {
  354. console.info("Data channel opened by the Videobridge!", dataChannel);
  355. // Code sample for sending string and/or binary data
  356. // Sends String message to the bridge
  357. //dataChannel.send("Hello bridge!");
  358. // Sends 12 bytes binary message to the bridge
  359. //dataChannel.send(new ArrayBuffer(12));
  360. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  361. };
  362. dataChannel.onerror = function (error) {
  363. console.error("Data Channel Error:", error, dataChannel);
  364. };
  365. dataChannel.onmessage = function (event) {
  366. var data = event.data;
  367. // JSON
  368. var obj;
  369. try {
  370. obj = JSON.parse(data);
  371. }
  372. catch (e) {
  373. console.error(
  374. "Failed to parse data channel message as JSON: ",
  375. data,
  376. dataChannel);
  377. }
  378. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  379. var colibriClass = obj.colibriClass;
  380. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  381. // Endpoint ID from the Videobridge.
  382. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  383. console.info(
  384. "Data channel new dominant speaker event: ",
  385. dominantSpeakerEndpoint);
  386. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  387. }
  388. else if ("InLastNChangeEvent" === colibriClass) {
  389. var oldValue = obj.oldValue;
  390. var newValue = obj.newValue;
  391. // Make sure that oldValue and newValue are of type boolean.
  392. var type;
  393. if ((type = typeof oldValue) !== 'boolean') {
  394. if (type === 'string') {
  395. oldValue = (oldValue == "true");
  396. } else {
  397. oldValue = new Boolean(oldValue).valueOf();
  398. }
  399. }
  400. if ((type = typeof newValue) !== 'boolean') {
  401. if (type === 'string') {
  402. newValue = (newValue == "true");
  403. } else {
  404. newValue = new Boolean(newValue).valueOf();
  405. }
  406. }
  407. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  408. }
  409. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  410. // The new/latest list of last-n endpoint IDs.
  411. var lastNEndpoints = obj.lastNEndpoints;
  412. // The list of endpoint IDs which are entering the list of
  413. // last-n at this time i.e. were not in the old list of last-n
  414. // endpoint IDs.
  415. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  416. console.log(
  417. "Data channel new last-n event: ",
  418. lastNEndpoints, endpointsEnteringLastN, obj);
  419. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  420. lastNEndpoints, endpointsEnteringLastN, obj);
  421. }
  422. else {
  423. console.debug("Data channel JSON-formatted message: ", obj);
  424. }
  425. }
  426. };
  427. dataChannel.onclose = function () {
  428. console.info("The Data Channel closed", dataChannel);
  429. var idx = _dataChannels.indexOf(dataChannel);
  430. if (idx > -1)
  431. _dataChannels = _dataChannels.splice(idx, 1);
  432. };
  433. _dataChannels.push(dataChannel);
  434. },
  435. /**
  436. * Binds "ondatachannel" event listener to given PeerConnection instance.
  437. * @param peerConnection WebRTC peer connection instance.
  438. */
  439. init: function (peerConnection, emitter) {
  440. if(!config.openSctp)
  441. return;
  442. peerConnection.ondatachannel = this.onDataChannel;
  443. eventEmitter = emitter;
  444. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  445. // Although it's not a requirement to open separate channels from both bridge
  446. // and peer as single channel can be used for sending and receiving data.
  447. // So either channel opened by the bridge or the one opened here is enough
  448. // for communication with the bridge.
  449. /*var dataChannelOptions =
  450. {
  451. reliable: true
  452. };
  453. var dataChannel
  454. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  455. // Can be used only when is in open state
  456. dataChannel.onopen = function ()
  457. {
  458. dataChannel.send("My channel !!!");
  459. };
  460. dataChannel.onmessage = function (event)
  461. {
  462. var msgData = event.data;
  463. console.info("Got My Data Channel Message:", msgData, dataChannel);
  464. };*/
  465. },
  466. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  467. handlePinnedEndpointEvent: onPinnedEndpointChanged
  468. };
  469. function onSelectedEndpointChanged(userResource) {
  470. console.log('selected endpoint changed: ', userResource);
  471. if (_dataChannels && _dataChannels.length != 0) {
  472. _dataChannels.some(function (dataChannel) {
  473. if (dataChannel.readyState == 'open') {
  474. console.log('sending selected endpoint changed ' +
  475. 'notification to the bridge: ', userResource);
  476. dataChannel.send(JSON.stringify({
  477. 'colibriClass': 'SelectedEndpointChangedEvent',
  478. 'selectedEndpoint':
  479. (!userResource || userResource === null)?
  480. null : userResource
  481. }));
  482. return true;
  483. }
  484. });
  485. }
  486. }
  487. function onPinnedEndpointChanged(userResource) {
  488. console.log('pinned endpoint changed: ', userResource);
  489. if (_dataChannels && _dataChannels.length != 0) {
  490. _dataChannels.some(function (dataChannel) {
  491. if (dataChannel.readyState == 'open') {
  492. dataChannel.send(JSON.stringify({
  493. 'colibriClass': 'PinnedEndpointChangedEvent',
  494. 'pinnedEndpoint':
  495. (!userResource || userResource == null)?
  496. null : userResource
  497. }));
  498. return true;
  499. }
  500. });
  501. }
  502. }
  503. module.exports = DataChannels;
  504. },{"../../service/RTC/RTCEvents":40}],9:[function(require,module,exports){
  505. /* global APP */
  506. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  507. var RTCEvents = require("../../service/RTC/RTCEvents");
  508. var RTCBrowserType = require("./RTCBrowserType");
  509. /**
  510. * This implements 'onended' callback normally fired by WebRTC after the stream
  511. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  512. * @param stream original WebRTC stream object to which 'onended' handling
  513. * will be added.
  514. */
  515. function implementOnEndedHandling(stream) {
  516. var originalStop = stream.stop;
  517. stream.stop = function () {
  518. originalStop.apply(stream);
  519. if (!stream.ended) {
  520. stream.ended = true;
  521. stream.onended();
  522. }
  523. };
  524. }
  525. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  526. this.stream = stream;
  527. this.eventEmitter = eventEmitter;
  528. this.type = type;
  529. this.videoType = videoType;
  530. this.isGUMStream = true;
  531. if(isGUMStream === false)
  532. this.isGUMStream = isGUMStream;
  533. var self = this;
  534. if(type == "audio") {
  535. this.getTracks = function () {
  536. return self.stream.getAudioTracks();
  537. };
  538. } else {
  539. this.getTracks = function () {
  540. return self.stream.getVideoTracks();
  541. };
  542. }
  543. this.stream.onended = function () {
  544. self.streamEnded();
  545. };
  546. if (RTCBrowserType.isFirefox()) {
  547. implementOnEndedHandling(this.stream);
  548. }
  549. }
  550. LocalStream.prototype.streamEnded = function () {
  551. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  552. };
  553. LocalStream.prototype.getOriginalStream = function()
  554. {
  555. return this.stream;
  556. };
  557. LocalStream.prototype.isAudioStream = function () {
  558. return this.type === "audio";
  559. };
  560. LocalStream.prototype.setMute = function (mute)
  561. {
  562. var isAudio = this.isAudioStream();
  563. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  564. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  565. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  566. // FIXME FF does not support 'removeStream' method used to mute
  567. RTCBrowserType.isFirefox()) {
  568. var tracks = this.getTracks();
  569. for (var idx = 0; idx < tracks.length; idx++) {
  570. tracks[idx].enabled = !mute;
  571. }
  572. this.eventEmitter.emit(eventType, mute);
  573. } else {
  574. if (mute) {
  575. APP.xmpp.removeStream(this.stream);
  576. this.stream.stop();
  577. this.eventEmitter.emit(eventType, true);
  578. } else {
  579. var self = this;
  580. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  581. (this.isAudioStream() ? ["audio"] : ["video"]),
  582. function (stream) {
  583. if (isAudio) {
  584. APP.RTC.changeLocalAudio(stream,
  585. function () {
  586. self.eventEmitter.emit(eventType, false);
  587. });
  588. } else {
  589. APP.RTC.changeLocalVideo(stream, false,
  590. function () {
  591. self.eventEmitter.emit(eventType, false);
  592. });
  593. }
  594. });
  595. }
  596. }
  597. };
  598. LocalStream.prototype.isMuted = function () {
  599. var tracks = [];
  600. if (this.isAudioStream()) {
  601. tracks = this.stream.getAudioTracks();
  602. } else {
  603. if (this.stream.ended)
  604. return true;
  605. tracks = this.stream.getVideoTracks();
  606. }
  607. for (var idx = 0; idx < tracks.length; idx++) {
  608. if(tracks[idx].enabled)
  609. return false;
  610. }
  611. return true;
  612. };
  613. LocalStream.prototype.getId = function () {
  614. return this.stream.getTracks()[0].id;
  615. };
  616. module.exports = LocalStream;
  617. },{"../../service/RTC/RTCEvents":40,"../../service/RTC/StreamEventTypes.js":42,"./RTCBrowserType":12}],10:[function(require,module,exports){
  618. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  619. /**
  620. * Creates a MediaStream object for the given data, session id and ssrc.
  621. * It is a wrapper class for the MediaStream.
  622. *
  623. * @param data the data object from which we obtain the stream,
  624. * the peerjid, etc.
  625. * @param sid the session id
  626. * @param ssrc the ssrc corresponding to this MediaStream
  627. *
  628. * @constructor
  629. */
  630. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  631. // XXX(gp) to minimize headaches in the future, we should build our
  632. // abstractions around tracks and not streams. ORTC is track based API.
  633. // Mozilla expects m-lines to represent media tracks.
  634. //
  635. // Practically, what I'm saying is that we should have a MediaTrack class
  636. // and not a MediaStream class.
  637. //
  638. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  639. // a track might have an associated RTX and FEC sources.
  640. this.sid = sid;
  641. this.stream = data.stream;
  642. this.peerjid = data.peerjid;
  643. this.videoType = data.videoType;
  644. this.ssrc = ssrc;
  645. this.type = (this.stream.getVideoTracks().length > 0)?
  646. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  647. this.muted = false;
  648. this.eventEmitter = eventEmitter;
  649. }
  650. MediaStream.prototype.getOriginalStream = function() {
  651. return this.stream;
  652. };
  653. MediaStream.prototype.setMute = function (value) {
  654. this.stream.muted = value;
  655. this.muted = value;
  656. };
  657. module.exports = MediaStream;
  658. },{"../../service/RTC/MediaStreamTypes":39}],11:[function(require,module,exports){
  659. /* global APP */
  660. var EventEmitter = require("events");
  661. var RTCBrowserType = require("./RTCBrowserType");
  662. var RTCUtils = require("./RTCUtils.js");
  663. var LocalStream = require("./LocalStream.js");
  664. var DataChannels = require("./DataChannels");
  665. var MediaStream = require("./MediaStream.js");
  666. var DesktopSharingEventTypes
  667. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  668. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  669. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  670. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  671. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  672. var UIEvents = require("../../service/UI/UIEvents");
  673. var eventEmitter = new EventEmitter();
  674. function getMediaStreamUsage()
  675. {
  676. var result = {
  677. audio: true,
  678. video: true
  679. };
  680. /** There are some issues with the desktop sharing
  681. * when this property is enabled.
  682. * WARNING: We must change the implementation to start video/audio if we
  683. * receive from the focus that the peer is not muted.
  684. var isSecureConnection = window.location.protocol == "https:";
  685. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  686. {
  687. result = {
  688. audio: false,
  689. video: false
  690. };
  691. }
  692. **/
  693. return result;
  694. }
  695. var RTC = {
  696. rtcUtils: null,
  697. devices: {
  698. audio: true,
  699. video: true
  700. },
  701. localStreams: [],
  702. remoteStreams: {},
  703. localAudio: null,
  704. localVideo: null,
  705. addStreamListener: function (listener, eventType) {
  706. eventEmitter.on(eventType, listener);
  707. },
  708. addListener: function (type, listener) {
  709. eventEmitter.on(type, listener);
  710. },
  711. removeStreamListener: function (listener, eventType) {
  712. if(!(eventType instanceof StreamEventTypes))
  713. throw "Illegal argument";
  714. eventEmitter.removeListener(eventType, listener);
  715. },
  716. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  717. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  718. //in firefox we have only one stream object
  719. if(this.localStreams.length == 0 ||
  720. this.localStreams[0].getOriginalStream() != stream)
  721. this.localStreams.push(localStream);
  722. if(isMuted === true)
  723. localStream.setMute(true);
  724. if(type == "audio") {
  725. this.localAudio = localStream;
  726. } else {
  727. this.localVideo = localStream;
  728. }
  729. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  730. if(change)
  731. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  732. eventEmitter.emit(eventType, localStream, isMuted);
  733. return localStream;
  734. },
  735. removeLocalStream: function (stream) {
  736. for(var i = 0; i < this.localStreams.length; i++) {
  737. if(this.localStreams[i].getOriginalStream() === stream) {
  738. delete this.localStreams[i];
  739. return;
  740. }
  741. }
  742. },
  743. createRemoteStream: function (data, sid, thessrc) {
  744. var remoteStream = new MediaStream(data, sid, thessrc,
  745. RTCBrowserType.getBrowserType(), eventEmitter);
  746. var jid = data.peerjid || APP.xmpp.myJid();
  747. if(!this.remoteStreams[jid]) {
  748. this.remoteStreams[jid] = {};
  749. }
  750. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  751. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  752. return remoteStream;
  753. },
  754. getPCConstraints: function () {
  755. return this.rtcUtils.pc_constraints;
  756. },
  757. getUserMediaWithConstraints:function(um, success_callback,
  758. failure_callback, resolution,
  759. bandwidth, fps, desktopStream)
  760. {
  761. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  762. failure_callback, resolution, bandwidth, fps, desktopStream);
  763. },
  764. attachMediaStream: function (elSelector, stream) {
  765. this.rtcUtils.attachMediaStream(elSelector, stream);
  766. },
  767. getStreamID: function (stream) {
  768. return this.rtcUtils.getStreamID(stream);
  769. },
  770. getVideoSrc: function (element) {
  771. return this.rtcUtils.getVideoSrc(element);
  772. },
  773. setVideoSrc: function (element, src) {
  774. this.rtcUtils.setVideoSrc(element, src);
  775. },
  776. getVideoElementName: function () {
  777. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  778. },
  779. dispose: function() {
  780. if (this.rtcUtils) {
  781. this.rtcUtils = null;
  782. }
  783. },
  784. stop: function () {
  785. this.dispose();
  786. },
  787. start: function () {
  788. var self = this;
  789. APP.desktopsharing.addListener(
  790. function (stream, isUsingScreenStream, callback) {
  791. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  792. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  793. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  794. DataChannels.init(event.peerconnection, eventEmitter);
  795. });
  796. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  797. DataChannels.handleSelectedEndpointEvent);
  798. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  799. DataChannels.handlePinnedEndpointEvent);
  800. // In case of IE we continue from 'onReady' callback
  801. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  802. // once it is initialized.
  803. var onReady = function () {
  804. eventEmitter.emit(RTCEvents.RTC_READY, true);
  805. self.rtcUtils.obtainAudioAndVideoPermissions(
  806. null, null, getMediaStreamUsage());
  807. };
  808. this.rtcUtils = new RTCUtils(this, onReady);
  809. // Call onReady() if Temasys plugin is not used
  810. if (!RTCBrowserType.isTemasysPluginUsed()) {
  811. onReady();
  812. }
  813. },
  814. muteRemoteVideoStream: function (jid, value) {
  815. var stream;
  816. if(this.remoteStreams[jid] &&
  817. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  818. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  819. }
  820. if(!stream)
  821. return true;
  822. if (value != stream.muted) {
  823. stream.setMute(value);
  824. return true;
  825. }
  826. return false;
  827. },
  828. switchVideoStreams: function (new_stream) {
  829. this.localVideo.stream = new_stream;
  830. this.localStreams = [];
  831. //in firefox we have only one stream object
  832. if (this.localAudio.getOriginalStream() != new_stream)
  833. this.localStreams.push(this.localAudio);
  834. this.localStreams.push(this.localVideo);
  835. },
  836. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  837. var oldStream = this.localVideo.getOriginalStream();
  838. var type = (isUsingScreenStream ? "screen" : "camera");
  839. var localCallback = callback;
  840. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  841. localCallback = function() {
  842. APP.xmpp.setVideoMute(false, function(mute) {
  843. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  844. });
  845. callback();
  846. };
  847. }
  848. // FIXME: Workaround for FF/IE/Safari
  849. if (stream && stream.videoStream) {
  850. stream = stream.videoStream;
  851. }
  852. var videoStream = this.rtcUtils.createStream(stream, true);
  853. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  854. // Stop the stream to trigger onended event for old stream
  855. oldStream.stop();
  856. this.switchVideoStreams(videoStream, oldStream);
  857. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  858. },
  859. changeLocalAudio: function (stream, callback) {
  860. var oldStream = this.localAudio.getOriginalStream();
  861. var newStream = this.rtcUtils.createStream(stream);
  862. this.localAudio = this.createLocalStream(newStream, "audio", true);
  863. // Stop the stream to trigger onended event for old stream
  864. oldStream.stop();
  865. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  866. },
  867. isVideoMuted: function (jid) {
  868. if (jid === APP.xmpp.myJid()) {
  869. var localVideo = APP.RTC.localVideo;
  870. return (!localVideo || localVideo.isMuted());
  871. } else {
  872. if (!APP.RTC.remoteStreams[jid] ||
  873. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  874. return null;
  875. }
  876. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  877. }
  878. },
  879. setVideoMute: function (mute, callback, options) {
  880. if (!this.localVideo)
  881. return;
  882. if (mute == APP.RTC.localVideo.isMuted())
  883. {
  884. APP.xmpp.sendVideoInfoPresence(mute);
  885. if (callback)
  886. callback(mute);
  887. }
  888. else
  889. {
  890. APP.RTC.localVideo.setMute(mute);
  891. APP.xmpp.setVideoMute(
  892. mute,
  893. callback,
  894. options);
  895. }
  896. },
  897. setDeviceAvailability: function (devices) {
  898. if(!devices)
  899. return;
  900. if(devices.audio === true || devices.audio === false)
  901. this.devices.audio = devices.audio;
  902. if(devices.video === true || devices.video === false)
  903. this.devices.video = devices.video;
  904. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  905. }
  906. };
  907. module.exports = RTC;
  908. },{"../../service/RTC/MediaStreamTypes":39,"../../service/RTC/RTCEvents.js":40,"../../service/RTC/StreamEventTypes.js":42,"../../service/UI/UIEvents":43,"../../service/desktopsharing/DesktopSharingEventTypes":45,"../../service/xmpp/XMPPEvents":46,"./DataChannels":8,"./LocalStream.js":9,"./MediaStream.js":10,"./RTCBrowserType":12,"./RTCUtils.js":13,"events":47}],12:[function(require,module,exports){
  909. var currentBrowser;
  910. var browserVersion;
  911. var RTCBrowserType = {
  912. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  913. RTC_BROWSER_OPERA: "rtc_browser.opera",
  914. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  915. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  916. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  917. getBrowserType: function () {
  918. return currentBrowser;
  919. },
  920. isChrome: function () {
  921. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  922. },
  923. isOpera: function () {
  924. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  925. },
  926. isFirefox: function () {
  927. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  928. },
  929. isIExplorer: function () {
  930. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  931. },
  932. isSafari: function () {
  933. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  934. },
  935. isTemasysPluginUsed: function () {
  936. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  937. },
  938. getFirefoxVersion: function () {
  939. return RTCBrowserType.isFirefox() ? browserVersion : null;
  940. },
  941. getChromeVersion: function () {
  942. return RTCBrowserType.isChrome() ? browserVersion : null;
  943. },
  944. usesPlanB: function() {
  945. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  946. RTCBrowserType.isTemasysPluginUsed();
  947. },
  948. usesUnifiedPlan: function() {
  949. return RTCBrowserType.isFirefox();
  950. }
  951. // Add version getters for other browsers when needed
  952. };
  953. // detectOpera() must be called before detectChrome() !!!
  954. // otherwise Opera wil be detected as Chrome
  955. function detectChrome() {
  956. if (navigator.webkitGetUserMedia) {
  957. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  958. var userAgent = navigator.userAgent.toLowerCase();
  959. // We can assume that user agent is chrome, because it's
  960. // enforced when 'ext' streaming method is set
  961. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  962. console.log("This appears to be Chrome, ver: " + ver);
  963. return ver;
  964. }
  965. return null;
  966. }
  967. function detectOpera() {
  968. var userAgent = navigator.userAgent;
  969. if (userAgent.match(/Opera|OPR/)) {
  970. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  971. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  972. console.info("This appears to be Opera, ver: " + version);
  973. return version;
  974. }
  975. return null;
  976. }
  977. function detectFirefox() {
  978. if (navigator.mozGetUserMedia) {
  979. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  980. var version = parseInt(
  981. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  982. console.log('This appears to be Firefox, ver: ' + version);
  983. return version;
  984. }
  985. return null;
  986. }
  987. function detectSafari() {
  988. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  989. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  990. console.info("This appears to be Safari");
  991. // FIXME detect Safari version when needed
  992. return 1;
  993. }
  994. return null;
  995. }
  996. function detectIE() {
  997. var version;
  998. var ua = window.navigator.userAgent;
  999. var msie = ua.indexOf('MSIE ');
  1000. if (msie > 0) {
  1001. // IE 10 or older => return version number
  1002. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1003. }
  1004. var trident = ua.indexOf('Trident/');
  1005. if (!version && trident > 0) {
  1006. // IE 11 => return version number
  1007. var rv = ua.indexOf('rv:');
  1008. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1009. }
  1010. var edge = ua.indexOf('Edge/');
  1011. if (!version && edge > 0) {
  1012. // IE 12 => return version number
  1013. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1014. }
  1015. if (version) {
  1016. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1017. console.info("This appears to be IExplorer, ver: " + version);
  1018. }
  1019. return version;
  1020. }
  1021. function detectBrowser() {
  1022. var version;
  1023. var detectors = [
  1024. detectOpera,
  1025. detectChrome,
  1026. detectFirefox,
  1027. detectIE,
  1028. detectSafari
  1029. ];
  1030. // Try all browser detectors
  1031. for (var i = 0; i < detectors.length; i++) {
  1032. version = detectors[i]();
  1033. if (version)
  1034. return version;
  1035. }
  1036. console.error("Failed to detect browser type");
  1037. return undefined;
  1038. }
  1039. browserVersion = detectBrowser();
  1040. module.exports = RTCBrowserType;
  1041. },{}],13:[function(require,module,exports){
  1042. /* global config, require, attachMediaStream, getUserMedia */
  1043. var RTCBrowserType = require("./RTCBrowserType");
  1044. var Resolutions = require("../../service/RTC/Resolutions");
  1045. var AdapterJS = require("./adapter.screenshare");
  1046. var SDPUtil = require("../xmpp/SDPUtil");
  1047. var currentResolution = null;
  1048. function getPreviousResolution(resolution) {
  1049. if(!Resolutions[resolution])
  1050. return null;
  1051. var order = Resolutions[resolution].order;
  1052. var res = null;
  1053. var resName = null;
  1054. for(var i in Resolutions) {
  1055. var tmp = Resolutions[i];
  1056. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1057. resName = i;
  1058. res = tmp;
  1059. }
  1060. }
  1061. return resName;
  1062. }
  1063. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1064. if (Resolutions[resolution]) {
  1065. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1066. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1067. }
  1068. else if (isAndroid) {
  1069. // FIXME can't remember if the purpose of this was to always request
  1070. // low resolution on Android ? if yes it should be moved up front
  1071. constraints.video.mandatory.minWidth = 320;
  1072. constraints.video.mandatory.minHeight = 240;
  1073. constraints.video.mandatory.maxFrameRate = 15;
  1074. }
  1075. if (constraints.video.mandatory.minWidth)
  1076. constraints.video.mandatory.maxWidth =
  1077. constraints.video.mandatory.minWidth;
  1078. if (constraints.video.mandatory.minHeight)
  1079. constraints.video.mandatory.maxHeight =
  1080. constraints.video.mandatory.minHeight;
  1081. }
  1082. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1083. {
  1084. var constraints = {audio: false, video: false};
  1085. if (um.indexOf('video') >= 0) {
  1086. // same behaviour as true
  1087. constraints.video = { mandatory: {}, optional: [] };
  1088. constraints.video.optional.push({ googLeakyBucket: true });
  1089. setResolutionConstraints(constraints, resolution, isAndroid);
  1090. }
  1091. if (um.indexOf('audio') >= 0) {
  1092. if (!RTCBrowserType.isFirefox()) {
  1093. // same behaviour as true
  1094. constraints.audio = { mandatory: {}, optional: []};
  1095. // if it is good enough for hangouts...
  1096. constraints.audio.optional.push(
  1097. {googEchoCancellation: true},
  1098. {googAutoGainControl: true},
  1099. {googNoiseSupression: true},
  1100. {googHighpassFilter: true},
  1101. {googNoisesuppression2: true},
  1102. {googEchoCancellation2: true},
  1103. {googAutoGainControl2: true}
  1104. );
  1105. } else {
  1106. constraints.audio = true;
  1107. }
  1108. }
  1109. if (um.indexOf('screen') >= 0) {
  1110. if (RTCBrowserType.isChrome()) {
  1111. constraints.video = {
  1112. mandatory: {
  1113. chromeMediaSource: "screen",
  1114. googLeakyBucket: true,
  1115. maxWidth: window.screen.width,
  1116. maxHeight: window.screen.height,
  1117. maxFrameRate: 3
  1118. },
  1119. optional: []
  1120. };
  1121. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1122. constraints.video = {
  1123. optional: [
  1124. {
  1125. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1126. }
  1127. ]
  1128. };
  1129. } else {
  1130. console.error(
  1131. "'screen' WebRTC media source is supported only in Chrome" +
  1132. " and with Temasys plugin");
  1133. }
  1134. }
  1135. if (um.indexOf('desktop') >= 0) {
  1136. constraints.video = {
  1137. mandatory: {
  1138. chromeMediaSource: "desktop",
  1139. chromeMediaSourceId: desktopStream,
  1140. googLeakyBucket: true,
  1141. maxWidth: window.screen.width,
  1142. maxHeight: window.screen.height,
  1143. maxFrameRate: 3
  1144. },
  1145. optional: []
  1146. };
  1147. }
  1148. if (bandwidth) {
  1149. if (!constraints.video) {
  1150. //same behaviour as true
  1151. constraints.video = {mandatory: {}, optional: []};
  1152. }
  1153. constraints.video.optional.push({bandwidth: bandwidth});
  1154. }
  1155. if (fps) {
  1156. // for some cameras it might be necessary to request 30fps
  1157. // so they choose 30fps mjpg over 10fps yuy2
  1158. if (!constraints.video) {
  1159. // same behaviour as true;
  1160. constraints.video = {mandatory: {}, optional: []};
  1161. }
  1162. constraints.video.mandatory.minFrameRate = fps;
  1163. }
  1164. return constraints;
  1165. }
  1166. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1167. function RTCUtils(RTCService, onTemasysPluginReady, options)
  1168. {
  1169. var self = this;
  1170. this.service = RTCService;
  1171. if (RTCBrowserType.isFirefox()) {
  1172. var FFversion = RTCBrowserType.getFirefoxVersion();
  1173. if (FFversion >= 40) {
  1174. this.peerconnection = mozRTCPeerConnection;
  1175. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1176. this.pc_constraints = {};
  1177. this.attachMediaStream = function (element, stream) {
  1178. // srcObject is being standardized and FF will eventually
  1179. // support that unprefixed. FF also supports the
  1180. // "element.src = URL.createObjectURL(...)" combo, but that
  1181. // will be deprecated in favour of srcObject.
  1182. //
  1183. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1184. // https://github.com/webrtc/samples/issues/302
  1185. if(!element[0])
  1186. return;
  1187. element[0].mozSrcObject = stream;
  1188. element[0].play();
  1189. };
  1190. this.getStreamID = function (stream) {
  1191. var id = stream.id;
  1192. if (!id) {
  1193. var tracks = stream.getVideoTracks();
  1194. if (!tracks || tracks.length === 0) {
  1195. tracks = stream.getAudioTracks();
  1196. }
  1197. id = tracks[0].id;
  1198. }
  1199. return SDPUtil.filter_special_chars(id);
  1200. };
  1201. this.getVideoSrc = function (element) {
  1202. if(!element)
  1203. return null;
  1204. return element.mozSrcObject;
  1205. };
  1206. this.setVideoSrc = function (element, src) {
  1207. if(element)
  1208. element.mozSrcObject = src;
  1209. };
  1210. RTCSessionDescription = mozRTCSessionDescription;
  1211. RTCIceCandidate = mozRTCIceCandidate;
  1212. } else {
  1213. console.error(
  1214. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1215. window.location.href = 'unsupported_browser.html';
  1216. return;
  1217. }
  1218. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1219. this.peerconnection = webkitRTCPeerConnection;
  1220. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1221. this.attachMediaStream = function (element, stream) {
  1222. element.attr('src', webkitURL.createObjectURL(stream));
  1223. };
  1224. this.getStreamID = function (stream) {
  1225. // streams from FF endpoints have the characters '{' and '}'
  1226. // that make jQuery choke.
  1227. return SDPUtil.filter_special_chars(stream.id);
  1228. };
  1229. this.getVideoSrc = function (element) {
  1230. if(!element)
  1231. return null;
  1232. return element.getAttribute("src");
  1233. };
  1234. this.setVideoSrc = function (element, src) {
  1235. if(element)
  1236. element.setAttribute("src", src);
  1237. };
  1238. // DTLS should now be enabled by default but..
  1239. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1240. if (options.useIPv6) {
  1241. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1242. this.pc_constraints.optional.push({googIPv6: true});
  1243. }
  1244. if (navigator.userAgent.indexOf('Android') != -1) {
  1245. this.pc_constraints = {}; // disable DTLS on Android
  1246. }
  1247. if (!webkitMediaStream.prototype.getVideoTracks) {
  1248. webkitMediaStream.prototype.getVideoTracks = function () {
  1249. return this.videoTracks;
  1250. };
  1251. }
  1252. if (!webkitMediaStream.prototype.getAudioTracks) {
  1253. webkitMediaStream.prototype.getAudioTracks = function () {
  1254. return this.audioTracks;
  1255. };
  1256. }
  1257. }
  1258. // Detect IE/Safari
  1259. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1260. //AdapterJS.WebRTCPlugin.setLogLevel(
  1261. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1262. AdapterJS.webRTCReady(function (isPlugin) {
  1263. self.peerconnection = RTCPeerConnection;
  1264. self.getUserMedia = getUserMedia;
  1265. self.attachMediaStream = function (elSel, stream) {
  1266. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1267. return;
  1268. }
  1269. attachMediaStream(elSel[0], stream);
  1270. };
  1271. self.getStreamID = function (stream) {
  1272. var id = SDPUtil.filter_special_chars(stream.label);
  1273. return id;
  1274. };
  1275. self.getVideoSrc = function (element) {
  1276. if (!element) {
  1277. console.warn("Attempt to get video SRC of null element");
  1278. return null;
  1279. }
  1280. var children = element.children;
  1281. for (var i = 0; i !== children.length; ++i) {
  1282. if (children[i].name === 'streamId') {
  1283. return children[i].value;
  1284. }
  1285. }
  1286. //console.info(element.id + " SRC: " + src);
  1287. return null;
  1288. };
  1289. self.setVideoSrc = function (element, src) {
  1290. //console.info("Set video src: ", element, src);
  1291. if (!src) {
  1292. console.warn("Not attaching video stream, 'src' is null");
  1293. return;
  1294. }
  1295. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1296. var stream = AdapterJS.WebRTCPlugin.plugin
  1297. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1298. attachMediaStream(element, stream);
  1299. };
  1300. onTemasysPluginReady(isPlugin);
  1301. });
  1302. } else {
  1303. try {
  1304. console.log('Browser does not appear to be WebRTC-capable');
  1305. } catch (e) { }
  1306. window.location.href = 'unsupported_browser.html';
  1307. }
  1308. }
  1309. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1310. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1311. desktopStream) {
  1312. currentResolution = resolution;
  1313. // Check if we are running on Android device
  1314. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1315. var constraints = getConstraints(
  1316. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1317. console.info("Get media constraints", constraints);
  1318. var self = this;
  1319. try {
  1320. this.getUserMedia(constraints,
  1321. function (stream) {
  1322. console.log('onUserMediaSuccess');
  1323. self.setAvailableDevices(um, true);
  1324. success_callback(stream);
  1325. },
  1326. function (error) {
  1327. self.setAvailableDevices(um, false);
  1328. console.warn('Failed to get access to local media. Error ',
  1329. error, constraints);
  1330. if (failure_callback) {
  1331. failure_callback(error);
  1332. }
  1333. });
  1334. } catch (e) {
  1335. console.error('GUM failed: ', e);
  1336. if(failure_callback) {
  1337. failure_callback(e);
  1338. }
  1339. }
  1340. };
  1341. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1342. var devices = {};
  1343. if(um.indexOf("video") != -1) {
  1344. devices.video = available;
  1345. }
  1346. if(um.indexOf("audio") != -1) {
  1347. devices.audio = available;
  1348. }
  1349. this.service.setDeviceAvailability(devices);
  1350. };
  1351. /**
  1352. * We ask for audio and video combined stream in order to get permissions and
  1353. * not to ask twice.
  1354. */
  1355. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1356. function(devices, callback, usageOptions)
  1357. {
  1358. var self = this;
  1359. // Get AV
  1360. var successCallback = function (stream) {
  1361. if(callback)
  1362. callback(stream, usageOptions);
  1363. else
  1364. self.successCallback(stream, usageOptions);
  1365. };
  1366. if(!devices)
  1367. devices = ['audio', 'video'];
  1368. var newDevices = [];
  1369. if(usageOptions)
  1370. for(var i = 0; i < devices.length; i++) {
  1371. var device = devices[i];
  1372. if(usageOptions[device] === true)
  1373. newDevices.push(device);
  1374. }
  1375. else
  1376. newDevices = devices;
  1377. if(newDevices.length === 0) {
  1378. successCallback();
  1379. return;
  1380. }
  1381. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1382. // With FF/IE we can't split the stream into audio and video because FF
  1383. // doesn't support media stream constructors. So, we need to get the
  1384. // audio stream separately from the video stream using two distinct GUM
  1385. // calls. Not very user friendly :-( but we don't have many other
  1386. // options neither.
  1387. //
  1388. // Note that we pack those 2 streams in a single object and pass it to
  1389. // the successCallback method.
  1390. var obtainVideo = function (audioStream) {
  1391. self.getUserMediaWithConstraints(
  1392. ['video'],
  1393. function (videoStream) {
  1394. return successCallback({
  1395. audioStream: audioStream,
  1396. videoStream: videoStream
  1397. });
  1398. },
  1399. function (error) {
  1400. console.error(
  1401. 'failed to obtain video stream - stop', error);
  1402. self.errorCallback(error);
  1403. },
  1404. config.resolution || '360');
  1405. };
  1406. var obtainAudio = function () {
  1407. self.getUserMediaWithConstraints(
  1408. ['audio'],
  1409. function (audioStream) {
  1410. if (newDevices.indexOf('video') !== -1)
  1411. obtainVideo(audioStream);
  1412. },
  1413. function (error) {
  1414. console.error(
  1415. 'failed to obtain audio stream - stop', error);
  1416. self.errorCallback(error);
  1417. }
  1418. );
  1419. };
  1420. if (newDevices.indexOf('audio') !== -1) {
  1421. obtainAudio();
  1422. } else {
  1423. obtainVideo(null);
  1424. }
  1425. } else {
  1426. this.getUserMediaWithConstraints(
  1427. newDevices,
  1428. function (stream) {
  1429. successCallback(stream);
  1430. },
  1431. function (error) {
  1432. self.errorCallback(error);
  1433. },
  1434. config.resolution || '360');
  1435. }
  1436. };
  1437. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1438. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1439. // it's an object with two properties: audioStream, videoStream.
  1440. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1441. console.log('got', stream, stream.getAudioTracks().length,
  1442. stream.getVideoTracks().length);
  1443. this.handleLocalStream(stream, usageOptions);
  1444. };
  1445. RTCUtils.prototype.errorCallback = function (error) {
  1446. var self = this;
  1447. console.error('failed to obtain audio/video stream - trying audio only', error);
  1448. var resolution = getPreviousResolution(currentResolution);
  1449. if(typeof error == "object" && error.constraintName && error.name
  1450. && (error.name == "ConstraintNotSatisfiedError" ||
  1451. error.name == "OverconstrainedError") &&
  1452. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1453. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1454. && resolution != null)
  1455. {
  1456. self.getUserMediaWithConstraints(['audio', 'video'],
  1457. function (stream) {
  1458. return self.successCallback(stream);
  1459. }, function (error) {
  1460. return self.errorCallback(error);
  1461. }, resolution);
  1462. }
  1463. else {
  1464. self.getUserMediaWithConstraints(
  1465. ['audio'],
  1466. function (stream) {
  1467. return self.successCallback(stream);
  1468. },
  1469. function (error) {
  1470. console.error('failed to obtain audio/video stream - stop',
  1471. error);
  1472. return self.successCallback(null);
  1473. }
  1474. );
  1475. }
  1476. };
  1477. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1478. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1479. // an object with two properties: audioStream, videoStream.
  1480. var audioStream, videoStream;
  1481. if(window.webkitMediaStream)
  1482. {
  1483. audioStream = new webkitMediaStream();
  1484. videoStream = new webkitMediaStream();
  1485. if(stream) {
  1486. var audioTracks = stream.getAudioTracks();
  1487. for (var i = 0; i < audioTracks.length; i++) {
  1488. audioStream.addTrack(audioTracks[i]);
  1489. }
  1490. var videoTracks = stream.getVideoTracks();
  1491. for (i = 0; i < videoTracks.length; i++) {
  1492. videoStream.addTrack(videoTracks[i]);
  1493. }
  1494. }
  1495. }
  1496. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1497. { // Firefox and Temasys plugin
  1498. if (stream && stream.audioStream)
  1499. audioStream = stream.audioStream;
  1500. else
  1501. audioStream = new DummyMediaStream("dummyAudio");
  1502. if (stream && stream.videoStream)
  1503. videoStream = stream.videoStream;
  1504. else
  1505. videoStream = new DummyMediaStream("dummyVideo");
  1506. }
  1507. var audioMuted = (usageOptions && usageOptions.audio === false),
  1508. videoMuted = (usageOptions && usageOptions.video === false);
  1509. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1510. videoGUM = (!usageOptions || usageOptions.video !== false);
  1511. this.service.createLocalStream(audioStream, "audio", null, null,
  1512. audioMuted, audioGUM);
  1513. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1514. videoMuted, videoGUM);
  1515. };
  1516. function DummyMediaStream(id) {
  1517. this.id = id;
  1518. this.label = id;
  1519. this.stop = function() { };
  1520. this.getAudioTracks = function() { return []; };
  1521. this.getVideoTracks = function() { return []; };
  1522. }
  1523. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1524. var newStream = null;
  1525. if (window.webkitMediaStream) {
  1526. newStream = new webkitMediaStream();
  1527. if (newStream) {
  1528. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1529. for (var i = 0; i < tracks.length; i++) {
  1530. newStream.addTrack(tracks[i]);
  1531. }
  1532. }
  1533. }
  1534. else {
  1535. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1536. if (stream) {
  1537. newStream = stream;
  1538. } else {
  1539. newStream =
  1540. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1541. }
  1542. }
  1543. return newStream;
  1544. };
  1545. module.exports = RTCUtils;
  1546. },{"../../service/RTC/Resolutions":41,"../xmpp/SDPUtil":16,"./RTCBrowserType":12,"./adapter.screenshare":14}],14:[function(require,module,exports){
  1547. /*! adapterjs - custom version from - 2015-08-12 */
  1548. // Adapter's interface.
  1549. var AdapterJS = AdapterJS || {};
  1550. // Browserify compatibility
  1551. if(typeof exports !== 'undefined') {
  1552. module.exports = AdapterJS;
  1553. }
  1554. AdapterJS.options = AdapterJS.options || {};
  1555. // uncomment to get virtual webcams
  1556. // AdapterJS.options.getAllCams = true;
  1557. // uncomment to prevent the install prompt when the plugin in not yet installed
  1558. // AdapterJS.options.hidePluginInstallPrompt = true;
  1559. // AdapterJS version
  1560. AdapterJS.VERSION = '0.11.1';
  1561. // This function will be called when the WebRTC API is ready to be used
  1562. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1563. // the plugin
  1564. // You may Override this function to synchronise the start of your application
  1565. // with the WebRTC API being ready.
  1566. // If you decide not to override use this synchronisation, it may result in
  1567. // an extensive CPU usage on the plugin start (once per tab loaded)
  1568. // Params:
  1569. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1570. //
  1571. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1572. // The WebRTC API is ready.
  1573. // Override me and do whatever you want here
  1574. };
  1575. // Sets a callback function to be called when the WebRTC interface is ready.
  1576. // The first argument is the function to callback.\
  1577. // Throws an error if the first argument is not a function
  1578. AdapterJS.webRTCReady = function (callback) {
  1579. if (typeof callback !== 'function') {
  1580. throw new Error('Callback provided is not a function');
  1581. }
  1582. if (true === AdapterJS.onwebrtcreadyDone) {
  1583. // All WebRTC interfaces are ready, just call the callback
  1584. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1585. } else {
  1586. // will be triggered automatically when your browser/plugin is ready.
  1587. AdapterJS.onwebrtcready = callback;
  1588. }
  1589. };
  1590. // Plugin namespace
  1591. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1592. // The object to store plugin information
  1593. AdapterJS.WebRTCPlugin.pluginInfo = {
  1594. prefix : 'Tem',
  1595. plugName : 'TemWebRTCPlugin',
  1596. pluginId : 'plugin0',
  1597. type : 'application/x-temwebrtcplugin',
  1598. onload : '__TemWebRTCReady0',
  1599. portalLink : 'http://skylink.io/plugin/',
  1600. downloadLink : null, //set below
  1601. companyName: 'Temasys'
  1602. };
  1603. if(!!navigator.platform.match(/^Mac/i)) {
  1604. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1605. }
  1606. else if(!!navigator.platform.match(/^Win/i)) {
  1607. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1608. }
  1609. // Unique identifier of each opened page
  1610. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1611. // Use this whenever you want to call the plugin.
  1612. AdapterJS.WebRTCPlugin.plugin = null;
  1613. // Set log level for the plugin once it is ready.
  1614. // The different values are
  1615. // This is an asynchronous function that will run when the plugin is ready
  1616. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1617. // Defines webrtc's JS interface according to the plugin's implementation.
  1618. // Define plugin Browsers as WebRTC Interface.
  1619. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1620. // This function detects whether or not a plugin is installed.
  1621. // Checks if Not IE (firefox, for example), else if it's IE,
  1622. // we're running IE and do something. If not it is not supported.
  1623. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1624. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1625. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1626. // Inject the HTML DOM object element into the page.
  1627. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1628. // States of readiness that the plugin goes through when
  1629. // being injected and stated
  1630. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1631. NONE : 0, // no plugin use
  1632. INITIALIZING : 1, // Detected need for plugin
  1633. INJECTING : 2, // Injecting plugin
  1634. INJECTED: 3, // Plugin element injected but not usable yet
  1635. READY: 4 // Plugin ready to be used
  1636. };
  1637. // Current state of the plugin. You cannot use the plugin before this is
  1638. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1639. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1640. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1641. // Used to make sure AdapterJS.onwebrtcready is only called once
  1642. AdapterJS.onwebrtcreadyDone = false;
  1643. // Log levels for the plugin.
  1644. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1645. /*
  1646. Log outputs are prefixed in some cases.
  1647. INFO: Information reported by the plugin.
  1648. ERROR: Errors originating from within the plugin.
  1649. WEBRTC: Error originating from within the libWebRTC library
  1650. */
  1651. // From the least verbose to the most verbose
  1652. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1653. NONE : 'NONE',
  1654. ERROR : 'ERROR',
  1655. WARNING : 'WARNING',
  1656. INFO: 'INFO',
  1657. VERBOSE: 'VERBOSE',
  1658. SENSITIVE: 'SENSITIVE'
  1659. };
  1660. // Does a waiting check before proceeding to load the plugin.
  1661. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1662. // This methid will use an interval to wait for the plugin to be ready.
  1663. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1664. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1665. // This function will be called when plugin is ready. It sends necessary
  1666. // details to the plugin.
  1667. // The function will wait for the document to be ready and the set the
  1668. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1669. // indicating that it can start being requested.
  1670. // This function is not in the IE/Safari condition brackets so that
  1671. // TemPluginLoaded function might be called on Chrome/Firefox.
  1672. // This function is the only private function that is not encapsulated to
  1673. // allow the plugin method to be called.
  1674. __TemWebRTCReady0 = function () {
  1675. if (document.readyState === 'complete') {
  1676. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1677. AdapterJS.maybeThroughWebRTCReady();
  1678. } else {
  1679. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1680. if (document.readyState === 'complete') {
  1681. // TODO: update comments, we wait for the document to be ready
  1682. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1683. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1684. AdapterJS.maybeThroughWebRTCReady();
  1685. }
  1686. }, 100);
  1687. }
  1688. };
  1689. AdapterJS.maybeThroughWebRTCReady = function() {
  1690. if (!AdapterJS.onwebrtcreadyDone) {
  1691. AdapterJS.onwebrtcreadyDone = true;
  1692. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1693. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1694. }
  1695. }
  1696. };
  1697. // Text namespace
  1698. AdapterJS.TEXT = {
  1699. PLUGIN: {
  1700. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1701. 'to work on this browser.',
  1702. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1703. BUTTON: 'Install Now'
  1704. },
  1705. REFRESH: {
  1706. REQUIRE_REFRESH: 'Please refresh page',
  1707. BUTTON: 'Refresh Page'
  1708. }
  1709. };
  1710. // The result of ice connection states.
  1711. // - starting: Ice connection is starting.
  1712. // - checking: Ice connection is checking.
  1713. // - connected Ice connection is connected.
  1714. // - completed Ice connection is connected.
  1715. // - done Ice connection has been completed.
  1716. // - disconnected Ice connection has been disconnected.
  1717. // - failed Ice connection has failed.
  1718. // - closed Ice connection is closed.
  1719. AdapterJS._iceConnectionStates = {
  1720. starting : 'starting',
  1721. checking : 'checking',
  1722. connected : 'connected',
  1723. completed : 'connected',
  1724. done : 'completed',
  1725. disconnected : 'disconnected',
  1726. failed : 'failed',
  1727. closed : 'closed'
  1728. };
  1729. //The IceConnection states that has been fired for each peer.
  1730. AdapterJS._iceConnectionFiredStates = [];
  1731. // Check if WebRTC Interface is defined.
  1732. AdapterJS.isDefined = null;
  1733. // This function helps to retrieve the webrtc detected browser information.
  1734. // This sets:
  1735. // - webrtcDetectedBrowser: The browser agent name.
  1736. // - webrtcDetectedVersion: The browser version.
  1737. // - webrtcDetectedType: The types of webRTC support.
  1738. // - 'moz': Mozilla implementation of webRTC.
  1739. // - 'webkit': WebKit implementation of webRTC.
  1740. // - 'plugin': Using the plugin implementation.
  1741. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1742. var hasMatch, checkMatch = navigator.userAgent.match(
  1743. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1744. if (/trident/i.test(checkMatch[1])) {
  1745. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1746. webrtcDetectedBrowser = 'IE';
  1747. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1748. } else if (checkMatch[1] === 'Chrome') {
  1749. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1750. if (hasMatch !== null) {
  1751. webrtcDetectedBrowser = 'opera';
  1752. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1753. }
  1754. }
  1755. if (navigator.userAgent.indexOf('Safari')) {
  1756. if (typeof InstallTrigger !== 'undefined') {
  1757. webrtcDetectedBrowser = 'firefox';
  1758. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1759. webrtcDetectedBrowser = 'IE';
  1760. } else if (
  1761. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1762. webrtcDetectedBrowser = 'safari';
  1763. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1764. webrtcDetectedBrowser = 'opera';
  1765. } else if (!!window.chrome) {
  1766. webrtcDetectedBrowser = 'chrome';
  1767. }
  1768. }
  1769. if (!webrtcDetectedBrowser) {
  1770. webrtcDetectedVersion = checkMatch[1];
  1771. }
  1772. if (!webrtcDetectedVersion) {
  1773. try {
  1774. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1775. [navigator.appName, navigator.appVersion, '-?'];
  1776. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1777. checkMatch.splice(1, 1, hasMatch[1]);
  1778. }
  1779. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1780. } catch (error) { }
  1781. }
  1782. };
  1783. // To fix configuration as some browsers does not support
  1784. // the 'urls' attribute.
  1785. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1786. if (pcConfig === null) {
  1787. return;
  1788. }
  1789. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1790. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1791. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1792. delete pcConfig.iceServers[i].urls;
  1793. }
  1794. }
  1795. };
  1796. AdapterJS.addEvent = function(elem, evnt, func) {
  1797. if (elem.addEventListener) { // W3C DOM
  1798. elem.addEventListener(evnt, func, false);
  1799. } else if (elem.attachEvent) {// OLD IE DOM
  1800. elem.attachEvent('on'+evnt, func);
  1801. } else { // No much to do
  1802. elem[evnt] = func;
  1803. }
  1804. };
  1805. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1806. // only inject once the page is ready
  1807. if (document.readyState !== 'complete') {
  1808. return;
  1809. }
  1810. var w = window;
  1811. var i = document.createElement('iframe');
  1812. i.style.position = 'fixed';
  1813. i.style.top = '-41px';
  1814. i.style.left = 0;
  1815. i.style.right = 0;
  1816. i.style.width = '100%';
  1817. i.style.height = '40px';
  1818. i.style.backgroundColor = '#ffffe1';
  1819. i.style.border = 'none';
  1820. i.style.borderBottom = '1px solid #888888';
  1821. i.style.zIndex = '9999999';
  1822. if(typeof i.style.webkitTransition === 'string') {
  1823. i.style.webkitTransition = 'all .5s ease-out';
  1824. } else if(typeof i.style.transition === 'string') {
  1825. i.style.transition = 'all .5s ease-out';
  1826. }
  1827. document.body.appendChild(i);
  1828. c = (i.contentWindow) ? i.contentWindow :
  1829. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1830. c.document.open();
  1831. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1832. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1833. 'middle; cursor: default;">' + text + '</span>');
  1834. if(buttonText && buttonLink) {
  1835. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1836. c.document.close();
  1837. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1838. if (!!displayRefreshBar) {
  1839. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1840. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1841. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1842. }
  1843. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1844. e.preventDefault();
  1845. try {
  1846. event.cancelBubble = true;
  1847. } catch(error) { }
  1848. var pluginInstallInterval = setInterval(function(){
  1849. if(! isIE) {
  1850. navigator.plugins.refresh(false);
  1851. }
  1852. AdapterJS.WebRTCPlugin.isPluginInstalled(
  1853. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  1854. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  1855. function() {
  1856. clearInterval(pluginInstallInterval);
  1857. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  1858. },
  1859. function() { //Does nothing because not used here
  1860. });
  1861. } , 500);
  1862. });
  1863. }else {
  1864. c.document.close();
  1865. }
  1866. AdapterJS.addEvent(c.document, 'click', function() {
  1867. w.document.body.removeChild(i);
  1868. });
  1869. setTimeout(function() {
  1870. if(typeof i.style.webkitTransform === 'string') {
  1871. i.style.webkitTransform = 'translateY(40px)';
  1872. } else if(typeof i.style.transform === 'string') {
  1873. i.style.transform = 'translateY(40px)';
  1874. } else {
  1875. i.style.top = '0px';
  1876. }
  1877. }, 300);
  1878. };
  1879. // -----------------------------------------------------------
  1880. // Detected webrtc implementation. Types are:
  1881. // - 'moz': Mozilla implementation of webRTC.
  1882. // - 'webkit': WebKit implementation of webRTC.
  1883. // - 'plugin': Using the plugin implementation.
  1884. webrtcDetectedType = null;
  1885. // Detected webrtc datachannel support. Types are:
  1886. // - 'SCTP': SCTP datachannel support.
  1887. // - 'RTP': RTP datachannel support.
  1888. webrtcDetectedDCSupport = null;
  1889. // Set the settings for creating DataChannels, MediaStream for
  1890. // Cross-browser compability.
  1891. // - This is only for SCTP based support browsers.
  1892. // the 'urls' attribute.
  1893. checkMediaDataChannelSettings =
  1894. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1895. if (typeof callback !== 'function') {
  1896. return;
  1897. }
  1898. var beOfferer = true;
  1899. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1900. // Nightly version does not require MozDontOfferDataChannel for interop
  1901. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1902. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1903. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1904. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1905. // Resends an updated version of constraints for MozDataChannel to work
  1906. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1907. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1908. try {
  1909. delete constraints.mandatory.MozDontOfferDataChannel;
  1910. } catch (error) {
  1911. console.error('Failed deleting MozDontOfferDataChannel');
  1912. console.error(error);
  1913. }
  1914. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1915. constraints.mandatory.MozDontOfferDataChannel = true;
  1916. }
  1917. if (!isLocalFirefox) {
  1918. // temporary measure to remove Moz* constraints in non Firefox browsers
  1919. for (var prop in constraints.mandatory) {
  1920. if (constraints.mandatory.hasOwnProperty(prop)) {
  1921. if (prop.indexOf('Moz') !== -1) {
  1922. delete constraints.mandatory[prop];
  1923. }
  1924. }
  1925. }
  1926. }
  1927. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1928. // interopability of the media stream
  1929. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1930. beOfferer = false;
  1931. }
  1932. callback(beOfferer, constraints);
  1933. };
  1934. // Handles the differences for all browsers ice connection state output.
  1935. // - Tested outcomes are:
  1936. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1937. // - Chrome (answerer) : 'checking' > 'connected'
  1938. // - Firefox (offerer) : 'checking' > 'connected'
  1939. // - Firefox (answerer): 'checking' > 'connected'
  1940. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1941. if (typeof callback !== 'function') {
  1942. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1943. return;
  1944. }
  1945. peerId = (peerId) ? peerId : 'peer';
  1946. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1947. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1948. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1949. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1950. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1951. }
  1952. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1953. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1954. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1955. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1956. setTimeout(function () {
  1957. AdapterJS._iceConnectionFiredStates[peerId]
  1958. .push(AdapterJS._iceConnectionStates.done);
  1959. callback(AdapterJS._iceConnectionStates.done);
  1960. }, 1000);
  1961. }
  1962. callback(iceConnectionState);
  1963. }
  1964. return;
  1965. };
  1966. // Firefox:
  1967. // - Creates iceServer from the url for Firefox.
  1968. // - Create iceServer with stun url.
  1969. // - Create iceServer with turn url.
  1970. // - Ignore the transport parameter from TURN url for FF version <=27.
  1971. // - Return null for createIceServer if transport=tcp.
  1972. // - FF 27 and above supports transport parameters in TURN url,
  1973. // - So passing in the full url to create iceServer.
  1974. // Chrome:
  1975. // - Creates iceServer from the url for Chrome M33 and earlier.
  1976. // - Create iceServer with stun url.
  1977. // - Chrome M28 & above uses below TURN format.
  1978. // Plugin:
  1979. // - Creates Ice Server for Plugin Browsers
  1980. // - If Stun - Create iceServer with stun url.
  1981. // - Else - Create iceServer with turn url
  1982. // - This is a WebRTC Function
  1983. createIceServer = null;
  1984. // Firefox:
  1985. // - Creates IceServers for Firefox
  1986. // - Use .url for FireFox.
  1987. // - Multiple Urls support
  1988. // Chrome:
  1989. // - Creates iceServers from the urls for Chrome M34 and above.
  1990. // - .urls is supported since Chrome M34.
  1991. // - Multiple Urls support
  1992. // Plugin:
  1993. // - Creates Ice Servers for Plugin Browsers
  1994. // - Multiple Urls support
  1995. // - This is a WebRTC Function
  1996. createIceServers = null;
  1997. //------------------------------------------------------------
  1998. //The RTCPeerConnection object.
  1999. RTCPeerConnection = null;
  2000. // Creates RTCSessionDescription object for Plugin Browsers
  2001. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2002. RTCSessionDescription : null;
  2003. // Creates RTCIceCandidate object for Plugin Browsers
  2004. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2005. RTCIceCandidate : null;
  2006. // Get UserMedia (only difference is the prefix).
  2007. // Code from Adam Barth.
  2008. getUserMedia = null;
  2009. // Attach a media stream to an element.
  2010. attachMediaStream = null;
  2011. // Re-attach a media stream to an element.
  2012. reattachMediaStream = null;
  2013. // Detected browser agent name. Types are:
  2014. // - 'firefox': Firefox browser.
  2015. // - 'chrome': Chrome browser.
  2016. // - 'opera': Opera browser.
  2017. // - 'safari': Safari browser.
  2018. // - 'IE' - Internet Explorer browser.
  2019. webrtcDetectedBrowser = null;
  2020. // Detected browser version.
  2021. webrtcDetectedVersion = null;
  2022. // Check for browser types and react accordingly
  2023. if (navigator.mozGetUserMedia) {
  2024. webrtcDetectedBrowser = 'firefox';
  2025. webrtcDetectedVersion = parseInt(navigator
  2026. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2027. webrtcDetectedType = 'moz';
  2028. webrtcDetectedDCSupport = 'SCTP';
  2029. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2030. AdapterJS.maybeFixConfiguration(pcConfig);
  2031. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2032. };
  2033. // The RTCSessionDescription object.
  2034. RTCSessionDescription = mozRTCSessionDescription;
  2035. window.RTCSessionDescription = RTCSessionDescription;
  2036. // The RTCIceCandidate object.
  2037. RTCIceCandidate = mozRTCIceCandidate;
  2038. window.RTCIceCandidate = RTCIceCandidate;
  2039. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2040. navigator.getUserMedia = window.getUserMedia;
  2041. // Shim for MediaStreamTrack.getSources.
  2042. MediaStreamTrack.getSources = function(successCb) {
  2043. setTimeout(function() {
  2044. var infos = [
  2045. { kind: 'audio', id: 'default', label:'', facing:'' },
  2046. { kind: 'video', id: 'default', label:'', facing:'' }
  2047. ];
  2048. successCb(infos);
  2049. }, 0);
  2050. };
  2051. createIceServer = function (url, username, password) {
  2052. var iceServer = null;
  2053. var url_parts = url.split(':');
  2054. if (url_parts[0].indexOf('stun') === 0) {
  2055. iceServer = { url : url };
  2056. } else if (url_parts[0].indexOf('turn') === 0) {
  2057. if (webrtcDetectedVersion < 27) {
  2058. var turn_url_parts = url.split('?');
  2059. if (turn_url_parts.length === 1 ||
  2060. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2061. iceServer = {
  2062. url : turn_url_parts[0],
  2063. credential : password,
  2064. username : username
  2065. };
  2066. }
  2067. } else {
  2068. iceServer = {
  2069. url : url,
  2070. credential : password,
  2071. username : username
  2072. };
  2073. }
  2074. }
  2075. return iceServer;
  2076. };
  2077. createIceServers = function (urls, username, password) {
  2078. var iceServers = [];
  2079. for (i = 0; i < urls.length; i++) {
  2080. var iceServer = createIceServer(urls[i], username, password);
  2081. if (iceServer !== null) {
  2082. iceServers.push(iceServer);
  2083. }
  2084. }
  2085. return iceServers;
  2086. };
  2087. attachMediaStream = function (element, stream) {
  2088. element.mozSrcObject = stream;
  2089. if (stream !== null)
  2090. element.play();
  2091. return element;
  2092. };
  2093. reattachMediaStream = function (to, from) {
  2094. to.mozSrcObject = from.mozSrcObject;
  2095. to.play();
  2096. return to;
  2097. };
  2098. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2099. if (!callback) {
  2100. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2101. ': 1 argument required, but only 0 present.');
  2102. }
  2103. return callback([]);
  2104. };
  2105. // Fake get{Video,Audio}Tracks
  2106. if (!MediaStream.prototype.getVideoTracks) {
  2107. MediaStream.prototype.getVideoTracks = function () {
  2108. return [];
  2109. };
  2110. }
  2111. if (!MediaStream.prototype.getAudioTracks) {
  2112. MediaStream.prototype.getAudioTracks = function () {
  2113. return [];
  2114. };
  2115. }
  2116. AdapterJS.maybeThroughWebRTCReady();
  2117. } else if (navigator.webkitGetUserMedia) {
  2118. webrtcDetectedBrowser = 'chrome';
  2119. webrtcDetectedType = 'webkit';
  2120. webrtcDetectedVersion = parseInt(navigator
  2121. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2122. // check if browser is opera 20+
  2123. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2124. if (checkIfOpera !== null) {
  2125. webrtcDetectedBrowser = 'opera';
  2126. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2127. }
  2128. // check browser datachannel support
  2129. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2130. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2131. webrtcDetectedDCSupport = 'SCTP';
  2132. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2133. webrtcDetectedVersion > 24) {
  2134. webrtcDetectedDCSupport = 'RTP';
  2135. } else {
  2136. webrtcDetectedDCSupport = '';
  2137. }
  2138. createIceServer = function (url, username, password) {
  2139. var iceServer = null;
  2140. var url_parts = url.split(':');
  2141. if (url_parts[0].indexOf('stun') === 0) {
  2142. iceServer = { 'url' : url };
  2143. } else if (url_parts[0].indexOf('turn') === 0) {
  2144. iceServer = {
  2145. 'url' : url,
  2146. 'credential' : password,
  2147. 'username' : username
  2148. };
  2149. }
  2150. return iceServer;
  2151. };
  2152. createIceServers = function (urls, username, password) {
  2153. var iceServers = [];
  2154. if (webrtcDetectedVersion >= 34) {
  2155. iceServers = {
  2156. 'urls' : urls,
  2157. 'credential' : password,
  2158. 'username' : username
  2159. };
  2160. } else {
  2161. for (i = 0; i < urls.length; i++) {
  2162. var iceServer = createIceServer(urls[i], username, password);
  2163. if (iceServer !== null) {
  2164. iceServers.push(iceServer);
  2165. }
  2166. }
  2167. }
  2168. return iceServers;
  2169. };
  2170. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2171. if (webrtcDetectedVersion < 34) {
  2172. AdapterJS.maybeFixConfiguration(pcConfig);
  2173. }
  2174. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2175. };
  2176. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2177. navigator.getUserMedia = window.getUserMedia;
  2178. attachMediaStream = function (element, stream) {
  2179. if (typeof element.srcObject !== 'undefined') {
  2180. element.srcObject = stream;
  2181. } else if (typeof element.mozSrcObject !== 'undefined') {
  2182. element.mozSrcObject = stream;
  2183. } else if (typeof element.src !== 'undefined') {
  2184. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2185. } else {
  2186. console.log('Error attaching stream to element.');
  2187. }
  2188. return element;
  2189. };
  2190. reattachMediaStream = function (to, from) {
  2191. to.src = from.src;
  2192. return to;
  2193. };
  2194. AdapterJS.maybeThroughWebRTCReady();
  2195. } else { // TRY TO USE PLUGIN
  2196. // IE 9 is not offering an implementation of console.log until you open a console
  2197. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2198. /* jshint -W020 */
  2199. console = {} || console;
  2200. // Implemented based on console specs from MDN
  2201. // You may override these functions
  2202. console.log = function (arg) {};
  2203. console.info = function (arg) {};
  2204. console.error = function (arg) {};
  2205. console.dir = function (arg) {};
  2206. console.exception = function (arg) {};
  2207. console.trace = function (arg) {};
  2208. console.warn = function (arg) {};
  2209. console.count = function (arg) {};
  2210. console.debug = function (arg) {};
  2211. console.count = function (arg) {};
  2212. console.time = function (arg) {};
  2213. console.timeEnd = function (arg) {};
  2214. console.group = function (arg) {};
  2215. console.groupCollapsed = function (arg) {};
  2216. console.groupEnd = function (arg) {};
  2217. /* jshint +W020 */
  2218. }
  2219. webrtcDetectedType = 'plugin';
  2220. webrtcDetectedDCSupport = 'plugin';
  2221. AdapterJS.parseWebrtcDetectedBrowser();
  2222. isIE = webrtcDetectedBrowser === 'IE';
  2223. /* jshint -W035 */
  2224. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2225. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2226. /* empty because it needs to prevent the function from running. */
  2227. }
  2228. };
  2229. /* jshint +W035 */
  2230. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2231. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2232. // Call immediately if possible
  2233. // Once the plugin is set, the code will always take this path
  2234. callback();
  2235. } else {
  2236. // otherwise start a 100ms interval
  2237. var checkPluginReadyState = setInterval(function () {
  2238. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2239. clearInterval(checkPluginReadyState);
  2240. callback();
  2241. }
  2242. }, 100);
  2243. }
  2244. };
  2245. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2246. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2247. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2248. });
  2249. };
  2250. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2251. // only inject once the page is ready
  2252. if (document.readyState !== 'complete') {
  2253. return;
  2254. }
  2255. // Prevent multiple injections
  2256. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2257. return;
  2258. }
  2259. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2260. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2261. var frag = document.createDocumentFragment();
  2262. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2263. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2264. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2265. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2266. '<param name="pluginId" value="' +
  2267. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2268. '<param name="windowless" value="false" /> ' +
  2269. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2270. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2271. '" />' +
  2272. // uncomment to be able to use virtual cams
  2273. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2274. '</object>';
  2275. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2276. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2277. }
  2278. document.body.appendChild(frag);
  2279. // Need to re-fetch the plugin
  2280. AdapterJS.WebRTCPlugin.plugin =
  2281. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2282. } else {
  2283. // Load Plugin
  2284. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2285. AdapterJS.WebRTCPlugin.plugin.id =
  2286. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2287. // IE will only start the plugin if it's ACTUALLY visible
  2288. if (isIE) {
  2289. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2290. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2291. } else { // The size of the plugin on Safari should be 0x0px
  2292. // so that the autorisation prompt is at the top
  2293. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2294. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2295. }
  2296. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2297. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2298. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2299. '<param name="pluginId" value="' +
  2300. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2301. '<param name="windowless" value="false" /> ' +
  2302. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2303. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2304. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2305. }
  2306. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2307. };
  2308. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2309. function (comName, plugName, installedCb, notInstalledCb) {
  2310. if (!isIE) {
  2311. var pluginArray = navigator.plugins;
  2312. for (var i = 0; i < pluginArray.length; i++) {
  2313. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2314. installedCb();
  2315. return;
  2316. }
  2317. }
  2318. notInstalledCb();
  2319. } else {
  2320. try {
  2321. var axo = new ActiveXObject(comName + '.' + plugName);
  2322. } catch (e) {
  2323. notInstalledCb();
  2324. return;
  2325. }
  2326. installedCb();
  2327. }
  2328. };
  2329. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2330. if (AdapterJS.WebRTCPlugin.pluginState ===
  2331. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2332. console.error("WebRTC interface has been defined already");
  2333. return;
  2334. }
  2335. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2336. AdapterJS.isDefined = function (variable) {
  2337. return variable !== null && variable !== undefined;
  2338. };
  2339. createIceServer = function (url, username, password) {
  2340. var iceServer = null;
  2341. var url_parts = url.split(':');
  2342. if (url_parts[0].indexOf('stun') === 0) {
  2343. iceServer = {
  2344. 'url' : url,
  2345. 'hasCredentials' : false
  2346. };
  2347. } else if (url_parts[0].indexOf('turn') === 0) {
  2348. iceServer = {
  2349. 'url' : url,
  2350. 'hasCredentials' : true,
  2351. 'credential' : password,
  2352. 'username' : username
  2353. };
  2354. }
  2355. return iceServer;
  2356. };
  2357. createIceServers = function (urls, username, password) {
  2358. var iceServers = [];
  2359. for (var i = 0; i < urls.length; ++i) {
  2360. iceServers.push(createIceServer(urls[i], username, password));
  2361. }
  2362. return iceServers;
  2363. };
  2364. RTCSessionDescription = function (info) {
  2365. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2366. return AdapterJS.WebRTCPlugin.plugin.
  2367. ConstructSessionDescription(info.type, info.sdp);
  2368. };
  2369. RTCPeerConnection = function (servers, constraints) {
  2370. var iceServers = null;
  2371. if (servers) {
  2372. iceServers = servers.iceServers;
  2373. for (var i = 0; i < iceServers.length; i++) {
  2374. if (iceServers[i].urls && !iceServers[i].url) {
  2375. iceServers[i].url = iceServers[i].urls;
  2376. }
  2377. iceServers[i].hasCredentials = AdapterJS.
  2378. isDefined(iceServers[i].username) &&
  2379. AdapterJS.isDefined(iceServers[i].credential);
  2380. }
  2381. }
  2382. var mandatory = (constraints && constraints.mandatory) ?
  2383. constraints.mandatory : null;
  2384. var optional = (constraints && constraints.optional) ?
  2385. constraints.optional : null;
  2386. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2387. return AdapterJS.WebRTCPlugin.plugin.
  2388. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2389. iceServers, mandatory, optional);
  2390. };
  2391. MediaStreamTrack = {};
  2392. MediaStreamTrack.getSources = function (callback) {
  2393. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2394. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2395. });
  2396. };
  2397. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2398. constraints.audio = constraints.audio || false;
  2399. constraints.video = constraints.video || false;
  2400. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2401. AdapterJS.WebRTCPlugin.plugin.
  2402. getUserMedia(constraints, successCallback, failureCallback);
  2403. });
  2404. };
  2405. window.navigator.getUserMedia = window.getUserMedia;
  2406. attachMediaStream = function (element, stream) {
  2407. if (!element || !element.parentNode) {
  2408. return;
  2409. }
  2410. var streamId
  2411. if (stream === null) {
  2412. streamId = '';
  2413. }
  2414. else {
  2415. stream.enableSoundTracks(true);
  2416. streamId = stream.id;
  2417. }
  2418. if (element.nodeName.toLowerCase() !== 'audio') {
  2419. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2420. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2421. var frag = document.createDocumentFragment();
  2422. var temp = document.createElement('div');
  2423. var classHTML = '';
  2424. if (element.className) {
  2425. classHTML = 'class="' + element.className + '" ';
  2426. } else if (element.attributes && element.attributes['class']) {
  2427. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2428. }
  2429. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2430. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2431. '<param name="pluginId" value="' + elementId + '" /> ' +
  2432. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2433. '<param name="windowless" value="true" /> ' +
  2434. '<param name="streamId" value="' + streamId + '" /> ' +
  2435. '</object>';
  2436. while (temp.firstChild) {
  2437. frag.appendChild(temp.firstChild);
  2438. }
  2439. var height = '';
  2440. var width = '';
  2441. if (element.getBoundingClientRect) {
  2442. var rectObject = element.getBoundingClientRect();
  2443. width = rectObject.width + 'px';
  2444. height = rectObject.height + 'px';
  2445. }
  2446. else if (element.width) {
  2447. width = element.width;
  2448. height = element.height;
  2449. } else {
  2450. // TODO: What scenario could bring us here?
  2451. }
  2452. element.parentNode.insertBefore(frag, element);
  2453. frag = document.getElementById(elementId);
  2454. frag.width = width;
  2455. frag.height = height;
  2456. element.parentNode.removeChild(element);
  2457. } else {
  2458. var children = element.children;
  2459. for (var i = 0; i !== children.length; ++i) {
  2460. if (children[i].name === 'streamId') {
  2461. children[i].value = streamId;
  2462. break;
  2463. }
  2464. }
  2465. element.setStreamId(streamId);
  2466. }
  2467. var newElement = document.getElementById(elementId);
  2468. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2469. if (isIE) { // on IE the event needs to be plugged manually
  2470. newElement.attachEvent('onplaying', newElement.onplaying);
  2471. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2472. newElement._TemOnClick = function (id) {
  2473. var arg = {
  2474. srcElement : document.getElementById(id)
  2475. };
  2476. newElement.onclick(arg);
  2477. };
  2478. }
  2479. return newElement;
  2480. } else {
  2481. return element;
  2482. }
  2483. };
  2484. reattachMediaStream = function (to, from) {
  2485. var stream = null;
  2486. var children = from.children;
  2487. for (var i = 0; i !== children.length; ++i) {
  2488. if (children[i].name === 'streamId') {
  2489. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2490. stream = AdapterJS.WebRTCPlugin.plugin
  2491. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2492. break;
  2493. }
  2494. }
  2495. if (stream !== null) {
  2496. return attachMediaStream(to, stream);
  2497. } else {
  2498. console.log('Could not find the stream associated with this element');
  2499. }
  2500. };
  2501. RTCIceCandidate = function (candidate) {
  2502. if (!candidate.sdpMid) {
  2503. candidate.sdpMid = '';
  2504. }
  2505. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2506. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2507. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2508. );
  2509. };
  2510. // inject plugin
  2511. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2512. AdapterJS.WebRTCPlugin.injectPlugin();
  2513. };
  2514. // This function will be called if the plugin is needed (browser different
  2515. // from Chrome or Firefox), but the plugin is not installed.
  2516. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2517. function() {
  2518. AdapterJS.addEvent(document,
  2519. 'readystatechange',
  2520. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2521. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2522. };
  2523. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2524. if (AdapterJS.options.hidePluginInstallPrompt) {
  2525. return;
  2526. }
  2527. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2528. if(downloadLink) { // if download link
  2529. var popupString;
  2530. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2531. popupString = 'This website requires you to install the ' +
  2532. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2533. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2534. ' WebRTC Plugin</a>' +
  2535. ' to work on this browser.';
  2536. } else { // no portal link, just print a generic explanation
  2537. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2538. }
  2539. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2540. } else { // no download link, just print a generic explanation
  2541. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2542. }
  2543. };
  2544. // Try to detect the plugin and act accordingly
  2545. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2546. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2547. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2548. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2549. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2550. }
  2551. (function () {
  2552. 'use strict';
  2553. var baseGetUserMedia = null;
  2554. AdapterJS.TEXT.EXTENSION = {
  2555. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2556. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2557. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2558. BUTTON_FF: 'Install Now',
  2559. BUTTON_CHROME: 'Go to Chrome Web Store'
  2560. };
  2561. var clone = function(obj) {
  2562. if (null == obj || "object" != typeof obj) return obj;
  2563. var copy = obj.constructor();
  2564. for (var attr in obj) {
  2565. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2566. }
  2567. return copy;
  2568. };
  2569. if (window.navigator.mozGetUserMedia) {
  2570. baseGetUserMedia = window.navigator.getUserMedia;
  2571. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2572. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2573. // intercepting screensharing requests
  2574. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2575. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2576. }
  2577. var updatedConstraints = clone(constraints);
  2578. //constraints.video.mediaSource = constraints.video.mediaSource;
  2579. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2580. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2581. // strange but this works anyway
  2582. var checkIfReady = setInterval(function () {
  2583. if (document.readyState === 'complete') {
  2584. clearInterval(checkIfReady);
  2585. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2586. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2587. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2588. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2589. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2590. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2591. } else {
  2592. failureCb(error);
  2593. }
  2594. });
  2595. }
  2596. }, 1);
  2597. } else { // regular GetUserMediaRequest
  2598. baseGetUserMedia(constraints, successCb, failureCb);
  2599. }
  2600. };
  2601. getUserMedia = navigator.getUserMedia;
  2602. } else if (window.navigator.webkitGetUserMedia) {
  2603. baseGetUserMedia = window.navigator.getUserMedia;
  2604. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2605. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2606. if (window.webrtcDetectedBrowser !== 'chrome') {
  2607. throw new Error('Current browser does not support screensharing');
  2608. }
  2609. // would be fine since no methods
  2610. var updatedConstraints = clone(constraints);
  2611. var chromeCallback = function(error, sourceId) {
  2612. if(!error) {
  2613. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2614. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2615. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2616. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2617. if (sourceId) {
  2618. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2619. }
  2620. delete updatedConstraints.video.mediaSource;
  2621. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2622. } else {
  2623. if (error === 'permission-denied') {
  2624. throw new Error('Permission denied for screen retrieval');
  2625. } else {
  2626. throw new Error('Failed retrieving selected screen');
  2627. }
  2628. }
  2629. };
  2630. var onIFrameCallback = function (event) {
  2631. if (!event.data) {
  2632. return;
  2633. }
  2634. if (event.data.chromeMediaSourceId) {
  2635. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2636. chromeCallback('permission-denied');
  2637. } else {
  2638. chromeCallback(null, event.data.chromeMediaSourceId);
  2639. }
  2640. }
  2641. if (event.data.chromeExtensionStatus) {
  2642. if (event.data.chromeExtensionStatus === 'not-installed') {
  2643. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2644. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2645. event.data.data, true, true);
  2646. } else {
  2647. chromeCallback(event.data.chromeExtensionStatus, null);
  2648. }
  2649. }
  2650. // this event listener is no more needed
  2651. window.removeEventListener('message', onIFrameCallback);
  2652. };
  2653. window.addEventListener('message', onIFrameCallback);
  2654. postFrameMessage({
  2655. captureSourceId: true
  2656. });
  2657. } else {
  2658. baseGetUserMedia(constraints, successCb, failureCb);
  2659. }
  2660. };
  2661. getUserMedia = navigator.getUserMedia;
  2662. } else {
  2663. baseGetUserMedia = window.navigator.getUserMedia;
  2664. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2665. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2666. // would be fine since no methods
  2667. var updatedConstraints = clone(constraints);
  2668. // wait for plugin to be ready
  2669. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2670. // check if screensharing feature is available
  2671. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2672. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2673. // set the constraints
  2674. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2675. updatedConstraints.video.optional.push({
  2676. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2677. });
  2678. delete updatedConstraints.video.mediaSource;
  2679. } else {
  2680. throw new Error('Your WebRTC plugin does not support screensharing');
  2681. }
  2682. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2683. });
  2684. } else {
  2685. baseGetUserMedia(constraints, successCb, failureCb);
  2686. }
  2687. };
  2688. getUserMedia = window.navigator.getUserMedia;
  2689. }
  2690. if (window.webrtcDetectedBrowser === 'chrome') {
  2691. var iframe = document.createElement('iframe');
  2692. iframe.onload = function() {
  2693. iframe.isLoaded = true;
  2694. };
  2695. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2696. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2697. iframe.style.display = 'none';
  2698. (document.body || document.documentElement).appendChild(iframe);
  2699. var postFrameMessage = function (object) {
  2700. object = object || {};
  2701. if (!iframe.isLoaded) {
  2702. setTimeout(function () {
  2703. iframe.contentWindow.postMessage(object, '*');
  2704. }, 100);
  2705. return;
  2706. }
  2707. iframe.contentWindow.postMessage(object, '*');
  2708. };
  2709. }
  2710. })();
  2711. },{}],15:[function(require,module,exports){
  2712. var email = '';
  2713. var displayName = '';
  2714. var userId;
  2715. var language = null;
  2716. function supportsLocalStorage() {
  2717. try {
  2718. return 'localStorage' in window && window.localStorage !== null;
  2719. } catch (e) {
  2720. console.log("localstorage is not supported");
  2721. return false;
  2722. }
  2723. }
  2724. function generateUniqueId() {
  2725. function _p8() {
  2726. return (Math.random().toString(16) + "000000000").substr(2, 8);
  2727. }
  2728. return _p8() + _p8() + _p8() + _p8();
  2729. }
  2730. if (supportsLocalStorage()) {
  2731. if (!window.localStorage.jitsiMeetId) {
  2732. window.localStorage.jitsiMeetId = generateUniqueId();
  2733. console.log("generated id", window.localStorage.jitsiMeetId);
  2734. }
  2735. userId = window.localStorage.jitsiMeetId || '';
  2736. email = window.localStorage.email || '';
  2737. displayName = window.localStorage.displayname || '';
  2738. language = window.localStorage.language;
  2739. } else {
  2740. console.log("local storage is not supported");
  2741. userId = generateUniqueId();
  2742. }
  2743. var Settings = {
  2744. setDisplayName: function (newDisplayName) {
  2745. displayName = newDisplayName;
  2746. window.localStorage.displayname = displayName;
  2747. return displayName;
  2748. },
  2749. setEmail: function (newEmail) {
  2750. email = newEmail;
  2751. window.localStorage.email = newEmail;
  2752. return email;
  2753. },
  2754. getSettings: function () {
  2755. return {
  2756. email: email,
  2757. displayName: displayName,
  2758. uid: userId,
  2759. language: language
  2760. };
  2761. },
  2762. setLanguage: function (lang) {
  2763. language = lang;
  2764. window.localStorage.language = lang;
  2765. }
  2766. };
  2767. module.exports = Settings;
  2768. },{}],16:[function(require,module,exports){
  2769. SDPUtil = {
  2770. filter_special_chars: function (text) {
  2771. return text.replace(/[\\\/\{,\}\+]/g, "");
  2772. },
  2773. iceparams: function (mediadesc, sessiondesc) {
  2774. var data = null;
  2775. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  2776. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  2777. data = {
  2778. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  2779. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  2780. };
  2781. }
  2782. return data;
  2783. },
  2784. parse_iceufrag: function (line) {
  2785. return line.substring(12);
  2786. },
  2787. build_iceufrag: function (frag) {
  2788. return 'a=ice-ufrag:' + frag;
  2789. },
  2790. parse_icepwd: function (line) {
  2791. return line.substring(10);
  2792. },
  2793. build_icepwd: function (pwd) {
  2794. return 'a=ice-pwd:' + pwd;
  2795. },
  2796. parse_mid: function (line) {
  2797. return line.substring(6);
  2798. },
  2799. parse_mline: function (line) {
  2800. var parts = line.substring(2).split(' '),
  2801. data = {};
  2802. data.media = parts.shift();
  2803. data.port = parts.shift();
  2804. data.proto = parts.shift();
  2805. if (parts[parts.length - 1] === '') { // trailing whitespace
  2806. parts.pop();
  2807. }
  2808. data.fmt = parts;
  2809. return data;
  2810. },
  2811. build_mline: function (mline) {
  2812. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  2813. },
  2814. parse_rtpmap: function (line) {
  2815. var parts = line.substring(9).split(' '),
  2816. data = {};
  2817. data.id = parts.shift();
  2818. parts = parts[0].split('/');
  2819. data.name = parts.shift();
  2820. data.clockrate = parts.shift();
  2821. data.channels = parts.length ? parts.shift() : '1';
  2822. return data;
  2823. },
  2824. /**
  2825. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  2826. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  2827. * @returns [SCTP port number, protocol, streams]
  2828. */
  2829. parse_sctpmap: function (line)
  2830. {
  2831. var parts = line.substring(10).split(' ');
  2832. var sctpPort = parts[0];
  2833. var protocol = parts[1];
  2834. // Stream count is optional
  2835. var streamCount = parts.length > 2 ? parts[2] : null;
  2836. return [sctpPort, protocol, streamCount];// SCTP port
  2837. },
  2838. build_rtpmap: function (el) {
  2839. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  2840. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  2841. line += '/' + el.getAttribute('channels');
  2842. }
  2843. return line;
  2844. },
  2845. parse_crypto: function (line) {
  2846. var parts = line.substring(9).split(' '),
  2847. data = {};
  2848. data.tag = parts.shift();
  2849. data['crypto-suite'] = parts.shift();
  2850. data['key-params'] = parts.shift();
  2851. if (parts.length) {
  2852. data['session-params'] = parts.join(' ');
  2853. }
  2854. return data;
  2855. },
  2856. parse_fingerprint: function (line) { // RFC 4572
  2857. var parts = line.substring(14).split(' '),
  2858. data = {};
  2859. data.hash = parts.shift();
  2860. data.fingerprint = parts.shift();
  2861. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  2862. return data;
  2863. },
  2864. parse_fmtp: function (line) {
  2865. var parts = line.split(' '),
  2866. i, key, value,
  2867. data = [];
  2868. parts.shift();
  2869. parts = parts.join(' ').split(';');
  2870. for (i = 0; i < parts.length; i++) {
  2871. key = parts[i].split('=')[0];
  2872. while (key.length && key[0] == ' ') {
  2873. key = key.substring(1);
  2874. }
  2875. value = parts[i].split('=')[1];
  2876. if (key && value) {
  2877. data.push({name: key, value: value});
  2878. } else if (key) {
  2879. // rfc 4733 (DTMF) style stuff
  2880. data.push({name: '', value: key});
  2881. }
  2882. }
  2883. return data;
  2884. },
  2885. parse_icecandidate: function (line) {
  2886. var candidate = {},
  2887. elems = line.split(' ');
  2888. candidate.foundation = elems[0].substring(12);
  2889. candidate.component = elems[1];
  2890. candidate.protocol = elems[2].toLowerCase();
  2891. candidate.priority = elems[3];
  2892. candidate.ip = elems[4];
  2893. candidate.port = elems[5];
  2894. // elems[6] => "typ"
  2895. candidate.type = elems[7];
  2896. candidate.generation = 0; // default value, may be overwritten below
  2897. for (var i = 8; i < elems.length; i += 2) {
  2898. switch (elems[i]) {
  2899. case 'raddr':
  2900. candidate['rel-addr'] = elems[i + 1];
  2901. break;
  2902. case 'rport':
  2903. candidate['rel-port'] = elems[i + 1];
  2904. break;
  2905. case 'generation':
  2906. candidate.generation = elems[i + 1];
  2907. break;
  2908. case 'tcptype':
  2909. candidate.tcptype = elems[i + 1];
  2910. break;
  2911. default: // TODO
  2912. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  2913. }
  2914. }
  2915. candidate.network = '1';
  2916. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  2917. return candidate;
  2918. },
  2919. build_icecandidate: function (cand) {
  2920. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  2921. line += ' ';
  2922. switch (cand.type) {
  2923. case 'srflx':
  2924. case 'prflx':
  2925. case 'relay':
  2926. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  2927. line += 'raddr';
  2928. line += ' ';
  2929. line += cand['rel-addr'];
  2930. line += ' ';
  2931. line += 'rport';
  2932. line += ' ';
  2933. line += cand['rel-port'];
  2934. line += ' ';
  2935. }
  2936. break;
  2937. }
  2938. if (cand.hasOwnAttribute('tcptype')) {
  2939. line += 'tcptype';
  2940. line += ' ';
  2941. line += cand.tcptype;
  2942. line += ' ';
  2943. }
  2944. line += 'generation';
  2945. line += ' ';
  2946. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  2947. return line;
  2948. },
  2949. parse_ssrc: function (desc) {
  2950. // proprietary mapping of a=ssrc lines
  2951. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  2952. // and parse according to that
  2953. var lines = desc.split('\r\n'),
  2954. data = {};
  2955. for (var i = 0; i < lines.length; i++) {
  2956. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  2957. var idx = lines[i].indexOf(' ');
  2958. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  2959. }
  2960. }
  2961. return data;
  2962. },
  2963. parse_rtcpfb: function (line) {
  2964. var parts = line.substr(10).split(' ');
  2965. var data = {};
  2966. data.pt = parts.shift();
  2967. data.type = parts.shift();
  2968. data.params = parts;
  2969. return data;
  2970. },
  2971. parse_extmap: function (line) {
  2972. var parts = line.substr(9).split(' ');
  2973. var data = {};
  2974. data.value = parts.shift();
  2975. if (data.value.indexOf('/') != -1) {
  2976. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  2977. data.value = data.value.substr(0, data.value.indexOf('/'));
  2978. } else {
  2979. data.direction = 'both';
  2980. }
  2981. data.uri = parts.shift();
  2982. data.params = parts;
  2983. return data;
  2984. },
  2985. find_line: function (haystack, needle, sessionpart) {
  2986. var lines = haystack.split('\r\n');
  2987. for (var i = 0; i < lines.length; i++) {
  2988. if (lines[i].substring(0, needle.length) == needle) {
  2989. return lines[i];
  2990. }
  2991. }
  2992. if (!sessionpart) {
  2993. return false;
  2994. }
  2995. // search session part
  2996. lines = sessionpart.split('\r\n');
  2997. for (var j = 0; j < lines.length; j++) {
  2998. if (lines[j].substring(0, needle.length) == needle) {
  2999. return lines[j];
  3000. }
  3001. }
  3002. return false;
  3003. },
  3004. find_lines: function (haystack, needle, sessionpart) {
  3005. var lines = haystack.split('\r\n'),
  3006. needles = [];
  3007. for (var i = 0; i < lines.length; i++) {
  3008. if (lines[i].substring(0, needle.length) == needle)
  3009. needles.push(lines[i]);
  3010. }
  3011. if (needles.length || !sessionpart) {
  3012. return needles;
  3013. }
  3014. // search session part
  3015. lines = sessionpart.split('\r\n');
  3016. for (var j = 0; j < lines.length; j++) {
  3017. if (lines[j].substring(0, needle.length) == needle) {
  3018. needles.push(lines[j]);
  3019. }
  3020. }
  3021. return needles;
  3022. },
  3023. candidateToJingle: function (line) {
  3024. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  3025. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  3026. if (line.indexOf('candidate:') === 0) {
  3027. line = 'a=' + line;
  3028. } else if (line.substring(0, 12) != 'a=candidate:') {
  3029. console.log('parseCandidate called with a line that is not a candidate line');
  3030. console.log(line);
  3031. return null;
  3032. }
  3033. if (line.substring(line.length - 2) == '\r\n') // chomp it
  3034. line = line.substring(0, line.length - 2);
  3035. var candidate = {},
  3036. elems = line.split(' '),
  3037. i;
  3038. if (elems[6] != 'typ') {
  3039. console.log('did not find typ in the right place');
  3040. console.log(line);
  3041. return null;
  3042. }
  3043. candidate.foundation = elems[0].substring(12);
  3044. candidate.component = elems[1];
  3045. candidate.protocol = elems[2].toLowerCase();
  3046. candidate.priority = elems[3];
  3047. candidate.ip = elems[4];
  3048. candidate.port = elems[5];
  3049. // elems[6] => "typ"
  3050. candidate.type = elems[7];
  3051. candidate.generation = '0'; // default, may be overwritten below
  3052. for (i = 8; i < elems.length; i += 2) {
  3053. switch (elems[i]) {
  3054. case 'raddr':
  3055. candidate['rel-addr'] = elems[i + 1];
  3056. break;
  3057. case 'rport':
  3058. candidate['rel-port'] = elems[i + 1];
  3059. break;
  3060. case 'generation':
  3061. candidate.generation = elems[i + 1];
  3062. break;
  3063. case 'tcptype':
  3064. candidate.tcptype = elems[i + 1];
  3065. break;
  3066. default: // TODO
  3067. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  3068. }
  3069. }
  3070. candidate.network = '1';
  3071. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  3072. return candidate;
  3073. },
  3074. candidateFromJingle: function (cand) {
  3075. var line = 'a=candidate:';
  3076. line += cand.getAttribute('foundation');
  3077. line += ' ';
  3078. line += cand.getAttribute('component');
  3079. line += ' ';
  3080. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  3081. line += ' ';
  3082. line += cand.getAttribute('priority');
  3083. line += ' ';
  3084. line += cand.getAttribute('ip');
  3085. line += ' ';
  3086. line += cand.getAttribute('port');
  3087. line += ' ';
  3088. line += 'typ';
  3089. line += ' ' + cand.getAttribute('type');
  3090. line += ' ';
  3091. switch (cand.getAttribute('type')) {
  3092. case 'srflx':
  3093. case 'prflx':
  3094. case 'relay':
  3095. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  3096. line += 'raddr';
  3097. line += ' ';
  3098. line += cand.getAttribute('rel-addr');
  3099. line += ' ';
  3100. line += 'rport';
  3101. line += ' ';
  3102. line += cand.getAttribute('rel-port');
  3103. line += ' ';
  3104. }
  3105. break;
  3106. }
  3107. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  3108. line += 'tcptype';
  3109. line += ' ';
  3110. line += cand.getAttribute('tcptype');
  3111. line += ' ';
  3112. }
  3113. line += 'generation';
  3114. line += ' ';
  3115. line += cand.getAttribute('generation') || '0';
  3116. return line + '\r\n';
  3117. }
  3118. };
  3119. module.exports = SDPUtil;
  3120. },{}],17:[function(require,module,exports){
  3121. /* global $, $iq, APP, config, messageHandler,
  3122. roomName, sessionTerminated, Strophe, Util */
  3123. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3124. var Settings = require("../settings/Settings");
  3125. var AuthenticationEvents
  3126. = require("../../service/authentication/AuthenticationEvents");
  3127. /**
  3128. * Contains logic responsible for enabling/disabling functionality available
  3129. * only to moderator users.
  3130. */
  3131. var connection = null;
  3132. var focusUserJid;
  3133. function createExpBackoffTimer(step) {
  3134. var count = 1;
  3135. return function (reset) {
  3136. // Reset call
  3137. if (reset) {
  3138. count = 1;
  3139. return;
  3140. }
  3141. // Calculate next timeout
  3142. var timeout = Math.pow(2, count - 1);
  3143. count += 1;
  3144. return timeout * step;
  3145. };
  3146. }
  3147. var getNextTimeout = createExpBackoffTimer(1000);
  3148. var getNextErrorTimeout = createExpBackoffTimer(1000);
  3149. // External authentication stuff
  3150. var externalAuthEnabled = false;
  3151. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  3152. // it will be enabled automatically if focus detects the component through
  3153. // service discovery.
  3154. var sipGatewayEnabled = null;
  3155. var eventEmitter = null;
  3156. var Moderator = {
  3157. isModerator: function () {
  3158. return connection && connection.emuc.isModerator();
  3159. },
  3160. isPeerModerator: function (peerJid) {
  3161. return connection &&
  3162. connection.emuc.getMemberRole(peerJid) === 'moderator';
  3163. },
  3164. isExternalAuthEnabled: function () {
  3165. return externalAuthEnabled;
  3166. },
  3167. isSipGatewayEnabled: function () {
  3168. return sipGatewayEnabled;
  3169. },
  3170. setConnection: function (con) {
  3171. connection = con;
  3172. },
  3173. init: function (xmpp, emitter) {
  3174. this.xmppService = xmpp;
  3175. sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  3176. eventEmitter = emitter;
  3177. // Message listener that talks to POPUP window
  3178. function listener(event) {
  3179. if (event.data && event.data.sessionId) {
  3180. if (event.origin !== window.location.origin) {
  3181. console.warn("Ignoring sessionId from different origin: " +
  3182. event.origin);
  3183. return;
  3184. }
  3185. localStorage.setItem('sessionId', event.data.sessionId);
  3186. // After popup is closed we will authenticate
  3187. }
  3188. }
  3189. // Register
  3190. if (window.addEventListener) {
  3191. window.addEventListener("message", listener, false);
  3192. } else {
  3193. window.attachEvent("onmessage", listener);
  3194. }
  3195. },
  3196. onMucMemberLeft: function (jid) {
  3197. console.info("Someone left is it focus ? " + jid);
  3198. var resource = Strophe.getResourceFromJid(jid);
  3199. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  3200. console.info(
  3201. "Focus has left the room - leaving conference");
  3202. //hangUp();
  3203. // We'd rather reload to have everything re-initialized
  3204. // FIXME: show some message before reload
  3205. location.reload();
  3206. }
  3207. },
  3208. setFocusUserJid: function (focusJid) {
  3209. if (!focusUserJid) {
  3210. focusUserJid = focusJid;
  3211. console.info("Focus jid set to: " + focusUserJid);
  3212. }
  3213. },
  3214. getFocusUserJid: function () {
  3215. return focusUserJid;
  3216. },
  3217. getFocusComponent: function () {
  3218. // Get focus component address
  3219. var focusComponent = this.xmppService.options.hosts.focus;
  3220. // If not specified use default: 'focus.domain'
  3221. if (!focusComponent) {
  3222. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  3223. }
  3224. return focusComponent;
  3225. },
  3226. createConferenceIq: function (roomName) {
  3227. // Generate create conference IQ
  3228. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  3229. // Session Id used for authentication
  3230. var sessionId = localStorage.getItem('sessionId');
  3231. var machineUID = Settings.getSettings().uid;
  3232. console.info(
  3233. "Session ID: " + sessionId + " machine UID: " + machineUID);
  3234. elem.c('conference', {
  3235. xmlns: 'http://jitsi.org/protocol/focus',
  3236. room: roomName,
  3237. 'machine-uid': machineUID
  3238. });
  3239. if (sessionId) {
  3240. elem.attrs({ 'session-id': sessionId});
  3241. }
  3242. if (this.xmppService.options.hosts.bridge !== undefined) {
  3243. elem.c(
  3244. 'property',
  3245. { name: 'bridge', value: this.xmppService.options.hosts.bridge})
  3246. .up();
  3247. }
  3248. // Tell the focus we have Jigasi configured
  3249. if (this.xmppService.options.hosts.call_control !== undefined) {
  3250. elem.c(
  3251. 'property',
  3252. { name: 'call_control', value: this.xmppService.options.hosts.call_control})
  3253. .up();
  3254. }
  3255. if (this.xmppService.options.channelLastN !== undefined) {
  3256. elem.c(
  3257. 'property',
  3258. { name: 'channelLastN', value: this.xmppService.options.channelLastN})
  3259. .up();
  3260. }
  3261. if (this.xmppService.options.adaptiveLastN !== undefined) {
  3262. elem.c(
  3263. 'property',
  3264. { name: 'adaptiveLastN', value: this.xmppService.options.adaptiveLastN})
  3265. .up();
  3266. }
  3267. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  3268. elem.c(
  3269. 'property',
  3270. { name: 'adaptiveSimulcast', value: this.xmppService.options.adaptiveSimulcast})
  3271. .up();
  3272. }
  3273. if (this.xmppService.options.openSctp !== undefined) {
  3274. elem.c(
  3275. 'property',
  3276. { name: 'openSctp', value: this.xmppService.options.openSctp})
  3277. .up();
  3278. }
  3279. if(this.xmppService.options.startAudioMuted !== undefined)
  3280. {
  3281. elem.c(
  3282. 'property',
  3283. { name: 'startAudioMuted', value: this.xmppService.options.startAudioMuted})
  3284. .up();
  3285. }
  3286. if(this.xmppService.options.startVideoMuted !== undefined)
  3287. {
  3288. elem.c(
  3289. 'property',
  3290. { name: 'startVideoMuted', value: this.xmppService.options.startVideoMuted})
  3291. .up();
  3292. }
  3293. elem.c(
  3294. 'property',
  3295. { name: 'simulcastMode', value: 'rewriting'})
  3296. .up();
  3297. elem.up();
  3298. return elem;
  3299. },
  3300. parseSessionId: function (resultIq) {
  3301. var sessionId = $(resultIq).find('conference').attr('session-id');
  3302. if (sessionId) {
  3303. console.info('Received sessionId: ' + sessionId);
  3304. localStorage.setItem('sessionId', sessionId);
  3305. }
  3306. },
  3307. parseConfigOptions: function (resultIq) {
  3308. Moderator.setFocusUserJid(
  3309. $(resultIq).find('conference').attr('focusjid'));
  3310. var authenticationEnabled
  3311. = $(resultIq).find(
  3312. '>conference>property' +
  3313. '[name=\'authentication\'][value=\'true\']').length > 0;
  3314. console.info("Authentication enabled: " + authenticationEnabled);
  3315. externalAuthEnabled = $(resultIq).find(
  3316. '>conference>property' +
  3317. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  3318. console.info('External authentication enabled: ' + externalAuthEnabled);
  3319. if (!externalAuthEnabled) {
  3320. // We expect to receive sessionId in 'internal' authentication mode
  3321. Moderator.parseSessionId(resultIq);
  3322. }
  3323. var authIdentity = $(resultIq).find('>conference').attr('identity');
  3324. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  3325. authenticationEnabled, authIdentity);
  3326. // Check if focus has auto-detected Jigasi component(this will be also
  3327. // included if we have passed our host from the config)
  3328. if ($(resultIq).find(
  3329. '>conference>property' +
  3330. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  3331. sipGatewayEnabled = true;
  3332. }
  3333. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  3334. },
  3335. // FIXME: we need to show the fact that we're waiting for the focus
  3336. // to the user(or that focus is not available)
  3337. allocateConferenceFocus: function (roomName, callback) {
  3338. // Try to use focus user JID from the config
  3339. Moderator.setFocusUserJid(this.xmppService.options.focusUserJid);
  3340. // Send create conference IQ
  3341. var iq = Moderator.createConferenceIq(roomName);
  3342. var self = this;
  3343. connection.sendIQ(
  3344. iq,
  3345. function (result) {
  3346. // Setup config options
  3347. Moderator.parseConfigOptions(result);
  3348. if ('true' === $(result).find('conference').attr('ready')) {
  3349. // Reset both timers
  3350. getNextTimeout(true);
  3351. getNextErrorTimeout(true);
  3352. // Exec callback
  3353. callback();
  3354. } else {
  3355. var waitMs = getNextTimeout();
  3356. console.info("Waiting for the focus... " + waitMs);
  3357. // Reset error timeout
  3358. getNextErrorTimeout(true);
  3359. window.setTimeout(
  3360. function () {
  3361. Moderator.allocateConferenceFocus(
  3362. roomName, callback);
  3363. }, waitMs);
  3364. }
  3365. },
  3366. function (error) {
  3367. // Invalid session ? remove and try again
  3368. // without session ID to get a new one
  3369. var invalidSession
  3370. = $(error).find('>error>session-invalid').length;
  3371. if (invalidSession) {
  3372. console.info("Session expired! - removing");
  3373. localStorage.removeItem("sessionId");
  3374. }
  3375. if ($(error).find('>error>graceful-shutdown').length) {
  3376. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  3377. return;
  3378. }
  3379. // Check for error returned by the reservation system
  3380. var reservationErr = $(error).find('>error>reservation-error');
  3381. if (reservationErr.length) {
  3382. // Trigger error event
  3383. var errorCode = reservationErr.attr('error-code');
  3384. var errorMsg;
  3385. if ($(error).find('>error>text')) {
  3386. errorMsg = $(error).find('>error>text').text();
  3387. }
  3388. eventEmitter.emit(
  3389. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  3390. return;
  3391. }
  3392. // Not authorized to create new room
  3393. if ($(error).find('>error>not-authorized').length) {
  3394. console.warn("Unauthorized to start the conference", error);
  3395. var toDomain
  3396. = Strophe.getDomainFromJid(error.getAttribute('to'));
  3397. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  3398. // FIXME: "is external" should come either from
  3399. // the focus or config.js
  3400. externalAuthEnabled = true;
  3401. }
  3402. eventEmitter.emit(
  3403. XMPPEvents.AUTHENTICATION_REQUIRED,
  3404. function () {
  3405. Moderator.allocateConferenceFocus(
  3406. roomName, callback);
  3407. });
  3408. return;
  3409. }
  3410. var waitMs = getNextErrorTimeout();
  3411. console.error("Focus error, retry after " + waitMs, error);
  3412. // Show message
  3413. var focusComponent = Moderator.getFocusComponent();
  3414. var retrySec = waitMs / 1000;
  3415. // FIXME: message is duplicated ?
  3416. // Do not show in case of session invalid
  3417. // which means just a retry
  3418. if (!invalidSession) {
  3419. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  3420. focusComponent, retrySec);
  3421. }
  3422. // Reset response timeout
  3423. getNextTimeout(true);
  3424. window.setTimeout(
  3425. function () {
  3426. Moderator.allocateConferenceFocus(roomName, callback);
  3427. }, waitMs);
  3428. }
  3429. );
  3430. },
  3431. getLoginUrl: function (roomName, urlCallback) {
  3432. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  3433. iq.c('login-url', {
  3434. xmlns: 'http://jitsi.org/protocol/focus',
  3435. room: roomName,
  3436. 'machine-uid': Settings.getSettings().uid
  3437. });
  3438. connection.sendIQ(
  3439. iq,
  3440. function (result) {
  3441. var url = $(result).find('login-url').attr('url');
  3442. url = url = decodeURIComponent(url);
  3443. if (url) {
  3444. console.info("Got auth url: " + url);
  3445. urlCallback(url);
  3446. } else {
  3447. console.error(
  3448. "Failed to get auth url from the focus", result);
  3449. }
  3450. },
  3451. function (error) {
  3452. console.error("Get auth url error", error);
  3453. }
  3454. );
  3455. },
  3456. getPopupLoginUrl: function (roomName, urlCallback) {
  3457. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  3458. iq.c('login-url', {
  3459. xmlns: 'http://jitsi.org/protocol/focus',
  3460. room: roomName,
  3461. 'machine-uid': Settings.getSettings().uid,
  3462. popup: true
  3463. });
  3464. connection.sendIQ(
  3465. iq,
  3466. function (result) {
  3467. var url = $(result).find('login-url').attr('url');
  3468. url = url = decodeURIComponent(url);
  3469. if (url) {
  3470. console.info("Got POPUP auth url: " + url);
  3471. urlCallback(url);
  3472. } else {
  3473. console.error(
  3474. "Failed to get POPUP auth url from the focus", result);
  3475. }
  3476. },
  3477. function (error) {
  3478. console.error('Get POPUP auth url error', error);
  3479. }
  3480. );
  3481. },
  3482. logout: function (callback) {
  3483. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  3484. var sessionId = localStorage.getItem('sessionId');
  3485. if (!sessionId) {
  3486. callback();
  3487. return;
  3488. }
  3489. iq.c('logout', {
  3490. xmlns: 'http://jitsi.org/protocol/focus',
  3491. 'session-id': sessionId
  3492. });
  3493. connection.sendIQ(
  3494. iq,
  3495. function (result) {
  3496. var logoutUrl = $(result).find('logout').attr('logout-url');
  3497. if (logoutUrl) {
  3498. logoutUrl = decodeURIComponent(logoutUrl);
  3499. }
  3500. console.info("Log out OK, url: " + logoutUrl, result);
  3501. localStorage.removeItem('sessionId');
  3502. callback(logoutUrl);
  3503. },
  3504. function (error) {
  3505. console.error("Logout error", error);
  3506. }
  3507. );
  3508. }
  3509. };
  3510. module.exports = Moderator;
  3511. },{"../../service/authentication/AuthenticationEvents":44,"../../service/xmpp/XMPPEvents":46,"../settings/Settings":15}],18:[function(require,module,exports){
  3512. /* global Strophe */
  3513. module.exports = function () {
  3514. Strophe.addConnectionPlugin('logger', {
  3515. // logs raw stanzas and makes them available for download as JSON
  3516. connection: null,
  3517. log: [],
  3518. init: function (conn) {
  3519. this.connection = conn;
  3520. this.connection.rawInput = this.log_incoming.bind(this);
  3521. this.connection.rawOutput = this.log_outgoing.bind(this);
  3522. },
  3523. log_incoming: function (stanza) {
  3524. this.log.push([new Date().getTime(), 'incoming', stanza]);
  3525. },
  3526. log_outgoing: function (stanza) {
  3527. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  3528. }
  3529. });
  3530. };
  3531. },{}],19:[function(require,module,exports){
  3532. /* jshint -W117 */
  3533. module.exports = function() {
  3534. Strophe.addConnectionPlugin('rayo',
  3535. {
  3536. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  3537. connection: null,
  3538. init: function (conn) {
  3539. this.connection = conn;
  3540. if (this.connection.disco) {
  3541. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  3542. }
  3543. this.connection.addHandler(
  3544. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  3545. },
  3546. onRayo: function (iq) {
  3547. console.info("Rayo IQ", iq);
  3548. },
  3549. dial: function (to, from, roomName, roomPass) {
  3550. var self = this;
  3551. var req = $iq(
  3552. {
  3553. type: 'set',
  3554. to: this.connection.emuc.focusMucJid
  3555. }
  3556. );
  3557. req.c('dial',
  3558. {
  3559. xmlns: this.RAYO_XMLNS,
  3560. to: to,
  3561. from: from
  3562. });
  3563. req.c('header',
  3564. {
  3565. name: 'JvbRoomName',
  3566. value: roomName
  3567. }).up();
  3568. if (roomPass !== null && roomPass.length) {
  3569. req.c('header',
  3570. {
  3571. name: 'JvbRoomPassword',
  3572. value: roomPass
  3573. }).up();
  3574. }
  3575. this.connection.sendIQ(
  3576. req,
  3577. function (result) {
  3578. console.info('Dial result ', result);
  3579. var resource = $(result).find('ref').attr('uri');
  3580. this.call_resource = resource.substr('xmpp:'.length);
  3581. console.info(
  3582. "Received call resource: " + this.call_resource);
  3583. },
  3584. function (error) {
  3585. console.info('Dial error ', error);
  3586. }
  3587. );
  3588. },
  3589. hang_up: function () {
  3590. if (!this.call_resource) {
  3591. console.warn("No call in progress");
  3592. return;
  3593. }
  3594. var self = this;
  3595. var req = $iq(
  3596. {
  3597. type: 'set',
  3598. to: this.call_resource
  3599. }
  3600. );
  3601. req.c('hangup',
  3602. {
  3603. xmlns: this.RAYO_XMLNS
  3604. });
  3605. this.connection.sendIQ(
  3606. req,
  3607. function (result) {
  3608. console.info('Hangup result ', result);
  3609. self.call_resource = null;
  3610. },
  3611. function (error) {
  3612. console.info('Hangup error ', error);
  3613. self.call_resource = null;
  3614. }
  3615. );
  3616. }
  3617. }
  3618. );
  3619. };
  3620. },{}],20:[function(require,module,exports){
  3621. /**
  3622. * Strophe logger implementation. Logs from level WARN and above.
  3623. */
  3624. module.exports = function () {
  3625. Strophe.log = function (level, msg) {
  3626. switch (level) {
  3627. case Strophe.LogLevel.WARN:
  3628. console.warn("Strophe: " + msg);
  3629. break;
  3630. case Strophe.LogLevel.ERROR:
  3631. case Strophe.LogLevel.FATAL:
  3632. console.error("Strophe: " + msg);
  3633. break;
  3634. }
  3635. };
  3636. Strophe.getStatusString = function (status) {
  3637. switch (status) {
  3638. case Strophe.Status.ERROR:
  3639. return "ERROR";
  3640. case Strophe.Status.CONNECTING:
  3641. return "CONNECTING";
  3642. case Strophe.Status.CONNFAIL:
  3643. return "CONNFAIL";
  3644. case Strophe.Status.AUTHENTICATING:
  3645. return "AUTHENTICATING";
  3646. case Strophe.Status.AUTHFAIL:
  3647. return "AUTHFAIL";
  3648. case Strophe.Status.CONNECTED:
  3649. return "CONNECTED";
  3650. case Strophe.Status.DISCONNECTED:
  3651. return "DISCONNECTED";
  3652. case Strophe.Status.DISCONNECTING:
  3653. return "DISCONNECTING";
  3654. case Strophe.Status.ATTACHED:
  3655. return "ATTACHED";
  3656. default:
  3657. return "unknown";
  3658. }
  3659. };
  3660. };
  3661. },{}],21:[function(require,module,exports){
  3662. /* global $, APP, config, Strophe*/
  3663. var Moderator = require("./moderator");
  3664. var EventEmitter = require("events");
  3665. var Pako = require("pako");
  3666. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  3667. var RTCEvents = require("../../service/RTC/RTCEvents");
  3668. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3669. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  3670. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  3671. var RTC = require("../RTC/RTC");
  3672. var authenticatedUser = false;
  3673. var disconnectInProgress = false;
  3674. function createConnection(bosh) {
  3675. bosh = bosh || '/http-bind';
  3676. return new Strophe.Connection(bosh);
  3677. };
  3678. //!!!!!!!!!! FIXME: ...
  3679. function initStrophePlugins()
  3680. {
  3681. // require("./strophe.emuc")(XMPP, eventEmitter);
  3682. // require("./strophe.jingle")(XMPP, eventEmitter);
  3683. // require("./strophe.moderate")(XMPP, eventEmitter);
  3684. require("./strophe.util")();
  3685. require("./strophe.rayo")();
  3686. require("./strophe.logger")();
  3687. }
  3688. //!!!!!!!!!! FIXME: ...
  3689. ///**
  3690. // * If given <tt>localStream</tt> is video one this method will advertise it's
  3691. // * video type in MUC presence.
  3692. // * @param localStream new or modified <tt>LocalStream</tt>.
  3693. // */
  3694. //function broadcastLocalVideoType(localStream) {
  3695. // if (localStream.videoType)
  3696. // XMPP.addToPresence('videoType', localStream.videoType);
  3697. //}
  3698. //
  3699. //function registerListeners() {
  3700. // RTC.addStreamListener(
  3701. // broadcastLocalVideoType,
  3702. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  3703. // );
  3704. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  3705. // XMPP.addToPresence("devices", devices);
  3706. // });
  3707. //}
  3708. function XMPP(options) {
  3709. this.sessionTerminated = false;
  3710. this.eventEmitter = new EventEmitter();
  3711. this.connection = null;
  3712. this.forceMuted = false;
  3713. this.options = options;
  3714. initStrophePlugins();
  3715. // registerListeners();
  3716. Moderator.init(this, this.eventEmitter);
  3717. this.connection = createConnection(options.bosh);
  3718. Moderator.setConnection(this.connection);
  3719. }
  3720. XMPP.prototype.getConnection = function(){ return connection; };
  3721. XMPP.prototype._connect = function (jid, password) {
  3722. var self = this;
  3723. // connection.connect() starts the connection process.
  3724. //
  3725. // As the connection process proceeds, the user supplied callback will
  3726. // be triggered multiple times with status updates. The callback should
  3727. // take two arguments - the status code and the error condition.
  3728. //
  3729. // The status code will be one of the values in the Strophe.Status
  3730. // constants. The error condition will be one of the conditions defined
  3731. // in RFC 3920 or the condition ‘strophe-parsererror’.
  3732. //
  3733. // The Parameters wait, hold and route are optional and only relevant
  3734. // for BOSH connections. Please see XEP 124 for a more detailed
  3735. // explanation of the optional parameters.
  3736. //
  3737. // Connection status constants for use by the connection handler
  3738. // callback.
  3739. //
  3740. // Status.ERROR - An error has occurred (websockets specific)
  3741. // Status.CONNECTING - The connection is currently being made
  3742. // Status.CONNFAIL - The connection attempt failed
  3743. // Status.AUTHENTICATING - The connection is authenticating
  3744. // Status.AUTHFAIL - The authentication attempt failed
  3745. // Status.CONNECTED - The connection has succeeded
  3746. // Status.DISCONNECTED - The connection has been terminated
  3747. // Status.DISCONNECTING - The connection is currently being terminated
  3748. // Status.ATTACHED - The connection has been attached
  3749. var anonymousConnectionFailed = false;
  3750. var connectionFailed = false;
  3751. var lastErrorMsg;
  3752. this.connection.connect(jid, password, function (status, msg) {
  3753. console.log('Strophe status changed to',
  3754. Strophe.getStatusString(status), msg);
  3755. if (status === Strophe.Status.CONNECTED) {
  3756. if (self.options.useStunTurn) {
  3757. self.connection.jingle.getStunAndTurnCredentials();
  3758. }
  3759. console.info("My Jabber ID: " + self.connection.jid);
  3760. if (password)
  3761. authenticatedUser = true;
  3762. if (self.connection && self.connection.connected &&
  3763. Strophe.getResourceFromJid(self.connection.jid)) {
  3764. // .connected is true while connecting?
  3765. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  3766. Strophe.getResourceFromJid(self.connection.jid));
  3767. }
  3768. } else if (status === Strophe.Status.CONNFAIL) {
  3769. if (msg === 'x-strophe-bad-non-anon-jid') {
  3770. anonymousConnectionFailed = true;
  3771. }
  3772. else
  3773. {
  3774. connectionFailed = true;
  3775. }
  3776. lastErrorMsg = msg;
  3777. } else if (status === Strophe.Status.DISCONNECTED) {
  3778. if (anonymousConnectionFailed) {
  3779. // prompt user for username and password
  3780. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  3781. JitsiConnectionErrors.PASSWORD_REQUIRED);
  3782. } else if(connectionFailed) {
  3783. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  3784. JitsiConnectionErrors.OTHER_ERROR,
  3785. msg ? msg : lastErrorMsg);
  3786. } else {
  3787. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  3788. msg ? msg : lastErrorMsg);
  3789. }
  3790. } else if (status === Strophe.Status.AUTHFAIL) {
  3791. // wrong password or username, prompt user
  3792. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  3793. JitsiConnectionErrors.PASSWORD_REQUIRED);
  3794. }
  3795. });
  3796. }
  3797. XMPP.prototype.connect = function (jid, password) {
  3798. if(!jid) {
  3799. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  3800. // Force authenticated domain if room is appended with '?login=true'
  3801. if (this.options.hosts.anonymousdomain &&
  3802. window.location.search.indexOf("login=true") !== -1) {
  3803. configDomain = this.options.hosts.domain;
  3804. }
  3805. jid = configDomain || window.location.hostname;
  3806. }
  3807. return this._connect(jid, password);
  3808. };
  3809. XMPP.prototype.joinRoom = function(roomName, useNicks, nick) {
  3810. var roomjid = roomName;
  3811. if (useNicks) {
  3812. if (nick) {
  3813. roomjid += '/' + nick;
  3814. } else {
  3815. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  3816. }
  3817. } else {
  3818. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  3819. if(!authenticatedUser)
  3820. tmpJid = tmpJid.substr(0, 8);
  3821. roomjid += '/' + tmpJid;
  3822. }
  3823. this.connection.emuc.doJoin(roomjid);
  3824. };
  3825. XMPP.prototype.myJid = function () {
  3826. if(!this.connection)
  3827. return null;
  3828. return this.connection.emuc.myroomjid;
  3829. }
  3830. XMPP.prototype.myResource = function () {
  3831. if(!this.connection || ! this.connection.emuc.myroomjid)
  3832. return null;
  3833. return Strophe.getResourceFromJid(this.connection.emuc.myroomjid);
  3834. }
  3835. XMPP.prototype.disposeConference = function (onUnload) {
  3836. var handler = this.connection.jingle.activecall;
  3837. if (handler && handler.peerconnection) {
  3838. // FIXME: probably removing streams is not required and close() should
  3839. // be enough
  3840. if (RTC.localAudio) {
  3841. handler.peerconnection.removeStream(
  3842. RTC.localAudio.getOriginalStream(), onUnload);
  3843. }
  3844. if (RTC.localVideo) {
  3845. handler.peerconnection.removeStream(
  3846. RTC.localVideo.getOriginalStream(), onUnload);
  3847. }
  3848. handler.peerconnection.close();
  3849. }
  3850. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  3851. this.connection.jingle.activecall = null;
  3852. if (!onUnload) {
  3853. this.sessionTerminated = true;
  3854. this.connection.emuc.doLeave();
  3855. }
  3856. };
  3857. XMPP.prototype.addListener = function(type, listener) {
  3858. this.eventEmitter.on(type, listener);
  3859. };
  3860. XMPP.prototype.removeListener = function (type, listener) {
  3861. this.eventEmitter.removeListener(type, listener);
  3862. };
  3863. XMPP.prototype.leaveRoom = function () {
  3864. this.connection.emuc.doLeave();
  3865. };
  3866. XMPP.prototype.allocateConferenceFocus = function(roomName, callback) {
  3867. Moderator.allocateConferenceFocus(roomName, callback);
  3868. };
  3869. XMPP.prototype.getLoginUrl = function (roomName, callback) {
  3870. Moderator.getLoginUrl(roomName, callback);
  3871. }
  3872. XMPP.prototype.getPopupLoginUrl = function (roomName, callback) {
  3873. Moderator.getPopupLoginUrl(roomName, callback);
  3874. };
  3875. XMPP.prototype.isModerator = function () {
  3876. return Moderator.isModerator();
  3877. };
  3878. XMPP.prototype.isSipGatewayEnabled = function () {
  3879. return Moderator.isSipGatewayEnabled();
  3880. }
  3881. XMPP.prototype.isExternalAuthEnabled = function () {
  3882. return Moderator.isExternalAuthEnabled();
  3883. };
  3884. XMPP.prototype.isConferenceInProgress = function () {
  3885. return this.connection && this.connection.jingle.activecall &&
  3886. this.connection.jingle.activecall.peerconnection;
  3887. };
  3888. XMPP.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  3889. if (this.isConferenceInProgress()) {
  3890. // FIXME: will block switchInProgress on true value in case of exception
  3891. this.connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  3892. } else {
  3893. // We are done immediately
  3894. console.warn("No conference handler or conference not started yet");
  3895. callback();
  3896. }
  3897. };
  3898. XMPP.prototype.sendVideoInfoPresence = function (mute) {
  3899. if(!this.connection)
  3900. return;
  3901. this.connection.emuc.addVideoInfoToPresence(mute);
  3902. this.connection.emuc.sendPresence();
  3903. };
  3904. XMPP.prototype.setVideoMute = function (mute, callback, options) {
  3905. if(!this.connection)
  3906. return;
  3907. var self = this;
  3908. var localCallback = function (mute) {
  3909. self.sendVideoInfoPresence(mute);
  3910. return callback(mute);
  3911. };
  3912. if(this.connection.jingle.activecall)
  3913. {
  3914. this.connection.jingle.activecall.setVideoMute(
  3915. mute, localCallback, options);
  3916. }
  3917. else {
  3918. localCallback(mute);
  3919. }
  3920. };
  3921. XMPP.prototype.setAudioMute = function (mute, callback) {
  3922. if (!(this.connection && RTC.localAudio)) {
  3923. return false;
  3924. }
  3925. if (this.forceMuted && !mute) {
  3926. console.info("Asking focus for unmute");
  3927. this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  3928. // FIXME: wait for result before resetting muted status
  3929. this.forceMuted = false;
  3930. }
  3931. if (mute == RTC.localAudio.isMuted()) {
  3932. // Nothing to do
  3933. return true;
  3934. }
  3935. RTC.localAudio.setMute(mute);
  3936. this.sendAudioInfoPresence(mute, callback);
  3937. return true;
  3938. };
  3939. XMPP.prototype.sendAudioInfoPresence = function(mute, callback) {
  3940. if(this.connection) {
  3941. this.connection.emuc.addAudioInfoToPresence(mute);
  3942. this.connection.emuc.sendPresence();
  3943. }
  3944. callback();
  3945. return true;
  3946. };
  3947. XMPP.prototype.addToPresence = function (name, value, dontSend) {
  3948. switch (name) {
  3949. case "displayName":
  3950. this.connection.emuc.addDisplayNameToPresence(value);
  3951. break;
  3952. case "prezi":
  3953. this.connection.emuc.addPreziToPresence(value, 0);
  3954. break;
  3955. case "preziSlide":
  3956. this.connection.emuc.addCurrentSlideToPresence(value);
  3957. break;
  3958. case "connectionQuality":
  3959. this.connection.emuc.addConnectionInfoToPresence(value);
  3960. break;
  3961. case "email":
  3962. this.connection.emuc.addEmailToPresence(value);
  3963. break;
  3964. case "devices":
  3965. this.connection.emuc.addDevicesToPresence(value);
  3966. break;
  3967. case "videoType":
  3968. this.connection.emuc.addVideoTypeToPresence(value);
  3969. break;
  3970. case "startMuted":
  3971. if(!Moderator.isModerator())
  3972. return;
  3973. this.connection.emuc.addStartMutedToPresence(value[0],
  3974. value[1]);
  3975. break;
  3976. default :
  3977. console.log("Unknown tag for presence: " + name);
  3978. return;
  3979. }
  3980. if (!dontSend)
  3981. this.connection.emuc.sendPresence();
  3982. };
  3983. /**
  3984. * Sends 'data' as a log message to the focus. Returns true iff a message
  3985. * was sent.
  3986. * @param data
  3987. * @returns {boolean} true iff a message was sent.
  3988. */
  3989. XMPP.prototype.sendLogs = function (data) {
  3990. if(!this.connection.emuc.focusMucJid)
  3991. return false;
  3992. var deflate = true;
  3993. var content = JSON.stringify(data);
  3994. if (deflate) {
  3995. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  3996. }
  3997. content = Base64.encode(content);
  3998. // XEP-0337-ish
  3999. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  4000. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  4001. id: 'PeerConnectionStats'});
  4002. message.c('message').t(content).up();
  4003. if (deflate) {
  4004. message.c('tag', {name: "deflated", value: "true"}).up();
  4005. }
  4006. message.up();
  4007. this.connection.send(message);
  4008. return true;
  4009. };
  4010. // Gets the logs from strophe.jingle.
  4011. XMPP.prototype.getJingleLog = function () {
  4012. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  4013. };
  4014. // Gets the logs from strophe.
  4015. XMPP.prototype.getXmppLog = function () {
  4016. return this.connection.logger ? this.connection.logger.log : null;
  4017. };
  4018. XMPP.prototype.sendChatMessage = function (message, nickname) {
  4019. this.connection.emuc.sendMessage(message, nickname);
  4020. };
  4021. XMPP.prototype.setSubject = function (topic) {
  4022. this.connection.emuc.setSubject(topic);
  4023. };
  4024. XMPP.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  4025. this.connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  4026. };
  4027. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  4028. this.connection.rayo.dial(to, from, roomName,roomPass);
  4029. };
  4030. XMPP.prototype.setMute = function (jid, mute) {
  4031. this.connection.moderate.setMute(jid, mute);
  4032. };
  4033. XMPP.prototype.eject = function (jid) {
  4034. this.connection.moderate.eject(jid);
  4035. };
  4036. XMPP.prototype.logout = function (callback) {
  4037. Moderator.logout(callback);
  4038. };
  4039. XMPP.prototype.findJidFromResource = function (resource) {
  4040. return this.connection.emuc.findJidFromResource(resource);
  4041. };
  4042. XMPP.prototype.getMembers = function () {
  4043. return this.connection.emuc.members;
  4044. };
  4045. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  4046. if (!this.isConferenceInProgress())
  4047. return null;
  4048. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  4049. };
  4050. // Returns true iff we have joined the MUC.
  4051. XMPP.prototype.isMUCJoined = function () {
  4052. return this.connection.emuc.joined;
  4053. };
  4054. XMPP.prototype.getSessions = function () {
  4055. return this.connection.jingle.sessions;
  4056. };
  4057. XMPP.prototype.removeStream = function (stream) {
  4058. if (!this.isConferenceInProgress())
  4059. return;
  4060. this.connection.jingle.activecall.peerconnection.removeStream(stream);
  4061. };
  4062. XMPP.prototype.disconnect = function (callback) {
  4063. if (disconnectInProgress || !this.connection || !this.connection.connected)
  4064. {
  4065. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  4066. return;
  4067. }
  4068. disconnectInProgress = true;
  4069. this.connection.disconnect();
  4070. };
  4071. module.exports = XMPP;
  4072. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":40,"../../service/RTC/StreamEventTypes":42,"../../service/xmpp/XMPPEvents":46,"../RTC/RTC":11,"./moderator":17,"./strophe.logger":18,"./strophe.rayo":19,"./strophe.util":20,"events":47,"pako":23}],22:[function(require,module,exports){
  4073. (function (process,global){
  4074. /*!
  4075. * @overview es6-promise - a tiny implementation of Promises/A+.
  4076. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  4077. * @license Licensed under MIT license
  4078. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  4079. * @version 3.0.2
  4080. */
  4081. (function() {
  4082. "use strict";
  4083. function lib$es6$promise$utils$$objectOrFunction(x) {
  4084. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  4085. }
  4086. function lib$es6$promise$utils$$isFunction(x) {
  4087. return typeof x === 'function';
  4088. }
  4089. function lib$es6$promise$utils$$isMaybeThenable(x) {
  4090. return typeof x === 'object' && x !== null;
  4091. }
  4092. var lib$es6$promise$utils$$_isArray;
  4093. if (!Array.isArray) {
  4094. lib$es6$promise$utils$$_isArray = function (x) {
  4095. return Object.prototype.toString.call(x) === '[object Array]';
  4096. };
  4097. } else {
  4098. lib$es6$promise$utils$$_isArray = Array.isArray;
  4099. }
  4100. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  4101. var lib$es6$promise$asap$$len = 0;
  4102. var lib$es6$promise$asap$$toString = {}.toString;
  4103. var lib$es6$promise$asap$$vertxNext;
  4104. var lib$es6$promise$asap$$customSchedulerFn;
  4105. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  4106. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  4107. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  4108. lib$es6$promise$asap$$len += 2;
  4109. if (lib$es6$promise$asap$$len === 2) {
  4110. // If len is 2, that means that we need to schedule an async flush.
  4111. // If additional callbacks are queued before the queue is flushed, they
  4112. // will be processed by this flush that we are scheduling.
  4113. if (lib$es6$promise$asap$$customSchedulerFn) {
  4114. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  4115. } else {
  4116. lib$es6$promise$asap$$scheduleFlush();
  4117. }
  4118. }
  4119. }
  4120. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  4121. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  4122. }
  4123. function lib$es6$promise$asap$$setAsap(asapFn) {
  4124. lib$es6$promise$asap$$asap = asapFn;
  4125. }
  4126. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  4127. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  4128. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  4129. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  4130. // test for web worker but not in IE10
  4131. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  4132. typeof importScripts !== 'undefined' &&
  4133. typeof MessageChannel !== 'undefined';
  4134. // node
  4135. function lib$es6$promise$asap$$useNextTick() {
  4136. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  4137. // see https://github.com/cujojs/when/issues/410 for details
  4138. return function() {
  4139. process.nextTick(lib$es6$promise$asap$$flush);
  4140. };
  4141. }
  4142. // vertx
  4143. function lib$es6$promise$asap$$useVertxTimer() {
  4144. return function() {
  4145. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  4146. };
  4147. }
  4148. function lib$es6$promise$asap$$useMutationObserver() {
  4149. var iterations = 0;
  4150. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  4151. var node = document.createTextNode('');
  4152. observer.observe(node, { characterData: true });
  4153. return function() {
  4154. node.data = (iterations = ++iterations % 2);
  4155. };
  4156. }
  4157. // web worker
  4158. function lib$es6$promise$asap$$useMessageChannel() {
  4159. var channel = new MessageChannel();
  4160. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  4161. return function () {
  4162. channel.port2.postMessage(0);
  4163. };
  4164. }
  4165. function lib$es6$promise$asap$$useSetTimeout() {
  4166. return function() {
  4167. setTimeout(lib$es6$promise$asap$$flush, 1);
  4168. };
  4169. }
  4170. var lib$es6$promise$asap$$queue = new Array(1000);
  4171. function lib$es6$promise$asap$$flush() {
  4172. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  4173. var callback = lib$es6$promise$asap$$queue[i];
  4174. var arg = lib$es6$promise$asap$$queue[i+1];
  4175. callback(arg);
  4176. lib$es6$promise$asap$$queue[i] = undefined;
  4177. lib$es6$promise$asap$$queue[i+1] = undefined;
  4178. }
  4179. lib$es6$promise$asap$$len = 0;
  4180. }
  4181. function lib$es6$promise$asap$$attemptVertx() {
  4182. try {
  4183. var r = require;
  4184. var vertx = r('vertx');
  4185. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  4186. return lib$es6$promise$asap$$useVertxTimer();
  4187. } catch(e) {
  4188. return lib$es6$promise$asap$$useSetTimeout();
  4189. }
  4190. }
  4191. var lib$es6$promise$asap$$scheduleFlush;
  4192. // Decide what async method to use to triggering processing of queued callbacks:
  4193. if (lib$es6$promise$asap$$isNode) {
  4194. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  4195. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  4196. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  4197. } else if (lib$es6$promise$asap$$isWorker) {
  4198. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  4199. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  4200. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  4201. } else {
  4202. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  4203. }
  4204. function lib$es6$promise$$internal$$noop() {}
  4205. var lib$es6$promise$$internal$$PENDING = void 0;
  4206. var lib$es6$promise$$internal$$FULFILLED = 1;
  4207. var lib$es6$promise$$internal$$REJECTED = 2;
  4208. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  4209. function lib$es6$promise$$internal$$selfFulfillment() {
  4210. return new TypeError("You cannot resolve a promise with itself");
  4211. }
  4212. function lib$es6$promise$$internal$$cannotReturnOwn() {
  4213. return new TypeError('A promises callback cannot return that same promise.');
  4214. }
  4215. function lib$es6$promise$$internal$$getThen(promise) {
  4216. try {
  4217. return promise.then;
  4218. } catch(error) {
  4219. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  4220. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  4221. }
  4222. }
  4223. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  4224. try {
  4225. then.call(value, fulfillmentHandler, rejectionHandler);
  4226. } catch(e) {
  4227. return e;
  4228. }
  4229. }
  4230. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  4231. lib$es6$promise$asap$$asap(function(promise) {
  4232. var sealed = false;
  4233. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  4234. if (sealed) { return; }
  4235. sealed = true;
  4236. if (thenable !== value) {
  4237. lib$es6$promise$$internal$$resolve(promise, value);
  4238. } else {
  4239. lib$es6$promise$$internal$$fulfill(promise, value);
  4240. }
  4241. }, function(reason) {
  4242. if (sealed) { return; }
  4243. sealed = true;
  4244. lib$es6$promise$$internal$$reject(promise, reason);
  4245. }, 'Settle: ' + (promise._label || ' unknown promise'));
  4246. if (!sealed && error) {
  4247. sealed = true;
  4248. lib$es6$promise$$internal$$reject(promise, error);
  4249. }
  4250. }, promise);
  4251. }
  4252. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  4253. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  4254. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  4255. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  4256. lib$es6$promise$$internal$$reject(promise, thenable._result);
  4257. } else {
  4258. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  4259. lib$es6$promise$$internal$$resolve(promise, value);
  4260. }, function(reason) {
  4261. lib$es6$promise$$internal$$reject(promise, reason);
  4262. });
  4263. }
  4264. }
  4265. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  4266. if (maybeThenable.constructor === promise.constructor) {
  4267. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  4268. } else {
  4269. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  4270. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  4271. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  4272. } else if (then === undefined) {
  4273. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  4274. } else if (lib$es6$promise$utils$$isFunction(then)) {
  4275. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  4276. } else {
  4277. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  4278. }
  4279. }
  4280. }
  4281. function lib$es6$promise$$internal$$resolve(promise, value) {
  4282. if (promise === value) {
  4283. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  4284. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  4285. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  4286. } else {
  4287. lib$es6$promise$$internal$$fulfill(promise, value);
  4288. }
  4289. }
  4290. function lib$es6$promise$$internal$$publishRejection(promise) {
  4291. if (promise._onerror) {
  4292. promise._onerror(promise._result);
  4293. }
  4294. lib$es6$promise$$internal$$publish(promise);
  4295. }
  4296. function lib$es6$promise$$internal$$fulfill(promise, value) {
  4297. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  4298. promise._result = value;
  4299. promise._state = lib$es6$promise$$internal$$FULFILLED;
  4300. if (promise._subscribers.length !== 0) {
  4301. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  4302. }
  4303. }
  4304. function lib$es6$promise$$internal$$reject(promise, reason) {
  4305. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  4306. promise._state = lib$es6$promise$$internal$$REJECTED;
  4307. promise._result = reason;
  4308. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  4309. }
  4310. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  4311. var subscribers = parent._subscribers;
  4312. var length = subscribers.length;
  4313. parent._onerror = null;
  4314. subscribers[length] = child;
  4315. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  4316. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  4317. if (length === 0 && parent._state) {
  4318. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  4319. }
  4320. }
  4321. function lib$es6$promise$$internal$$publish(promise) {
  4322. var subscribers = promise._subscribers;
  4323. var settled = promise._state;
  4324. if (subscribers.length === 0) { return; }
  4325. var child, callback, detail = promise._result;
  4326. for (var i = 0; i < subscribers.length; i += 3) {
  4327. child = subscribers[i];
  4328. callback = subscribers[i + settled];
  4329. if (child) {
  4330. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  4331. } else {
  4332. callback(detail);
  4333. }
  4334. }
  4335. promise._subscribers.length = 0;
  4336. }
  4337. function lib$es6$promise$$internal$$ErrorObject() {
  4338. this.error = null;
  4339. }
  4340. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  4341. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  4342. try {
  4343. return callback(detail);
  4344. } catch(e) {
  4345. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  4346. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  4347. }
  4348. }
  4349. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  4350. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  4351. value, error, succeeded, failed;
  4352. if (hasCallback) {
  4353. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  4354. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  4355. failed = true;
  4356. error = value.error;
  4357. value = null;
  4358. } else {
  4359. succeeded = true;
  4360. }
  4361. if (promise === value) {
  4362. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  4363. return;
  4364. }
  4365. } else {
  4366. value = detail;
  4367. succeeded = true;
  4368. }
  4369. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  4370. // noop
  4371. } else if (hasCallback && succeeded) {
  4372. lib$es6$promise$$internal$$resolve(promise, value);
  4373. } else if (failed) {
  4374. lib$es6$promise$$internal$$reject(promise, error);
  4375. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  4376. lib$es6$promise$$internal$$fulfill(promise, value);
  4377. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  4378. lib$es6$promise$$internal$$reject(promise, value);
  4379. }
  4380. }
  4381. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  4382. try {
  4383. resolver(function resolvePromise(value){
  4384. lib$es6$promise$$internal$$resolve(promise, value);
  4385. }, function rejectPromise(reason) {
  4386. lib$es6$promise$$internal$$reject(promise, reason);
  4387. });
  4388. } catch(e) {
  4389. lib$es6$promise$$internal$$reject(promise, e);
  4390. }
  4391. }
  4392. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  4393. var enumerator = this;
  4394. enumerator._instanceConstructor = Constructor;
  4395. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  4396. if (enumerator._validateInput(input)) {
  4397. enumerator._input = input;
  4398. enumerator.length = input.length;
  4399. enumerator._remaining = input.length;
  4400. enumerator._init();
  4401. if (enumerator.length === 0) {
  4402. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  4403. } else {
  4404. enumerator.length = enumerator.length || 0;
  4405. enumerator._enumerate();
  4406. if (enumerator._remaining === 0) {
  4407. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  4408. }
  4409. }
  4410. } else {
  4411. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  4412. }
  4413. }
  4414. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  4415. return lib$es6$promise$utils$$isArray(input);
  4416. };
  4417. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  4418. return new Error('Array Methods must be provided an Array');
  4419. };
  4420. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  4421. this._result = new Array(this.length);
  4422. };
  4423. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  4424. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  4425. var enumerator = this;
  4426. var length = enumerator.length;
  4427. var promise = enumerator.promise;
  4428. var input = enumerator._input;
  4429. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  4430. enumerator._eachEntry(input[i], i);
  4431. }
  4432. };
  4433. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  4434. var enumerator = this;
  4435. var c = enumerator._instanceConstructor;
  4436. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  4437. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  4438. entry._onerror = null;
  4439. enumerator._settledAt(entry._state, i, entry._result);
  4440. } else {
  4441. enumerator._willSettleAt(c.resolve(entry), i);
  4442. }
  4443. } else {
  4444. enumerator._remaining--;
  4445. enumerator._result[i] = entry;
  4446. }
  4447. };
  4448. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  4449. var enumerator = this;
  4450. var promise = enumerator.promise;
  4451. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  4452. enumerator._remaining--;
  4453. if (state === lib$es6$promise$$internal$$REJECTED) {
  4454. lib$es6$promise$$internal$$reject(promise, value);
  4455. } else {
  4456. enumerator._result[i] = value;
  4457. }
  4458. }
  4459. if (enumerator._remaining === 0) {
  4460. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  4461. }
  4462. };
  4463. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  4464. var enumerator = this;
  4465. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  4466. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  4467. }, function(reason) {
  4468. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  4469. });
  4470. };
  4471. function lib$es6$promise$promise$all$$all(entries) {
  4472. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  4473. }
  4474. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  4475. function lib$es6$promise$promise$race$$race(entries) {
  4476. /*jshint validthis:true */
  4477. var Constructor = this;
  4478. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  4479. if (!lib$es6$promise$utils$$isArray(entries)) {
  4480. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  4481. return promise;
  4482. }
  4483. var length = entries.length;
  4484. function onFulfillment(value) {
  4485. lib$es6$promise$$internal$$resolve(promise, value);
  4486. }
  4487. function onRejection(reason) {
  4488. lib$es6$promise$$internal$$reject(promise, reason);
  4489. }
  4490. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  4491. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  4492. }
  4493. return promise;
  4494. }
  4495. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  4496. function lib$es6$promise$promise$resolve$$resolve(object) {
  4497. /*jshint validthis:true */
  4498. var Constructor = this;
  4499. if (object && typeof object === 'object' && object.constructor === Constructor) {
  4500. return object;
  4501. }
  4502. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  4503. lib$es6$promise$$internal$$resolve(promise, object);
  4504. return promise;
  4505. }
  4506. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  4507. function lib$es6$promise$promise$reject$$reject(reason) {
  4508. /*jshint validthis:true */
  4509. var Constructor = this;
  4510. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  4511. lib$es6$promise$$internal$$reject(promise, reason);
  4512. return promise;
  4513. }
  4514. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  4515. var lib$es6$promise$promise$$counter = 0;
  4516. function lib$es6$promise$promise$$needsResolver() {
  4517. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  4518. }
  4519. function lib$es6$promise$promise$$needsNew() {
  4520. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  4521. }
  4522. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  4523. /**
  4524. Promise objects represent the eventual result of an asynchronous operation. The
  4525. primary way of interacting with a promise is through its `then` method, which
  4526. registers callbacks to receive either a promise's eventual value or the reason
  4527. why the promise cannot be fulfilled.
  4528. Terminology
  4529. -----------
  4530. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  4531. - `thenable` is an object or function that defines a `then` method.
  4532. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  4533. - `exception` is a value that is thrown using the throw statement.
  4534. - `reason` is a value that indicates why a promise was rejected.
  4535. - `settled` the final resting state of a promise, fulfilled or rejected.
  4536. A promise can be in one of three states: pending, fulfilled, or rejected.
  4537. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  4538. state. Promises that are rejected have a rejection reason and are in the
  4539. rejected state. A fulfillment value is never a thenable.
  4540. Promises can also be said to *resolve* a value. If this value is also a
  4541. promise, then the original promise's settled state will match the value's
  4542. settled state. So a promise that *resolves* a promise that rejects will
  4543. itself reject, and a promise that *resolves* a promise that fulfills will
  4544. itself fulfill.
  4545. Basic Usage:
  4546. ------------
  4547. ```js
  4548. var promise = new Promise(function(resolve, reject) {
  4549. // on success
  4550. resolve(value);
  4551. // on failure
  4552. reject(reason);
  4553. });
  4554. promise.then(function(value) {
  4555. // on fulfillment
  4556. }, function(reason) {
  4557. // on rejection
  4558. });
  4559. ```
  4560. Advanced Usage:
  4561. ---------------
  4562. Promises shine when abstracting away asynchronous interactions such as
  4563. `XMLHttpRequest`s.
  4564. ```js
  4565. function getJSON(url) {
  4566. return new Promise(function(resolve, reject){
  4567. var xhr = new XMLHttpRequest();
  4568. xhr.open('GET', url);
  4569. xhr.onreadystatechange = handler;
  4570. xhr.responseType = 'json';
  4571. xhr.setRequestHeader('Accept', 'application/json');
  4572. xhr.send();
  4573. function handler() {
  4574. if (this.readyState === this.DONE) {
  4575. if (this.status === 200) {
  4576. resolve(this.response);
  4577. } else {
  4578. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  4579. }
  4580. }
  4581. };
  4582. });
  4583. }
  4584. getJSON('/posts.json').then(function(json) {
  4585. // on fulfillment
  4586. }, function(reason) {
  4587. // on rejection
  4588. });
  4589. ```
  4590. Unlike callbacks, promises are great composable primitives.
  4591. ```js
  4592. Promise.all([
  4593. getJSON('/posts'),
  4594. getJSON('/comments')
  4595. ]).then(function(values){
  4596. values[0] // => postsJSON
  4597. values[1] // => commentsJSON
  4598. return values;
  4599. });
  4600. ```
  4601. @class Promise
  4602. @param {function} resolver
  4603. Useful for tooling.
  4604. @constructor
  4605. */
  4606. function lib$es6$promise$promise$$Promise(resolver) {
  4607. this._id = lib$es6$promise$promise$$counter++;
  4608. this._state = undefined;
  4609. this._result = undefined;
  4610. this._subscribers = [];
  4611. if (lib$es6$promise$$internal$$noop !== resolver) {
  4612. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  4613. lib$es6$promise$promise$$needsResolver();
  4614. }
  4615. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  4616. lib$es6$promise$promise$$needsNew();
  4617. }
  4618. lib$es6$promise$$internal$$initializePromise(this, resolver);
  4619. }
  4620. }
  4621. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  4622. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  4623. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  4624. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  4625. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  4626. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  4627. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  4628. lib$es6$promise$promise$$Promise.prototype = {
  4629. constructor: lib$es6$promise$promise$$Promise,
  4630. /**
  4631. The primary way of interacting with a promise is through its `then` method,
  4632. which registers callbacks to receive either a promise's eventual value or the
  4633. reason why the promise cannot be fulfilled.
  4634. ```js
  4635. findUser().then(function(user){
  4636. // user is available
  4637. }, function(reason){
  4638. // user is unavailable, and you are given the reason why
  4639. });
  4640. ```
  4641. Chaining
  4642. --------
  4643. The return value of `then` is itself a promise. This second, 'downstream'
  4644. promise is resolved with the return value of the first promise's fulfillment
  4645. or rejection handler, or rejected if the handler throws an exception.
  4646. ```js
  4647. findUser().then(function (user) {
  4648. return user.name;
  4649. }, function (reason) {
  4650. return 'default name';
  4651. }).then(function (userName) {
  4652. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  4653. // will be `'default name'`
  4654. });
  4655. findUser().then(function (user) {
  4656. throw new Error('Found user, but still unhappy');
  4657. }, function (reason) {
  4658. throw new Error('`findUser` rejected and we're unhappy');
  4659. }).then(function (value) {
  4660. // never reached
  4661. }, function (reason) {
  4662. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  4663. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  4664. });
  4665. ```
  4666. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  4667. ```js
  4668. findUser().then(function (user) {
  4669. throw new PedagogicalException('Upstream error');
  4670. }).then(function (value) {
  4671. // never reached
  4672. }).then(function (value) {
  4673. // never reached
  4674. }, function (reason) {
  4675. // The `PedgagocialException` is propagated all the way down to here
  4676. });
  4677. ```
  4678. Assimilation
  4679. ------------
  4680. Sometimes the value you want to propagate to a downstream promise can only be
  4681. retrieved asynchronously. This can be achieved by returning a promise in the
  4682. fulfillment or rejection handler. The downstream promise will then be pending
  4683. until the returned promise is settled. This is called *assimilation*.
  4684. ```js
  4685. findUser().then(function (user) {
  4686. return findCommentsByAuthor(user);
  4687. }).then(function (comments) {
  4688. // The user's comments are now available
  4689. });
  4690. ```
  4691. If the assimliated promise rejects, then the downstream promise will also reject.
  4692. ```js
  4693. findUser().then(function (user) {
  4694. return findCommentsByAuthor(user);
  4695. }).then(function (comments) {
  4696. // If `findCommentsByAuthor` fulfills, we'll have the value here
  4697. }, function (reason) {
  4698. // If `findCommentsByAuthor` rejects, we'll have the reason here
  4699. });
  4700. ```
  4701. Simple Example
  4702. --------------
  4703. Synchronous Example
  4704. ```javascript
  4705. var result;
  4706. try {
  4707. result = findResult();
  4708. // success
  4709. } catch(reason) {
  4710. // failure
  4711. }
  4712. ```
  4713. Errback Example
  4714. ```js
  4715. findResult(function(result, err){
  4716. if (err) {
  4717. // failure
  4718. } else {
  4719. // success
  4720. }
  4721. });
  4722. ```
  4723. Promise Example;
  4724. ```javascript
  4725. findResult().then(function(result){
  4726. // success
  4727. }, function(reason){
  4728. // failure
  4729. });
  4730. ```
  4731. Advanced Example
  4732. --------------
  4733. Synchronous Example
  4734. ```javascript
  4735. var author, books;
  4736. try {
  4737. author = findAuthor();
  4738. books = findBooksByAuthor(author);
  4739. // success
  4740. } catch(reason) {
  4741. // failure
  4742. }
  4743. ```
  4744. Errback Example
  4745. ```js
  4746. function foundBooks(books) {
  4747. }
  4748. function failure(reason) {
  4749. }
  4750. findAuthor(function(author, err){
  4751. if (err) {
  4752. failure(err);
  4753. // failure
  4754. } else {
  4755. try {
  4756. findBoooksByAuthor(author, function(books, err) {
  4757. if (err) {
  4758. failure(err);
  4759. } else {
  4760. try {
  4761. foundBooks(books);
  4762. } catch(reason) {
  4763. failure(reason);
  4764. }
  4765. }
  4766. });
  4767. } catch(error) {
  4768. failure(err);
  4769. }
  4770. // success
  4771. }
  4772. });
  4773. ```
  4774. Promise Example;
  4775. ```javascript
  4776. findAuthor().
  4777. then(findBooksByAuthor).
  4778. then(function(books){
  4779. // found books
  4780. }).catch(function(reason){
  4781. // something went wrong
  4782. });
  4783. ```
  4784. @method then
  4785. @param {Function} onFulfilled
  4786. @param {Function} onRejected
  4787. Useful for tooling.
  4788. @return {Promise}
  4789. */
  4790. then: function(onFulfillment, onRejection) {
  4791. var parent = this;
  4792. var state = parent._state;
  4793. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  4794. return this;
  4795. }
  4796. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  4797. var result = parent._result;
  4798. if (state) {
  4799. var callback = arguments[state - 1];
  4800. lib$es6$promise$asap$$asap(function(){
  4801. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  4802. });
  4803. } else {
  4804. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  4805. }
  4806. return child;
  4807. },
  4808. /**
  4809. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  4810. as the catch block of a try/catch statement.
  4811. ```js
  4812. function findAuthor(){
  4813. throw new Error('couldn't find that author');
  4814. }
  4815. // synchronous
  4816. try {
  4817. findAuthor();
  4818. } catch(reason) {
  4819. // something went wrong
  4820. }
  4821. // async with promises
  4822. findAuthor().catch(function(reason){
  4823. // something went wrong
  4824. });
  4825. ```
  4826. @method catch
  4827. @param {Function} onRejection
  4828. Useful for tooling.
  4829. @return {Promise}
  4830. */
  4831. 'catch': function(onRejection) {
  4832. return this.then(null, onRejection);
  4833. }
  4834. };
  4835. function lib$es6$promise$polyfill$$polyfill() {
  4836. var local;
  4837. if (typeof global !== 'undefined') {
  4838. local = global;
  4839. } else if (typeof self !== 'undefined') {
  4840. local = self;
  4841. } else {
  4842. try {
  4843. local = Function('return this')();
  4844. } catch (e) {
  4845. throw new Error('polyfill failed because global object is unavailable in this environment');
  4846. }
  4847. }
  4848. var P = local.Promise;
  4849. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  4850. return;
  4851. }
  4852. local.Promise = lib$es6$promise$promise$$default;
  4853. }
  4854. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  4855. var lib$es6$promise$umd$$ES6Promise = {
  4856. 'Promise': lib$es6$promise$promise$$default,
  4857. 'polyfill': lib$es6$promise$polyfill$$default
  4858. };
  4859. /* global define:true module:true window: true */
  4860. if (typeof define === 'function' && define['amd']) {
  4861. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  4862. } else if (typeof module !== 'undefined' && module['exports']) {
  4863. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  4864. } else if (typeof this !== 'undefined') {
  4865. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  4866. }
  4867. lib$es6$promise$polyfill$$default();
  4868. }).call(this);
  4869. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4870. },{"_process":48}],23:[function(require,module,exports){
  4871. // Top level file is just a mixin of submodules & constants
  4872. 'use strict';
  4873. var assign = require('./lib/utils/common').assign;
  4874. var deflate = require('./lib/deflate');
  4875. var inflate = require('./lib/inflate');
  4876. var constants = require('./lib/zlib/constants');
  4877. var pako = {};
  4878. assign(pako, deflate, inflate, constants);
  4879. module.exports = pako;
  4880. },{"./lib/deflate":24,"./lib/inflate":25,"./lib/utils/common":26,"./lib/zlib/constants":29}],24:[function(require,module,exports){
  4881. 'use strict';
  4882. var zlib_deflate = require('./zlib/deflate.js');
  4883. var utils = require('./utils/common');
  4884. var strings = require('./utils/strings');
  4885. var msg = require('./zlib/messages');
  4886. var zstream = require('./zlib/zstream');
  4887. var toString = Object.prototype.toString;
  4888. /* Public constants ==========================================================*/
  4889. /* ===========================================================================*/
  4890. var Z_NO_FLUSH = 0;
  4891. var Z_FINISH = 4;
  4892. var Z_OK = 0;
  4893. var Z_STREAM_END = 1;
  4894. var Z_SYNC_FLUSH = 2;
  4895. var Z_DEFAULT_COMPRESSION = -1;
  4896. var Z_DEFAULT_STRATEGY = 0;
  4897. var Z_DEFLATED = 8;
  4898. /* ===========================================================================*/
  4899. /**
  4900. * class Deflate
  4901. *
  4902. * Generic JS-style wrapper for zlib calls. If you don't need
  4903. * streaming behaviour - use more simple functions: [[deflate]],
  4904. * [[deflateRaw]] and [[gzip]].
  4905. **/
  4906. /* internal
  4907. * Deflate.chunks -> Array
  4908. *
  4909. * Chunks of output data, if [[Deflate#onData]] not overriden.
  4910. **/
  4911. /**
  4912. * Deflate.result -> Uint8Array|Array
  4913. *
  4914. * Compressed result, generated by default [[Deflate#onData]]
  4915. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  4916. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  4917. * push a chunk with explicit flush (call [[Deflate#push]] with
  4918. * `Z_SYNC_FLUSH` param).
  4919. **/
  4920. /**
  4921. * Deflate.err -> Number
  4922. *
  4923. * Error code after deflate finished. 0 (Z_OK) on success.
  4924. * You will not need it in real life, because deflate errors
  4925. * are possible only on wrong options or bad `onData` / `onEnd`
  4926. * custom handlers.
  4927. **/
  4928. /**
  4929. * Deflate.msg -> String
  4930. *
  4931. * Error message, if [[Deflate.err]] != 0
  4932. **/
  4933. /**
  4934. * new Deflate(options)
  4935. * - options (Object): zlib deflate options.
  4936. *
  4937. * Creates new deflator instance with specified params. Throws exception
  4938. * on bad params. Supported options:
  4939. *
  4940. * - `level`
  4941. * - `windowBits`
  4942. * - `memLevel`
  4943. * - `strategy`
  4944. *
  4945. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4946. * for more information on these.
  4947. *
  4948. * Additional options, for internal needs:
  4949. *
  4950. * - `chunkSize` - size of generated data chunks (16K by default)
  4951. * - `raw` (Boolean) - do raw deflate
  4952. * - `gzip` (Boolean) - create gzip wrapper
  4953. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4954. * (each char code [0..255])
  4955. * - `header` (Object) - custom header for gzip
  4956. * - `text` (Boolean) - true if compressed data believed to be text
  4957. * - `time` (Number) - modification time, unix timestamp
  4958. * - `os` (Number) - operation system code
  4959. * - `extra` (Array) - array of bytes with extra data (max 65536)
  4960. * - `name` (String) - file name (binary string)
  4961. * - `comment` (String) - comment (binary string)
  4962. * - `hcrc` (Boolean) - true if header crc should be added
  4963. *
  4964. * ##### Example:
  4965. *
  4966. * ```javascript
  4967. * var pako = require('pako')
  4968. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4969. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4970. *
  4971. * var deflate = new pako.Deflate({ level: 3});
  4972. *
  4973. * deflate.push(chunk1, false);
  4974. * deflate.push(chunk2, true); // true -> last chunk
  4975. *
  4976. * if (deflate.err) { throw new Error(deflate.err); }
  4977. *
  4978. * console.log(deflate.result);
  4979. * ```
  4980. **/
  4981. var Deflate = function(options) {
  4982. this.options = utils.assign({
  4983. level: Z_DEFAULT_COMPRESSION,
  4984. method: Z_DEFLATED,
  4985. chunkSize: 16384,
  4986. windowBits: 15,
  4987. memLevel: 8,
  4988. strategy: Z_DEFAULT_STRATEGY,
  4989. to: ''
  4990. }, options || {});
  4991. var opt = this.options;
  4992. if (opt.raw && (opt.windowBits > 0)) {
  4993. opt.windowBits = -opt.windowBits;
  4994. }
  4995. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  4996. opt.windowBits += 16;
  4997. }
  4998. this.err = 0; // error code, if happens (0 = Z_OK)
  4999. this.msg = ''; // error message
  5000. this.ended = false; // used to avoid multiple onEnd() calls
  5001. this.chunks = []; // chunks of compressed data
  5002. this.strm = new zstream();
  5003. this.strm.avail_out = 0;
  5004. var status = zlib_deflate.deflateInit2(
  5005. this.strm,
  5006. opt.level,
  5007. opt.method,
  5008. opt.windowBits,
  5009. opt.memLevel,
  5010. opt.strategy
  5011. );
  5012. if (status !== Z_OK) {
  5013. throw new Error(msg[status]);
  5014. }
  5015. if (opt.header) {
  5016. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  5017. }
  5018. };
  5019. /**
  5020. * Deflate#push(data[, mode]) -> Boolean
  5021. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  5022. * converted to utf8 byte sequence.
  5023. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5024. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5025. *
  5026. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  5027. * new compressed chunks. Returns `true` on success. The last data block must have
  5028. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5029. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5030. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  5031. *
  5032. * On fail call [[Deflate#onEnd]] with error code and return false.
  5033. *
  5034. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5035. * array format is detected automatically). Also, don't skip last param and always
  5036. * use the same type in your code (boolean or number). That will improve JS speed.
  5037. *
  5038. * For regular `Array`-s make sure all elements are [0..255].
  5039. *
  5040. * ##### Example
  5041. *
  5042. * ```javascript
  5043. * push(chunk, false); // push one of data chunks
  5044. * ...
  5045. * push(chunk, true); // push last chunk
  5046. * ```
  5047. **/
  5048. Deflate.prototype.push = function(data, mode) {
  5049. var strm = this.strm;
  5050. var chunkSize = this.options.chunkSize;
  5051. var status, _mode;
  5052. if (this.ended) { return false; }
  5053. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  5054. // Convert data if needed
  5055. if (typeof data === 'string') {
  5056. // If we need to compress text, change encoding to utf8.
  5057. strm.input = strings.string2buf(data);
  5058. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5059. strm.input = new Uint8Array(data);
  5060. } else {
  5061. strm.input = data;
  5062. }
  5063. strm.next_in = 0;
  5064. strm.avail_in = strm.input.length;
  5065. do {
  5066. if (strm.avail_out === 0) {
  5067. strm.output = new utils.Buf8(chunkSize);
  5068. strm.next_out = 0;
  5069. strm.avail_out = chunkSize;
  5070. }
  5071. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  5072. if (status !== Z_STREAM_END && status !== Z_OK) {
  5073. this.onEnd(status);
  5074. this.ended = true;
  5075. return false;
  5076. }
  5077. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  5078. if (this.options.to === 'string') {
  5079. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  5080. } else {
  5081. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5082. }
  5083. }
  5084. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  5085. // Finalize on the last chunk.
  5086. if (_mode === Z_FINISH) {
  5087. status = zlib_deflate.deflateEnd(this.strm);
  5088. this.onEnd(status);
  5089. this.ended = true;
  5090. return status === Z_OK;
  5091. }
  5092. // callback interim results if Z_SYNC_FLUSH.
  5093. if (_mode === Z_SYNC_FLUSH) {
  5094. this.onEnd(Z_OK);
  5095. strm.avail_out = 0;
  5096. return true;
  5097. }
  5098. return true;
  5099. };
  5100. /**
  5101. * Deflate#onData(chunk) -> Void
  5102. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5103. * on js engine support. When string output requested, each chunk
  5104. * will be string.
  5105. *
  5106. * By default, stores data blocks in `chunks[]` property and glue
  5107. * those in `onEnd`. Override this handler, if you need another behaviour.
  5108. **/
  5109. Deflate.prototype.onData = function(chunk) {
  5110. this.chunks.push(chunk);
  5111. };
  5112. /**
  5113. * Deflate#onEnd(status) -> Void
  5114. * - status (Number): deflate status. 0 (Z_OK) on success,
  5115. * other if not.
  5116. *
  5117. * Called once after you tell deflate that the input stream is
  5118. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5119. * or if an error happened. By default - join collected chunks,
  5120. * free memory and fill `results` / `err` properties.
  5121. **/
  5122. Deflate.prototype.onEnd = function(status) {
  5123. // On success - join
  5124. if (status === Z_OK) {
  5125. if (this.options.to === 'string') {
  5126. this.result = this.chunks.join('');
  5127. } else {
  5128. this.result = utils.flattenChunks(this.chunks);
  5129. }
  5130. }
  5131. this.chunks = [];
  5132. this.err = status;
  5133. this.msg = this.strm.msg;
  5134. };
  5135. /**
  5136. * deflate(data[, options]) -> Uint8Array|Array|String
  5137. * - data (Uint8Array|Array|String): input data to compress.
  5138. * - options (Object): zlib deflate options.
  5139. *
  5140. * Compress `data` with deflate alrorythm and `options`.
  5141. *
  5142. * Supported options are:
  5143. *
  5144. * - level
  5145. * - windowBits
  5146. * - memLevel
  5147. * - strategy
  5148. *
  5149. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5150. * for more information on these.
  5151. *
  5152. * Sugar (options):
  5153. *
  5154. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5155. * negative windowBits implicitly.
  5156. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5157. * (each char code [0..255])
  5158. *
  5159. * ##### Example:
  5160. *
  5161. * ```javascript
  5162. * var pako = require('pako')
  5163. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  5164. *
  5165. * console.log(pako.deflate(data));
  5166. * ```
  5167. **/
  5168. function deflate(input, options) {
  5169. var deflator = new Deflate(options);
  5170. deflator.push(input, true);
  5171. // That will never happens, if you don't cheat with options :)
  5172. if (deflator.err) { throw deflator.msg; }
  5173. return deflator.result;
  5174. }
  5175. /**
  5176. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  5177. * - data (Uint8Array|Array|String): input data to compress.
  5178. * - options (Object): zlib deflate options.
  5179. *
  5180. * The same as [[deflate]], but creates raw data, without wrapper
  5181. * (header and adler32 crc).
  5182. **/
  5183. function deflateRaw(input, options) {
  5184. options = options || {};
  5185. options.raw = true;
  5186. return deflate(input, options);
  5187. }
  5188. /**
  5189. * gzip(data[, options]) -> Uint8Array|Array|String
  5190. * - data (Uint8Array|Array|String): input data to compress.
  5191. * - options (Object): zlib deflate options.
  5192. *
  5193. * The same as [[deflate]], but create gzip wrapper instead of
  5194. * deflate one.
  5195. **/
  5196. function gzip(input, options) {
  5197. options = options || {};
  5198. options.gzip = true;
  5199. return deflate(input, options);
  5200. }
  5201. exports.Deflate = Deflate;
  5202. exports.deflate = deflate;
  5203. exports.deflateRaw = deflateRaw;
  5204. exports.gzip = gzip;
  5205. },{"./utils/common":26,"./utils/strings":27,"./zlib/deflate.js":31,"./zlib/messages":36,"./zlib/zstream":38}],25:[function(require,module,exports){
  5206. 'use strict';
  5207. var zlib_inflate = require('./zlib/inflate.js');
  5208. var utils = require('./utils/common');
  5209. var strings = require('./utils/strings');
  5210. var c = require('./zlib/constants');
  5211. var msg = require('./zlib/messages');
  5212. var zstream = require('./zlib/zstream');
  5213. var gzheader = require('./zlib/gzheader');
  5214. var toString = Object.prototype.toString;
  5215. /**
  5216. * class Inflate
  5217. *
  5218. * Generic JS-style wrapper for zlib calls. If you don't need
  5219. * streaming behaviour - use more simple functions: [[inflate]]
  5220. * and [[inflateRaw]].
  5221. **/
  5222. /* internal
  5223. * inflate.chunks -> Array
  5224. *
  5225. * Chunks of output data, if [[Inflate#onData]] not overriden.
  5226. **/
  5227. /**
  5228. * Inflate.result -> Uint8Array|Array|String
  5229. *
  5230. * Uncompressed result, generated by default [[Inflate#onData]]
  5231. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  5232. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  5233. * push a chunk with explicit flush (call [[Inflate#push]] with
  5234. * `Z_SYNC_FLUSH` param).
  5235. **/
  5236. /**
  5237. * Inflate.err -> Number
  5238. *
  5239. * Error code after inflate finished. 0 (Z_OK) on success.
  5240. * Should be checked if broken data possible.
  5241. **/
  5242. /**
  5243. * Inflate.msg -> String
  5244. *
  5245. * Error message, if [[Inflate.err]] != 0
  5246. **/
  5247. /**
  5248. * new Inflate(options)
  5249. * - options (Object): zlib inflate options.
  5250. *
  5251. * Creates new inflator instance with specified params. Throws exception
  5252. * on bad params. Supported options:
  5253. *
  5254. * - `windowBits`
  5255. *
  5256. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5257. * for more information on these.
  5258. *
  5259. * Additional options, for internal needs:
  5260. *
  5261. * - `chunkSize` - size of generated data chunks (16K by default)
  5262. * - `raw` (Boolean) - do raw inflate
  5263. * - `to` (String) - if equal to 'string', then result will be converted
  5264. * from utf8 to utf16 (javascript) string. When string output requested,
  5265. * chunk length can differ from `chunkSize`, depending on content.
  5266. *
  5267. * By default, when no options set, autodetect deflate/gzip data format via
  5268. * wrapper header.
  5269. *
  5270. * ##### Example:
  5271. *
  5272. * ```javascript
  5273. * var pako = require('pako')
  5274. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5275. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5276. *
  5277. * var inflate = new pako.Inflate({ level: 3});
  5278. *
  5279. * inflate.push(chunk1, false);
  5280. * inflate.push(chunk2, true); // true -> last chunk
  5281. *
  5282. * if (inflate.err) { throw new Error(inflate.err); }
  5283. *
  5284. * console.log(inflate.result);
  5285. * ```
  5286. **/
  5287. var Inflate = function(options) {
  5288. this.options = utils.assign({
  5289. chunkSize: 16384,
  5290. windowBits: 0,
  5291. to: ''
  5292. }, options || {});
  5293. var opt = this.options;
  5294. // Force window size for `raw` data, if not set directly,
  5295. // because we have no header for autodetect.
  5296. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  5297. opt.windowBits = -opt.windowBits;
  5298. if (opt.windowBits === 0) { opt.windowBits = -15; }
  5299. }
  5300. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  5301. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  5302. !(options && options.windowBits)) {
  5303. opt.windowBits += 32;
  5304. }
  5305. // Gzip header has no info about windows size, we can do autodetect only
  5306. // for deflate. So, if window size not set, force it to max when gzip possible
  5307. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  5308. // bit 3 (16) -> gzipped data
  5309. // bit 4 (32) -> autodetect gzip/deflate
  5310. if ((opt.windowBits & 15) === 0) {
  5311. opt.windowBits |= 15;
  5312. }
  5313. }
  5314. this.err = 0; // error code, if happens (0 = Z_OK)
  5315. this.msg = ''; // error message
  5316. this.ended = false; // used to avoid multiple onEnd() calls
  5317. this.chunks = []; // chunks of compressed data
  5318. this.strm = new zstream();
  5319. this.strm.avail_out = 0;
  5320. var status = zlib_inflate.inflateInit2(
  5321. this.strm,
  5322. opt.windowBits
  5323. );
  5324. if (status !== c.Z_OK) {
  5325. throw new Error(msg[status]);
  5326. }
  5327. this.header = new gzheader();
  5328. zlib_inflate.inflateGetHeader(this.strm, this.header);
  5329. };
  5330. /**
  5331. * Inflate#push(data[, mode]) -> Boolean
  5332. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  5333. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5334. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5335. *
  5336. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  5337. * new output chunks. Returns `true` on success. The last data block must have
  5338. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5339. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5340. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  5341. *
  5342. * On fail call [[Inflate#onEnd]] with error code and return false.
  5343. *
  5344. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5345. * format is detected automatically). Also, don't skip last param and always
  5346. * use the same type in your code (boolean or number). That will improve JS speed.
  5347. *
  5348. * For regular `Array`-s make sure all elements are [0..255].
  5349. *
  5350. * ##### Example
  5351. *
  5352. * ```javascript
  5353. * push(chunk, false); // push one of data chunks
  5354. * ...
  5355. * push(chunk, true); // push last chunk
  5356. * ```
  5357. **/
  5358. Inflate.prototype.push = function(data, mode) {
  5359. var strm = this.strm;
  5360. var chunkSize = this.options.chunkSize;
  5361. var status, _mode;
  5362. var next_out_utf8, tail, utf8str;
  5363. if (this.ended) { return false; }
  5364. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  5365. // Convert data if needed
  5366. if (typeof data === 'string') {
  5367. // Only binary strings can be decompressed on practice
  5368. strm.input = strings.binstring2buf(data);
  5369. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5370. strm.input = new Uint8Array(data);
  5371. } else {
  5372. strm.input = data;
  5373. }
  5374. strm.next_in = 0;
  5375. strm.avail_in = strm.input.length;
  5376. do {
  5377. if (strm.avail_out === 0) {
  5378. strm.output = new utils.Buf8(chunkSize);
  5379. strm.next_out = 0;
  5380. strm.avail_out = chunkSize;
  5381. }
  5382. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  5383. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  5384. this.onEnd(status);
  5385. this.ended = true;
  5386. return false;
  5387. }
  5388. if (strm.next_out) {
  5389. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  5390. if (this.options.to === 'string') {
  5391. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  5392. tail = strm.next_out - next_out_utf8;
  5393. utf8str = strings.buf2string(strm.output, next_out_utf8);
  5394. // move tail
  5395. strm.next_out = tail;
  5396. strm.avail_out = chunkSize - tail;
  5397. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  5398. this.onData(utf8str);
  5399. } else {
  5400. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5401. }
  5402. }
  5403. }
  5404. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  5405. if (status === c.Z_STREAM_END) {
  5406. _mode = c.Z_FINISH;
  5407. }
  5408. // Finalize on the last chunk.
  5409. if (_mode === c.Z_FINISH) {
  5410. status = zlib_inflate.inflateEnd(this.strm);
  5411. this.onEnd(status);
  5412. this.ended = true;
  5413. return status === c.Z_OK;
  5414. }
  5415. // callback interim results if Z_SYNC_FLUSH.
  5416. if (_mode === c.Z_SYNC_FLUSH) {
  5417. this.onEnd(c.Z_OK);
  5418. strm.avail_out = 0;
  5419. return true;
  5420. }
  5421. return true;
  5422. };
  5423. /**
  5424. * Inflate#onData(chunk) -> Void
  5425. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5426. * on js engine support. When string output requested, each chunk
  5427. * will be string.
  5428. *
  5429. * By default, stores data blocks in `chunks[]` property and glue
  5430. * those in `onEnd`. Override this handler, if you need another behaviour.
  5431. **/
  5432. Inflate.prototype.onData = function(chunk) {
  5433. this.chunks.push(chunk);
  5434. };
  5435. /**
  5436. * Inflate#onEnd(status) -> Void
  5437. * - status (Number): inflate status. 0 (Z_OK) on success,
  5438. * other if not.
  5439. *
  5440. * Called either after you tell inflate that the input stream is
  5441. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5442. * or if an error happened. By default - join collected chunks,
  5443. * free memory and fill `results` / `err` properties.
  5444. **/
  5445. Inflate.prototype.onEnd = function(status) {
  5446. // On success - join
  5447. if (status === c.Z_OK) {
  5448. if (this.options.to === 'string') {
  5449. // Glue & convert here, until we teach pako to send
  5450. // utf8 alligned strings to onData
  5451. this.result = this.chunks.join('');
  5452. } else {
  5453. this.result = utils.flattenChunks(this.chunks);
  5454. }
  5455. }
  5456. this.chunks = [];
  5457. this.err = status;
  5458. this.msg = this.strm.msg;
  5459. };
  5460. /**
  5461. * inflate(data[, options]) -> Uint8Array|Array|String
  5462. * - data (Uint8Array|Array|String): input data to decompress.
  5463. * - options (Object): zlib inflate options.
  5464. *
  5465. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  5466. * format via wrapper header by default. That's why we don't provide
  5467. * separate `ungzip` method.
  5468. *
  5469. * Supported options are:
  5470. *
  5471. * - windowBits
  5472. *
  5473. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5474. * for more information.
  5475. *
  5476. * Sugar (options):
  5477. *
  5478. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5479. * negative windowBits implicitly.
  5480. * - `to` (String) - if equal to 'string', then result will be converted
  5481. * from utf8 to utf16 (javascript) string. When string output requested,
  5482. * chunk length can differ from `chunkSize`, depending on content.
  5483. *
  5484. *
  5485. * ##### Example:
  5486. *
  5487. * ```javascript
  5488. * var pako = require('pako')
  5489. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  5490. * , output;
  5491. *
  5492. * try {
  5493. * output = pako.inflate(input);
  5494. * } catch (err)
  5495. * console.log(err);
  5496. * }
  5497. * ```
  5498. **/
  5499. function inflate(input, options) {
  5500. var inflator = new Inflate(options);
  5501. inflator.push(input, true);
  5502. // That will never happens, if you don't cheat with options :)
  5503. if (inflator.err) { throw inflator.msg; }
  5504. return inflator.result;
  5505. }
  5506. /**
  5507. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  5508. * - data (Uint8Array|Array|String): input data to decompress.
  5509. * - options (Object): zlib inflate options.
  5510. *
  5511. * The same as [[inflate]], but creates raw data, without wrapper
  5512. * (header and adler32 crc).
  5513. **/
  5514. function inflateRaw(input, options) {
  5515. options = options || {};
  5516. options.raw = true;
  5517. return inflate(input, options);
  5518. }
  5519. /**
  5520. * ungzip(data[, options]) -> Uint8Array|Array|String
  5521. * - data (Uint8Array|Array|String): input data to decompress.
  5522. * - options (Object): zlib inflate options.
  5523. *
  5524. * Just shortcut to [[inflate]], because it autodetects format
  5525. * by header.content. Done for convenience.
  5526. **/
  5527. exports.Inflate = Inflate;
  5528. exports.inflate = inflate;
  5529. exports.inflateRaw = inflateRaw;
  5530. exports.ungzip = inflate;
  5531. },{"./utils/common":26,"./utils/strings":27,"./zlib/constants":29,"./zlib/gzheader":32,"./zlib/inflate.js":34,"./zlib/messages":36,"./zlib/zstream":38}],26:[function(require,module,exports){
  5532. 'use strict';
  5533. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  5534. (typeof Uint16Array !== 'undefined') &&
  5535. (typeof Int32Array !== 'undefined');
  5536. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  5537. var sources = Array.prototype.slice.call(arguments, 1);
  5538. while (sources.length) {
  5539. var source = sources.shift();
  5540. if (!source) { continue; }
  5541. if (typeof source !== 'object') {
  5542. throw new TypeError(source + 'must be non-object');
  5543. }
  5544. for (var p in source) {
  5545. if (source.hasOwnProperty(p)) {
  5546. obj[p] = source[p];
  5547. }
  5548. }
  5549. }
  5550. return obj;
  5551. };
  5552. // reduce buffer size, avoiding mem copy
  5553. exports.shrinkBuf = function (buf, size) {
  5554. if (buf.length === size) { return buf; }
  5555. if (buf.subarray) { return buf.subarray(0, size); }
  5556. buf.length = size;
  5557. return buf;
  5558. };
  5559. var fnTyped = {
  5560. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5561. if (src.subarray && dest.subarray) {
  5562. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  5563. return;
  5564. }
  5565. // Fallback to ordinary array
  5566. for (var i=0; i<len; i++) {
  5567. dest[dest_offs + i] = src[src_offs + i];
  5568. }
  5569. },
  5570. // Join array of chunks to single array.
  5571. flattenChunks: function(chunks) {
  5572. var i, l, len, pos, chunk, result;
  5573. // calculate data length
  5574. len = 0;
  5575. for (i=0, l=chunks.length; i<l; i++) {
  5576. len += chunks[i].length;
  5577. }
  5578. // join chunks
  5579. result = new Uint8Array(len);
  5580. pos = 0;
  5581. for (i=0, l=chunks.length; i<l; i++) {
  5582. chunk = chunks[i];
  5583. result.set(chunk, pos);
  5584. pos += chunk.length;
  5585. }
  5586. return result;
  5587. }
  5588. };
  5589. var fnUntyped = {
  5590. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5591. for (var i=0; i<len; i++) {
  5592. dest[dest_offs + i] = src[src_offs + i];
  5593. }
  5594. },
  5595. // Join array of chunks to single array.
  5596. flattenChunks: function(chunks) {
  5597. return [].concat.apply([], chunks);
  5598. }
  5599. };
  5600. // Enable/Disable typed arrays use, for testing
  5601. //
  5602. exports.setTyped = function (on) {
  5603. if (on) {
  5604. exports.Buf8 = Uint8Array;
  5605. exports.Buf16 = Uint16Array;
  5606. exports.Buf32 = Int32Array;
  5607. exports.assign(exports, fnTyped);
  5608. } else {
  5609. exports.Buf8 = Array;
  5610. exports.Buf16 = Array;
  5611. exports.Buf32 = Array;
  5612. exports.assign(exports, fnUntyped);
  5613. }
  5614. };
  5615. exports.setTyped(TYPED_OK);
  5616. },{}],27:[function(require,module,exports){
  5617. // String encode/decode helpers
  5618. 'use strict';
  5619. var utils = require('./common');
  5620. // Quick check if we can use fast array to bin string conversion
  5621. //
  5622. // - apply(Array) can fail on Android 2.2
  5623. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  5624. //
  5625. var STR_APPLY_OK = true;
  5626. var STR_APPLY_UIA_OK = true;
  5627. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  5628. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  5629. // Table with utf8 lengths (calculated by first byte of sequence)
  5630. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  5631. // because max possible codepoint is 0x10ffff
  5632. var _utf8len = new utils.Buf8(256);
  5633. for (var q=0; q<256; q++) {
  5634. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  5635. }
  5636. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  5637. // convert string to array (typed, when possible)
  5638. exports.string2buf = function (str) {
  5639. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  5640. // count binary size
  5641. for (m_pos = 0; m_pos < str_len; m_pos++) {
  5642. c = str.charCodeAt(m_pos);
  5643. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  5644. c2 = str.charCodeAt(m_pos+1);
  5645. if ((c2 & 0xfc00) === 0xdc00) {
  5646. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5647. m_pos++;
  5648. }
  5649. }
  5650. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  5651. }
  5652. // allocate buffer
  5653. buf = new utils.Buf8(buf_len);
  5654. // convert
  5655. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  5656. c = str.charCodeAt(m_pos);
  5657. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  5658. c2 = str.charCodeAt(m_pos+1);
  5659. if ((c2 & 0xfc00) === 0xdc00) {
  5660. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5661. m_pos++;
  5662. }
  5663. }
  5664. if (c < 0x80) {
  5665. /* one byte */
  5666. buf[i++] = c;
  5667. } else if (c < 0x800) {
  5668. /* two bytes */
  5669. buf[i++] = 0xC0 | (c >>> 6);
  5670. buf[i++] = 0x80 | (c & 0x3f);
  5671. } else if (c < 0x10000) {
  5672. /* three bytes */
  5673. buf[i++] = 0xE0 | (c >>> 12);
  5674. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5675. buf[i++] = 0x80 | (c & 0x3f);
  5676. } else {
  5677. /* four bytes */
  5678. buf[i++] = 0xf0 | (c >>> 18);
  5679. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  5680. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5681. buf[i++] = 0x80 | (c & 0x3f);
  5682. }
  5683. }
  5684. return buf;
  5685. };
  5686. // Helper (used in 2 places)
  5687. function buf2binstring(buf, len) {
  5688. // use fallback for big arrays to avoid stack overflow
  5689. if (len < 65537) {
  5690. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  5691. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  5692. }
  5693. }
  5694. var result = '';
  5695. for (var i=0; i < len; i++) {
  5696. result += String.fromCharCode(buf[i]);
  5697. }
  5698. return result;
  5699. }
  5700. // Convert byte array to binary string
  5701. exports.buf2binstring = function(buf) {
  5702. return buf2binstring(buf, buf.length);
  5703. };
  5704. // Convert binary string (typed, when possible)
  5705. exports.binstring2buf = function(str) {
  5706. var buf = new utils.Buf8(str.length);
  5707. for (var i=0, len=buf.length; i < len; i++) {
  5708. buf[i] = str.charCodeAt(i);
  5709. }
  5710. return buf;
  5711. };
  5712. // convert array to string
  5713. exports.buf2string = function (buf, max) {
  5714. var i, out, c, c_len;
  5715. var len = max || buf.length;
  5716. // Reserve max possible length (2 words per char)
  5717. // NB: by unknown reasons, Array is significantly faster for
  5718. // String.fromCharCode.apply than Uint16Array.
  5719. var utf16buf = new Array(len*2);
  5720. for (out=0, i=0; i<len;) {
  5721. c = buf[i++];
  5722. // quick process ascii
  5723. if (c < 0x80) { utf16buf[out++] = c; continue; }
  5724. c_len = _utf8len[c];
  5725. // skip 5 & 6 byte codes
  5726. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  5727. // apply mask on first byte
  5728. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  5729. // join the rest
  5730. while (c_len > 1 && i < len) {
  5731. c = (c << 6) | (buf[i++] & 0x3f);
  5732. c_len--;
  5733. }
  5734. // terminated by end of string?
  5735. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5736. if (c < 0x10000) {
  5737. utf16buf[out++] = c;
  5738. } else {
  5739. c -= 0x10000;
  5740. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5741. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5742. }
  5743. }
  5744. return buf2binstring(utf16buf, out);
  5745. };
  5746. // Calculate max possible position in utf8 buffer,
  5747. // that will not break sequence. If that's not possible
  5748. // - (very small limits) return max size as is.
  5749. //
  5750. // buf[] - utf8 bytes array
  5751. // max - length limit (mandatory);
  5752. exports.utf8border = function(buf, max) {
  5753. var pos;
  5754. max = max || buf.length;
  5755. if (max > buf.length) { max = buf.length; }
  5756. // go back from last position, until start of sequence found
  5757. pos = max-1;
  5758. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  5759. // Fuckup - very small and broken sequence,
  5760. // return max, because we should return something anyway.
  5761. if (pos < 0) { return max; }
  5762. // If we came to start of buffer - that means vuffer is too small,
  5763. // return max too.
  5764. if (pos === 0) { return max; }
  5765. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  5766. };
  5767. },{"./common":26}],28:[function(require,module,exports){
  5768. 'use strict';
  5769. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  5770. // It doesn't worth to make additional optimizationa as in original.
  5771. // Small size is preferable.
  5772. function adler32(adler, buf, len, pos) {
  5773. var s1 = (adler & 0xffff) |0,
  5774. s2 = ((adler >>> 16) & 0xffff) |0,
  5775. n = 0;
  5776. while (len !== 0) {
  5777. // Set limit ~ twice less than 5552, to keep
  5778. // s2 in 31-bits, because we force signed ints.
  5779. // in other case %= will fail.
  5780. n = len > 2000 ? 2000 : len;
  5781. len -= n;
  5782. do {
  5783. s1 = (s1 + buf[pos++]) |0;
  5784. s2 = (s2 + s1) |0;
  5785. } while (--n);
  5786. s1 %= 65521;
  5787. s2 %= 65521;
  5788. }
  5789. return (s1 | (s2 << 16)) |0;
  5790. }
  5791. module.exports = adler32;
  5792. },{}],29:[function(require,module,exports){
  5793. module.exports = {
  5794. /* Allowed flush values; see deflate() and inflate() below for details */
  5795. Z_NO_FLUSH: 0,
  5796. Z_PARTIAL_FLUSH: 1,
  5797. Z_SYNC_FLUSH: 2,
  5798. Z_FULL_FLUSH: 3,
  5799. Z_FINISH: 4,
  5800. Z_BLOCK: 5,
  5801. Z_TREES: 6,
  5802. /* Return codes for the compression/decompression functions. Negative values
  5803. * are errors, positive values are used for special but normal events.
  5804. */
  5805. Z_OK: 0,
  5806. Z_STREAM_END: 1,
  5807. Z_NEED_DICT: 2,
  5808. Z_ERRNO: -1,
  5809. Z_STREAM_ERROR: -2,
  5810. Z_DATA_ERROR: -3,
  5811. //Z_MEM_ERROR: -4,
  5812. Z_BUF_ERROR: -5,
  5813. //Z_VERSION_ERROR: -6,
  5814. /* compression levels */
  5815. Z_NO_COMPRESSION: 0,
  5816. Z_BEST_SPEED: 1,
  5817. Z_BEST_COMPRESSION: 9,
  5818. Z_DEFAULT_COMPRESSION: -1,
  5819. Z_FILTERED: 1,
  5820. Z_HUFFMAN_ONLY: 2,
  5821. Z_RLE: 3,
  5822. Z_FIXED: 4,
  5823. Z_DEFAULT_STRATEGY: 0,
  5824. /* Possible values of the data_type field (though see inflate()) */
  5825. Z_BINARY: 0,
  5826. Z_TEXT: 1,
  5827. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  5828. Z_UNKNOWN: 2,
  5829. /* The deflate compression method */
  5830. Z_DEFLATED: 8
  5831. //Z_NULL: null // Use -1 or null inline, depending on var type
  5832. };
  5833. },{}],30:[function(require,module,exports){
  5834. 'use strict';
  5835. // Note: we can't get significant speed boost here.
  5836. // So write code to minimize size - no pregenerated tables
  5837. // and array tools dependencies.
  5838. // Use ordinary array, since untyped makes no boost here
  5839. function makeTable() {
  5840. var c, table = [];
  5841. for (var n =0; n < 256; n++) {
  5842. c = n;
  5843. for (var k =0; k < 8; k++) {
  5844. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  5845. }
  5846. table[n] = c;
  5847. }
  5848. return table;
  5849. }
  5850. // Create table on load. Just 255 signed longs. Not a problem.
  5851. var crcTable = makeTable();
  5852. function crc32(crc, buf, len, pos) {
  5853. var t = crcTable,
  5854. end = pos + len;
  5855. crc = crc ^ (-1);
  5856. for (var i = pos; i < end; i++) {
  5857. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  5858. }
  5859. return (crc ^ (-1)); // >>> 0;
  5860. }
  5861. module.exports = crc32;
  5862. },{}],31:[function(require,module,exports){
  5863. 'use strict';
  5864. var utils = require('../utils/common');
  5865. var trees = require('./trees');
  5866. var adler32 = require('./adler32');
  5867. var crc32 = require('./crc32');
  5868. var msg = require('./messages');
  5869. /* Public constants ==========================================================*/
  5870. /* ===========================================================================*/
  5871. /* Allowed flush values; see deflate() and inflate() below for details */
  5872. var Z_NO_FLUSH = 0;
  5873. var Z_PARTIAL_FLUSH = 1;
  5874. //var Z_SYNC_FLUSH = 2;
  5875. var Z_FULL_FLUSH = 3;
  5876. var Z_FINISH = 4;
  5877. var Z_BLOCK = 5;
  5878. //var Z_TREES = 6;
  5879. /* Return codes for the compression/decompression functions. Negative values
  5880. * are errors, positive values are used for special but normal events.
  5881. */
  5882. var Z_OK = 0;
  5883. var Z_STREAM_END = 1;
  5884. //var Z_NEED_DICT = 2;
  5885. //var Z_ERRNO = -1;
  5886. var Z_STREAM_ERROR = -2;
  5887. var Z_DATA_ERROR = -3;
  5888. //var Z_MEM_ERROR = -4;
  5889. var Z_BUF_ERROR = -5;
  5890. //var Z_VERSION_ERROR = -6;
  5891. /* compression levels */
  5892. //var Z_NO_COMPRESSION = 0;
  5893. //var Z_BEST_SPEED = 1;
  5894. //var Z_BEST_COMPRESSION = 9;
  5895. var Z_DEFAULT_COMPRESSION = -1;
  5896. var Z_FILTERED = 1;
  5897. var Z_HUFFMAN_ONLY = 2;
  5898. var Z_RLE = 3;
  5899. var Z_FIXED = 4;
  5900. var Z_DEFAULT_STRATEGY = 0;
  5901. /* Possible values of the data_type field (though see inflate()) */
  5902. //var Z_BINARY = 0;
  5903. //var Z_TEXT = 1;
  5904. //var Z_ASCII = 1; // = Z_TEXT
  5905. var Z_UNKNOWN = 2;
  5906. /* The deflate compression method */
  5907. var Z_DEFLATED = 8;
  5908. /*============================================================================*/
  5909. var MAX_MEM_LEVEL = 9;
  5910. /* Maximum value for memLevel in deflateInit2 */
  5911. var MAX_WBITS = 15;
  5912. /* 32K LZ77 window */
  5913. var DEF_MEM_LEVEL = 8;
  5914. var LENGTH_CODES = 29;
  5915. /* number of length codes, not counting the special END_BLOCK code */
  5916. var LITERALS = 256;
  5917. /* number of literal bytes 0..255 */
  5918. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  5919. /* number of Literal or Length codes, including the END_BLOCK code */
  5920. var D_CODES = 30;
  5921. /* number of distance codes */
  5922. var BL_CODES = 19;
  5923. /* number of codes used to transfer the bit lengths */
  5924. var HEAP_SIZE = 2*L_CODES + 1;
  5925. /* maximum heap size */
  5926. var MAX_BITS = 15;
  5927. /* All codes must not exceed MAX_BITS bits */
  5928. var MIN_MATCH = 3;
  5929. var MAX_MATCH = 258;
  5930. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  5931. var PRESET_DICT = 0x20;
  5932. var INIT_STATE = 42;
  5933. var EXTRA_STATE = 69;
  5934. var NAME_STATE = 73;
  5935. var COMMENT_STATE = 91;
  5936. var HCRC_STATE = 103;
  5937. var BUSY_STATE = 113;
  5938. var FINISH_STATE = 666;
  5939. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  5940. var BS_BLOCK_DONE = 2; /* block flush performed */
  5941. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  5942. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  5943. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  5944. function err(strm, errorCode) {
  5945. strm.msg = msg[errorCode];
  5946. return errorCode;
  5947. }
  5948. function rank(f) {
  5949. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  5950. }
  5951. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  5952. /* =========================================================================
  5953. * Flush as much pending output as possible. All deflate() output goes
  5954. * through this function so some applications may wish to modify it
  5955. * to avoid allocating a large strm->output buffer and copying into it.
  5956. * (See also read_buf()).
  5957. */
  5958. function flush_pending(strm) {
  5959. var s = strm.state;
  5960. //_tr_flush_bits(s);
  5961. var len = s.pending;
  5962. if (len > strm.avail_out) {
  5963. len = strm.avail_out;
  5964. }
  5965. if (len === 0) { return; }
  5966. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  5967. strm.next_out += len;
  5968. s.pending_out += len;
  5969. strm.total_out += len;
  5970. strm.avail_out -= len;
  5971. s.pending -= len;
  5972. if (s.pending === 0) {
  5973. s.pending_out = 0;
  5974. }
  5975. }
  5976. function flush_block_only (s, last) {
  5977. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  5978. s.block_start = s.strstart;
  5979. flush_pending(s.strm);
  5980. }
  5981. function put_byte(s, b) {
  5982. s.pending_buf[s.pending++] = b;
  5983. }
  5984. /* =========================================================================
  5985. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  5986. * IN assertion: the stream state is correct and there is enough room in
  5987. * pending_buf.
  5988. */
  5989. function putShortMSB(s, b) {
  5990. // put_byte(s, (Byte)(b >> 8));
  5991. // put_byte(s, (Byte)(b & 0xff));
  5992. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  5993. s.pending_buf[s.pending++] = b & 0xff;
  5994. }
  5995. /* ===========================================================================
  5996. * Read a new buffer from the current input stream, update the adler32
  5997. * and total number of bytes read. All deflate() input goes through
  5998. * this function so some applications may wish to modify it to avoid
  5999. * allocating a large strm->input buffer and copying from it.
  6000. * (See also flush_pending()).
  6001. */
  6002. function read_buf(strm, buf, start, size) {
  6003. var len = strm.avail_in;
  6004. if (len > size) { len = size; }
  6005. if (len === 0) { return 0; }
  6006. strm.avail_in -= len;
  6007. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6008. if (strm.state.wrap === 1) {
  6009. strm.adler = adler32(strm.adler, buf, len, start);
  6010. }
  6011. else if (strm.state.wrap === 2) {
  6012. strm.adler = crc32(strm.adler, buf, len, start);
  6013. }
  6014. strm.next_in += len;
  6015. strm.total_in += len;
  6016. return len;
  6017. }
  6018. /* ===========================================================================
  6019. * Set match_start to the longest match starting at the given string and
  6020. * return its length. Matches shorter or equal to prev_length are discarded,
  6021. * in which case the result is equal to prev_length and match_start is
  6022. * garbage.
  6023. * IN assertions: cur_match is the head of the hash chain for the current
  6024. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6025. * OUT assertion: the match length is not greater than s->lookahead.
  6026. */
  6027. function longest_match(s, cur_match) {
  6028. var chain_length = s.max_chain_length; /* max hash chain length */
  6029. var scan = s.strstart; /* current string */
  6030. var match; /* matched string */
  6031. var len; /* length of current match */
  6032. var best_len = s.prev_length; /* best match length so far */
  6033. var nice_match = s.nice_match; /* stop if match long enough */
  6034. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6035. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6036. var _win = s.window; // shortcut
  6037. var wmask = s.w_mask;
  6038. var prev = s.prev;
  6039. /* Stop when cur_match becomes <= limit. To simplify the code,
  6040. * we prevent matches with the string of window index 0.
  6041. */
  6042. var strend = s.strstart + MAX_MATCH;
  6043. var scan_end1 = _win[scan + best_len - 1];
  6044. var scan_end = _win[scan + best_len];
  6045. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6046. * It is easy to get rid of this optimization if necessary.
  6047. */
  6048. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6049. /* Do not waste too much time if we already have a good match: */
  6050. if (s.prev_length >= s.good_match) {
  6051. chain_length >>= 2;
  6052. }
  6053. /* Do not look for matches beyond the end of the input. This is necessary
  6054. * to make deflate deterministic.
  6055. */
  6056. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6057. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6058. do {
  6059. // Assert(cur_match < s->strstart, "no future");
  6060. match = cur_match;
  6061. /* Skip to next match if the match length cannot increase
  6062. * or if the match length is less than 2. Note that the checks below
  6063. * for insufficient lookahead only occur occasionally for performance
  6064. * reasons. Therefore uninitialized memory will be accessed, and
  6065. * conditional jumps will be made that depend on those values.
  6066. * However the length of the match is limited to the lookahead, so
  6067. * the output of deflate is not affected by the uninitialized values.
  6068. */
  6069. if (_win[match + best_len] !== scan_end ||
  6070. _win[match + best_len - 1] !== scan_end1 ||
  6071. _win[match] !== _win[scan] ||
  6072. _win[++match] !== _win[scan + 1]) {
  6073. continue;
  6074. }
  6075. /* The check at best_len-1 can be removed because it will be made
  6076. * again later. (This heuristic is not always a win.)
  6077. * It is not necessary to compare scan[2] and match[2] since they
  6078. * are always equal when the other bytes match, given that
  6079. * the hash keys are equal and that HASH_BITS >= 8.
  6080. */
  6081. scan += 2;
  6082. match++;
  6083. // Assert(*scan == *match, "match[2]?");
  6084. /* We check for insufficient lookahead only every 8th comparison;
  6085. * the 256th check will be made at strstart+258.
  6086. */
  6087. do {
  6088. /*jshint noempty:false*/
  6089. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6090. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6091. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6092. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6093. scan < strend);
  6094. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6095. len = MAX_MATCH - (strend - scan);
  6096. scan = strend - MAX_MATCH;
  6097. if (len > best_len) {
  6098. s.match_start = cur_match;
  6099. best_len = len;
  6100. if (len >= nice_match) {
  6101. break;
  6102. }
  6103. scan_end1 = _win[scan + best_len - 1];
  6104. scan_end = _win[scan + best_len];
  6105. }
  6106. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6107. if (best_len <= s.lookahead) {
  6108. return best_len;
  6109. }
  6110. return s.lookahead;
  6111. }
  6112. /* ===========================================================================
  6113. * Fill the window when the lookahead becomes insufficient.
  6114. * Updates strstart and lookahead.
  6115. *
  6116. * IN assertion: lookahead < MIN_LOOKAHEAD
  6117. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6118. * At least one byte has been read, or avail_in == 0; reads are
  6119. * performed for at least two bytes (required for the zip translate_eol
  6120. * option -- not supported here).
  6121. */
  6122. function fill_window(s) {
  6123. var _w_size = s.w_size;
  6124. var p, n, m, more, str;
  6125. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6126. do {
  6127. more = s.window_size - s.lookahead - s.strstart;
  6128. // JS ints have 32 bit, block below not needed
  6129. /* Deal with !@#$% 64K limit: */
  6130. //if (sizeof(int) <= 2) {
  6131. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6132. // more = wsize;
  6133. //
  6134. // } else if (more == (unsigned)(-1)) {
  6135. // /* Very unlikely, but possible on 16 bit machine if
  6136. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6137. // */
  6138. // more--;
  6139. // }
  6140. //}
  6141. /* If the window is almost full and there is insufficient lookahead,
  6142. * move the upper half to the lower one to make room in the upper half.
  6143. */
  6144. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6145. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6146. s.match_start -= _w_size;
  6147. s.strstart -= _w_size;
  6148. /* we now have strstart >= MAX_DIST */
  6149. s.block_start -= _w_size;
  6150. /* Slide the hash table (could be avoided with 32 bit values
  6151. at the expense of memory usage). We slide even when level == 0
  6152. to keep the hash table consistent if we switch back to level > 0
  6153. later. (Using level 0 permanently is not an optimal usage of
  6154. zlib, so we don't care about this pathological case.)
  6155. */
  6156. n = s.hash_size;
  6157. p = n;
  6158. do {
  6159. m = s.head[--p];
  6160. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6161. } while (--n);
  6162. n = _w_size;
  6163. p = n;
  6164. do {
  6165. m = s.prev[--p];
  6166. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6167. /* If n is not on any hash chain, prev[n] is garbage but
  6168. * its value will never be used.
  6169. */
  6170. } while (--n);
  6171. more += _w_size;
  6172. }
  6173. if (s.strm.avail_in === 0) {
  6174. break;
  6175. }
  6176. /* If there was no sliding:
  6177. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6178. * more == window_size - lookahead - strstart
  6179. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6180. * => more >= window_size - 2*WSIZE + 2
  6181. * In the BIG_MEM or MMAP case (not yet supported),
  6182. * window_size == input_size + MIN_LOOKAHEAD &&
  6183. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6184. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6185. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6186. */
  6187. //Assert(more >= 2, "more < 2");
  6188. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6189. s.lookahead += n;
  6190. /* Initialize the hash value now that we have some input: */
  6191. if (s.lookahead + s.insert >= MIN_MATCH) {
  6192. str = s.strstart - s.insert;
  6193. s.ins_h = s.window[str];
  6194. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6195. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6196. //#if MIN_MATCH != 3
  6197. // Call update_hash() MIN_MATCH-3 more times
  6198. //#endif
  6199. while (s.insert) {
  6200. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6201. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  6202. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6203. s.head[s.ins_h] = str;
  6204. str++;
  6205. s.insert--;
  6206. if (s.lookahead + s.insert < MIN_MATCH) {
  6207. break;
  6208. }
  6209. }
  6210. }
  6211. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6212. * but this is not important since only literal bytes will be emitted.
  6213. */
  6214. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6215. /* If the WIN_INIT bytes after the end of the current data have never been
  6216. * written, then zero those bytes in order to avoid memory check reports of
  6217. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6218. * the longest match routines. Update the high water mark for the next
  6219. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6220. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6221. */
  6222. // if (s.high_water < s.window_size) {
  6223. // var curr = s.strstart + s.lookahead;
  6224. // var init = 0;
  6225. //
  6226. // if (s.high_water < curr) {
  6227. // /* Previous high water mark below current data -- zero WIN_INIT
  6228. // * bytes or up to end of window, whichever is less.
  6229. // */
  6230. // init = s.window_size - curr;
  6231. // if (init > WIN_INIT)
  6232. // init = WIN_INIT;
  6233. // zmemzero(s->window + curr, (unsigned)init);
  6234. // s->high_water = curr + init;
  6235. // }
  6236. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6237. // /* High water mark at or above current data, but below current data
  6238. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6239. // * to end of window, whichever is less.
  6240. // */
  6241. // init = (ulg)curr + WIN_INIT - s->high_water;
  6242. // if (init > s->window_size - s->high_water)
  6243. // init = s->window_size - s->high_water;
  6244. // zmemzero(s->window + s->high_water, (unsigned)init);
  6245. // s->high_water += init;
  6246. // }
  6247. // }
  6248. //
  6249. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6250. // "not enough room for search");
  6251. }
  6252. /* ===========================================================================
  6253. * Copy without compression as much as possible from the input stream, return
  6254. * the current block state.
  6255. * This function does not insert new strings in the dictionary since
  6256. * uncompressible data is probably not useful. This function is used
  6257. * only for the level=0 compression option.
  6258. * NOTE: this function should be optimized to avoid extra copying from
  6259. * window to pending_buf.
  6260. */
  6261. function deflate_stored(s, flush) {
  6262. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6263. * to pending_buf_size, and each stored block has a 5 byte header:
  6264. */
  6265. var max_block_size = 0xffff;
  6266. if (max_block_size > s.pending_buf_size - 5) {
  6267. max_block_size = s.pending_buf_size - 5;
  6268. }
  6269. /* Copy as much as possible from input to output: */
  6270. for (;;) {
  6271. /* Fill the window as much as possible: */
  6272. if (s.lookahead <= 1) {
  6273. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6274. // s->block_start >= (long)s->w_size, "slide too late");
  6275. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6276. // s.block_start >= s.w_size)) {
  6277. // throw new Error("slide too late");
  6278. // }
  6279. fill_window(s);
  6280. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6281. return BS_NEED_MORE;
  6282. }
  6283. if (s.lookahead === 0) {
  6284. break;
  6285. }
  6286. /* flush the current block */
  6287. }
  6288. //Assert(s->block_start >= 0L, "block gone");
  6289. // if (s.block_start < 0) throw new Error("block gone");
  6290. s.strstart += s.lookahead;
  6291. s.lookahead = 0;
  6292. /* Emit a stored block if pending_buf will be full: */
  6293. var max_start = s.block_start + max_block_size;
  6294. if (s.strstart === 0 || s.strstart >= max_start) {
  6295. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6296. s.lookahead = s.strstart - max_start;
  6297. s.strstart = max_start;
  6298. /*** FLUSH_BLOCK(s, 0); ***/
  6299. flush_block_only(s, false);
  6300. if (s.strm.avail_out === 0) {
  6301. return BS_NEED_MORE;
  6302. }
  6303. /***/
  6304. }
  6305. /* Flush if we may have to slide, otherwise block_start may become
  6306. * negative and the data will be gone:
  6307. */
  6308. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6309. /*** FLUSH_BLOCK(s, 0); ***/
  6310. flush_block_only(s, false);
  6311. if (s.strm.avail_out === 0) {
  6312. return BS_NEED_MORE;
  6313. }
  6314. /***/
  6315. }
  6316. }
  6317. s.insert = 0;
  6318. if (flush === Z_FINISH) {
  6319. /*** FLUSH_BLOCK(s, 1); ***/
  6320. flush_block_only(s, true);
  6321. if (s.strm.avail_out === 0) {
  6322. return BS_FINISH_STARTED;
  6323. }
  6324. /***/
  6325. return BS_FINISH_DONE;
  6326. }
  6327. if (s.strstart > s.block_start) {
  6328. /*** FLUSH_BLOCK(s, 0); ***/
  6329. flush_block_only(s, false);
  6330. if (s.strm.avail_out === 0) {
  6331. return BS_NEED_MORE;
  6332. }
  6333. /***/
  6334. }
  6335. return BS_NEED_MORE;
  6336. }
  6337. /* ===========================================================================
  6338. * Compress as much as possible from the input stream, return the current
  6339. * block state.
  6340. * This function does not perform lazy evaluation of matches and inserts
  6341. * new strings in the dictionary only for unmatched strings or for short
  6342. * matches. It is used only for the fast compression options.
  6343. */
  6344. function deflate_fast(s, flush) {
  6345. var hash_head; /* head of the hash chain */
  6346. var bflush; /* set if current block must be flushed */
  6347. for (;;) {
  6348. /* Make sure that we always have enough lookahead, except
  6349. * at the end of the input file. We need MAX_MATCH bytes
  6350. * for the next match, plus MIN_MATCH bytes to insert the
  6351. * string following the next match.
  6352. */
  6353. if (s.lookahead < MIN_LOOKAHEAD) {
  6354. fill_window(s);
  6355. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6356. return BS_NEED_MORE;
  6357. }
  6358. if (s.lookahead === 0) {
  6359. break; /* flush the current block */
  6360. }
  6361. }
  6362. /* Insert the string window[strstart .. strstart+2] in the
  6363. * dictionary, and set hash_head to the head of the hash chain:
  6364. */
  6365. hash_head = 0/*NIL*/;
  6366. if (s.lookahead >= MIN_MATCH) {
  6367. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6368. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6369. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6370. s.head[s.ins_h] = s.strstart;
  6371. /***/
  6372. }
  6373. /* Find the longest match, discarding those <= prev_length.
  6374. * At this point we have always match_length < MIN_MATCH
  6375. */
  6376. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6377. /* To simplify the code, we prevent matches with the string
  6378. * of window index 0 (in particular we have to avoid a match
  6379. * of the string with itself at the start of the input file).
  6380. */
  6381. s.match_length = longest_match(s, hash_head);
  6382. /* longest_match() sets match_start */
  6383. }
  6384. if (s.match_length >= MIN_MATCH) {
  6385. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6386. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6387. s.match_length - MIN_MATCH, bflush); ***/
  6388. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6389. s.lookahead -= s.match_length;
  6390. /* Insert new strings in the hash table only if the match length
  6391. * is not too large. This saves time but degrades compression.
  6392. */
  6393. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6394. s.match_length--; /* string at strstart already in table */
  6395. do {
  6396. s.strstart++;
  6397. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6398. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6399. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6400. s.head[s.ins_h] = s.strstart;
  6401. /***/
  6402. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6403. * always MIN_MATCH bytes ahead.
  6404. */
  6405. } while (--s.match_length !== 0);
  6406. s.strstart++;
  6407. } else
  6408. {
  6409. s.strstart += s.match_length;
  6410. s.match_length = 0;
  6411. s.ins_h = s.window[s.strstart];
  6412. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6413. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6414. //#if MIN_MATCH != 3
  6415. // Call UPDATE_HASH() MIN_MATCH-3 more times
  6416. //#endif
  6417. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6418. * matter since it will be recomputed at next deflate call.
  6419. */
  6420. }
  6421. } else {
  6422. /* No match, output a literal byte */
  6423. //Tracevv((stderr,"%c", s.window[s.strstart]));
  6424. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6425. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6426. s.lookahead--;
  6427. s.strstart++;
  6428. }
  6429. if (bflush) {
  6430. /*** FLUSH_BLOCK(s, 0); ***/
  6431. flush_block_only(s, false);
  6432. if (s.strm.avail_out === 0) {
  6433. return BS_NEED_MORE;
  6434. }
  6435. /***/
  6436. }
  6437. }
  6438. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  6439. if (flush === Z_FINISH) {
  6440. /*** FLUSH_BLOCK(s, 1); ***/
  6441. flush_block_only(s, true);
  6442. if (s.strm.avail_out === 0) {
  6443. return BS_FINISH_STARTED;
  6444. }
  6445. /***/
  6446. return BS_FINISH_DONE;
  6447. }
  6448. if (s.last_lit) {
  6449. /*** FLUSH_BLOCK(s, 0); ***/
  6450. flush_block_only(s, false);
  6451. if (s.strm.avail_out === 0) {
  6452. return BS_NEED_MORE;
  6453. }
  6454. /***/
  6455. }
  6456. return BS_BLOCK_DONE;
  6457. }
  6458. /* ===========================================================================
  6459. * Same as above, but achieves better compression. We use a lazy
  6460. * evaluation for matches: a match is finally adopted only if there is
  6461. * no better match at the next window position.
  6462. */
  6463. function deflate_slow(s, flush) {
  6464. var hash_head; /* head of hash chain */
  6465. var bflush; /* set if current block must be flushed */
  6466. var max_insert;
  6467. /* Process the input block. */
  6468. for (;;) {
  6469. /* Make sure that we always have enough lookahead, except
  6470. * at the end of the input file. We need MAX_MATCH bytes
  6471. * for the next match, plus MIN_MATCH bytes to insert the
  6472. * string following the next match.
  6473. */
  6474. if (s.lookahead < MIN_LOOKAHEAD) {
  6475. fill_window(s);
  6476. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6477. return BS_NEED_MORE;
  6478. }
  6479. if (s.lookahead === 0) { break; } /* flush the current block */
  6480. }
  6481. /* Insert the string window[strstart .. strstart+2] in the
  6482. * dictionary, and set hash_head to the head of the hash chain:
  6483. */
  6484. hash_head = 0/*NIL*/;
  6485. if (s.lookahead >= MIN_MATCH) {
  6486. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6487. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6488. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6489. s.head[s.ins_h] = s.strstart;
  6490. /***/
  6491. }
  6492. /* Find the longest match, discarding those <= prev_length.
  6493. */
  6494. s.prev_length = s.match_length;
  6495. s.prev_match = s.match_start;
  6496. s.match_length = MIN_MATCH-1;
  6497. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6498. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6499. /* To simplify the code, we prevent matches with the string
  6500. * of window index 0 (in particular we have to avoid a match
  6501. * of the string with itself at the start of the input file).
  6502. */
  6503. s.match_length = longest_match(s, hash_head);
  6504. /* longest_match() sets match_start */
  6505. if (s.match_length <= 5 &&
  6506. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6507. /* If prev_match is also MIN_MATCH, match_start is garbage
  6508. * but we will ignore the current match anyway.
  6509. */
  6510. s.match_length = MIN_MATCH-1;
  6511. }
  6512. }
  6513. /* If there was a match at the previous step and the current
  6514. * match is not better, output the previous match:
  6515. */
  6516. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  6517. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  6518. /* Do not insert strings in hash table beyond this. */
  6519. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  6520. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  6521. s.prev_length - MIN_MATCH, bflush);***/
  6522. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  6523. /* Insert in hash table all strings up to the end of the match.
  6524. * strstart-1 and strstart are already inserted. If there is not
  6525. * enough lookahead, the last two strings are not inserted in
  6526. * the hash table.
  6527. */
  6528. s.lookahead -= s.prev_length-1;
  6529. s.prev_length -= 2;
  6530. do {
  6531. if (++s.strstart <= max_insert) {
  6532. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6533. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6534. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6535. s.head[s.ins_h] = s.strstart;
  6536. /***/
  6537. }
  6538. } while (--s.prev_length !== 0);
  6539. s.match_available = 0;
  6540. s.match_length = MIN_MATCH-1;
  6541. s.strstart++;
  6542. if (bflush) {
  6543. /*** FLUSH_BLOCK(s, 0); ***/
  6544. flush_block_only(s, false);
  6545. if (s.strm.avail_out === 0) {
  6546. return BS_NEED_MORE;
  6547. }
  6548. /***/
  6549. }
  6550. } else if (s.match_available) {
  6551. /* If there was no match at the previous position, output a
  6552. * single literal. If there was a match but the current match
  6553. * is longer, truncate the previous match to a single literal.
  6554. */
  6555. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6556. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6557. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  6558. if (bflush) {
  6559. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  6560. flush_block_only(s, false);
  6561. /***/
  6562. }
  6563. s.strstart++;
  6564. s.lookahead--;
  6565. if (s.strm.avail_out === 0) {
  6566. return BS_NEED_MORE;
  6567. }
  6568. } else {
  6569. /* There is no previous match to compare with, wait for
  6570. * the next step to decide.
  6571. */
  6572. s.match_available = 1;
  6573. s.strstart++;
  6574. s.lookahead--;
  6575. }
  6576. }
  6577. //Assert (flush != Z_NO_FLUSH, "no flush?");
  6578. if (s.match_available) {
  6579. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6580. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6581. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  6582. s.match_available = 0;
  6583. }
  6584. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  6585. if (flush === Z_FINISH) {
  6586. /*** FLUSH_BLOCK(s, 1); ***/
  6587. flush_block_only(s, true);
  6588. if (s.strm.avail_out === 0) {
  6589. return BS_FINISH_STARTED;
  6590. }
  6591. /***/
  6592. return BS_FINISH_DONE;
  6593. }
  6594. if (s.last_lit) {
  6595. /*** FLUSH_BLOCK(s, 0); ***/
  6596. flush_block_only(s, false);
  6597. if (s.strm.avail_out === 0) {
  6598. return BS_NEED_MORE;
  6599. }
  6600. /***/
  6601. }
  6602. return BS_BLOCK_DONE;
  6603. }
  6604. /* ===========================================================================
  6605. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  6606. * one. Do not maintain a hash table. (It will be regenerated if this run of
  6607. * deflate switches away from Z_RLE.)
  6608. */
  6609. function deflate_rle(s, flush) {
  6610. var bflush; /* set if current block must be flushed */
  6611. var prev; /* byte at distance one to match */
  6612. var scan, strend; /* scan goes up to strend for length of run */
  6613. var _win = s.window;
  6614. for (;;) {
  6615. /* Make sure that we always have enough lookahead, except
  6616. * at the end of the input file. We need MAX_MATCH bytes
  6617. * for the longest run, plus one for the unrolled loop.
  6618. */
  6619. if (s.lookahead <= MAX_MATCH) {
  6620. fill_window(s);
  6621. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  6622. return BS_NEED_MORE;
  6623. }
  6624. if (s.lookahead === 0) { break; } /* flush the current block */
  6625. }
  6626. /* See how many times the previous byte repeats */
  6627. s.match_length = 0;
  6628. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  6629. scan = s.strstart - 1;
  6630. prev = _win[scan];
  6631. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  6632. strend = s.strstart + MAX_MATCH;
  6633. do {
  6634. /*jshint noempty:false*/
  6635. } while (prev === _win[++scan] && prev === _win[++scan] &&
  6636. prev === _win[++scan] && prev === _win[++scan] &&
  6637. prev === _win[++scan] && prev === _win[++scan] &&
  6638. prev === _win[++scan] && prev === _win[++scan] &&
  6639. scan < strend);
  6640. s.match_length = MAX_MATCH - (strend - scan);
  6641. if (s.match_length > s.lookahead) {
  6642. s.match_length = s.lookahead;
  6643. }
  6644. }
  6645. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  6646. }
  6647. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  6648. if (s.match_length >= MIN_MATCH) {
  6649. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  6650. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  6651. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  6652. s.lookahead -= s.match_length;
  6653. s.strstart += s.match_length;
  6654. s.match_length = 0;
  6655. } else {
  6656. /* No match, output a literal byte */
  6657. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6658. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6659. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6660. s.lookahead--;
  6661. s.strstart++;
  6662. }
  6663. if (bflush) {
  6664. /*** FLUSH_BLOCK(s, 0); ***/
  6665. flush_block_only(s, false);
  6666. if (s.strm.avail_out === 0) {
  6667. return BS_NEED_MORE;
  6668. }
  6669. /***/
  6670. }
  6671. }
  6672. s.insert = 0;
  6673. if (flush === Z_FINISH) {
  6674. /*** FLUSH_BLOCK(s, 1); ***/
  6675. flush_block_only(s, true);
  6676. if (s.strm.avail_out === 0) {
  6677. return BS_FINISH_STARTED;
  6678. }
  6679. /***/
  6680. return BS_FINISH_DONE;
  6681. }
  6682. if (s.last_lit) {
  6683. /*** FLUSH_BLOCK(s, 0); ***/
  6684. flush_block_only(s, false);
  6685. if (s.strm.avail_out === 0) {
  6686. return BS_NEED_MORE;
  6687. }
  6688. /***/
  6689. }
  6690. return BS_BLOCK_DONE;
  6691. }
  6692. /* ===========================================================================
  6693. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  6694. * (It will be regenerated if this run of deflate switches away from Huffman.)
  6695. */
  6696. function deflate_huff(s, flush) {
  6697. var bflush; /* set if current block must be flushed */
  6698. for (;;) {
  6699. /* Make sure that we have a literal to write. */
  6700. if (s.lookahead === 0) {
  6701. fill_window(s);
  6702. if (s.lookahead === 0) {
  6703. if (flush === Z_NO_FLUSH) {
  6704. return BS_NEED_MORE;
  6705. }
  6706. break; /* flush the current block */
  6707. }
  6708. }
  6709. /* Output a literal byte */
  6710. s.match_length = 0;
  6711. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6712. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6713. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6714. s.lookahead--;
  6715. s.strstart++;
  6716. if (bflush) {
  6717. /*** FLUSH_BLOCK(s, 0); ***/
  6718. flush_block_only(s, false);
  6719. if (s.strm.avail_out === 0) {
  6720. return BS_NEED_MORE;
  6721. }
  6722. /***/
  6723. }
  6724. }
  6725. s.insert = 0;
  6726. if (flush === Z_FINISH) {
  6727. /*** FLUSH_BLOCK(s, 1); ***/
  6728. flush_block_only(s, true);
  6729. if (s.strm.avail_out === 0) {
  6730. return BS_FINISH_STARTED;
  6731. }
  6732. /***/
  6733. return BS_FINISH_DONE;
  6734. }
  6735. if (s.last_lit) {
  6736. /*** FLUSH_BLOCK(s, 0); ***/
  6737. flush_block_only(s, false);
  6738. if (s.strm.avail_out === 0) {
  6739. return BS_NEED_MORE;
  6740. }
  6741. /***/
  6742. }
  6743. return BS_BLOCK_DONE;
  6744. }
  6745. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  6746. * the desired pack level (0..9). The values given below have been tuned to
  6747. * exclude worst case performance for pathological files. Better values may be
  6748. * found for specific files.
  6749. */
  6750. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  6751. this.good_length = good_length;
  6752. this.max_lazy = max_lazy;
  6753. this.nice_length = nice_length;
  6754. this.max_chain = max_chain;
  6755. this.func = func;
  6756. };
  6757. var configuration_table;
  6758. configuration_table = [
  6759. /* good lazy nice chain */
  6760. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  6761. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  6762. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  6763. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  6764. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  6765. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  6766. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  6767. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  6768. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  6769. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  6770. ];
  6771. /* ===========================================================================
  6772. * Initialize the "longest match" routines for a new zlib stream
  6773. */
  6774. function lm_init(s) {
  6775. s.window_size = 2 * s.w_size;
  6776. /*** CLEAR_HASH(s); ***/
  6777. zero(s.head); // Fill with NIL (= 0);
  6778. /* Set the default configuration parameters:
  6779. */
  6780. s.max_lazy_match = configuration_table[s.level].max_lazy;
  6781. s.good_match = configuration_table[s.level].good_length;
  6782. s.nice_match = configuration_table[s.level].nice_length;
  6783. s.max_chain_length = configuration_table[s.level].max_chain;
  6784. s.strstart = 0;
  6785. s.block_start = 0;
  6786. s.lookahead = 0;
  6787. s.insert = 0;
  6788. s.match_length = s.prev_length = MIN_MATCH - 1;
  6789. s.match_available = 0;
  6790. s.ins_h = 0;
  6791. }
  6792. function DeflateState() {
  6793. this.strm = null; /* pointer back to this zlib stream */
  6794. this.status = 0; /* as the name implies */
  6795. this.pending_buf = null; /* output still pending */
  6796. this.pending_buf_size = 0; /* size of pending_buf */
  6797. this.pending_out = 0; /* next pending byte to output to the stream */
  6798. this.pending = 0; /* nb of bytes in the pending buffer */
  6799. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  6800. this.gzhead = null; /* gzip header information to write */
  6801. this.gzindex = 0; /* where in extra, name, or comment */
  6802. this.method = Z_DEFLATED; /* can only be DEFLATED */
  6803. this.last_flush = -1; /* value of flush param for previous deflate call */
  6804. this.w_size = 0; /* LZ77 window size (32K by default) */
  6805. this.w_bits = 0; /* log2(w_size) (8..16) */
  6806. this.w_mask = 0; /* w_size - 1 */
  6807. this.window = null;
  6808. /* Sliding window. Input bytes are read into the second half of the window,
  6809. * and move to the first half later to keep a dictionary of at least wSize
  6810. * bytes. With this organization, matches are limited to a distance of
  6811. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  6812. * performed with a length multiple of the block size.
  6813. */
  6814. this.window_size = 0;
  6815. /* Actual size of window: 2*wSize, except when the user input buffer
  6816. * is directly used as sliding window.
  6817. */
  6818. this.prev = null;
  6819. /* Link to older string with same hash index. To limit the size of this
  6820. * array to 64K, this link is maintained only for the last 32K strings.
  6821. * An index in this array is thus a window index modulo 32K.
  6822. */
  6823. this.head = null; /* Heads of the hash chains or NIL. */
  6824. this.ins_h = 0; /* hash index of string to be inserted */
  6825. this.hash_size = 0; /* number of elements in hash table */
  6826. this.hash_bits = 0; /* log2(hash_size) */
  6827. this.hash_mask = 0; /* hash_size-1 */
  6828. this.hash_shift = 0;
  6829. /* Number of bits by which ins_h must be shifted at each input
  6830. * step. It must be such that after MIN_MATCH steps, the oldest
  6831. * byte no longer takes part in the hash key, that is:
  6832. * hash_shift * MIN_MATCH >= hash_bits
  6833. */
  6834. this.block_start = 0;
  6835. /* Window position at the beginning of the current output block. Gets
  6836. * negative when the window is moved backwards.
  6837. */
  6838. this.match_length = 0; /* length of best match */
  6839. this.prev_match = 0; /* previous match */
  6840. this.match_available = 0; /* set if previous match exists */
  6841. this.strstart = 0; /* start of string to insert */
  6842. this.match_start = 0; /* start of matching string */
  6843. this.lookahead = 0; /* number of valid bytes ahead in window */
  6844. this.prev_length = 0;
  6845. /* Length of the best match at previous step. Matches not greater than this
  6846. * are discarded. This is used in the lazy match evaluation.
  6847. */
  6848. this.max_chain_length = 0;
  6849. /* To speed up deflation, hash chains are never searched beyond this
  6850. * length. A higher limit improves compression ratio but degrades the
  6851. * speed.
  6852. */
  6853. this.max_lazy_match = 0;
  6854. /* Attempt to find a better match only when the current match is strictly
  6855. * smaller than this value. This mechanism is used only for compression
  6856. * levels >= 4.
  6857. */
  6858. // That's alias to max_lazy_match, don't use directly
  6859. //this.max_insert_length = 0;
  6860. /* Insert new strings in the hash table only if the match length is not
  6861. * greater than this length. This saves time but degrades compression.
  6862. * max_insert_length is used only for compression levels <= 3.
  6863. */
  6864. this.level = 0; /* compression level (1..9) */
  6865. this.strategy = 0; /* favor or force Huffman coding*/
  6866. this.good_match = 0;
  6867. /* Use a faster search when the previous match is longer than this */
  6868. this.nice_match = 0; /* Stop searching when current match exceeds this */
  6869. /* used by trees.c: */
  6870. /* Didn't use ct_data typedef below to suppress compiler warning */
  6871. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  6872. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  6873. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  6874. // Use flat array of DOUBLE size, with interleaved fata,
  6875. // because JS does not support effective
  6876. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  6877. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  6878. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  6879. zero(this.dyn_ltree);
  6880. zero(this.dyn_dtree);
  6881. zero(this.bl_tree);
  6882. this.l_desc = null; /* desc. for literal tree */
  6883. this.d_desc = null; /* desc. for distance tree */
  6884. this.bl_desc = null; /* desc. for bit length tree */
  6885. //ush bl_count[MAX_BITS+1];
  6886. this.bl_count = new utils.Buf16(MAX_BITS+1);
  6887. /* number of codes at each bit length for an optimal tree */
  6888. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  6889. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  6890. zero(this.heap);
  6891. this.heap_len = 0; /* number of elements in the heap */
  6892. this.heap_max = 0; /* element of largest frequency */
  6893. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  6894. * The same heap array is used to build all trees.
  6895. */
  6896. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  6897. zero(this.depth);
  6898. /* Depth of each subtree used as tie breaker for trees of equal frequency
  6899. */
  6900. this.l_buf = 0; /* buffer index for literals or lengths */
  6901. this.lit_bufsize = 0;
  6902. /* Size of match buffer for literals/lengths. There are 4 reasons for
  6903. * limiting lit_bufsize to 64K:
  6904. * - frequencies can be kept in 16 bit counters
  6905. * - if compression is not successful for the first block, all input
  6906. * data is still in the window so we can still emit a stored block even
  6907. * when input comes from standard input. (This can also be done for
  6908. * all blocks if lit_bufsize is not greater than 32K.)
  6909. * - if compression is not successful for a file smaller than 64K, we can
  6910. * even emit a stored file instead of a stored block (saving 5 bytes).
  6911. * This is applicable only for zip (not gzip or zlib).
  6912. * - creating new Huffman trees less frequently may not provide fast
  6913. * adaptation to changes in the input data statistics. (Take for
  6914. * example a binary file with poorly compressible code followed by
  6915. * a highly compressible string table.) Smaller buffer sizes give
  6916. * fast adaptation but have of course the overhead of transmitting
  6917. * trees more frequently.
  6918. * - I can't count above 4
  6919. */
  6920. this.last_lit = 0; /* running index in l_buf */
  6921. this.d_buf = 0;
  6922. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  6923. * the same number of elements. To use different lengths, an extra flag
  6924. * array would be necessary.
  6925. */
  6926. this.opt_len = 0; /* bit length of current block with optimal trees */
  6927. this.static_len = 0; /* bit length of current block with static trees */
  6928. this.matches = 0; /* number of string matches in current block */
  6929. this.insert = 0; /* bytes at end of window left to insert */
  6930. this.bi_buf = 0;
  6931. /* Output buffer. bits are inserted starting at the bottom (least
  6932. * significant bits).
  6933. */
  6934. this.bi_valid = 0;
  6935. /* Number of valid bits in bi_buf. All bits above the last valid bit
  6936. * are always zero.
  6937. */
  6938. // Used for window memory init. We safely ignore it for JS. That makes
  6939. // sense only for pointers and memory check tools.
  6940. //this.high_water = 0;
  6941. /* High water mark offset in window for initialized bytes -- bytes above
  6942. * this are set to zero in order to avoid memory check warnings when
  6943. * longest match routines access bytes past the input. This is then
  6944. * updated to the new high water mark.
  6945. */
  6946. }
  6947. function deflateResetKeep(strm) {
  6948. var s;
  6949. if (!strm || !strm.state) {
  6950. return err(strm, Z_STREAM_ERROR);
  6951. }
  6952. strm.total_in = strm.total_out = 0;
  6953. strm.data_type = Z_UNKNOWN;
  6954. s = strm.state;
  6955. s.pending = 0;
  6956. s.pending_out = 0;
  6957. if (s.wrap < 0) {
  6958. s.wrap = -s.wrap;
  6959. /* was made negative by deflate(..., Z_FINISH); */
  6960. }
  6961. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  6962. strm.adler = (s.wrap === 2) ?
  6963. 0 // crc32(0, Z_NULL, 0)
  6964. :
  6965. 1; // adler32(0, Z_NULL, 0)
  6966. s.last_flush = Z_NO_FLUSH;
  6967. trees._tr_init(s);
  6968. return Z_OK;
  6969. }
  6970. function deflateReset(strm) {
  6971. var ret = deflateResetKeep(strm);
  6972. if (ret === Z_OK) {
  6973. lm_init(strm.state);
  6974. }
  6975. return ret;
  6976. }
  6977. function deflateSetHeader(strm, head) {
  6978. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6979. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  6980. strm.state.gzhead = head;
  6981. return Z_OK;
  6982. }
  6983. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  6984. if (!strm) { // === Z_NULL
  6985. return Z_STREAM_ERROR;
  6986. }
  6987. var wrap = 1;
  6988. if (level === Z_DEFAULT_COMPRESSION) {
  6989. level = 6;
  6990. }
  6991. if (windowBits < 0) { /* suppress zlib wrapper */
  6992. wrap = 0;
  6993. windowBits = -windowBits;
  6994. }
  6995. else if (windowBits > 15) {
  6996. wrap = 2; /* write gzip wrapper instead */
  6997. windowBits -= 16;
  6998. }
  6999. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7000. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7001. strategy < 0 || strategy > Z_FIXED) {
  7002. return err(strm, Z_STREAM_ERROR);
  7003. }
  7004. if (windowBits === 8) {
  7005. windowBits = 9;
  7006. }
  7007. /* until 256-byte window bug fixed */
  7008. var s = new DeflateState();
  7009. strm.state = s;
  7010. s.strm = strm;
  7011. s.wrap = wrap;
  7012. s.gzhead = null;
  7013. s.w_bits = windowBits;
  7014. s.w_size = 1 << s.w_bits;
  7015. s.w_mask = s.w_size - 1;
  7016. s.hash_bits = memLevel + 7;
  7017. s.hash_size = 1 << s.hash_bits;
  7018. s.hash_mask = s.hash_size - 1;
  7019. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7020. s.window = new utils.Buf8(s.w_size * 2);
  7021. s.head = new utils.Buf16(s.hash_size);
  7022. s.prev = new utils.Buf16(s.w_size);
  7023. // Don't need mem init magic for JS.
  7024. //s.high_water = 0; /* nothing written to s->window yet */
  7025. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7026. s.pending_buf_size = s.lit_bufsize * 4;
  7027. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7028. s.d_buf = s.lit_bufsize >> 1;
  7029. s.l_buf = (1 + 2) * s.lit_bufsize;
  7030. s.level = level;
  7031. s.strategy = strategy;
  7032. s.method = method;
  7033. return deflateReset(strm);
  7034. }
  7035. function deflateInit(strm, level) {
  7036. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7037. }
  7038. function deflate(strm, flush) {
  7039. var old_flush, s;
  7040. var beg, val; // for gzip header write only
  7041. if (!strm || !strm.state ||
  7042. flush > Z_BLOCK || flush < 0) {
  7043. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7044. }
  7045. s = strm.state;
  7046. if (!strm.output ||
  7047. (!strm.input && strm.avail_in !== 0) ||
  7048. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7049. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7050. }
  7051. s.strm = strm; /* just in case */
  7052. old_flush = s.last_flush;
  7053. s.last_flush = flush;
  7054. /* Write the header */
  7055. if (s.status === INIT_STATE) {
  7056. if (s.wrap === 2) { // GZIP header
  7057. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7058. put_byte(s, 31);
  7059. put_byte(s, 139);
  7060. put_byte(s, 8);
  7061. if (!s.gzhead) { // s->gzhead == Z_NULL
  7062. put_byte(s, 0);
  7063. put_byte(s, 0);
  7064. put_byte(s, 0);
  7065. put_byte(s, 0);
  7066. put_byte(s, 0);
  7067. put_byte(s, s.level === 9 ? 2 :
  7068. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7069. 4 : 0));
  7070. put_byte(s, OS_CODE);
  7071. s.status = BUSY_STATE;
  7072. }
  7073. else {
  7074. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7075. (s.gzhead.hcrc ? 2 : 0) +
  7076. (!s.gzhead.extra ? 0 : 4) +
  7077. (!s.gzhead.name ? 0 : 8) +
  7078. (!s.gzhead.comment ? 0 : 16)
  7079. );
  7080. put_byte(s, s.gzhead.time & 0xff);
  7081. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7082. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7083. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7084. put_byte(s, s.level === 9 ? 2 :
  7085. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7086. 4 : 0));
  7087. put_byte(s, s.gzhead.os & 0xff);
  7088. if (s.gzhead.extra && s.gzhead.extra.length) {
  7089. put_byte(s, s.gzhead.extra.length & 0xff);
  7090. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7091. }
  7092. if (s.gzhead.hcrc) {
  7093. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7094. }
  7095. s.gzindex = 0;
  7096. s.status = EXTRA_STATE;
  7097. }
  7098. }
  7099. else // DEFLATE header
  7100. {
  7101. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7102. var level_flags = -1;
  7103. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7104. level_flags = 0;
  7105. } else if (s.level < 6) {
  7106. level_flags = 1;
  7107. } else if (s.level === 6) {
  7108. level_flags = 2;
  7109. } else {
  7110. level_flags = 3;
  7111. }
  7112. header |= (level_flags << 6);
  7113. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7114. header += 31 - (header % 31);
  7115. s.status = BUSY_STATE;
  7116. putShortMSB(s, header);
  7117. /* Save the adler32 of the preset dictionary: */
  7118. if (s.strstart !== 0) {
  7119. putShortMSB(s, strm.adler >>> 16);
  7120. putShortMSB(s, strm.adler & 0xffff);
  7121. }
  7122. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7123. }
  7124. }
  7125. //#ifdef GZIP
  7126. if (s.status === EXTRA_STATE) {
  7127. if (s.gzhead.extra/* != Z_NULL*/) {
  7128. beg = s.pending; /* start of bytes to update crc */
  7129. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7130. if (s.pending === s.pending_buf_size) {
  7131. if (s.gzhead.hcrc && s.pending > beg) {
  7132. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7133. }
  7134. flush_pending(strm);
  7135. beg = s.pending;
  7136. if (s.pending === s.pending_buf_size) {
  7137. break;
  7138. }
  7139. }
  7140. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7141. s.gzindex++;
  7142. }
  7143. if (s.gzhead.hcrc && s.pending > beg) {
  7144. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7145. }
  7146. if (s.gzindex === s.gzhead.extra.length) {
  7147. s.gzindex = 0;
  7148. s.status = NAME_STATE;
  7149. }
  7150. }
  7151. else {
  7152. s.status = NAME_STATE;
  7153. }
  7154. }
  7155. if (s.status === NAME_STATE) {
  7156. if (s.gzhead.name/* != Z_NULL*/) {
  7157. beg = s.pending; /* start of bytes to update crc */
  7158. //int val;
  7159. do {
  7160. if (s.pending === s.pending_buf_size) {
  7161. if (s.gzhead.hcrc && s.pending > beg) {
  7162. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7163. }
  7164. flush_pending(strm);
  7165. beg = s.pending;
  7166. if (s.pending === s.pending_buf_size) {
  7167. val = 1;
  7168. break;
  7169. }
  7170. }
  7171. // JS specific: little magic to add zero terminator to end of string
  7172. if (s.gzindex < s.gzhead.name.length) {
  7173. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7174. } else {
  7175. val = 0;
  7176. }
  7177. put_byte(s, val);
  7178. } while (val !== 0);
  7179. if (s.gzhead.hcrc && s.pending > beg) {
  7180. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7181. }
  7182. if (val === 0) {
  7183. s.gzindex = 0;
  7184. s.status = COMMENT_STATE;
  7185. }
  7186. }
  7187. else {
  7188. s.status = COMMENT_STATE;
  7189. }
  7190. }
  7191. if (s.status === COMMENT_STATE) {
  7192. if (s.gzhead.comment/* != Z_NULL*/) {
  7193. beg = s.pending; /* start of bytes to update crc */
  7194. //int val;
  7195. do {
  7196. if (s.pending === s.pending_buf_size) {
  7197. if (s.gzhead.hcrc && s.pending > beg) {
  7198. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7199. }
  7200. flush_pending(strm);
  7201. beg = s.pending;
  7202. if (s.pending === s.pending_buf_size) {
  7203. val = 1;
  7204. break;
  7205. }
  7206. }
  7207. // JS specific: little magic to add zero terminator to end of string
  7208. if (s.gzindex < s.gzhead.comment.length) {
  7209. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7210. } else {
  7211. val = 0;
  7212. }
  7213. put_byte(s, val);
  7214. } while (val !== 0);
  7215. if (s.gzhead.hcrc && s.pending > beg) {
  7216. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7217. }
  7218. if (val === 0) {
  7219. s.status = HCRC_STATE;
  7220. }
  7221. }
  7222. else {
  7223. s.status = HCRC_STATE;
  7224. }
  7225. }
  7226. if (s.status === HCRC_STATE) {
  7227. if (s.gzhead.hcrc) {
  7228. if (s.pending + 2 > s.pending_buf_size) {
  7229. flush_pending(strm);
  7230. }
  7231. if (s.pending + 2 <= s.pending_buf_size) {
  7232. put_byte(s, strm.adler & 0xff);
  7233. put_byte(s, (strm.adler >> 8) & 0xff);
  7234. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7235. s.status = BUSY_STATE;
  7236. }
  7237. }
  7238. else {
  7239. s.status = BUSY_STATE;
  7240. }
  7241. }
  7242. //#endif
  7243. /* Flush as much pending output as possible */
  7244. if (s.pending !== 0) {
  7245. flush_pending(strm);
  7246. if (strm.avail_out === 0) {
  7247. /* Since avail_out is 0, deflate will be called again with
  7248. * more output space, but possibly with both pending and
  7249. * avail_in equal to zero. There won't be anything to do,
  7250. * but this is not an error situation so make sure we
  7251. * return OK instead of BUF_ERROR at next call of deflate:
  7252. */
  7253. s.last_flush = -1;
  7254. return Z_OK;
  7255. }
  7256. /* Make sure there is something to do and avoid duplicate consecutive
  7257. * flushes. For repeated and useless calls with Z_FINISH, we keep
  7258. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7259. */
  7260. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7261. flush !== Z_FINISH) {
  7262. return err(strm, Z_BUF_ERROR);
  7263. }
  7264. /* User must not provide more input after the first FINISH: */
  7265. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7266. return err(strm, Z_BUF_ERROR);
  7267. }
  7268. /* Start a new block or continue the current one.
  7269. */
  7270. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7271. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7272. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7273. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7274. configuration_table[s.level].func(s, flush));
  7275. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7276. s.status = FINISH_STATE;
  7277. }
  7278. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7279. if (strm.avail_out === 0) {
  7280. s.last_flush = -1;
  7281. /* avoid BUF_ERROR next call, see above */
  7282. }
  7283. return Z_OK;
  7284. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7285. * of deflate should use the same flush parameter to make sure
  7286. * that the flush is complete. So we don't have to output an
  7287. * empty block here, this will be done at next call. This also
  7288. * ensures that for a very small output buffer, we emit at most
  7289. * one empty block.
  7290. */
  7291. }
  7292. if (bstate === BS_BLOCK_DONE) {
  7293. if (flush === Z_PARTIAL_FLUSH) {
  7294. trees._tr_align(s);
  7295. }
  7296. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7297. trees._tr_stored_block(s, 0, 0, false);
  7298. /* For a full flush, this empty block will be recognized
  7299. * as a special marker by inflate_sync().
  7300. */
  7301. if (flush === Z_FULL_FLUSH) {
  7302. /*** CLEAR_HASH(s); ***/ /* forget history */
  7303. zero(s.head); // Fill with NIL (= 0);
  7304. if (s.lookahead === 0) {
  7305. s.strstart = 0;
  7306. s.block_start = 0;
  7307. s.insert = 0;
  7308. }
  7309. }
  7310. }
  7311. flush_pending(strm);
  7312. if (strm.avail_out === 0) {
  7313. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7314. return Z_OK;
  7315. }
  7316. }
  7317. }
  7318. //Assert(strm->avail_out > 0, "bug2");
  7319. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7320. if (flush !== Z_FINISH) { return Z_OK; }
  7321. if (s.wrap <= 0) { return Z_STREAM_END; }
  7322. /* Write the trailer */
  7323. if (s.wrap === 2) {
  7324. put_byte(s, strm.adler & 0xff);
  7325. put_byte(s, (strm.adler >> 8) & 0xff);
  7326. put_byte(s, (strm.adler >> 16) & 0xff);
  7327. put_byte(s, (strm.adler >> 24) & 0xff);
  7328. put_byte(s, strm.total_in & 0xff);
  7329. put_byte(s, (strm.total_in >> 8) & 0xff);
  7330. put_byte(s, (strm.total_in >> 16) & 0xff);
  7331. put_byte(s, (strm.total_in >> 24) & 0xff);
  7332. }
  7333. else
  7334. {
  7335. putShortMSB(s, strm.adler >>> 16);
  7336. putShortMSB(s, strm.adler & 0xffff);
  7337. }
  7338. flush_pending(strm);
  7339. /* If avail_out is zero, the application will call deflate again
  7340. * to flush the rest.
  7341. */
  7342. if (s.wrap > 0) { s.wrap = -s.wrap; }
  7343. /* write the trailer only once! */
  7344. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7345. }
  7346. function deflateEnd(strm) {
  7347. var status;
  7348. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7349. return Z_STREAM_ERROR;
  7350. }
  7351. status = strm.state.status;
  7352. if (status !== INIT_STATE &&
  7353. status !== EXTRA_STATE &&
  7354. status !== NAME_STATE &&
  7355. status !== COMMENT_STATE &&
  7356. status !== HCRC_STATE &&
  7357. status !== BUSY_STATE &&
  7358. status !== FINISH_STATE
  7359. ) {
  7360. return err(strm, Z_STREAM_ERROR);
  7361. }
  7362. strm.state = null;
  7363. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7364. }
  7365. /* =========================================================================
  7366. * Copy the source state to the destination state
  7367. */
  7368. //function deflateCopy(dest, source) {
  7369. //
  7370. //}
  7371. exports.deflateInit = deflateInit;
  7372. exports.deflateInit2 = deflateInit2;
  7373. exports.deflateReset = deflateReset;
  7374. exports.deflateResetKeep = deflateResetKeep;
  7375. exports.deflateSetHeader = deflateSetHeader;
  7376. exports.deflate = deflate;
  7377. exports.deflateEnd = deflateEnd;
  7378. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  7379. /* Not implemented
  7380. exports.deflateBound = deflateBound;
  7381. exports.deflateCopy = deflateCopy;
  7382. exports.deflateSetDictionary = deflateSetDictionary;
  7383. exports.deflateParams = deflateParams;
  7384. exports.deflatePending = deflatePending;
  7385. exports.deflatePrime = deflatePrime;
  7386. exports.deflateTune = deflateTune;
  7387. */
  7388. },{"../utils/common":26,"./adler32":28,"./crc32":30,"./messages":36,"./trees":37}],32:[function(require,module,exports){
  7389. 'use strict';
  7390. function GZheader() {
  7391. /* true if compressed data believed to be text */
  7392. this.text = 0;
  7393. /* modification time */
  7394. this.time = 0;
  7395. /* extra flags (not used when writing a gzip file) */
  7396. this.xflags = 0;
  7397. /* operating system */
  7398. this.os = 0;
  7399. /* pointer to extra field or Z_NULL if none */
  7400. this.extra = null;
  7401. /* extra field length (valid if extra != Z_NULL) */
  7402. this.extra_len = 0; // Actually, we don't need it in JS,
  7403. // but leave for few code modifications
  7404. //
  7405. // Setup limits is not necessary because in js we should not preallocate memory
  7406. // for inflate use constant limit in 65536 bytes
  7407. //
  7408. /* space at extra (only when reading header) */
  7409. // this.extra_max = 0;
  7410. /* pointer to zero-terminated file name or Z_NULL */
  7411. this.name = '';
  7412. /* space at name (only when reading header) */
  7413. // this.name_max = 0;
  7414. /* pointer to zero-terminated comment or Z_NULL */
  7415. this.comment = '';
  7416. /* space at comment (only when reading header) */
  7417. // this.comm_max = 0;
  7418. /* true if there was or will be a header crc */
  7419. this.hcrc = 0;
  7420. /* true when done reading gzip header (not used when writing a gzip file) */
  7421. this.done = false;
  7422. }
  7423. module.exports = GZheader;
  7424. },{}],33:[function(require,module,exports){
  7425. 'use strict';
  7426. // See state defs from inflate.js
  7427. var BAD = 30; /* got a data error -- remain here until reset */
  7428. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7429. /*
  7430. Decode literal, length, and distance codes and write out the resulting
  7431. literal and match bytes until either not enough input or output is
  7432. available, an end-of-block is encountered, or a data error is encountered.
  7433. When large enough input and output buffers are supplied to inflate(), for
  7434. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  7435. inflate execution time is spent in this routine.
  7436. Entry assumptions:
  7437. state.mode === LEN
  7438. strm.avail_in >= 6
  7439. strm.avail_out >= 258
  7440. start >= strm.avail_out
  7441. state.bits < 8
  7442. On return, state.mode is one of:
  7443. LEN -- ran out of enough output space or enough available input
  7444. TYPE -- reached end of block code, inflate() to interpret next block
  7445. BAD -- error in block data
  7446. Notes:
  7447. - The maximum input bits used by a length/distance pair is 15 bits for the
  7448. length code, 5 bits for the length extra, 15 bits for the distance code,
  7449. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  7450. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  7451. checking for available input while decoding.
  7452. - The maximum bytes that a single length/distance pair can output is 258
  7453. bytes, which is the maximum length that can be coded. inflate_fast()
  7454. requires strm.avail_out >= 258 for each loop to avoid checking for
  7455. output space.
  7456. */
  7457. module.exports = function inflate_fast(strm, start) {
  7458. var state;
  7459. var _in; /* local strm.input */
  7460. var last; /* have enough input while in < last */
  7461. var _out; /* local strm.output */
  7462. var beg; /* inflate()'s initial strm.output */
  7463. var end; /* while out < end, enough space available */
  7464. //#ifdef INFLATE_STRICT
  7465. var dmax; /* maximum distance from zlib header */
  7466. //#endif
  7467. var wsize; /* window size or zero if not using window */
  7468. var whave; /* valid bytes in the window */
  7469. var wnext; /* window write index */
  7470. var window; /* allocated sliding window, if wsize != 0 */
  7471. var hold; /* local strm.hold */
  7472. var bits; /* local strm.bits */
  7473. var lcode; /* local strm.lencode */
  7474. var dcode; /* local strm.distcode */
  7475. var lmask; /* mask for first level of length codes */
  7476. var dmask; /* mask for first level of distance codes */
  7477. var here; /* retrieved table entry */
  7478. var op; /* code bits, operation, extra bits, or */
  7479. /* window position, window bytes to copy */
  7480. var len; /* match length, unused bytes */
  7481. var dist; /* match distance */
  7482. var from; /* where to copy match from */
  7483. var from_source;
  7484. var input, output; // JS specific, because we have no pointers
  7485. /* copy state to local variables */
  7486. state = strm.state;
  7487. //here = state.here;
  7488. _in = strm.next_in;
  7489. input = strm.input;
  7490. last = _in + (strm.avail_in - 5);
  7491. _out = strm.next_out;
  7492. output = strm.output;
  7493. beg = _out - (start - strm.avail_out);
  7494. end = _out + (strm.avail_out - 257);
  7495. //#ifdef INFLATE_STRICT
  7496. dmax = state.dmax;
  7497. //#endif
  7498. wsize = state.wsize;
  7499. whave = state.whave;
  7500. wnext = state.wnext;
  7501. window = state.window;
  7502. hold = state.hold;
  7503. bits = state.bits;
  7504. lcode = state.lencode;
  7505. dcode = state.distcode;
  7506. lmask = (1 << state.lenbits) - 1;
  7507. dmask = (1 << state.distbits) - 1;
  7508. /* decode literals and length/distances until end-of-block or not enough
  7509. input data or output space */
  7510. top:
  7511. do {
  7512. if (bits < 15) {
  7513. hold += input[_in++] << bits;
  7514. bits += 8;
  7515. hold += input[_in++] << bits;
  7516. bits += 8;
  7517. }
  7518. here = lcode[hold & lmask];
  7519. dolen:
  7520. for (;;) { // Goto emulation
  7521. op = here >>> 24/*here.bits*/;
  7522. hold >>>= op;
  7523. bits -= op;
  7524. op = (here >>> 16) & 0xff/*here.op*/;
  7525. if (op === 0) { /* literal */
  7526. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  7527. // "inflate: literal '%c'\n" :
  7528. // "inflate: literal 0x%02x\n", here.val));
  7529. output[_out++] = here & 0xffff/*here.val*/;
  7530. }
  7531. else if (op & 16) { /* length base */
  7532. len = here & 0xffff/*here.val*/;
  7533. op &= 15; /* number of extra bits */
  7534. if (op) {
  7535. if (bits < op) {
  7536. hold += input[_in++] << bits;
  7537. bits += 8;
  7538. }
  7539. len += hold & ((1 << op) - 1);
  7540. hold >>>= op;
  7541. bits -= op;
  7542. }
  7543. //Tracevv((stderr, "inflate: length %u\n", len));
  7544. if (bits < 15) {
  7545. hold += input[_in++] << bits;
  7546. bits += 8;
  7547. hold += input[_in++] << bits;
  7548. bits += 8;
  7549. }
  7550. here = dcode[hold & dmask];
  7551. dodist:
  7552. for (;;) { // goto emulation
  7553. op = here >>> 24/*here.bits*/;
  7554. hold >>>= op;
  7555. bits -= op;
  7556. op = (here >>> 16) & 0xff/*here.op*/;
  7557. if (op & 16) { /* distance base */
  7558. dist = here & 0xffff/*here.val*/;
  7559. op &= 15; /* number of extra bits */
  7560. if (bits < op) {
  7561. hold += input[_in++] << bits;
  7562. bits += 8;
  7563. if (bits < op) {
  7564. hold += input[_in++] << bits;
  7565. bits += 8;
  7566. }
  7567. }
  7568. dist += hold & ((1 << op) - 1);
  7569. //#ifdef INFLATE_STRICT
  7570. if (dist > dmax) {
  7571. strm.msg = 'invalid distance too far back';
  7572. state.mode = BAD;
  7573. break top;
  7574. }
  7575. //#endif
  7576. hold >>>= op;
  7577. bits -= op;
  7578. //Tracevv((stderr, "inflate: distance %u\n", dist));
  7579. op = _out - beg; /* max distance in output */
  7580. if (dist > op) { /* see if copy from window */
  7581. op = dist - op; /* distance back in window */
  7582. if (op > whave) {
  7583. if (state.sane) {
  7584. strm.msg = 'invalid distance too far back';
  7585. state.mode = BAD;
  7586. break top;
  7587. }
  7588. // (!) This block is disabled in zlib defailts,
  7589. // don't enable it for binary compatibility
  7590. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  7591. // if (len <= op - whave) {
  7592. // do {
  7593. // output[_out++] = 0;
  7594. // } while (--len);
  7595. // continue top;
  7596. // }
  7597. // len -= op - whave;
  7598. // do {
  7599. // output[_out++] = 0;
  7600. // } while (--op > whave);
  7601. // if (op === 0) {
  7602. // from = _out - dist;
  7603. // do {
  7604. // output[_out++] = output[from++];
  7605. // } while (--len);
  7606. // continue top;
  7607. // }
  7608. //#endif
  7609. }
  7610. from = 0; // window index
  7611. from_source = window;
  7612. if (wnext === 0) { /* very common case */
  7613. from += wsize - op;
  7614. if (op < len) { /* some from window */
  7615. len -= op;
  7616. do {
  7617. output[_out++] = window[from++];
  7618. } while (--op);
  7619. from = _out - dist; /* rest from output */
  7620. from_source = output;
  7621. }
  7622. }
  7623. else if (wnext < op) { /* wrap around window */
  7624. from += wsize + wnext - op;
  7625. op -= wnext;
  7626. if (op < len) { /* some from end of window */
  7627. len -= op;
  7628. do {
  7629. output[_out++] = window[from++];
  7630. } while (--op);
  7631. from = 0;
  7632. if (wnext < len) { /* some from start of window */
  7633. op = wnext;
  7634. len -= op;
  7635. do {
  7636. output[_out++] = window[from++];
  7637. } while (--op);
  7638. from = _out - dist; /* rest from output */
  7639. from_source = output;
  7640. }
  7641. }
  7642. }
  7643. else { /* contiguous in window */
  7644. from += wnext - op;
  7645. if (op < len) { /* some from window */
  7646. len -= op;
  7647. do {
  7648. output[_out++] = window[from++];
  7649. } while (--op);
  7650. from = _out - dist; /* rest from output */
  7651. from_source = output;
  7652. }
  7653. }
  7654. while (len > 2) {
  7655. output[_out++] = from_source[from++];
  7656. output[_out++] = from_source[from++];
  7657. output[_out++] = from_source[from++];
  7658. len -= 3;
  7659. }
  7660. if (len) {
  7661. output[_out++] = from_source[from++];
  7662. if (len > 1) {
  7663. output[_out++] = from_source[from++];
  7664. }
  7665. }
  7666. }
  7667. else {
  7668. from = _out - dist; /* copy direct from output */
  7669. do { /* minimum length is three */
  7670. output[_out++] = output[from++];
  7671. output[_out++] = output[from++];
  7672. output[_out++] = output[from++];
  7673. len -= 3;
  7674. } while (len > 2);
  7675. if (len) {
  7676. output[_out++] = output[from++];
  7677. if (len > 1) {
  7678. output[_out++] = output[from++];
  7679. }
  7680. }
  7681. }
  7682. }
  7683. else if ((op & 64) === 0) { /* 2nd level distance code */
  7684. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7685. continue dodist;
  7686. }
  7687. else {
  7688. strm.msg = 'invalid distance code';
  7689. state.mode = BAD;
  7690. break top;
  7691. }
  7692. break; // need to emulate goto via "continue"
  7693. }
  7694. }
  7695. else if ((op & 64) === 0) { /* 2nd level length code */
  7696. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7697. continue dolen;
  7698. }
  7699. else if (op & 32) { /* end-of-block */
  7700. //Tracevv((stderr, "inflate: end of block\n"));
  7701. state.mode = TYPE;
  7702. break top;
  7703. }
  7704. else {
  7705. strm.msg = 'invalid literal/length code';
  7706. state.mode = BAD;
  7707. break top;
  7708. }
  7709. break; // need to emulate goto via "continue"
  7710. }
  7711. } while (_in < last && _out < end);
  7712. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  7713. len = bits >> 3;
  7714. _in -= len;
  7715. bits -= len << 3;
  7716. hold &= (1 << bits) - 1;
  7717. /* update state and return */
  7718. strm.next_in = _in;
  7719. strm.next_out = _out;
  7720. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  7721. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  7722. state.hold = hold;
  7723. state.bits = bits;
  7724. return;
  7725. };
  7726. },{}],34:[function(require,module,exports){
  7727. 'use strict';
  7728. var utils = require('../utils/common');
  7729. var adler32 = require('./adler32');
  7730. var crc32 = require('./crc32');
  7731. var inflate_fast = require('./inffast');
  7732. var inflate_table = require('./inftrees');
  7733. var CODES = 0;
  7734. var LENS = 1;
  7735. var DISTS = 2;
  7736. /* Public constants ==========================================================*/
  7737. /* ===========================================================================*/
  7738. /* Allowed flush values; see deflate() and inflate() below for details */
  7739. //var Z_NO_FLUSH = 0;
  7740. //var Z_PARTIAL_FLUSH = 1;
  7741. //var Z_SYNC_FLUSH = 2;
  7742. //var Z_FULL_FLUSH = 3;
  7743. var Z_FINISH = 4;
  7744. var Z_BLOCK = 5;
  7745. var Z_TREES = 6;
  7746. /* Return codes for the compression/decompression functions. Negative values
  7747. * are errors, positive values are used for special but normal events.
  7748. */
  7749. var Z_OK = 0;
  7750. var Z_STREAM_END = 1;
  7751. var Z_NEED_DICT = 2;
  7752. //var Z_ERRNO = -1;
  7753. var Z_STREAM_ERROR = -2;
  7754. var Z_DATA_ERROR = -3;
  7755. var Z_MEM_ERROR = -4;
  7756. var Z_BUF_ERROR = -5;
  7757. //var Z_VERSION_ERROR = -6;
  7758. /* The deflate compression method */
  7759. var Z_DEFLATED = 8;
  7760. /* STATES ====================================================================*/
  7761. /* ===========================================================================*/
  7762. var HEAD = 1; /* i: waiting for magic header */
  7763. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  7764. var TIME = 3; /* i: waiting for modification time (gzip) */
  7765. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  7766. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  7767. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  7768. var NAME = 7; /* i: waiting for end of file name (gzip) */
  7769. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  7770. var HCRC = 9; /* i: waiting for header crc (gzip) */
  7771. var DICTID = 10; /* i: waiting for dictionary check value */
  7772. var DICT = 11; /* waiting for inflateSetDictionary() call */
  7773. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7774. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  7775. var STORED = 14; /* i: waiting for stored size (length and complement) */
  7776. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  7777. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  7778. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  7779. var LENLENS = 18; /* i: waiting for code length code lengths */
  7780. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  7781. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  7782. var LEN = 21; /* i: waiting for length/lit/eob code */
  7783. var LENEXT = 22; /* i: waiting for length extra bits */
  7784. var DIST = 23; /* i: waiting for distance code */
  7785. var DISTEXT = 24; /* i: waiting for distance extra bits */
  7786. var MATCH = 25; /* o: waiting for output space to copy string */
  7787. var LIT = 26; /* o: waiting for output space to write literal */
  7788. var CHECK = 27; /* i: waiting for 32-bit check value */
  7789. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  7790. var DONE = 29; /* finished check, done -- remain here until reset */
  7791. var BAD = 30; /* got a data error -- remain here until reset */
  7792. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  7793. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  7794. /* ===========================================================================*/
  7795. var ENOUGH_LENS = 852;
  7796. var ENOUGH_DISTS = 592;
  7797. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  7798. var MAX_WBITS = 15;
  7799. /* 32K LZ77 window */
  7800. var DEF_WBITS = MAX_WBITS;
  7801. function ZSWAP32(q) {
  7802. return (((q >>> 24) & 0xff) +
  7803. ((q >>> 8) & 0xff00) +
  7804. ((q & 0xff00) << 8) +
  7805. ((q & 0xff) << 24));
  7806. }
  7807. function InflateState() {
  7808. this.mode = 0; /* current inflate mode */
  7809. this.last = false; /* true if processing last block */
  7810. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7811. this.havedict = false; /* true if dictionary provided */
  7812. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  7813. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  7814. this.check = 0; /* protected copy of check value */
  7815. this.total = 0; /* protected copy of output count */
  7816. // TODO: may be {}
  7817. this.head = null; /* where to save gzip header information */
  7818. /* sliding window */
  7819. this.wbits = 0; /* log base 2 of requested window size */
  7820. this.wsize = 0; /* window size or zero if not using window */
  7821. this.whave = 0; /* valid bytes in the window */
  7822. this.wnext = 0; /* window write index */
  7823. this.window = null; /* allocated sliding window, if needed */
  7824. /* bit accumulator */
  7825. this.hold = 0; /* input bit accumulator */
  7826. this.bits = 0; /* number of bits in "in" */
  7827. /* for string and stored block copying */
  7828. this.length = 0; /* literal or length of data to copy */
  7829. this.offset = 0; /* distance back to copy string from */
  7830. /* for table and code decoding */
  7831. this.extra = 0; /* extra bits needed */
  7832. /* fixed and dynamic code tables */
  7833. this.lencode = null; /* starting table for length/literal codes */
  7834. this.distcode = null; /* starting table for distance codes */
  7835. this.lenbits = 0; /* index bits for lencode */
  7836. this.distbits = 0; /* index bits for distcode */
  7837. /* dynamic table building */
  7838. this.ncode = 0; /* number of code length code lengths */
  7839. this.nlen = 0; /* number of length code lengths */
  7840. this.ndist = 0; /* number of distance code lengths */
  7841. this.have = 0; /* number of code lengths in lens[] */
  7842. this.next = null; /* next available space in codes[] */
  7843. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  7844. this.work = new utils.Buf16(288); /* work area for code table building */
  7845. /*
  7846. because we don't have pointers in js, we use lencode and distcode directly
  7847. as buffers so we don't need codes
  7848. */
  7849. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  7850. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  7851. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  7852. this.sane = 0; /* if false, allow invalid distance too far */
  7853. this.back = 0; /* bits back of last unprocessed length/lit */
  7854. this.was = 0; /* initial length of match */
  7855. }
  7856. function inflateResetKeep(strm) {
  7857. var state;
  7858. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7859. state = strm.state;
  7860. strm.total_in = strm.total_out = state.total = 0;
  7861. strm.msg = ''; /*Z_NULL*/
  7862. if (state.wrap) { /* to support ill-conceived Java test suite */
  7863. strm.adler = state.wrap & 1;
  7864. }
  7865. state.mode = HEAD;
  7866. state.last = 0;
  7867. state.havedict = 0;
  7868. state.dmax = 32768;
  7869. state.head = null/*Z_NULL*/;
  7870. state.hold = 0;
  7871. state.bits = 0;
  7872. //state.lencode = state.distcode = state.next = state.codes;
  7873. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  7874. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  7875. state.sane = 1;
  7876. state.back = -1;
  7877. //Tracev((stderr, "inflate: reset\n"));
  7878. return Z_OK;
  7879. }
  7880. function inflateReset(strm) {
  7881. var state;
  7882. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7883. state = strm.state;
  7884. state.wsize = 0;
  7885. state.whave = 0;
  7886. state.wnext = 0;
  7887. return inflateResetKeep(strm);
  7888. }
  7889. function inflateReset2(strm, windowBits) {
  7890. var wrap;
  7891. var state;
  7892. /* get the state */
  7893. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7894. state = strm.state;
  7895. /* extract wrap request from windowBits parameter */
  7896. if (windowBits < 0) {
  7897. wrap = 0;
  7898. windowBits = -windowBits;
  7899. }
  7900. else {
  7901. wrap = (windowBits >> 4) + 1;
  7902. if (windowBits < 48) {
  7903. windowBits &= 15;
  7904. }
  7905. }
  7906. /* set number of window bits, free window if different */
  7907. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  7908. return Z_STREAM_ERROR;
  7909. }
  7910. if (state.window !== null && state.wbits !== windowBits) {
  7911. state.window = null;
  7912. }
  7913. /* update state and reset the rest of it */
  7914. state.wrap = wrap;
  7915. state.wbits = windowBits;
  7916. return inflateReset(strm);
  7917. }
  7918. function inflateInit2(strm, windowBits) {
  7919. var ret;
  7920. var state;
  7921. if (!strm) { return Z_STREAM_ERROR; }
  7922. //strm.msg = Z_NULL; /* in case we return an error */
  7923. state = new InflateState();
  7924. //if (state === Z_NULL) return Z_MEM_ERROR;
  7925. //Tracev((stderr, "inflate: allocated\n"));
  7926. strm.state = state;
  7927. state.window = null/*Z_NULL*/;
  7928. ret = inflateReset2(strm, windowBits);
  7929. if (ret !== Z_OK) {
  7930. strm.state = null/*Z_NULL*/;
  7931. }
  7932. return ret;
  7933. }
  7934. function inflateInit(strm) {
  7935. return inflateInit2(strm, DEF_WBITS);
  7936. }
  7937. /*
  7938. Return state with length and distance decoding tables and index sizes set to
  7939. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  7940. If BUILDFIXED is defined, then instead this routine builds the tables the
  7941. first time it's called, and returns those tables the first time and
  7942. thereafter. This reduces the size of the code by about 2K bytes, in
  7943. exchange for a little execution time. However, BUILDFIXED should not be
  7944. used for threaded applications, since the rewriting of the tables and virgin
  7945. may not be thread-safe.
  7946. */
  7947. var virgin = true;
  7948. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  7949. function fixedtables(state) {
  7950. /* build fixed huffman tables if first call (may not be thread safe) */
  7951. if (virgin) {
  7952. var sym;
  7953. lenfix = new utils.Buf32(512);
  7954. distfix = new utils.Buf32(32);
  7955. /* literal/length table */
  7956. sym = 0;
  7957. while (sym < 144) { state.lens[sym++] = 8; }
  7958. while (sym < 256) { state.lens[sym++] = 9; }
  7959. while (sym < 280) { state.lens[sym++] = 7; }
  7960. while (sym < 288) { state.lens[sym++] = 8; }
  7961. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  7962. /* distance table */
  7963. sym = 0;
  7964. while (sym < 32) { state.lens[sym++] = 5; }
  7965. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  7966. /* do this just once */
  7967. virgin = false;
  7968. }
  7969. state.lencode = lenfix;
  7970. state.lenbits = 9;
  7971. state.distcode = distfix;
  7972. state.distbits = 5;
  7973. }
  7974. /*
  7975. Update the window with the last wsize (normally 32K) bytes written before
  7976. returning. If window does not exist yet, create it. This is only called
  7977. when a window is already in use, or when output has been written during this
  7978. inflate call, but the end of the deflate stream has not been reached yet.
  7979. It is also called to create a window for dictionary data when a dictionary
  7980. is loaded.
  7981. Providing output buffers larger than 32K to inflate() should provide a speed
  7982. advantage, since only the last 32K of output is copied to the sliding window
  7983. upon return from inflate(), and since all distances after the first 32K of
  7984. output will fall in the output data, making match copies simpler and faster.
  7985. The advantage may be dependent on the size of the processor's data caches.
  7986. */
  7987. function updatewindow(strm, src, end, copy) {
  7988. var dist;
  7989. var state = strm.state;
  7990. /* if it hasn't been done already, allocate space for the window */
  7991. if (state.window === null) {
  7992. state.wsize = 1 << state.wbits;
  7993. state.wnext = 0;
  7994. state.whave = 0;
  7995. state.window = new utils.Buf8(state.wsize);
  7996. }
  7997. /* copy state->wsize or less output bytes into the circular window */
  7998. if (copy >= state.wsize) {
  7999. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  8000. state.wnext = 0;
  8001. state.whave = state.wsize;
  8002. }
  8003. else {
  8004. dist = state.wsize - state.wnext;
  8005. if (dist > copy) {
  8006. dist = copy;
  8007. }
  8008. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8009. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  8010. copy -= dist;
  8011. if (copy) {
  8012. //zmemcpy(state->window, end - copy, copy);
  8013. utils.arraySet(state.window,src, end - copy, copy, 0);
  8014. state.wnext = copy;
  8015. state.whave = state.wsize;
  8016. }
  8017. else {
  8018. state.wnext += dist;
  8019. if (state.wnext === state.wsize) { state.wnext = 0; }
  8020. if (state.whave < state.wsize) { state.whave += dist; }
  8021. }
  8022. }
  8023. return 0;
  8024. }
  8025. function inflate(strm, flush) {
  8026. var state;
  8027. var input, output; // input/output buffers
  8028. var next; /* next input INDEX */
  8029. var put; /* next output INDEX */
  8030. var have, left; /* available input and output */
  8031. var hold; /* bit buffer */
  8032. var bits; /* bits in bit buffer */
  8033. var _in, _out; /* save starting available input and output */
  8034. var copy; /* number of stored or match bytes to copy */
  8035. var from; /* where to copy match bytes from */
  8036. var from_source;
  8037. var here = 0; /* current decoding table entry */
  8038. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8039. //var last; /* parent table entry */
  8040. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8041. var len; /* length to copy for repeats, bits to drop */
  8042. var ret; /* return code */
  8043. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  8044. var opts;
  8045. var n; // temporary var for NEED_BITS
  8046. var order = /* permutation of code lengths */
  8047. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  8048. if (!strm || !strm.state || !strm.output ||
  8049. (!strm.input && strm.avail_in !== 0)) {
  8050. return Z_STREAM_ERROR;
  8051. }
  8052. state = strm.state;
  8053. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  8054. //--- LOAD() ---
  8055. put = strm.next_out;
  8056. output = strm.output;
  8057. left = strm.avail_out;
  8058. next = strm.next_in;
  8059. input = strm.input;
  8060. have = strm.avail_in;
  8061. hold = state.hold;
  8062. bits = state.bits;
  8063. //---
  8064. _in = have;
  8065. _out = left;
  8066. ret = Z_OK;
  8067. inf_leave: // goto emulation
  8068. for (;;) {
  8069. switch (state.mode) {
  8070. case HEAD:
  8071. if (state.wrap === 0) {
  8072. state.mode = TYPEDO;
  8073. break;
  8074. }
  8075. //=== NEEDBITS(16);
  8076. while (bits < 16) {
  8077. if (have === 0) { break inf_leave; }
  8078. have--;
  8079. hold += input[next++] << bits;
  8080. bits += 8;
  8081. }
  8082. //===//
  8083. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  8084. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8085. //=== CRC2(state.check, hold);
  8086. hbuf[0] = hold & 0xff;
  8087. hbuf[1] = (hold >>> 8) & 0xff;
  8088. state.check = crc32(state.check, hbuf, 2, 0);
  8089. //===//
  8090. //=== INITBITS();
  8091. hold = 0;
  8092. bits = 0;
  8093. //===//
  8094. state.mode = FLAGS;
  8095. break;
  8096. }
  8097. state.flags = 0; /* expect zlib header */
  8098. if (state.head) {
  8099. state.head.done = false;
  8100. }
  8101. if (!(state.wrap & 1) || /* check if zlib header allowed */
  8102. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8103. strm.msg = 'incorrect header check';
  8104. state.mode = BAD;
  8105. break;
  8106. }
  8107. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8108. strm.msg = 'unknown compression method';
  8109. state.mode = BAD;
  8110. break;
  8111. }
  8112. //--- DROPBITS(4) ---//
  8113. hold >>>= 4;
  8114. bits -= 4;
  8115. //---//
  8116. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8117. if (state.wbits === 0) {
  8118. state.wbits = len;
  8119. }
  8120. else if (len > state.wbits) {
  8121. strm.msg = 'invalid window size';
  8122. state.mode = BAD;
  8123. break;
  8124. }
  8125. state.dmax = 1 << len;
  8126. //Tracev((stderr, "inflate: zlib header ok\n"));
  8127. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8128. state.mode = hold & 0x200 ? DICTID : TYPE;
  8129. //=== INITBITS();
  8130. hold = 0;
  8131. bits = 0;
  8132. //===//
  8133. break;
  8134. case FLAGS:
  8135. //=== NEEDBITS(16); */
  8136. while (bits < 16) {
  8137. if (have === 0) { break inf_leave; }
  8138. have--;
  8139. hold += input[next++] << bits;
  8140. bits += 8;
  8141. }
  8142. //===//
  8143. state.flags = hold;
  8144. if ((state.flags & 0xff) !== Z_DEFLATED) {
  8145. strm.msg = 'unknown compression method';
  8146. state.mode = BAD;
  8147. break;
  8148. }
  8149. if (state.flags & 0xe000) {
  8150. strm.msg = 'unknown header flags set';
  8151. state.mode = BAD;
  8152. break;
  8153. }
  8154. if (state.head) {
  8155. state.head.text = ((hold >> 8) & 1);
  8156. }
  8157. if (state.flags & 0x0200) {
  8158. //=== CRC2(state.check, hold);
  8159. hbuf[0] = hold & 0xff;
  8160. hbuf[1] = (hold >>> 8) & 0xff;
  8161. state.check = crc32(state.check, hbuf, 2, 0);
  8162. //===//
  8163. }
  8164. //=== INITBITS();
  8165. hold = 0;
  8166. bits = 0;
  8167. //===//
  8168. state.mode = TIME;
  8169. /* falls through */
  8170. case TIME:
  8171. //=== NEEDBITS(32); */
  8172. while (bits < 32) {
  8173. if (have === 0) { break inf_leave; }
  8174. have--;
  8175. hold += input[next++] << bits;
  8176. bits += 8;
  8177. }
  8178. //===//
  8179. if (state.head) {
  8180. state.head.time = hold;
  8181. }
  8182. if (state.flags & 0x0200) {
  8183. //=== CRC4(state.check, hold)
  8184. hbuf[0] = hold & 0xff;
  8185. hbuf[1] = (hold >>> 8) & 0xff;
  8186. hbuf[2] = (hold >>> 16) & 0xff;
  8187. hbuf[3] = (hold >>> 24) & 0xff;
  8188. state.check = crc32(state.check, hbuf, 4, 0);
  8189. //===
  8190. }
  8191. //=== INITBITS();
  8192. hold = 0;
  8193. bits = 0;
  8194. //===//
  8195. state.mode = OS;
  8196. /* falls through */
  8197. case OS:
  8198. //=== NEEDBITS(16); */
  8199. while (bits < 16) {
  8200. if (have === 0) { break inf_leave; }
  8201. have--;
  8202. hold += input[next++] << bits;
  8203. bits += 8;
  8204. }
  8205. //===//
  8206. if (state.head) {
  8207. state.head.xflags = (hold & 0xff);
  8208. state.head.os = (hold >> 8);
  8209. }
  8210. if (state.flags & 0x0200) {
  8211. //=== CRC2(state.check, hold);
  8212. hbuf[0] = hold & 0xff;
  8213. hbuf[1] = (hold >>> 8) & 0xff;
  8214. state.check = crc32(state.check, hbuf, 2, 0);
  8215. //===//
  8216. }
  8217. //=== INITBITS();
  8218. hold = 0;
  8219. bits = 0;
  8220. //===//
  8221. state.mode = EXLEN;
  8222. /* falls through */
  8223. case EXLEN:
  8224. if (state.flags & 0x0400) {
  8225. //=== NEEDBITS(16); */
  8226. while (bits < 16) {
  8227. if (have === 0) { break inf_leave; }
  8228. have--;
  8229. hold += input[next++] << bits;
  8230. bits += 8;
  8231. }
  8232. //===//
  8233. state.length = hold;
  8234. if (state.head) {
  8235. state.head.extra_len = hold;
  8236. }
  8237. if (state.flags & 0x0200) {
  8238. //=== CRC2(state.check, hold);
  8239. hbuf[0] = hold & 0xff;
  8240. hbuf[1] = (hold >>> 8) & 0xff;
  8241. state.check = crc32(state.check, hbuf, 2, 0);
  8242. //===//
  8243. }
  8244. //=== INITBITS();
  8245. hold = 0;
  8246. bits = 0;
  8247. //===//
  8248. }
  8249. else if (state.head) {
  8250. state.head.extra = null/*Z_NULL*/;
  8251. }
  8252. state.mode = EXTRA;
  8253. /* falls through */
  8254. case EXTRA:
  8255. if (state.flags & 0x0400) {
  8256. copy = state.length;
  8257. if (copy > have) { copy = have; }
  8258. if (copy) {
  8259. if (state.head) {
  8260. len = state.head.extra_len - state.length;
  8261. if (!state.head.extra) {
  8262. // Use untyped array for more conveniend processing later
  8263. state.head.extra = new Array(state.head.extra_len);
  8264. }
  8265. utils.arraySet(
  8266. state.head.extra,
  8267. input,
  8268. next,
  8269. // extra field is limited to 65536 bytes
  8270. // - no need for additional size check
  8271. copy,
  8272. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  8273. len
  8274. );
  8275. //zmemcpy(state.head.extra + len, next,
  8276. // len + copy > state.head.extra_max ?
  8277. // state.head.extra_max - len : copy);
  8278. }
  8279. if (state.flags & 0x0200) {
  8280. state.check = crc32(state.check, input, copy, next);
  8281. }
  8282. have -= copy;
  8283. next += copy;
  8284. state.length -= copy;
  8285. }
  8286. if (state.length) { break inf_leave; }
  8287. }
  8288. state.length = 0;
  8289. state.mode = NAME;
  8290. /* falls through */
  8291. case NAME:
  8292. if (state.flags & 0x0800) {
  8293. if (have === 0) { break inf_leave; }
  8294. copy = 0;
  8295. do {
  8296. // TODO: 2 or 1 bytes?
  8297. len = input[next + copy++];
  8298. /* use constant limit because in js we should not preallocate memory */
  8299. if (state.head && len &&
  8300. (state.length < 65536 /*state.head.name_max*/)) {
  8301. state.head.name += String.fromCharCode(len);
  8302. }
  8303. } while (len && copy < have);
  8304. if (state.flags & 0x0200) {
  8305. state.check = crc32(state.check, input, copy, next);
  8306. }
  8307. have -= copy;
  8308. next += copy;
  8309. if (len) { break inf_leave; }
  8310. }
  8311. else if (state.head) {
  8312. state.head.name = null;
  8313. }
  8314. state.length = 0;
  8315. state.mode = COMMENT;
  8316. /* falls through */
  8317. case COMMENT:
  8318. if (state.flags & 0x1000) {
  8319. if (have === 0) { break inf_leave; }
  8320. copy = 0;
  8321. do {
  8322. len = input[next + copy++];
  8323. /* use constant limit because in js we should not preallocate memory */
  8324. if (state.head && len &&
  8325. (state.length < 65536 /*state.head.comm_max*/)) {
  8326. state.head.comment += String.fromCharCode(len);
  8327. }
  8328. } while (len && copy < have);
  8329. if (state.flags & 0x0200) {
  8330. state.check = crc32(state.check, input, copy, next);
  8331. }
  8332. have -= copy;
  8333. next += copy;
  8334. if (len) { break inf_leave; }
  8335. }
  8336. else if (state.head) {
  8337. state.head.comment = null;
  8338. }
  8339. state.mode = HCRC;
  8340. /* falls through */
  8341. case HCRC:
  8342. if (state.flags & 0x0200) {
  8343. //=== NEEDBITS(16); */
  8344. while (bits < 16) {
  8345. if (have === 0) { break inf_leave; }
  8346. have--;
  8347. hold += input[next++] << bits;
  8348. bits += 8;
  8349. }
  8350. //===//
  8351. if (hold !== (state.check & 0xffff)) {
  8352. strm.msg = 'header crc mismatch';
  8353. state.mode = BAD;
  8354. break;
  8355. }
  8356. //=== INITBITS();
  8357. hold = 0;
  8358. bits = 0;
  8359. //===//
  8360. }
  8361. if (state.head) {
  8362. state.head.hcrc = ((state.flags >> 9) & 1);
  8363. state.head.done = true;
  8364. }
  8365. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  8366. state.mode = TYPE;
  8367. break;
  8368. case DICTID:
  8369. //=== NEEDBITS(32); */
  8370. while (bits < 32) {
  8371. if (have === 0) { break inf_leave; }
  8372. have--;
  8373. hold += input[next++] << bits;
  8374. bits += 8;
  8375. }
  8376. //===//
  8377. strm.adler = state.check = ZSWAP32(hold);
  8378. //=== INITBITS();
  8379. hold = 0;
  8380. bits = 0;
  8381. //===//
  8382. state.mode = DICT;
  8383. /* falls through */
  8384. case DICT:
  8385. if (state.havedict === 0) {
  8386. //--- RESTORE() ---
  8387. strm.next_out = put;
  8388. strm.avail_out = left;
  8389. strm.next_in = next;
  8390. strm.avail_in = have;
  8391. state.hold = hold;
  8392. state.bits = bits;
  8393. //---
  8394. return Z_NEED_DICT;
  8395. }
  8396. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8397. state.mode = TYPE;
  8398. /* falls through */
  8399. case TYPE:
  8400. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  8401. /* falls through */
  8402. case TYPEDO:
  8403. if (state.last) {
  8404. //--- BYTEBITS() ---//
  8405. hold >>>= bits & 7;
  8406. bits -= bits & 7;
  8407. //---//
  8408. state.mode = CHECK;
  8409. break;
  8410. }
  8411. //=== NEEDBITS(3); */
  8412. while (bits < 3) {
  8413. if (have === 0) { break inf_leave; }
  8414. have--;
  8415. hold += input[next++] << bits;
  8416. bits += 8;
  8417. }
  8418. //===//
  8419. state.last = (hold & 0x01)/*BITS(1)*/;
  8420. //--- DROPBITS(1) ---//
  8421. hold >>>= 1;
  8422. bits -= 1;
  8423. //---//
  8424. switch ((hold & 0x03)/*BITS(2)*/) {
  8425. case 0: /* stored block */
  8426. //Tracev((stderr, "inflate: stored block%s\n",
  8427. // state.last ? " (last)" : ""));
  8428. state.mode = STORED;
  8429. break;
  8430. case 1: /* fixed block */
  8431. fixedtables(state);
  8432. //Tracev((stderr, "inflate: fixed codes block%s\n",
  8433. // state.last ? " (last)" : ""));
  8434. state.mode = LEN_; /* decode codes */
  8435. if (flush === Z_TREES) {
  8436. //--- DROPBITS(2) ---//
  8437. hold >>>= 2;
  8438. bits -= 2;
  8439. //---//
  8440. break inf_leave;
  8441. }
  8442. break;
  8443. case 2: /* dynamic block */
  8444. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  8445. // state.last ? " (last)" : ""));
  8446. state.mode = TABLE;
  8447. break;
  8448. case 3:
  8449. strm.msg = 'invalid block type';
  8450. state.mode = BAD;
  8451. }
  8452. //--- DROPBITS(2) ---//
  8453. hold >>>= 2;
  8454. bits -= 2;
  8455. //---//
  8456. break;
  8457. case STORED:
  8458. //--- BYTEBITS() ---// /* go to byte boundary */
  8459. hold >>>= bits & 7;
  8460. bits -= bits & 7;
  8461. //---//
  8462. //=== NEEDBITS(32); */
  8463. while (bits < 32) {
  8464. if (have === 0) { break inf_leave; }
  8465. have--;
  8466. hold += input[next++] << bits;
  8467. bits += 8;
  8468. }
  8469. //===//
  8470. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  8471. strm.msg = 'invalid stored block lengths';
  8472. state.mode = BAD;
  8473. break;
  8474. }
  8475. state.length = hold & 0xffff;
  8476. //Tracev((stderr, "inflate: stored length %u\n",
  8477. // state.length));
  8478. //=== INITBITS();
  8479. hold = 0;
  8480. bits = 0;
  8481. //===//
  8482. state.mode = COPY_;
  8483. if (flush === Z_TREES) { break inf_leave; }
  8484. /* falls through */
  8485. case COPY_:
  8486. state.mode = COPY;
  8487. /* falls through */
  8488. case COPY:
  8489. copy = state.length;
  8490. if (copy) {
  8491. if (copy > have) { copy = have; }
  8492. if (copy > left) { copy = left; }
  8493. if (copy === 0) { break inf_leave; }
  8494. //--- zmemcpy(put, next, copy); ---
  8495. utils.arraySet(output, input, next, copy, put);
  8496. //---//
  8497. have -= copy;
  8498. next += copy;
  8499. left -= copy;
  8500. put += copy;
  8501. state.length -= copy;
  8502. break;
  8503. }
  8504. //Tracev((stderr, "inflate: stored end\n"));
  8505. state.mode = TYPE;
  8506. break;
  8507. case TABLE:
  8508. //=== NEEDBITS(14); */
  8509. while (bits < 14) {
  8510. if (have === 0) { break inf_leave; }
  8511. have--;
  8512. hold += input[next++] << bits;
  8513. bits += 8;
  8514. }
  8515. //===//
  8516. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  8517. //--- DROPBITS(5) ---//
  8518. hold >>>= 5;
  8519. bits -= 5;
  8520. //---//
  8521. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  8522. //--- DROPBITS(5) ---//
  8523. hold >>>= 5;
  8524. bits -= 5;
  8525. //---//
  8526. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  8527. //--- DROPBITS(4) ---//
  8528. hold >>>= 4;
  8529. bits -= 4;
  8530. //---//
  8531. //#ifndef PKZIP_BUG_WORKAROUND
  8532. if (state.nlen > 286 || state.ndist > 30) {
  8533. strm.msg = 'too many length or distance symbols';
  8534. state.mode = BAD;
  8535. break;
  8536. }
  8537. //#endif
  8538. //Tracev((stderr, "inflate: table sizes ok\n"));
  8539. state.have = 0;
  8540. state.mode = LENLENS;
  8541. /* falls through */
  8542. case LENLENS:
  8543. while (state.have < state.ncode) {
  8544. //=== NEEDBITS(3);
  8545. while (bits < 3) {
  8546. if (have === 0) { break inf_leave; }
  8547. have--;
  8548. hold += input[next++] << bits;
  8549. bits += 8;
  8550. }
  8551. //===//
  8552. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  8553. //--- DROPBITS(3) ---//
  8554. hold >>>= 3;
  8555. bits -= 3;
  8556. //---//
  8557. }
  8558. while (state.have < 19) {
  8559. state.lens[order[state.have++]] = 0;
  8560. }
  8561. // We have separate tables & no pointers. 2 commented lines below not needed.
  8562. //state.next = state.codes;
  8563. //state.lencode = state.next;
  8564. // Switch to use dynamic table
  8565. state.lencode = state.lendyn;
  8566. state.lenbits = 7;
  8567. opts = {bits: state.lenbits};
  8568. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  8569. state.lenbits = opts.bits;
  8570. if (ret) {
  8571. strm.msg = 'invalid code lengths set';
  8572. state.mode = BAD;
  8573. break;
  8574. }
  8575. //Tracev((stderr, "inflate: code lengths ok\n"));
  8576. state.have = 0;
  8577. state.mode = CODELENS;
  8578. /* falls through */
  8579. case CODELENS:
  8580. while (state.have < state.nlen + state.ndist) {
  8581. for (;;) {
  8582. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  8583. here_bits = here >>> 24;
  8584. here_op = (here >>> 16) & 0xff;
  8585. here_val = here & 0xffff;
  8586. if ((here_bits) <= bits) { break; }
  8587. //--- PULLBYTE() ---//
  8588. if (have === 0) { break inf_leave; }
  8589. have--;
  8590. hold += input[next++] << bits;
  8591. bits += 8;
  8592. //---//
  8593. }
  8594. if (here_val < 16) {
  8595. //--- DROPBITS(here.bits) ---//
  8596. hold >>>= here_bits;
  8597. bits -= here_bits;
  8598. //---//
  8599. state.lens[state.have++] = here_val;
  8600. }
  8601. else {
  8602. if (here_val === 16) {
  8603. //=== NEEDBITS(here.bits + 2);
  8604. n = here_bits + 2;
  8605. while (bits < n) {
  8606. if (have === 0) { break inf_leave; }
  8607. have--;
  8608. hold += input[next++] << bits;
  8609. bits += 8;
  8610. }
  8611. //===//
  8612. //--- DROPBITS(here.bits) ---//
  8613. hold >>>= here_bits;
  8614. bits -= here_bits;
  8615. //---//
  8616. if (state.have === 0) {
  8617. strm.msg = 'invalid bit length repeat';
  8618. state.mode = BAD;
  8619. break;
  8620. }
  8621. len = state.lens[state.have - 1];
  8622. copy = 3 + (hold & 0x03);//BITS(2);
  8623. //--- DROPBITS(2) ---//
  8624. hold >>>= 2;
  8625. bits -= 2;
  8626. //---//
  8627. }
  8628. else if (here_val === 17) {
  8629. //=== NEEDBITS(here.bits + 3);
  8630. n = here_bits + 3;
  8631. while (bits < n) {
  8632. if (have === 0) { break inf_leave; }
  8633. have--;
  8634. hold += input[next++] << bits;
  8635. bits += 8;
  8636. }
  8637. //===//
  8638. //--- DROPBITS(here.bits) ---//
  8639. hold >>>= here_bits;
  8640. bits -= here_bits;
  8641. //---//
  8642. len = 0;
  8643. copy = 3 + (hold & 0x07);//BITS(3);
  8644. //--- DROPBITS(3) ---//
  8645. hold >>>= 3;
  8646. bits -= 3;
  8647. //---//
  8648. }
  8649. else {
  8650. //=== NEEDBITS(here.bits + 7);
  8651. n = here_bits + 7;
  8652. while (bits < n) {
  8653. if (have === 0) { break inf_leave; }
  8654. have--;
  8655. hold += input[next++] << bits;
  8656. bits += 8;
  8657. }
  8658. //===//
  8659. //--- DROPBITS(here.bits) ---//
  8660. hold >>>= here_bits;
  8661. bits -= here_bits;
  8662. //---//
  8663. len = 0;
  8664. copy = 11 + (hold & 0x7f);//BITS(7);
  8665. //--- DROPBITS(7) ---//
  8666. hold >>>= 7;
  8667. bits -= 7;
  8668. //---//
  8669. }
  8670. if (state.have + copy > state.nlen + state.ndist) {
  8671. strm.msg = 'invalid bit length repeat';
  8672. state.mode = BAD;
  8673. break;
  8674. }
  8675. while (copy--) {
  8676. state.lens[state.have++] = len;
  8677. }
  8678. }
  8679. }
  8680. /* handle error breaks in while */
  8681. if (state.mode === BAD) { break; }
  8682. /* check for end-of-block code (better have one) */
  8683. if (state.lens[256] === 0) {
  8684. strm.msg = 'invalid code -- missing end-of-block';
  8685. state.mode = BAD;
  8686. break;
  8687. }
  8688. /* build code tables -- note: do not change the lenbits or distbits
  8689. values here (9 and 6) without reading the comments in inftrees.h
  8690. concerning the ENOUGH constants, which depend on those values */
  8691. state.lenbits = 9;
  8692. opts = {bits: state.lenbits};
  8693. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  8694. // We have separate tables & no pointers. 2 commented lines below not needed.
  8695. // state.next_index = opts.table_index;
  8696. state.lenbits = opts.bits;
  8697. // state.lencode = state.next;
  8698. if (ret) {
  8699. strm.msg = 'invalid literal/lengths set';
  8700. state.mode = BAD;
  8701. break;
  8702. }
  8703. state.distbits = 6;
  8704. //state.distcode.copy(state.codes);
  8705. // Switch to use dynamic table
  8706. state.distcode = state.distdyn;
  8707. opts = {bits: state.distbits};
  8708. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  8709. // We have separate tables & no pointers. 2 commented lines below not needed.
  8710. // state.next_index = opts.table_index;
  8711. state.distbits = opts.bits;
  8712. // state.distcode = state.next;
  8713. if (ret) {
  8714. strm.msg = 'invalid distances set';
  8715. state.mode = BAD;
  8716. break;
  8717. }
  8718. //Tracev((stderr, 'inflate: codes ok\n'));
  8719. state.mode = LEN_;
  8720. if (flush === Z_TREES) { break inf_leave; }
  8721. /* falls through */
  8722. case LEN_:
  8723. state.mode = LEN;
  8724. /* falls through */
  8725. case LEN:
  8726. if (have >= 6 && left >= 258) {
  8727. //--- RESTORE() ---
  8728. strm.next_out = put;
  8729. strm.avail_out = left;
  8730. strm.next_in = next;
  8731. strm.avail_in = have;
  8732. state.hold = hold;
  8733. state.bits = bits;
  8734. //---
  8735. inflate_fast(strm, _out);
  8736. //--- LOAD() ---
  8737. put = strm.next_out;
  8738. output = strm.output;
  8739. left = strm.avail_out;
  8740. next = strm.next_in;
  8741. input = strm.input;
  8742. have = strm.avail_in;
  8743. hold = state.hold;
  8744. bits = state.bits;
  8745. //---
  8746. if (state.mode === TYPE) {
  8747. state.back = -1;
  8748. }
  8749. break;
  8750. }
  8751. state.back = 0;
  8752. for (;;) {
  8753. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  8754. here_bits = here >>> 24;
  8755. here_op = (here >>> 16) & 0xff;
  8756. here_val = here & 0xffff;
  8757. if (here_bits <= bits) { break; }
  8758. //--- PULLBYTE() ---//
  8759. if (have === 0) { break inf_leave; }
  8760. have--;
  8761. hold += input[next++] << bits;
  8762. bits += 8;
  8763. //---//
  8764. }
  8765. if (here_op && (here_op & 0xf0) === 0) {
  8766. last_bits = here_bits;
  8767. last_op = here_op;
  8768. last_val = here_val;
  8769. for (;;) {
  8770. here = state.lencode[last_val +
  8771. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  8772. here_bits = here >>> 24;
  8773. here_op = (here >>> 16) & 0xff;
  8774. here_val = here & 0xffff;
  8775. if ((last_bits + here_bits) <= bits) { break; }
  8776. //--- PULLBYTE() ---//
  8777. if (have === 0) { break inf_leave; }
  8778. have--;
  8779. hold += input[next++] << bits;
  8780. bits += 8;
  8781. //---//
  8782. }
  8783. //--- DROPBITS(last.bits) ---//
  8784. hold >>>= last_bits;
  8785. bits -= last_bits;
  8786. //---//
  8787. state.back += last_bits;
  8788. }
  8789. //--- DROPBITS(here.bits) ---//
  8790. hold >>>= here_bits;
  8791. bits -= here_bits;
  8792. //---//
  8793. state.back += here_bits;
  8794. state.length = here_val;
  8795. if (here_op === 0) {
  8796. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8797. // "inflate: literal '%c'\n" :
  8798. // "inflate: literal 0x%02x\n", here.val));
  8799. state.mode = LIT;
  8800. break;
  8801. }
  8802. if (here_op & 32) {
  8803. //Tracevv((stderr, "inflate: end of block\n"));
  8804. state.back = -1;
  8805. state.mode = TYPE;
  8806. break;
  8807. }
  8808. if (here_op & 64) {
  8809. strm.msg = 'invalid literal/length code';
  8810. state.mode = BAD;
  8811. break;
  8812. }
  8813. state.extra = here_op & 15;
  8814. state.mode = LENEXT;
  8815. /* falls through */
  8816. case LENEXT:
  8817. if (state.extra) {
  8818. //=== NEEDBITS(state.extra);
  8819. n = state.extra;
  8820. while (bits < n) {
  8821. if (have === 0) { break inf_leave; }
  8822. have--;
  8823. hold += input[next++] << bits;
  8824. bits += 8;
  8825. }
  8826. //===//
  8827. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  8828. //--- DROPBITS(state.extra) ---//
  8829. hold >>>= state.extra;
  8830. bits -= state.extra;
  8831. //---//
  8832. state.back += state.extra;
  8833. }
  8834. //Tracevv((stderr, "inflate: length %u\n", state.length));
  8835. state.was = state.length;
  8836. state.mode = DIST;
  8837. /* falls through */
  8838. case DIST:
  8839. for (;;) {
  8840. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  8841. here_bits = here >>> 24;
  8842. here_op = (here >>> 16) & 0xff;
  8843. here_val = here & 0xffff;
  8844. if ((here_bits) <= bits) { break; }
  8845. //--- PULLBYTE() ---//
  8846. if (have === 0) { break inf_leave; }
  8847. have--;
  8848. hold += input[next++] << bits;
  8849. bits += 8;
  8850. //---//
  8851. }
  8852. if ((here_op & 0xf0) === 0) {
  8853. last_bits = here_bits;
  8854. last_op = here_op;
  8855. last_val = here_val;
  8856. for (;;) {
  8857. here = state.distcode[last_val +
  8858. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  8859. here_bits = here >>> 24;
  8860. here_op = (here >>> 16) & 0xff;
  8861. here_val = here & 0xffff;
  8862. if ((last_bits + here_bits) <= bits) { break; }
  8863. //--- PULLBYTE() ---//
  8864. if (have === 0) { break inf_leave; }
  8865. have--;
  8866. hold += input[next++] << bits;
  8867. bits += 8;
  8868. //---//
  8869. }
  8870. //--- DROPBITS(last.bits) ---//
  8871. hold >>>= last_bits;
  8872. bits -= last_bits;
  8873. //---//
  8874. state.back += last_bits;
  8875. }
  8876. //--- DROPBITS(here.bits) ---//
  8877. hold >>>= here_bits;
  8878. bits -= here_bits;
  8879. //---//
  8880. state.back += here_bits;
  8881. if (here_op & 64) {
  8882. strm.msg = 'invalid distance code';
  8883. state.mode = BAD;
  8884. break;
  8885. }
  8886. state.offset = here_val;
  8887. state.extra = (here_op) & 15;
  8888. state.mode = DISTEXT;
  8889. /* falls through */
  8890. case DISTEXT:
  8891. if (state.extra) {
  8892. //=== NEEDBITS(state.extra);
  8893. n = state.extra;
  8894. while (bits < n) {
  8895. if (have === 0) { break inf_leave; }
  8896. have--;
  8897. hold += input[next++] << bits;
  8898. bits += 8;
  8899. }
  8900. //===//
  8901. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  8902. //--- DROPBITS(state.extra) ---//
  8903. hold >>>= state.extra;
  8904. bits -= state.extra;
  8905. //---//
  8906. state.back += state.extra;
  8907. }
  8908. //#ifdef INFLATE_STRICT
  8909. if (state.offset > state.dmax) {
  8910. strm.msg = 'invalid distance too far back';
  8911. state.mode = BAD;
  8912. break;
  8913. }
  8914. //#endif
  8915. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  8916. state.mode = MATCH;
  8917. /* falls through */
  8918. case MATCH:
  8919. if (left === 0) { break inf_leave; }
  8920. copy = _out - left;
  8921. if (state.offset > copy) { /* copy from window */
  8922. copy = state.offset - copy;
  8923. if (copy > state.whave) {
  8924. if (state.sane) {
  8925. strm.msg = 'invalid distance too far back';
  8926. state.mode = BAD;
  8927. break;
  8928. }
  8929. // (!) This block is disabled in zlib defailts,
  8930. // don't enable it for binary compatibility
  8931. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8932. // Trace((stderr, "inflate.c too far\n"));
  8933. // copy -= state.whave;
  8934. // if (copy > state.length) { copy = state.length; }
  8935. // if (copy > left) { copy = left; }
  8936. // left -= copy;
  8937. // state.length -= copy;
  8938. // do {
  8939. // output[put++] = 0;
  8940. // } while (--copy);
  8941. // if (state.length === 0) { state.mode = LEN; }
  8942. // break;
  8943. //#endif
  8944. }
  8945. if (copy > state.wnext) {
  8946. copy -= state.wnext;
  8947. from = state.wsize - copy;
  8948. }
  8949. else {
  8950. from = state.wnext - copy;
  8951. }
  8952. if (copy > state.length) { copy = state.length; }
  8953. from_source = state.window;
  8954. }
  8955. else { /* copy from output */
  8956. from_source = output;
  8957. from = put - state.offset;
  8958. copy = state.length;
  8959. }
  8960. if (copy > left) { copy = left; }
  8961. left -= copy;
  8962. state.length -= copy;
  8963. do {
  8964. output[put++] = from_source[from++];
  8965. } while (--copy);
  8966. if (state.length === 0) { state.mode = LEN; }
  8967. break;
  8968. case LIT:
  8969. if (left === 0) { break inf_leave; }
  8970. output[put++] = state.length;
  8971. left--;
  8972. state.mode = LEN;
  8973. break;
  8974. case CHECK:
  8975. if (state.wrap) {
  8976. //=== NEEDBITS(32);
  8977. while (bits < 32) {
  8978. if (have === 0) { break inf_leave; }
  8979. have--;
  8980. // Use '|' insdead of '+' to make sure that result is signed
  8981. hold |= input[next++] << bits;
  8982. bits += 8;
  8983. }
  8984. //===//
  8985. _out -= left;
  8986. strm.total_out += _out;
  8987. state.total += _out;
  8988. if (_out) {
  8989. strm.adler = state.check =
  8990. /*UPDATE(state.check, put - _out, _out);*/
  8991. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  8992. }
  8993. _out = left;
  8994. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  8995. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  8996. strm.msg = 'incorrect data check';
  8997. state.mode = BAD;
  8998. break;
  8999. }
  9000. //=== INITBITS();
  9001. hold = 0;
  9002. bits = 0;
  9003. //===//
  9004. //Tracev((stderr, "inflate: check matches trailer\n"));
  9005. }
  9006. state.mode = LENGTH;
  9007. /* falls through */
  9008. case LENGTH:
  9009. if (state.wrap && state.flags) {
  9010. //=== NEEDBITS(32);
  9011. while (bits < 32) {
  9012. if (have === 0) { break inf_leave; }
  9013. have--;
  9014. hold += input[next++] << bits;
  9015. bits += 8;
  9016. }
  9017. //===//
  9018. if (hold !== (state.total & 0xffffffff)) {
  9019. strm.msg = 'incorrect length check';
  9020. state.mode = BAD;
  9021. break;
  9022. }
  9023. //=== INITBITS();
  9024. hold = 0;
  9025. bits = 0;
  9026. //===//
  9027. //Tracev((stderr, "inflate: length matches trailer\n"));
  9028. }
  9029. state.mode = DONE;
  9030. /* falls through */
  9031. case DONE:
  9032. ret = Z_STREAM_END;
  9033. break inf_leave;
  9034. case BAD:
  9035. ret = Z_DATA_ERROR;
  9036. break inf_leave;
  9037. case MEM:
  9038. return Z_MEM_ERROR;
  9039. case SYNC:
  9040. /* falls through */
  9041. default:
  9042. return Z_STREAM_ERROR;
  9043. }
  9044. }
  9045. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9046. /*
  9047. Return from inflate(), updating the total counts and the check value.
  9048. If there was no progress during the inflate() call, return a buffer
  9049. error. Call updatewindow() to create and/or update the window state.
  9050. Note: a memory error from inflate() is non-recoverable.
  9051. */
  9052. //--- RESTORE() ---
  9053. strm.next_out = put;
  9054. strm.avail_out = left;
  9055. strm.next_in = next;
  9056. strm.avail_in = have;
  9057. state.hold = hold;
  9058. state.bits = bits;
  9059. //---
  9060. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9061. (state.mode < CHECK || flush !== Z_FINISH))) {
  9062. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9063. state.mode = MEM;
  9064. return Z_MEM_ERROR;
  9065. }
  9066. }
  9067. _in -= strm.avail_in;
  9068. _out -= strm.avail_out;
  9069. strm.total_in += _in;
  9070. strm.total_out += _out;
  9071. state.total += _out;
  9072. if (state.wrap && _out) {
  9073. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9074. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9075. }
  9076. strm.data_type = state.bits + (state.last ? 64 : 0) +
  9077. (state.mode === TYPE ? 128 : 0) +
  9078. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9079. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9080. ret = Z_BUF_ERROR;
  9081. }
  9082. return ret;
  9083. }
  9084. function inflateEnd(strm) {
  9085. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9086. return Z_STREAM_ERROR;
  9087. }
  9088. var state = strm.state;
  9089. if (state.window) {
  9090. state.window = null;
  9091. }
  9092. strm.state = null;
  9093. return Z_OK;
  9094. }
  9095. function inflateGetHeader(strm, head) {
  9096. var state;
  9097. /* check state */
  9098. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9099. state = strm.state;
  9100. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9101. /* save header structure */
  9102. state.head = head;
  9103. head.done = false;
  9104. return Z_OK;
  9105. }
  9106. exports.inflateReset = inflateReset;
  9107. exports.inflateReset2 = inflateReset2;
  9108. exports.inflateResetKeep = inflateResetKeep;
  9109. exports.inflateInit = inflateInit;
  9110. exports.inflateInit2 = inflateInit2;
  9111. exports.inflate = inflate;
  9112. exports.inflateEnd = inflateEnd;
  9113. exports.inflateGetHeader = inflateGetHeader;
  9114. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  9115. /* Not implemented
  9116. exports.inflateCopy = inflateCopy;
  9117. exports.inflateGetDictionary = inflateGetDictionary;
  9118. exports.inflateMark = inflateMark;
  9119. exports.inflatePrime = inflatePrime;
  9120. exports.inflateSetDictionary = inflateSetDictionary;
  9121. exports.inflateSync = inflateSync;
  9122. exports.inflateSyncPoint = inflateSyncPoint;
  9123. exports.inflateUndermine = inflateUndermine;
  9124. */
  9125. },{"../utils/common":26,"./adler32":28,"./crc32":30,"./inffast":33,"./inftrees":35}],35:[function(require,module,exports){
  9126. 'use strict';
  9127. var utils = require('../utils/common');
  9128. var MAXBITS = 15;
  9129. var ENOUGH_LENS = 852;
  9130. var ENOUGH_DISTS = 592;
  9131. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9132. var CODES = 0;
  9133. var LENS = 1;
  9134. var DISTS = 2;
  9135. var lbase = [ /* Length codes 257..285 base */
  9136. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  9137. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  9138. ];
  9139. var lext = [ /* Length codes 257..285 extra */
  9140. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  9141. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  9142. ];
  9143. var dbase = [ /* Distance codes 0..29 base */
  9144. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  9145. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  9146. 8193, 12289, 16385, 24577, 0, 0
  9147. ];
  9148. var dext = [ /* Distance codes 0..29 extra */
  9149. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  9150. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  9151. 28, 28, 29, 29, 64, 64
  9152. ];
  9153. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  9154. {
  9155. var bits = opts.bits;
  9156. //here = opts.here; /* table entry for duplication */
  9157. var len = 0; /* a code's length in bits */
  9158. var sym = 0; /* index of code symbols */
  9159. var min = 0, max = 0; /* minimum and maximum code lengths */
  9160. var root = 0; /* number of index bits for root table */
  9161. var curr = 0; /* number of index bits for current table */
  9162. var drop = 0; /* code bits to drop for sub-table */
  9163. var left = 0; /* number of prefix codes available */
  9164. var used = 0; /* code entries in table used */
  9165. var huff = 0; /* Huffman code */
  9166. var incr; /* for incrementing code, index */
  9167. var fill; /* index for replicating entries */
  9168. var low; /* low bits for current root entry */
  9169. var mask; /* mask for low root bits */
  9170. var next; /* next available space in table */
  9171. var base = null; /* base value table to use */
  9172. var base_index = 0;
  9173. // var shoextra; /* extra bits table to use */
  9174. var end; /* use base and extra for symbol > end */
  9175. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  9176. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  9177. var extra = null;
  9178. var extra_index = 0;
  9179. var here_bits, here_op, here_val;
  9180. /*
  9181. Process a set of code lengths to create a canonical Huffman code. The
  9182. code lengths are lens[0..codes-1]. Each length corresponds to the
  9183. symbols 0..codes-1. The Huffman code is generated by first sorting the
  9184. symbols by length from short to long, and retaining the symbol order
  9185. for codes with equal lengths. Then the code starts with all zero bits
  9186. for the first code of the shortest length, and the codes are integer
  9187. increments for the same length, and zeros are appended as the length
  9188. increases. For the deflate format, these bits are stored backwards
  9189. from their more natural integer increment ordering, and so when the
  9190. decoding tables are built in the large loop below, the integer codes
  9191. are incremented backwards.
  9192. This routine assumes, but does not check, that all of the entries in
  9193. lens[] are in the range 0..MAXBITS. The caller must assure this.
  9194. 1..MAXBITS is interpreted as that code length. zero means that that
  9195. symbol does not occur in this code.
  9196. The codes are sorted by computing a count of codes for each length,
  9197. creating from that a table of starting indices for each length in the
  9198. sorted table, and then entering the symbols in order in the sorted
  9199. table. The sorted table is work[], with that space being provided by
  9200. the caller.
  9201. The length counts are used for other purposes as well, i.e. finding
  9202. the minimum and maximum length codes, determining if there are any
  9203. codes at all, checking for a valid set of lengths, and looking ahead
  9204. at length counts to determine sub-table sizes when building the
  9205. decoding tables.
  9206. */
  9207. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  9208. for (len = 0; len <= MAXBITS; len++) {
  9209. count[len] = 0;
  9210. }
  9211. for (sym = 0; sym < codes; sym++) {
  9212. count[lens[lens_index + sym]]++;
  9213. }
  9214. /* bound code lengths, force root to be within code lengths */
  9215. root = bits;
  9216. for (max = MAXBITS; max >= 1; max--) {
  9217. if (count[max] !== 0) { break; }
  9218. }
  9219. if (root > max) {
  9220. root = max;
  9221. }
  9222. if (max === 0) { /* no symbols to code at all */
  9223. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  9224. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  9225. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  9226. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9227. //table.op[opts.table_index] = 64;
  9228. //table.bits[opts.table_index] = 1;
  9229. //table.val[opts.table_index++] = 0;
  9230. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9231. opts.bits = 1;
  9232. return 0; /* no symbols, but wait for decoding to report error */
  9233. }
  9234. for (min = 1; min < max; min++) {
  9235. if (count[min] !== 0) { break; }
  9236. }
  9237. if (root < min) {
  9238. root = min;
  9239. }
  9240. /* check for an over-subscribed or incomplete set of lengths */
  9241. left = 1;
  9242. for (len = 1; len <= MAXBITS; len++) {
  9243. left <<= 1;
  9244. left -= count[len];
  9245. if (left < 0) {
  9246. return -1;
  9247. } /* over-subscribed */
  9248. }
  9249. if (left > 0 && (type === CODES || max !== 1)) {
  9250. return -1; /* incomplete set */
  9251. }
  9252. /* generate offsets into symbol table for each length for sorting */
  9253. offs[1] = 0;
  9254. for (len = 1; len < MAXBITS; len++) {
  9255. offs[len + 1] = offs[len] + count[len];
  9256. }
  9257. /* sort symbols by length, by symbol order within each length */
  9258. for (sym = 0; sym < codes; sym++) {
  9259. if (lens[lens_index + sym] !== 0) {
  9260. work[offs[lens[lens_index + sym]]++] = sym;
  9261. }
  9262. }
  9263. /*
  9264. Create and fill in decoding tables. In this loop, the table being
  9265. filled is at next and has curr index bits. The code being used is huff
  9266. with length len. That code is converted to an index by dropping drop
  9267. bits off of the bottom. For codes where len is less than drop + curr,
  9268. those top drop + curr - len bits are incremented through all values to
  9269. fill the table with replicated entries.
  9270. root is the number of index bits for the root table. When len exceeds
  9271. root, sub-tables are created pointed to by the root entry with an index
  9272. of the low root bits of huff. This is saved in low to check for when a
  9273. new sub-table should be started. drop is zero when the root table is
  9274. being filled, and drop is root when sub-tables are being filled.
  9275. When a new sub-table is needed, it is necessary to look ahead in the
  9276. code lengths to determine what size sub-table is needed. The length
  9277. counts are used for this, and so count[] is decremented as codes are
  9278. entered in the tables.
  9279. used keeps track of how many table entries have been allocated from the
  9280. provided *table space. It is checked for LENS and DIST tables against
  9281. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  9282. the initial root table size constants. See the comments in inftrees.h
  9283. for more information.
  9284. sym increments through all symbols, and the loop terminates when
  9285. all codes of length max, i.e. all codes, have been processed. This
  9286. routine permits incomplete codes, so another loop after this one fills
  9287. in the rest of the decoding tables with invalid code markers.
  9288. */
  9289. /* set up for code type */
  9290. // poor man optimization - use if-else instead of switch,
  9291. // to avoid deopts in old v8
  9292. if (type === CODES) {
  9293. base = extra = work; /* dummy value--not used */
  9294. end = 19;
  9295. } else if (type === LENS) {
  9296. base = lbase;
  9297. base_index -= 257;
  9298. extra = lext;
  9299. extra_index -= 257;
  9300. end = 256;
  9301. } else { /* DISTS */
  9302. base = dbase;
  9303. extra = dext;
  9304. end = -1;
  9305. }
  9306. /* initialize opts for loop */
  9307. huff = 0; /* starting code */
  9308. sym = 0; /* starting code symbol */
  9309. len = min; /* starting code length */
  9310. next = table_index; /* current table to fill in */
  9311. curr = root; /* current table index bits */
  9312. drop = 0; /* current bits to drop from code for index */
  9313. low = -1; /* trigger new sub-table when len > root */
  9314. used = 1 << root; /* use root table entries */
  9315. mask = used - 1; /* mask for comparing low */
  9316. /* check available table space */
  9317. if ((type === LENS && used > ENOUGH_LENS) ||
  9318. (type === DISTS && used > ENOUGH_DISTS)) {
  9319. return 1;
  9320. }
  9321. var i=0;
  9322. /* process all codes and make table entries */
  9323. for (;;) {
  9324. i++;
  9325. /* create table entry */
  9326. here_bits = len - drop;
  9327. if (work[sym] < end) {
  9328. here_op = 0;
  9329. here_val = work[sym];
  9330. }
  9331. else if (work[sym] > end) {
  9332. here_op = extra[extra_index + work[sym]];
  9333. here_val = base[base_index + work[sym]];
  9334. }
  9335. else {
  9336. here_op = 32 + 64; /* end of block */
  9337. here_val = 0;
  9338. }
  9339. /* replicate for those indices with low len bits equal to huff */
  9340. incr = 1 << (len - drop);
  9341. fill = 1 << curr;
  9342. min = fill; /* save offset to next table */
  9343. do {
  9344. fill -= incr;
  9345. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  9346. } while (fill !== 0);
  9347. /* backwards increment the len-bit code huff */
  9348. incr = 1 << (len - 1);
  9349. while (huff & incr) {
  9350. incr >>= 1;
  9351. }
  9352. if (incr !== 0) {
  9353. huff &= incr - 1;
  9354. huff += incr;
  9355. } else {
  9356. huff = 0;
  9357. }
  9358. /* go to next symbol, update count, len */
  9359. sym++;
  9360. if (--count[len] === 0) {
  9361. if (len === max) { break; }
  9362. len = lens[lens_index + work[sym]];
  9363. }
  9364. /* create new sub-table if needed */
  9365. if (len > root && (huff & mask) !== low) {
  9366. /* if first time, transition to sub-tables */
  9367. if (drop === 0) {
  9368. drop = root;
  9369. }
  9370. /* increment past last table */
  9371. next += min; /* here min is 1 << curr */
  9372. /* determine length of next table */
  9373. curr = len - drop;
  9374. left = 1 << curr;
  9375. while (curr + drop < max) {
  9376. left -= count[curr + drop];
  9377. if (left <= 0) { break; }
  9378. curr++;
  9379. left <<= 1;
  9380. }
  9381. /* check for enough space */
  9382. used += 1 << curr;
  9383. if ((type === LENS && used > ENOUGH_LENS) ||
  9384. (type === DISTS && used > ENOUGH_DISTS)) {
  9385. return 1;
  9386. }
  9387. /* point entry in root table to sub-table */
  9388. low = huff & mask;
  9389. /*table.op[low] = curr;
  9390. table.bits[low] = root;
  9391. table.val[low] = next - opts.table_index;*/
  9392. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  9393. }
  9394. }
  9395. /* fill in remaining table entry if code is incomplete (guaranteed to have
  9396. at most one remaining entry, since if the code is incomplete, the
  9397. maximum code length that was allowed to get this far is one bit) */
  9398. if (huff !== 0) {
  9399. //table.op[next + huff] = 64; /* invalid code marker */
  9400. //table.bits[next + huff] = len - drop;
  9401. //table.val[next + huff] = 0;
  9402. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  9403. }
  9404. /* set return parameters */
  9405. //opts.table_index += used;
  9406. opts.bits = root;
  9407. return 0;
  9408. };
  9409. },{"../utils/common":26}],36:[function(require,module,exports){
  9410. 'use strict';
  9411. module.exports = {
  9412. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  9413. '1': 'stream end', /* Z_STREAM_END 1 */
  9414. '0': '', /* Z_OK 0 */
  9415. '-1': 'file error', /* Z_ERRNO (-1) */
  9416. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  9417. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  9418. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  9419. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  9420. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  9421. };
  9422. },{}],37:[function(require,module,exports){
  9423. 'use strict';
  9424. var utils = require('../utils/common');
  9425. /* Public constants ==========================================================*/
  9426. /* ===========================================================================*/
  9427. //var Z_FILTERED = 1;
  9428. //var Z_HUFFMAN_ONLY = 2;
  9429. //var Z_RLE = 3;
  9430. var Z_FIXED = 4;
  9431. //var Z_DEFAULT_STRATEGY = 0;
  9432. /* Possible values of the data_type field (though see inflate()) */
  9433. var Z_BINARY = 0;
  9434. var Z_TEXT = 1;
  9435. //var Z_ASCII = 1; // = Z_TEXT
  9436. var Z_UNKNOWN = 2;
  9437. /*============================================================================*/
  9438. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  9439. // From zutil.h
  9440. var STORED_BLOCK = 0;
  9441. var STATIC_TREES = 1;
  9442. var DYN_TREES = 2;
  9443. /* The three kinds of block type */
  9444. var MIN_MATCH = 3;
  9445. var MAX_MATCH = 258;
  9446. /* The minimum and maximum match lengths */
  9447. // From deflate.h
  9448. /* ===========================================================================
  9449. * Internal compression state.
  9450. */
  9451. var LENGTH_CODES = 29;
  9452. /* number of length codes, not counting the special END_BLOCK code */
  9453. var LITERALS = 256;
  9454. /* number of literal bytes 0..255 */
  9455. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  9456. /* number of Literal or Length codes, including the END_BLOCK code */
  9457. var D_CODES = 30;
  9458. /* number of distance codes */
  9459. var BL_CODES = 19;
  9460. /* number of codes used to transfer the bit lengths */
  9461. var HEAP_SIZE = 2*L_CODES + 1;
  9462. /* maximum heap size */
  9463. var MAX_BITS = 15;
  9464. /* All codes must not exceed MAX_BITS bits */
  9465. var Buf_size = 16;
  9466. /* size of bit buffer in bi_buf */
  9467. /* ===========================================================================
  9468. * Constants
  9469. */
  9470. var MAX_BL_BITS = 7;
  9471. /* Bit length codes must not exceed MAX_BL_BITS bits */
  9472. var END_BLOCK = 256;
  9473. /* end of block literal code */
  9474. var REP_3_6 = 16;
  9475. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  9476. var REPZ_3_10 = 17;
  9477. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  9478. var REPZ_11_138 = 18;
  9479. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  9480. var extra_lbits = /* extra bits for each length code */
  9481. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  9482. var extra_dbits = /* extra bits for each distance code */
  9483. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  9484. var extra_blbits = /* extra bits for each bit length code */
  9485. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  9486. var bl_order =
  9487. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  9488. /* The lengths of the bit length codes are sent in order of decreasing
  9489. * probability, to avoid transmitting the lengths for unused bit length codes.
  9490. */
  9491. /* ===========================================================================
  9492. * Local data. These are initialized only once.
  9493. */
  9494. // We pre-fill arrays with 0 to avoid uninitialized gaps
  9495. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  9496. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  9497. var static_ltree = new Array((L_CODES+2) * 2);
  9498. zero(static_ltree);
  9499. /* The static literal tree. Since the bit lengths are imposed, there is no
  9500. * need for the L_CODES extra codes used during heap construction. However
  9501. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  9502. * below).
  9503. */
  9504. var static_dtree = new Array(D_CODES * 2);
  9505. zero(static_dtree);
  9506. /* The static distance tree. (Actually a trivial tree since all codes use
  9507. * 5 bits.)
  9508. */
  9509. var _dist_code = new Array(DIST_CODE_LEN);
  9510. zero(_dist_code);
  9511. /* Distance codes. The first 256 values correspond to the distances
  9512. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  9513. * the 15 bit distances.
  9514. */
  9515. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  9516. zero(_length_code);
  9517. /* length code for each normalized match length (0 == MIN_MATCH) */
  9518. var base_length = new Array(LENGTH_CODES);
  9519. zero(base_length);
  9520. /* First normalized length for each code (0 = MIN_MATCH) */
  9521. var base_dist = new Array(D_CODES);
  9522. zero(base_dist);
  9523. /* First normalized distance for each code (0 = distance of 1) */
  9524. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  9525. this.static_tree = static_tree; /* static tree or NULL */
  9526. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  9527. this.extra_base = extra_base; /* base index for extra_bits */
  9528. this.elems = elems; /* max number of elements in the tree */
  9529. this.max_length = max_length; /* max bit length for the codes */
  9530. // show if `static_tree` has data or dummy - needed for monomorphic objects
  9531. this.has_stree = static_tree && static_tree.length;
  9532. };
  9533. var static_l_desc;
  9534. var static_d_desc;
  9535. var static_bl_desc;
  9536. var TreeDesc = function(dyn_tree, stat_desc) {
  9537. this.dyn_tree = dyn_tree; /* the dynamic tree */
  9538. this.max_code = 0; /* largest code with non zero frequency */
  9539. this.stat_desc = stat_desc; /* the corresponding static tree */
  9540. };
  9541. function d_code(dist) {
  9542. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  9543. }
  9544. /* ===========================================================================
  9545. * Output a short LSB first on the stream.
  9546. * IN assertion: there is enough room in pendingBuf.
  9547. */
  9548. function put_short (s, w) {
  9549. // put_byte(s, (uch)((w) & 0xff));
  9550. // put_byte(s, (uch)((ush)(w) >> 8));
  9551. s.pending_buf[s.pending++] = (w) & 0xff;
  9552. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  9553. }
  9554. /* ===========================================================================
  9555. * Send a value on a given number of bits.
  9556. * IN assertion: length <= 16 and value fits in length bits.
  9557. */
  9558. function send_bits(s, value, length) {
  9559. if (s.bi_valid > (Buf_size - length)) {
  9560. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9561. put_short(s, s.bi_buf);
  9562. s.bi_buf = value >> (Buf_size - s.bi_valid);
  9563. s.bi_valid += length - Buf_size;
  9564. } else {
  9565. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9566. s.bi_valid += length;
  9567. }
  9568. }
  9569. function send_code(s, c, tree) {
  9570. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  9571. }
  9572. /* ===========================================================================
  9573. * Reverse the first len bits of a code, using straightforward code (a faster
  9574. * method would use a table)
  9575. * IN assertion: 1 <= len <= 15
  9576. */
  9577. function bi_reverse(code, len) {
  9578. var res = 0;
  9579. do {
  9580. res |= code & 1;
  9581. code >>>= 1;
  9582. res <<= 1;
  9583. } while (--len > 0);
  9584. return res >>> 1;
  9585. }
  9586. /* ===========================================================================
  9587. * Flush the bit buffer, keeping at most 7 bits in it.
  9588. */
  9589. function bi_flush(s) {
  9590. if (s.bi_valid === 16) {
  9591. put_short(s, s.bi_buf);
  9592. s.bi_buf = 0;
  9593. s.bi_valid = 0;
  9594. } else if (s.bi_valid >= 8) {
  9595. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  9596. s.bi_buf >>= 8;
  9597. s.bi_valid -= 8;
  9598. }
  9599. }
  9600. /* ===========================================================================
  9601. * Compute the optimal bit lengths for a tree and update the total bit length
  9602. * for the current block.
  9603. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  9604. * above are the tree nodes sorted by increasing frequency.
  9605. * OUT assertions: the field len is set to the optimal bit length, the
  9606. * array bl_count contains the frequencies for each bit length.
  9607. * The length opt_len is updated; static_len is also updated if stree is
  9608. * not null.
  9609. */
  9610. function gen_bitlen(s, desc)
  9611. // deflate_state *s;
  9612. // tree_desc *desc; /* the tree descriptor */
  9613. {
  9614. var tree = desc.dyn_tree;
  9615. var max_code = desc.max_code;
  9616. var stree = desc.stat_desc.static_tree;
  9617. var has_stree = desc.stat_desc.has_stree;
  9618. var extra = desc.stat_desc.extra_bits;
  9619. var base = desc.stat_desc.extra_base;
  9620. var max_length = desc.stat_desc.max_length;
  9621. var h; /* heap index */
  9622. var n, m; /* iterate over the tree elements */
  9623. var bits; /* bit length */
  9624. var xbits; /* extra bits */
  9625. var f; /* frequency */
  9626. var overflow = 0; /* number of elements with bit length too large */
  9627. for (bits = 0; bits <= MAX_BITS; bits++) {
  9628. s.bl_count[bits] = 0;
  9629. }
  9630. /* In a first pass, compute the optimal bit lengths (which may
  9631. * overflow in the case of the bit length tree).
  9632. */
  9633. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  9634. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  9635. n = s.heap[h];
  9636. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  9637. if (bits > max_length) {
  9638. bits = max_length;
  9639. overflow++;
  9640. }
  9641. tree[n*2 + 1]/*.Len*/ = bits;
  9642. /* We overwrite tree[n].Dad which is no longer needed */
  9643. if (n > max_code) { continue; } /* not a leaf node */
  9644. s.bl_count[bits]++;
  9645. xbits = 0;
  9646. if (n >= base) {
  9647. xbits = extra[n-base];
  9648. }
  9649. f = tree[n * 2]/*.Freq*/;
  9650. s.opt_len += f * (bits + xbits);
  9651. if (has_stree) {
  9652. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  9653. }
  9654. }
  9655. if (overflow === 0) { return; }
  9656. // Trace((stderr,"\nbit length overflow\n"));
  9657. /* This happens for example on obj2 and pic of the Calgary corpus */
  9658. /* Find the first bit length which could increase: */
  9659. do {
  9660. bits = max_length-1;
  9661. while (s.bl_count[bits] === 0) { bits--; }
  9662. s.bl_count[bits]--; /* move one leaf down the tree */
  9663. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  9664. s.bl_count[max_length]--;
  9665. /* The brother of the overflow item also moves one step up,
  9666. * but this does not affect bl_count[max_length]
  9667. */
  9668. overflow -= 2;
  9669. } while (overflow > 0);
  9670. /* Now recompute all bit lengths, scanning in increasing frequency.
  9671. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  9672. * lengths instead of fixing only the wrong ones. This idea is taken
  9673. * from 'ar' written by Haruhiko Okumura.)
  9674. */
  9675. for (bits = max_length; bits !== 0; bits--) {
  9676. n = s.bl_count[bits];
  9677. while (n !== 0) {
  9678. m = s.heap[--h];
  9679. if (m > max_code) { continue; }
  9680. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  9681. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  9682. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  9683. tree[m*2 + 1]/*.Len*/ = bits;
  9684. }
  9685. n--;
  9686. }
  9687. }
  9688. }
  9689. /* ===========================================================================
  9690. * Generate the codes for a given tree and bit counts (which need not be
  9691. * optimal).
  9692. * IN assertion: the array bl_count contains the bit length statistics for
  9693. * the given tree and the field len is set for all tree elements.
  9694. * OUT assertion: the field code is set for all tree elements of non
  9695. * zero code length.
  9696. */
  9697. function gen_codes(tree, max_code, bl_count)
  9698. // ct_data *tree; /* the tree to decorate */
  9699. // int max_code; /* largest code with non zero frequency */
  9700. // ushf *bl_count; /* number of codes at each bit length */
  9701. {
  9702. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  9703. var code = 0; /* running code value */
  9704. var bits; /* bit index */
  9705. var n; /* code index */
  9706. /* The distribution counts are first used to generate the code values
  9707. * without bit reversal.
  9708. */
  9709. for (bits = 1; bits <= MAX_BITS; bits++) {
  9710. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  9711. }
  9712. /* Check that the bit counts in bl_count are consistent. The last code
  9713. * must be all ones.
  9714. */
  9715. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9716. // "inconsistent bit counts");
  9717. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9718. for (n = 0; n <= max_code; n++) {
  9719. var len = tree[n*2 + 1]/*.Len*/;
  9720. if (len === 0) { continue; }
  9721. /* Now reverse the bits */
  9722. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  9723. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  9724. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  9725. }
  9726. }
  9727. /* ===========================================================================
  9728. * Initialize the various 'constant' tables.
  9729. */
  9730. function tr_static_init() {
  9731. var n; /* iterates over tree elements */
  9732. var bits; /* bit counter */
  9733. var length; /* length value */
  9734. var code; /* code value */
  9735. var dist; /* distance index */
  9736. var bl_count = new Array(MAX_BITS+1);
  9737. /* number of codes at each bit length for an optimal tree */
  9738. // do check in _tr_init()
  9739. //if (static_init_done) return;
  9740. /* For some embedded targets, global variables are not initialized: */
  9741. /*#ifdef NO_INIT_GLOBAL_POINTERS
  9742. static_l_desc.static_tree = static_ltree;
  9743. static_l_desc.extra_bits = extra_lbits;
  9744. static_d_desc.static_tree = static_dtree;
  9745. static_d_desc.extra_bits = extra_dbits;
  9746. static_bl_desc.extra_bits = extra_blbits;
  9747. #endif*/
  9748. /* Initialize the mapping length (0..255) -> length code (0..28) */
  9749. length = 0;
  9750. for (code = 0; code < LENGTH_CODES-1; code++) {
  9751. base_length[code] = length;
  9752. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  9753. _length_code[length++] = code;
  9754. }
  9755. }
  9756. //Assert (length == 256, "tr_static_init: length != 256");
  9757. /* Note that the length 255 (match length 258) can be represented
  9758. * in two different ways: code 284 + 5 bits or code 285, so we
  9759. * overwrite length_code[255] to use the best encoding:
  9760. */
  9761. _length_code[length-1] = code;
  9762. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  9763. dist = 0;
  9764. for (code = 0 ; code < 16; code++) {
  9765. base_dist[code] = dist;
  9766. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  9767. _dist_code[dist++] = code;
  9768. }
  9769. }
  9770. //Assert (dist == 256, "tr_static_init: dist != 256");
  9771. dist >>= 7; /* from now on, all distances are divided by 128 */
  9772. for (; code < D_CODES; code++) {
  9773. base_dist[code] = dist << 7;
  9774. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  9775. _dist_code[256 + dist++] = code;
  9776. }
  9777. }
  9778. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  9779. /* Construct the codes of the static literal tree */
  9780. for (bits = 0; bits <= MAX_BITS; bits++) {
  9781. bl_count[bits] = 0;
  9782. }
  9783. n = 0;
  9784. while (n <= 143) {
  9785. static_ltree[n*2 + 1]/*.Len*/ = 8;
  9786. n++;
  9787. bl_count[8]++;
  9788. }
  9789. while (n <= 255) {
  9790. static_ltree[n*2 + 1]/*.Len*/ = 9;
  9791. n++;
  9792. bl_count[9]++;
  9793. }
  9794. while (n <= 279) {
  9795. static_ltree[n*2 + 1]/*.Len*/ = 7;
  9796. n++;
  9797. bl_count[7]++;
  9798. }
  9799. while (n <= 287) {
  9800. static_ltree[n*2 + 1]/*.Len*/ = 8;
  9801. n++;
  9802. bl_count[8]++;
  9803. }
  9804. /* Codes 286 and 287 do not exist, but we must include them in the
  9805. * tree construction to get a canonical Huffman tree (longest code
  9806. * all ones)
  9807. */
  9808. gen_codes(static_ltree, L_CODES+1, bl_count);
  9809. /* The static distance tree is trivial: */
  9810. for (n = 0; n < D_CODES; n++) {
  9811. static_dtree[n*2 + 1]/*.Len*/ = 5;
  9812. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  9813. }
  9814. // Now data ready and we can init static trees
  9815. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  9816. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  9817. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  9818. //static_init_done = true;
  9819. }
  9820. /* ===========================================================================
  9821. * Initialize a new block.
  9822. */
  9823. function init_block(s) {
  9824. var n; /* iterates over tree elements */
  9825. /* Initialize the trees. */
  9826. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  9827. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  9828. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  9829. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  9830. s.opt_len = s.static_len = 0;
  9831. s.last_lit = s.matches = 0;
  9832. }
  9833. /* ===========================================================================
  9834. * Flush the bit buffer and align the output on a byte boundary
  9835. */
  9836. function bi_windup(s)
  9837. {
  9838. if (s.bi_valid > 8) {
  9839. put_short(s, s.bi_buf);
  9840. } else if (s.bi_valid > 0) {
  9841. //put_byte(s, (Byte)s->bi_buf);
  9842. s.pending_buf[s.pending++] = s.bi_buf;
  9843. }
  9844. s.bi_buf = 0;
  9845. s.bi_valid = 0;
  9846. }
  9847. /* ===========================================================================
  9848. * Copy a stored block, storing first the length and its
  9849. * one's complement if requested.
  9850. */
  9851. function copy_block(s, buf, len, header)
  9852. //DeflateState *s;
  9853. //charf *buf; /* the input data */
  9854. //unsigned len; /* its length */
  9855. //int header; /* true if block header must be written */
  9856. {
  9857. bi_windup(s); /* align on byte boundary */
  9858. if (header) {
  9859. put_short(s, len);
  9860. put_short(s, ~len);
  9861. }
  9862. // while (len--) {
  9863. // put_byte(s, *buf++);
  9864. // }
  9865. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  9866. s.pending += len;
  9867. }
  9868. /* ===========================================================================
  9869. * Compares to subtrees, using the tree depth as tie breaker when
  9870. * the subtrees have equal frequency. This minimizes the worst case length.
  9871. */
  9872. function smaller(tree, n, m, depth) {
  9873. var _n2 = n*2;
  9874. var _m2 = m*2;
  9875. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  9876. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  9877. }
  9878. /* ===========================================================================
  9879. * Restore the heap property by moving down the tree starting at node k,
  9880. * exchanging a node with the smallest of its two sons if necessary, stopping
  9881. * when the heap property is re-established (each father smaller than its
  9882. * two sons).
  9883. */
  9884. function pqdownheap(s, tree, k)
  9885. // deflate_state *s;
  9886. // ct_data *tree; /* the tree to restore */
  9887. // int k; /* node to move down */
  9888. {
  9889. var v = s.heap[k];
  9890. var j = k << 1; /* left son of k */
  9891. while (j <= s.heap_len) {
  9892. /* Set j to the smallest of the two sons: */
  9893. if (j < s.heap_len &&
  9894. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  9895. j++;
  9896. }
  9897. /* Exit if v is smaller than both sons */
  9898. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  9899. /* Exchange v with the smallest son */
  9900. s.heap[k] = s.heap[j];
  9901. k = j;
  9902. /* And continue down the tree, setting j to the left son of k */
  9903. j <<= 1;
  9904. }
  9905. s.heap[k] = v;
  9906. }
  9907. // inlined manually
  9908. // var SMALLEST = 1;
  9909. /* ===========================================================================
  9910. * Send the block data compressed using the given Huffman trees
  9911. */
  9912. function compress_block(s, ltree, dtree)
  9913. // deflate_state *s;
  9914. // const ct_data *ltree; /* literal tree */
  9915. // const ct_data *dtree; /* distance tree */
  9916. {
  9917. var dist; /* distance of matched string */
  9918. var lc; /* match length or unmatched char (if dist == 0) */
  9919. var lx = 0; /* running index in l_buf */
  9920. var code; /* the code to send */
  9921. var extra; /* number of extra bits to send */
  9922. if (s.last_lit !== 0) {
  9923. do {
  9924. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  9925. lc = s.pending_buf[s.l_buf + lx];
  9926. lx++;
  9927. if (dist === 0) {
  9928. send_code(s, lc, ltree); /* send a literal byte */
  9929. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  9930. } else {
  9931. /* Here, lc is the match length - MIN_MATCH */
  9932. code = _length_code[lc];
  9933. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  9934. extra = extra_lbits[code];
  9935. if (extra !== 0) {
  9936. lc -= base_length[code];
  9937. send_bits(s, lc, extra); /* send the extra length bits */
  9938. }
  9939. dist--; /* dist is now the match distance - 1 */
  9940. code = d_code(dist);
  9941. //Assert (code < D_CODES, "bad d_code");
  9942. send_code(s, code, dtree); /* send the distance code */
  9943. extra = extra_dbits[code];
  9944. if (extra !== 0) {
  9945. dist -= base_dist[code];
  9946. send_bits(s, dist, extra); /* send the extra distance bits */
  9947. }
  9948. } /* literal or match pair ? */
  9949. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  9950. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  9951. // "pendingBuf overflow");
  9952. } while (lx < s.last_lit);
  9953. }
  9954. send_code(s, END_BLOCK, ltree);
  9955. }
  9956. /* ===========================================================================
  9957. * Construct one Huffman tree and assigns the code bit strings and lengths.
  9958. * Update the total bit length for the current block.
  9959. * IN assertion: the field freq is set for all tree elements.
  9960. * OUT assertions: the fields len and code are set to the optimal bit length
  9961. * and corresponding code. The length opt_len is updated; static_len is
  9962. * also updated if stree is not null. The field max_code is set.
  9963. */
  9964. function build_tree(s, desc)
  9965. // deflate_state *s;
  9966. // tree_desc *desc; /* the tree descriptor */
  9967. {
  9968. var tree = desc.dyn_tree;
  9969. var stree = desc.stat_desc.static_tree;
  9970. var has_stree = desc.stat_desc.has_stree;
  9971. var elems = desc.stat_desc.elems;
  9972. var n, m; /* iterate over heap elements */
  9973. var max_code = -1; /* largest code with non zero frequency */
  9974. var node; /* new node being created */
  9975. /* Construct the initial heap, with least frequent element in
  9976. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  9977. * heap[0] is not used.
  9978. */
  9979. s.heap_len = 0;
  9980. s.heap_max = HEAP_SIZE;
  9981. for (n = 0; n < elems; n++) {
  9982. if (tree[n * 2]/*.Freq*/ !== 0) {
  9983. s.heap[++s.heap_len] = max_code = n;
  9984. s.depth[n] = 0;
  9985. } else {
  9986. tree[n*2 + 1]/*.Len*/ = 0;
  9987. }
  9988. }
  9989. /* The pkzip format requires that at least one distance code exists,
  9990. * and that at least one bit should be sent even if there is only one
  9991. * possible code. So to avoid special checks later on we force at least
  9992. * two codes of non zero frequency.
  9993. */
  9994. while (s.heap_len < 2) {
  9995. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  9996. tree[node * 2]/*.Freq*/ = 1;
  9997. s.depth[node] = 0;
  9998. s.opt_len--;
  9999. if (has_stree) {
  10000. s.static_len -= stree[node*2 + 1]/*.Len*/;
  10001. }
  10002. /* node is 0 or 1 so it does not have extra bits */
  10003. }
  10004. desc.max_code = max_code;
  10005. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  10006. * establish sub-heaps of increasing lengths:
  10007. */
  10008. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  10009. /* Construct the Huffman tree by repeatedly combining the least two
  10010. * frequent nodes.
  10011. */
  10012. node = elems; /* next internal node of the tree */
  10013. do {
  10014. //pqremove(s, tree, n); /* n = node of least frequency */
  10015. /*** pqremove ***/
  10016. n = s.heap[1/*SMALLEST*/];
  10017. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  10018. pqdownheap(s, tree, 1/*SMALLEST*/);
  10019. /***/
  10020. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  10021. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  10022. s.heap[--s.heap_max] = m;
  10023. /* Create a new node father of n and m */
  10024. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  10025. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  10026. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  10027. /* and insert the new node in the heap */
  10028. s.heap[1/*SMALLEST*/] = node++;
  10029. pqdownheap(s, tree, 1/*SMALLEST*/);
  10030. } while (s.heap_len >= 2);
  10031. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  10032. /* At this point, the fields freq and dad are set. We can now
  10033. * generate the bit lengths.
  10034. */
  10035. gen_bitlen(s, desc);
  10036. /* The field len is now set, we can generate the bit codes */
  10037. gen_codes(tree, max_code, s.bl_count);
  10038. }
  10039. /* ===========================================================================
  10040. * Scan a literal or distance tree to determine the frequencies of the codes
  10041. * in the bit length tree.
  10042. */
  10043. function scan_tree(s, tree, max_code)
  10044. // deflate_state *s;
  10045. // ct_data *tree; /* the tree to be scanned */
  10046. // int max_code; /* and its largest code of non zero frequency */
  10047. {
  10048. var n; /* iterates over all tree elements */
  10049. var prevlen = -1; /* last emitted length */
  10050. var curlen; /* length of current code */
  10051. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  10052. var count = 0; /* repeat count of the current code */
  10053. var max_count = 7; /* max repeat count */
  10054. var min_count = 4; /* min repeat count */
  10055. if (nextlen === 0) {
  10056. max_count = 138;
  10057. min_count = 3;
  10058. }
  10059. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  10060. for (n = 0; n <= max_code; n++) {
  10061. curlen = nextlen;
  10062. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  10063. if (++count < max_count && curlen === nextlen) {
  10064. continue;
  10065. } else if (count < min_count) {
  10066. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  10067. } else if (curlen !== 0) {
  10068. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  10069. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  10070. } else if (count <= 10) {
  10071. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  10072. } else {
  10073. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  10074. }
  10075. count = 0;
  10076. prevlen = curlen;
  10077. if (nextlen === 0) {
  10078. max_count = 138;
  10079. min_count = 3;
  10080. } else if (curlen === nextlen) {
  10081. max_count = 6;
  10082. min_count = 3;
  10083. } else {
  10084. max_count = 7;
  10085. min_count = 4;
  10086. }
  10087. }
  10088. }
  10089. /* ===========================================================================
  10090. * Send a literal or distance tree in compressed form, using the codes in
  10091. * bl_tree.
  10092. */
  10093. function send_tree(s, tree, max_code)
  10094. // deflate_state *s;
  10095. // ct_data *tree; /* the tree to be scanned */
  10096. // int max_code; /* and its largest code of non zero frequency */
  10097. {
  10098. var n; /* iterates over all tree elements */
  10099. var prevlen = -1; /* last emitted length */
  10100. var curlen; /* length of current code */
  10101. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  10102. var count = 0; /* repeat count of the current code */
  10103. var max_count = 7; /* max repeat count */
  10104. var min_count = 4; /* min repeat count */
  10105. /* tree[max_code+1].Len = -1; */ /* guard already set */
  10106. if (nextlen === 0) {
  10107. max_count = 138;
  10108. min_count = 3;
  10109. }
  10110. for (n = 0; n <= max_code; n++) {
  10111. curlen = nextlen;
  10112. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  10113. if (++count < max_count && curlen === nextlen) {
  10114. continue;
  10115. } else if (count < min_count) {
  10116. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  10117. } else if (curlen !== 0) {
  10118. if (curlen !== prevlen) {
  10119. send_code(s, curlen, s.bl_tree);
  10120. count--;
  10121. }
  10122. //Assert(count >= 3 && count <= 6, " 3_6?");
  10123. send_code(s, REP_3_6, s.bl_tree);
  10124. send_bits(s, count-3, 2);
  10125. } else if (count <= 10) {
  10126. send_code(s, REPZ_3_10, s.bl_tree);
  10127. send_bits(s, count-3, 3);
  10128. } else {
  10129. send_code(s, REPZ_11_138, s.bl_tree);
  10130. send_bits(s, count-11, 7);
  10131. }
  10132. count = 0;
  10133. prevlen = curlen;
  10134. if (nextlen === 0) {
  10135. max_count = 138;
  10136. min_count = 3;
  10137. } else if (curlen === nextlen) {
  10138. max_count = 6;
  10139. min_count = 3;
  10140. } else {
  10141. max_count = 7;
  10142. min_count = 4;
  10143. }
  10144. }
  10145. }
  10146. /* ===========================================================================
  10147. * Construct the Huffman tree for the bit lengths and return the index in
  10148. * bl_order of the last bit length code to send.
  10149. */
  10150. function build_bl_tree(s) {
  10151. var max_blindex; /* index of last bit length code of non zero freq */
  10152. /* Determine the bit length frequencies for literal and distance trees */
  10153. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  10154. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  10155. /* Build the bit length tree: */
  10156. build_tree(s, s.bl_desc);
  10157. /* opt_len now includes the length of the tree representations, except
  10158. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  10159. */
  10160. /* Determine the number of bit length codes to send. The pkzip format
  10161. * requires that at least 4 bit length codes be sent. (appnote.txt says
  10162. * 3 but the actual value used is 4.)
  10163. */
  10164. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  10165. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  10166. break;
  10167. }
  10168. }
  10169. /* Update opt_len to include the bit length tree and counts */
  10170. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  10171. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  10172. // s->opt_len, s->static_len));
  10173. return max_blindex;
  10174. }
  10175. /* ===========================================================================
  10176. * Send the header for a block using dynamic Huffman trees: the counts, the
  10177. * lengths of the bit length codes, the literal tree and the distance tree.
  10178. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  10179. */
  10180. function send_all_trees(s, lcodes, dcodes, blcodes)
  10181. // deflate_state *s;
  10182. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  10183. {
  10184. var rank; /* index in bl_order */
  10185. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  10186. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  10187. // "too many codes");
  10188. //Tracev((stderr, "\nbl counts: "));
  10189. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  10190. send_bits(s, dcodes-1, 5);
  10191. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  10192. for (rank = 0; rank < blcodes; rank++) {
  10193. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  10194. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  10195. }
  10196. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  10197. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  10198. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  10199. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  10200. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  10201. }
  10202. /* ===========================================================================
  10203. * Check if the data type is TEXT or BINARY, using the following algorithm:
  10204. * - TEXT if the two conditions below are satisfied:
  10205. * a) There are no non-portable control characters belonging to the
  10206. * "black list" (0..6, 14..25, 28..31).
  10207. * b) There is at least one printable character belonging to the
  10208. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  10209. * - BINARY otherwise.
  10210. * - The following partially-portable control characters form a
  10211. * "gray list" that is ignored in this detection algorithm:
  10212. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  10213. * IN assertion: the fields Freq of dyn_ltree are set.
  10214. */
  10215. function detect_data_type(s) {
  10216. /* black_mask is the bit mask of black-listed bytes
  10217. * set bits 0..6, 14..25, and 28..31
  10218. * 0xf3ffc07f = binary 11110011111111111100000001111111
  10219. */
  10220. var black_mask = 0xf3ffc07f;
  10221. var n;
  10222. /* Check for non-textual ("black-listed") bytes. */
  10223. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  10224. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  10225. return Z_BINARY;
  10226. }
  10227. }
  10228. /* Check for textual ("white-listed") bytes. */
  10229. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  10230. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  10231. return Z_TEXT;
  10232. }
  10233. for (n = 32; n < LITERALS; n++) {
  10234. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  10235. return Z_TEXT;
  10236. }
  10237. }
  10238. /* There are no "black-listed" or "white-listed" bytes:
  10239. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  10240. */
  10241. return Z_BINARY;
  10242. }
  10243. var static_init_done = false;
  10244. /* ===========================================================================
  10245. * Initialize the tree data structures for a new zlib stream.
  10246. */
  10247. function _tr_init(s)
  10248. {
  10249. if (!static_init_done) {
  10250. tr_static_init();
  10251. static_init_done = true;
  10252. }
  10253. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  10254. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  10255. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  10256. s.bi_buf = 0;
  10257. s.bi_valid = 0;
  10258. /* Initialize the first block of the first file: */
  10259. init_block(s);
  10260. }
  10261. /* ===========================================================================
  10262. * Send a stored block
  10263. */
  10264. function _tr_stored_block(s, buf, stored_len, last)
  10265. //DeflateState *s;
  10266. //charf *buf; /* input block */
  10267. //ulg stored_len; /* length of input block */
  10268. //int last; /* one if this is the last block for a file */
  10269. {
  10270. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  10271. copy_block(s, buf, stored_len, true); /* with header */
  10272. }
  10273. /* ===========================================================================
  10274. * Send one empty static block to give enough lookahead for inflate.
  10275. * This takes 10 bits, of which 7 may remain in the bit buffer.
  10276. */
  10277. function _tr_align(s) {
  10278. send_bits(s, STATIC_TREES<<1, 3);
  10279. send_code(s, END_BLOCK, static_ltree);
  10280. bi_flush(s);
  10281. }
  10282. /* ===========================================================================
  10283. * Determine the best encoding for the current block: dynamic trees, static
  10284. * trees or store, and output the encoded block to the zip file.
  10285. */
  10286. function _tr_flush_block(s, buf, stored_len, last)
  10287. //DeflateState *s;
  10288. //charf *buf; /* input block, or NULL if too old */
  10289. //ulg stored_len; /* length of input block */
  10290. //int last; /* one if this is the last block for a file */
  10291. {
  10292. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  10293. var max_blindex = 0; /* index of last bit length code of non zero freq */
  10294. /* Build the Huffman trees unless a stored block is forced */
  10295. if (s.level > 0) {
  10296. /* Check if the file is binary or text */
  10297. if (s.strm.data_type === Z_UNKNOWN) {
  10298. s.strm.data_type = detect_data_type(s);
  10299. }
  10300. /* Construct the literal and distance trees */
  10301. build_tree(s, s.l_desc);
  10302. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  10303. // s->static_len));
  10304. build_tree(s, s.d_desc);
  10305. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  10306. // s->static_len));
  10307. /* At this point, opt_len and static_len are the total bit lengths of
  10308. * the compressed block data, excluding the tree representations.
  10309. */
  10310. /* Build the bit length tree for the above two trees, and get the index
  10311. * in bl_order of the last bit length code to send.
  10312. */
  10313. max_blindex = build_bl_tree(s);
  10314. /* Determine the best encoding. Compute the block lengths in bytes. */
  10315. opt_lenb = (s.opt_len+3+7) >>> 3;
  10316. static_lenb = (s.static_len+3+7) >>> 3;
  10317. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  10318. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  10319. // s->last_lit));
  10320. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  10321. } else {
  10322. // Assert(buf != (char*)0, "lost buf");
  10323. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  10324. }
  10325. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  10326. /* 4: two words for the lengths */
  10327. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10328. * Otherwise we can't have processed more than WSIZE input bytes since
  10329. * the last block flush, because compression would have been
  10330. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10331. * transform a block into a stored block.
  10332. */
  10333. _tr_stored_block(s, buf, stored_len, last);
  10334. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  10335. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  10336. compress_block(s, static_ltree, static_dtree);
  10337. } else {
  10338. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  10339. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  10340. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  10341. }
  10342. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  10343. /* The above check is made mod 2^32, for files larger than 512 MB
  10344. * and uLong implemented on 32 bits.
  10345. */
  10346. init_block(s);
  10347. if (last) {
  10348. bi_windup(s);
  10349. }
  10350. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  10351. // s->compressed_len-7*last));
  10352. }
  10353. /* ===========================================================================
  10354. * Save the match info and tally the frequency counts. Return true if
  10355. * the current block must be flushed.
  10356. */
  10357. function _tr_tally(s, dist, lc)
  10358. // deflate_state *s;
  10359. // unsigned dist; /* distance of matched string */
  10360. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  10361. {
  10362. //var out_length, in_length, dcode;
  10363. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  10364. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  10365. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  10366. s.last_lit++;
  10367. if (dist === 0) {
  10368. /* lc is the unmatched char */
  10369. s.dyn_ltree[lc*2]/*.Freq*/++;
  10370. } else {
  10371. s.matches++;
  10372. /* Here, lc is the match length - MIN_MATCH */
  10373. dist--; /* dist = match distance - 1 */
  10374. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  10375. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  10376. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  10377. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  10378. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  10379. }
  10380. // (!) This block is disabled in zlib defailts,
  10381. // don't enable it for binary compatibility
  10382. //#ifdef TRUNCATE_BLOCK
  10383. // /* Try to guess if it is profitable to stop the current block here */
  10384. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  10385. // /* Compute an upper bound for the compressed length */
  10386. // out_length = s.last_lit*8;
  10387. // in_length = s.strstart - s.block_start;
  10388. //
  10389. // for (dcode = 0; dcode < D_CODES; dcode++) {
  10390. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  10391. // }
  10392. // out_length >>>= 3;
  10393. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  10394. // // s->last_lit, in_length, out_length,
  10395. // // 100L - out_length*100L/in_length));
  10396. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  10397. // return true;
  10398. // }
  10399. // }
  10400. //#endif
  10401. return (s.last_lit === s.lit_bufsize-1);
  10402. /* We avoid equality with lit_bufsize because of wraparound at 64K
  10403. * on 16 bit machines and because stored blocks are restricted to
  10404. * 64K-1 bytes.
  10405. */
  10406. }
  10407. exports._tr_init = _tr_init;
  10408. exports._tr_stored_block = _tr_stored_block;
  10409. exports._tr_flush_block = _tr_flush_block;
  10410. exports._tr_tally = _tr_tally;
  10411. exports._tr_align = _tr_align;
  10412. },{"../utils/common":26}],38:[function(require,module,exports){
  10413. 'use strict';
  10414. function ZStream() {
  10415. /* next input byte */
  10416. this.input = null; // JS specific, because we have no pointers
  10417. this.next_in = 0;
  10418. /* number of bytes available at input */
  10419. this.avail_in = 0;
  10420. /* total number of input bytes read so far */
  10421. this.total_in = 0;
  10422. /* next output byte should be put there */
  10423. this.output = null; // JS specific, because we have no pointers
  10424. this.next_out = 0;
  10425. /* remaining free space at output */
  10426. this.avail_out = 0;
  10427. /* total number of bytes output so far */
  10428. this.total_out = 0;
  10429. /* last error message, NULL if no error */
  10430. this.msg = ''/*Z_NULL*/;
  10431. /* not visible by applications */
  10432. this.state = null;
  10433. /* best guess about the data type: binary or text */
  10434. this.data_type = 2/*Z_UNKNOWN*/;
  10435. /* adler32 value of the uncompressed data */
  10436. this.adler = 0;
  10437. }
  10438. module.exports = ZStream;
  10439. },{}],39:[function(require,module,exports){
  10440. var MediaStreamType = {
  10441. VIDEO_TYPE: "Video",
  10442. AUDIO_TYPE: "Audio"
  10443. };
  10444. module.exports = MediaStreamType;
  10445. },{}],40:[function(require,module,exports){
  10446. var RTCEvents = {
  10447. RTC_READY: "rtc.ready",
  10448. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  10449. LASTN_CHANGED: "rtc.lastn_changed",
  10450. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  10451. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  10452. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  10453. AUDIO_MUTE: "rtc.audio_mute",
  10454. VIDEO_MUTE: "rtc.video_mute"
  10455. };
  10456. module.exports = RTCEvents;
  10457. },{}],41:[function(require,module,exports){
  10458. var Resolutions = {
  10459. "1080": {
  10460. width: 1920,
  10461. height: 1080,
  10462. order: 7
  10463. },
  10464. "fullhd": {
  10465. width: 1920,
  10466. height: 1080,
  10467. order: 7
  10468. },
  10469. "720": {
  10470. width: 1280,
  10471. height: 720,
  10472. order: 6
  10473. },
  10474. "hd": {
  10475. width: 1280,
  10476. height: 720,
  10477. order: 6
  10478. },
  10479. "960": {
  10480. width: 960,
  10481. height: 720,
  10482. order: 5
  10483. },
  10484. "640": {
  10485. width: 640,
  10486. height: 480,
  10487. order: 4
  10488. },
  10489. "vga": {
  10490. width: 640,
  10491. height: 480,
  10492. order: 4
  10493. },
  10494. "360": {
  10495. width: 640,
  10496. height: 360,
  10497. order: 3
  10498. },
  10499. "320": {
  10500. width: 320,
  10501. height: 240,
  10502. order: 2
  10503. },
  10504. "180": {
  10505. width: 320,
  10506. height: 180,
  10507. order: 1
  10508. }
  10509. };
  10510. module.exports = Resolutions;
  10511. },{}],42:[function(require,module,exports){
  10512. var StreamEventTypes = {
  10513. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  10514. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  10515. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  10516. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  10517. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  10518. };
  10519. module.exports = StreamEventTypes;
  10520. },{}],43:[function(require,module,exports){
  10521. var UIEvents = {
  10522. NICKNAME_CHANGED: "UI.nickname_changed",
  10523. SELECTED_ENDPOINT: "UI.selected_endpoint",
  10524. PINNED_ENDPOINT: "UI.pinned_endpoint",
  10525. LARGEVIDEO_INIT: "UI.largevideo_init"
  10526. };
  10527. module.exports = UIEvents;
  10528. },{}],44:[function(require,module,exports){
  10529. var AuthenticationEvents = {
  10530. /**
  10531. * Event callback arguments:
  10532. * function(authenticationEnabled, userIdentity)
  10533. * authenticationEnabled - indicates whether authentication has been enabled
  10534. * in this session
  10535. * userIdentity - if user has been logged in then it contains user name. If
  10536. * contains 'null' or 'undefined' then user is not logged in.
  10537. */
  10538. IDENTITY_UPDATED: "authentication.identity_updated"
  10539. };
  10540. module.exports = AuthenticationEvents;
  10541. },{}],45:[function(require,module,exports){
  10542. var DesktopSharingEventTypes = {
  10543. INIT: "ds.init",
  10544. SWITCHING_DONE: "ds.switching_done",
  10545. NEW_STREAM_CREATED: "ds.new_stream_created"
  10546. };
  10547. module.exports = DesktopSharingEventTypes;
  10548. },{}],46:[function(require,module,exports){
  10549. var XMPPEvents = {
  10550. CONNECTION_FAILED: "xmpp.connection.failed",
  10551. // Indicates an interrupted connection event.
  10552. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  10553. // Indicates a restored connection event.
  10554. CONNECTION_RESTORED: "xmpp.connection.restored",
  10555. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  10556. CALL_INCOMING: "xmpp.callincoming.jingle",
  10557. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  10558. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  10559. KICKED: "xmpp.kicked",
  10560. BRIDGE_DOWN: "xmpp.bridge_down",
  10561. USER_ID_CHANGED: "xmpp.user_id_changed",
  10562. // We joined the MUC
  10563. MUC_JOINED: "xmpp.muc_joined",
  10564. // A member joined the MUC
  10565. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  10566. // A member left the MUC
  10567. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  10568. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  10569. MUC_DESTROYED: "xmpp.muc_destroyed",
  10570. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  10571. REMOTE_STATS: "xmpp.remote_stats",
  10572. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  10573. PRESENCE_STATUS: "xmpp.presence_status",
  10574. RESERVATION_ERROR: "xmpp.room_reservation_error",
  10575. SUBJECT_CHANGED: "xmpp.subject_changed",
  10576. MESSAGE_RECEIVED: "xmpp.message_received",
  10577. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  10578. PASSWORD_REQUIRED: "xmpp.password_required",
  10579. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  10580. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  10581. ETHERPAD: "xmpp.etherpad",
  10582. DEVICE_AVAILABLE: "xmpp.device_available",
  10583. VIDEO_TYPE: "xmpp.video_type",
  10584. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  10585. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  10586. AUDIO_MUTED: "xmpp.audio_muted",
  10587. VIDEO_MUTED: "xmpp.video_muted",
  10588. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  10589. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  10590. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  10591. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  10592. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  10593. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  10594. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  10595. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  10596. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  10597. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  10598. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  10599. // xmpp is connected and obtained user media
  10600. READY_TO_JOIN: 'xmpp.ready_to_join'
  10601. };
  10602. module.exports = XMPPEvents;
  10603. },{}],47:[function(require,module,exports){
  10604. // Copyright Joyent, Inc. and other Node contributors.
  10605. //
  10606. // Permission is hereby granted, free of charge, to any person obtaining a
  10607. // copy of this software and associated documentation files (the
  10608. // "Software"), to deal in the Software without restriction, including
  10609. // without limitation the rights to use, copy, modify, merge, publish,
  10610. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10611. // persons to whom the Software is furnished to do so, subject to the
  10612. // following conditions:
  10613. //
  10614. // The above copyright notice and this permission notice shall be included
  10615. // in all copies or substantial portions of the Software.
  10616. //
  10617. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10618. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10619. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10620. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10621. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10622. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10623. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10624. function EventEmitter() {
  10625. this._events = this._events || {};
  10626. this._maxListeners = this._maxListeners || undefined;
  10627. }
  10628. module.exports = EventEmitter;
  10629. // Backwards-compat with node 0.10.x
  10630. EventEmitter.EventEmitter = EventEmitter;
  10631. EventEmitter.prototype._events = undefined;
  10632. EventEmitter.prototype._maxListeners = undefined;
  10633. // By default EventEmitters will print a warning if more than 10 listeners are
  10634. // added to it. This is a useful default which helps finding memory leaks.
  10635. EventEmitter.defaultMaxListeners = 10;
  10636. // Obviously not all Emitters should be limited to 10. This function allows
  10637. // that to be increased. Set to zero for unlimited.
  10638. EventEmitter.prototype.setMaxListeners = function(n) {
  10639. if (!isNumber(n) || n < 0 || isNaN(n))
  10640. throw TypeError('n must be a positive number');
  10641. this._maxListeners = n;
  10642. return this;
  10643. };
  10644. EventEmitter.prototype.emit = function(type) {
  10645. var er, handler, len, args, i, listeners;
  10646. if (!this._events)
  10647. this._events = {};
  10648. // If there is no 'error' event listener then throw.
  10649. if (type === 'error') {
  10650. if (!this._events.error ||
  10651. (isObject(this._events.error) && !this._events.error.length)) {
  10652. er = arguments[1];
  10653. if (er instanceof Error) {
  10654. throw er; // Unhandled 'error' event
  10655. }
  10656. throw TypeError('Uncaught, unspecified "error" event.');
  10657. }
  10658. }
  10659. handler = this._events[type];
  10660. if (isUndefined(handler))
  10661. return false;
  10662. if (isFunction(handler)) {
  10663. switch (arguments.length) {
  10664. // fast cases
  10665. case 1:
  10666. handler.call(this);
  10667. break;
  10668. case 2:
  10669. handler.call(this, arguments[1]);
  10670. break;
  10671. case 3:
  10672. handler.call(this, arguments[1], arguments[2]);
  10673. break;
  10674. // slower
  10675. default:
  10676. len = arguments.length;
  10677. args = new Array(len - 1);
  10678. for (i = 1; i < len; i++)
  10679. args[i - 1] = arguments[i];
  10680. handler.apply(this, args);
  10681. }
  10682. } else if (isObject(handler)) {
  10683. len = arguments.length;
  10684. args = new Array(len - 1);
  10685. for (i = 1; i < len; i++)
  10686. args[i - 1] = arguments[i];
  10687. listeners = handler.slice();
  10688. len = listeners.length;
  10689. for (i = 0; i < len; i++)
  10690. listeners[i].apply(this, args);
  10691. }
  10692. return true;
  10693. };
  10694. EventEmitter.prototype.addListener = function(type, listener) {
  10695. var m;
  10696. if (!isFunction(listener))
  10697. throw TypeError('listener must be a function');
  10698. if (!this._events)
  10699. this._events = {};
  10700. // To avoid recursion in the case that type === "newListener"! Before
  10701. // adding it to the listeners, first emit "newListener".
  10702. if (this._events.newListener)
  10703. this.emit('newListener', type,
  10704. isFunction(listener.listener) ?
  10705. listener.listener : listener);
  10706. if (!this._events[type])
  10707. // Optimize the case of one listener. Don't need the extra array object.
  10708. this._events[type] = listener;
  10709. else if (isObject(this._events[type]))
  10710. // If we've already got an array, just append.
  10711. this._events[type].push(listener);
  10712. else
  10713. // Adding the second element, need to change to array.
  10714. this._events[type] = [this._events[type], listener];
  10715. // Check for listener leak
  10716. if (isObject(this._events[type]) && !this._events[type].warned) {
  10717. var m;
  10718. if (!isUndefined(this._maxListeners)) {
  10719. m = this._maxListeners;
  10720. } else {
  10721. m = EventEmitter.defaultMaxListeners;
  10722. }
  10723. if (m && m > 0 && this._events[type].length > m) {
  10724. this._events[type].warned = true;
  10725. console.error('(node) warning: possible EventEmitter memory ' +
  10726. 'leak detected. %d listeners added. ' +
  10727. 'Use emitter.setMaxListeners() to increase limit.',
  10728. this._events[type].length);
  10729. if (typeof console.trace === 'function') {
  10730. // not supported in IE 10
  10731. console.trace();
  10732. }
  10733. }
  10734. }
  10735. return this;
  10736. };
  10737. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  10738. EventEmitter.prototype.once = function(type, listener) {
  10739. if (!isFunction(listener))
  10740. throw TypeError('listener must be a function');
  10741. var fired = false;
  10742. function g() {
  10743. this.removeListener(type, g);
  10744. if (!fired) {
  10745. fired = true;
  10746. listener.apply(this, arguments);
  10747. }
  10748. }
  10749. g.listener = listener;
  10750. this.on(type, g);
  10751. return this;
  10752. };
  10753. // emits a 'removeListener' event iff the listener was removed
  10754. EventEmitter.prototype.removeListener = function(type, listener) {
  10755. var list, position, length, i;
  10756. if (!isFunction(listener))
  10757. throw TypeError('listener must be a function');
  10758. if (!this._events || !this._events[type])
  10759. return this;
  10760. list = this._events[type];
  10761. length = list.length;
  10762. position = -1;
  10763. if (list === listener ||
  10764. (isFunction(list.listener) && list.listener === listener)) {
  10765. delete this._events[type];
  10766. if (this._events.removeListener)
  10767. this.emit('removeListener', type, listener);
  10768. } else if (isObject(list)) {
  10769. for (i = length; i-- > 0;) {
  10770. if (list[i] === listener ||
  10771. (list[i].listener && list[i].listener === listener)) {
  10772. position = i;
  10773. break;
  10774. }
  10775. }
  10776. if (position < 0)
  10777. return this;
  10778. if (list.length === 1) {
  10779. list.length = 0;
  10780. delete this._events[type];
  10781. } else {
  10782. list.splice(position, 1);
  10783. }
  10784. if (this._events.removeListener)
  10785. this.emit('removeListener', type, listener);
  10786. }
  10787. return this;
  10788. };
  10789. EventEmitter.prototype.removeAllListeners = function(type) {
  10790. var key, listeners;
  10791. if (!this._events)
  10792. return this;
  10793. // not listening for removeListener, no need to emit
  10794. if (!this._events.removeListener) {
  10795. if (arguments.length === 0)
  10796. this._events = {};
  10797. else if (this._events[type])
  10798. delete this._events[type];
  10799. return this;
  10800. }
  10801. // emit removeListener for all listeners on all events
  10802. if (arguments.length === 0) {
  10803. for (key in this._events) {
  10804. if (key === 'removeListener') continue;
  10805. this.removeAllListeners(key);
  10806. }
  10807. this.removeAllListeners('removeListener');
  10808. this._events = {};
  10809. return this;
  10810. }
  10811. listeners = this._events[type];
  10812. if (isFunction(listeners)) {
  10813. this.removeListener(type, listeners);
  10814. } else {
  10815. // LIFO order
  10816. while (listeners.length)
  10817. this.removeListener(type, listeners[listeners.length - 1]);
  10818. }
  10819. delete this._events[type];
  10820. return this;
  10821. };
  10822. EventEmitter.prototype.listeners = function(type) {
  10823. var ret;
  10824. if (!this._events || !this._events[type])
  10825. ret = [];
  10826. else if (isFunction(this._events[type]))
  10827. ret = [this._events[type]];
  10828. else
  10829. ret = this._events[type].slice();
  10830. return ret;
  10831. };
  10832. EventEmitter.listenerCount = function(emitter, type) {
  10833. var ret;
  10834. if (!emitter._events || !emitter._events[type])
  10835. ret = 0;
  10836. else if (isFunction(emitter._events[type]))
  10837. ret = 1;
  10838. else
  10839. ret = emitter._events[type].length;
  10840. return ret;
  10841. };
  10842. function isFunction(arg) {
  10843. return typeof arg === 'function';
  10844. }
  10845. function isNumber(arg) {
  10846. return typeof arg === 'number';
  10847. }
  10848. function isObject(arg) {
  10849. return typeof arg === 'object' && arg !== null;
  10850. }
  10851. function isUndefined(arg) {
  10852. return arg === void 0;
  10853. }
  10854. },{}],48:[function(require,module,exports){
  10855. // shim for using process in browser
  10856. var process = module.exports = {};
  10857. var queue = [];
  10858. var draining = false;
  10859. function drainQueue() {
  10860. if (draining) {
  10861. return;
  10862. }
  10863. draining = true;
  10864. var currentQueue;
  10865. var len = queue.length;
  10866. while(len) {
  10867. currentQueue = queue;
  10868. queue = [];
  10869. var i = -1;
  10870. while (++i < len) {
  10871. currentQueue[i]();
  10872. }
  10873. len = queue.length;
  10874. }
  10875. draining = false;
  10876. }
  10877. process.nextTick = function (fun) {
  10878. queue.push(fun);
  10879. if (!draining) {
  10880. setTimeout(drainQueue, 0);
  10881. }
  10882. };
  10883. process.title = 'browser';
  10884. process.browser = true;
  10885. process.env = {};
  10886. process.argv = [];
  10887. process.version = ''; // empty string to avoid regexp issues
  10888. function noop() {}
  10889. process.on = noop;
  10890. process.addListener = noop;
  10891. process.once = noop;
  10892. process.off = noop;
  10893. process.removeListener = noop;
  10894. process.removeAllListeners = noop;
  10895. process.emit = noop;
  10896. process.binding = function (name) {
  10897. throw new Error('process.binding is not supported');
  10898. };
  10899. // TODO(shtylman)
  10900. process.cwd = function () { return '/' };
  10901. process.chdir = function (dir) {
  10902. throw new Error('process.chdir is not supported');
  10903. };
  10904. process.umask = function() { return 0; };
  10905. },{}]},{},[7])(7)
  10906. });