uniapp,h5

socket.io.js 151KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908
  1. /*!
  2. * Socket.IO v4.8.0
  3. * (c) 2014-2024 Guillermo Rauch
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.io = factory());
  10. })(this, (function () { 'use strict';
  11. function _arrayLikeToArray(r, a) {
  12. (null == a || a > r.length) && (a = r.length);
  13. for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  14. return n;
  15. }
  16. function _arrayWithoutHoles(r) {
  17. if (Array.isArray(r)) return _arrayLikeToArray(r);
  18. }
  19. function _construct(t, e, r) {
  20. if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
  21. var o = [null];
  22. o.push.apply(o, e);
  23. var p = new (t.bind.apply(t, o))();
  24. return r && _setPrototypeOf(p, r.prototype), p;
  25. }
  26. function _defineProperties(e, r) {
  27. for (var t = 0; t < r.length; t++) {
  28. var o = r[t];
  29. o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
  30. }
  31. }
  32. function _createClass(e, r, t) {
  33. return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
  34. writable: !1
  35. }), e;
  36. }
  37. function _createForOfIteratorHelper(r, e) {
  38. var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  39. if (!t) {
  40. if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
  41. t && (r = t);
  42. var n = 0,
  43. F = function () {};
  44. return {
  45. s: F,
  46. n: function () {
  47. return n >= r.length ? {
  48. done: !0
  49. } : {
  50. done: !1,
  51. value: r[n++]
  52. };
  53. },
  54. e: function (r) {
  55. throw r;
  56. },
  57. f: F
  58. };
  59. }
  60. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  61. }
  62. var o,
  63. a = !0,
  64. u = !1;
  65. return {
  66. s: function () {
  67. t = t.call(r);
  68. },
  69. n: function () {
  70. var r = t.next();
  71. return a = r.done, r;
  72. },
  73. e: function (r) {
  74. u = !0, o = r;
  75. },
  76. f: function () {
  77. try {
  78. a || null == t.return || t.return();
  79. } finally {
  80. if (u) throw o;
  81. }
  82. }
  83. };
  84. }
  85. function _extends() {
  86. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  87. for (var e = 1; e < arguments.length; e++) {
  88. var t = arguments[e];
  89. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  90. }
  91. return n;
  92. }, _extends.apply(null, arguments);
  93. }
  94. function _getPrototypeOf(t) {
  95. return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
  96. return t.__proto__ || Object.getPrototypeOf(t);
  97. }, _getPrototypeOf(t);
  98. }
  99. function _inheritsLoose(t, o) {
  100. t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
  101. }
  102. function _isNativeFunction(t) {
  103. try {
  104. return -1 !== Function.toString.call(t).indexOf("[native code]");
  105. } catch (n) {
  106. return "function" == typeof t;
  107. }
  108. }
  109. function _isNativeReflectConstruct() {
  110. try {
  111. var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  112. } catch (t) {}
  113. return (_isNativeReflectConstruct = function () {
  114. return !!t;
  115. })();
  116. }
  117. function _iterableToArray(r) {
  118. if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
  119. }
  120. function _nonIterableSpread() {
  121. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  122. }
  123. function _setPrototypeOf(t, e) {
  124. return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
  125. return t.__proto__ = e, t;
  126. }, _setPrototypeOf(t, e);
  127. }
  128. function _toConsumableArray(r) {
  129. return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
  130. }
  131. function _toPrimitive(t, r) {
  132. if ("object" != typeof t || !t) return t;
  133. var e = t[Symbol.toPrimitive];
  134. if (void 0 !== e) {
  135. var i = e.call(t, r || "default");
  136. if ("object" != typeof i) return i;
  137. throw new TypeError("@@toPrimitive must return a primitive value.");
  138. }
  139. return ("string" === r ? String : Number)(t);
  140. }
  141. function _toPropertyKey(t) {
  142. var i = _toPrimitive(t, "string");
  143. return "symbol" == typeof i ? i : i + "";
  144. }
  145. function _typeof(o) {
  146. "@babel/helpers - typeof";
  147. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
  148. return typeof o;
  149. } : function (o) {
  150. return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  151. }, _typeof(o);
  152. }
  153. function _unsupportedIterableToArray(r, a) {
  154. if (r) {
  155. if ("string" == typeof r) return _arrayLikeToArray(r, a);
  156. var t = {}.toString.call(r).slice(8, -1);
  157. return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  158. }
  159. }
  160. function _wrapNativeSuper(t) {
  161. var r = "function" == typeof Map ? new Map() : void 0;
  162. return _wrapNativeSuper = function (t) {
  163. if (null === t || !_isNativeFunction(t)) return t;
  164. if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
  165. if (void 0 !== r) {
  166. if (r.has(t)) return r.get(t);
  167. r.set(t, Wrapper);
  168. }
  169. function Wrapper() {
  170. return _construct(t, arguments, _getPrototypeOf(this).constructor);
  171. }
  172. return Wrapper.prototype = Object.create(t.prototype, {
  173. constructor: {
  174. value: Wrapper,
  175. enumerable: !1,
  176. writable: !0,
  177. configurable: !0
  178. }
  179. }), _setPrototypeOf(Wrapper, t);
  180. }, _wrapNativeSuper(t);
  181. }
  182. var PACKET_TYPES = Object.create(null); // no Map = no polyfill
  183. PACKET_TYPES["open"] = "0";
  184. PACKET_TYPES["close"] = "1";
  185. PACKET_TYPES["ping"] = "2";
  186. PACKET_TYPES["pong"] = "3";
  187. PACKET_TYPES["message"] = "4";
  188. PACKET_TYPES["upgrade"] = "5";
  189. PACKET_TYPES["noop"] = "6";
  190. var PACKET_TYPES_REVERSE = Object.create(null);
  191. Object.keys(PACKET_TYPES).forEach(function (key) {
  192. PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
  193. });
  194. var ERROR_PACKET = {
  195. type: "error",
  196. data: "parser error"
  197. };
  198. var withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
  199. var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
  200. // ArrayBuffer.isView method is not defined in IE10
  201. var isView$1 = function isView(obj) {
  202. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
  203. };
  204. var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
  205. var type = _ref.type,
  206. data = _ref.data;
  207. if (withNativeBlob$1 && data instanceof Blob) {
  208. if (supportsBinary) {
  209. return callback(data);
  210. } else {
  211. return encodeBlobAsBase64(data, callback);
  212. }
  213. } else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) {
  214. if (supportsBinary) {
  215. return callback(data);
  216. } else {
  217. return encodeBlobAsBase64(new Blob([data]), callback);
  218. }
  219. }
  220. // plain string
  221. return callback(PACKET_TYPES[type] + (data || ""));
  222. };
  223. var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
  224. var fileReader = new FileReader();
  225. fileReader.onload = function () {
  226. var content = fileReader.result.split(",")[1];
  227. callback("b" + (content || ""));
  228. };
  229. return fileReader.readAsDataURL(data);
  230. };
  231. function toArray(data) {
  232. if (data instanceof Uint8Array) {
  233. return data;
  234. } else if (data instanceof ArrayBuffer) {
  235. return new Uint8Array(data);
  236. } else {
  237. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  238. }
  239. }
  240. var TEXT_ENCODER;
  241. function encodePacketToBinary(packet, callback) {
  242. if (withNativeBlob$1 && packet.data instanceof Blob) {
  243. return packet.data.arrayBuffer().then(toArray).then(callback);
  244. } else if (withNativeArrayBuffer$2 && (packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
  245. return callback(toArray(packet.data));
  246. }
  247. encodePacket(packet, false, function (encoded) {
  248. if (!TEXT_ENCODER) {
  249. TEXT_ENCODER = new TextEncoder();
  250. }
  251. callback(TEXT_ENCODER.encode(encoded));
  252. });
  253. }
  254. // imported from https://github.com/socketio/base64-arraybuffer
  255. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  256. // Use a lookup table to find the index.
  257. var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  258. for (var i = 0; i < chars.length; i++) {
  259. lookup$1[chars.charCodeAt(i)] = i;
  260. }
  261. var decode$1 = function decode(base64) {
  262. var bufferLength = base64.length * 0.75,
  263. len = base64.length,
  264. i,
  265. p = 0,
  266. encoded1,
  267. encoded2,
  268. encoded3,
  269. encoded4;
  270. if (base64[base64.length - 1] === '=') {
  271. bufferLength--;
  272. if (base64[base64.length - 2] === '=') {
  273. bufferLength--;
  274. }
  275. }
  276. var arraybuffer = new ArrayBuffer(bufferLength),
  277. bytes = new Uint8Array(arraybuffer);
  278. for (i = 0; i < len; i += 4) {
  279. encoded1 = lookup$1[base64.charCodeAt(i)];
  280. encoded2 = lookup$1[base64.charCodeAt(i + 1)];
  281. encoded3 = lookup$1[base64.charCodeAt(i + 2)];
  282. encoded4 = lookup$1[base64.charCodeAt(i + 3)];
  283. bytes[p++] = encoded1 << 2 | encoded2 >> 4;
  284. bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
  285. bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  286. }
  287. return arraybuffer;
  288. };
  289. var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
  290. var decodePacket = function decodePacket(encodedPacket, binaryType) {
  291. if (typeof encodedPacket !== "string") {
  292. return {
  293. type: "message",
  294. data: mapBinary(encodedPacket, binaryType)
  295. };
  296. }
  297. var type = encodedPacket.charAt(0);
  298. if (type === "b") {
  299. return {
  300. type: "message",
  301. data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
  302. };
  303. }
  304. var packetType = PACKET_TYPES_REVERSE[type];
  305. if (!packetType) {
  306. return ERROR_PACKET;
  307. }
  308. return encodedPacket.length > 1 ? {
  309. type: PACKET_TYPES_REVERSE[type],
  310. data: encodedPacket.substring(1)
  311. } : {
  312. type: PACKET_TYPES_REVERSE[type]
  313. };
  314. };
  315. var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
  316. if (withNativeArrayBuffer$1) {
  317. var decoded = decode$1(data);
  318. return mapBinary(decoded, binaryType);
  319. } else {
  320. return {
  321. base64: true,
  322. data: data
  323. }; // fallback for old browsers
  324. }
  325. };
  326. var mapBinary = function mapBinary(data, binaryType) {
  327. switch (binaryType) {
  328. case "blob":
  329. if (data instanceof Blob) {
  330. // from WebSocket + binaryType "blob"
  331. return data;
  332. } else {
  333. // from HTTP long-polling or WebTransport
  334. return new Blob([data]);
  335. }
  336. case "arraybuffer":
  337. default:
  338. if (data instanceof ArrayBuffer) {
  339. // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
  340. return data;
  341. } else {
  342. // from WebTransport (Uint8Array)
  343. return data.buffer;
  344. }
  345. }
  346. };
  347. var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
  348. var encodePayload = function encodePayload(packets, callback) {
  349. // some packets may be added to the array while encoding, so the initial length must be saved
  350. var length = packets.length;
  351. var encodedPackets = new Array(length);
  352. var count = 0;
  353. packets.forEach(function (packet, i) {
  354. // force base64 encoding for binary packets
  355. encodePacket(packet, false, function (encodedPacket) {
  356. encodedPackets[i] = encodedPacket;
  357. if (++count === length) {
  358. callback(encodedPackets.join(SEPARATOR));
  359. }
  360. });
  361. });
  362. };
  363. var decodePayload = function decodePayload(encodedPayload, binaryType) {
  364. var encodedPackets = encodedPayload.split(SEPARATOR);
  365. var packets = [];
  366. for (var i = 0; i < encodedPackets.length; i++) {
  367. var decodedPacket = decodePacket(encodedPackets[i], binaryType);
  368. packets.push(decodedPacket);
  369. if (decodedPacket.type === "error") {
  370. break;
  371. }
  372. }
  373. return packets;
  374. };
  375. function createPacketEncoderStream() {
  376. return new TransformStream({
  377. transform: function transform(packet, controller) {
  378. encodePacketToBinary(packet, function (encodedPacket) {
  379. var payloadLength = encodedPacket.length;
  380. var header;
  381. // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length
  382. if (payloadLength < 126) {
  383. header = new Uint8Array(1);
  384. new DataView(header.buffer).setUint8(0, payloadLength);
  385. } else if (payloadLength < 65536) {
  386. header = new Uint8Array(3);
  387. var view = new DataView(header.buffer);
  388. view.setUint8(0, 126);
  389. view.setUint16(1, payloadLength);
  390. } else {
  391. header = new Uint8Array(9);
  392. var _view = new DataView(header.buffer);
  393. _view.setUint8(0, 127);
  394. _view.setBigUint64(1, BigInt(payloadLength));
  395. }
  396. // first bit indicates whether the payload is plain text (0) or binary (1)
  397. if (packet.data && typeof packet.data !== "string") {
  398. header[0] |= 0x80;
  399. }
  400. controller.enqueue(header);
  401. controller.enqueue(encodedPacket);
  402. });
  403. }
  404. });
  405. }
  406. var TEXT_DECODER;
  407. function totalLength(chunks) {
  408. return chunks.reduce(function (acc, chunk) {
  409. return acc + chunk.length;
  410. }, 0);
  411. }
  412. function concatChunks(chunks, size) {
  413. if (chunks[0].length === size) {
  414. return chunks.shift();
  415. }
  416. var buffer = new Uint8Array(size);
  417. var j = 0;
  418. for (var i = 0; i < size; i++) {
  419. buffer[i] = chunks[0][j++];
  420. if (j === chunks[0].length) {
  421. chunks.shift();
  422. j = 0;
  423. }
  424. }
  425. if (chunks.length && j < chunks[0].length) {
  426. chunks[0] = chunks[0].slice(j);
  427. }
  428. return buffer;
  429. }
  430. function createPacketDecoderStream(maxPayload, binaryType) {
  431. if (!TEXT_DECODER) {
  432. TEXT_DECODER = new TextDecoder();
  433. }
  434. var chunks = [];
  435. var state = 0 /* State.READ_HEADER */;
  436. var expectedLength = -1;
  437. var isBinary = false;
  438. return new TransformStream({
  439. transform: function transform(chunk, controller) {
  440. chunks.push(chunk);
  441. while (true) {
  442. if (state === 0 /* State.READ_HEADER */) {
  443. if (totalLength(chunks) < 1) {
  444. break;
  445. }
  446. var header = concatChunks(chunks, 1);
  447. isBinary = (header[0] & 0x80) === 0x80;
  448. expectedLength = header[0] & 0x7f;
  449. if (expectedLength < 126) {
  450. state = 3 /* State.READ_PAYLOAD */;
  451. } else if (expectedLength === 126) {
  452. state = 1 /* State.READ_EXTENDED_LENGTH_16 */;
  453. } else {
  454. state = 2 /* State.READ_EXTENDED_LENGTH_64 */;
  455. }
  456. } else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {
  457. if (totalLength(chunks) < 2) {
  458. break;
  459. }
  460. var headerArray = concatChunks(chunks, 2);
  461. expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
  462. state = 3 /* State.READ_PAYLOAD */;
  463. } else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {
  464. if (totalLength(chunks) < 8) {
  465. break;
  466. }
  467. var _headerArray = concatChunks(chunks, 8);
  468. var view = new DataView(_headerArray.buffer, _headerArray.byteOffset, _headerArray.length);
  469. var n = view.getUint32(0);
  470. if (n > Math.pow(2, 53 - 32) - 1) {
  471. // the maximum safe integer in JavaScript is 2^53 - 1
  472. controller.enqueue(ERROR_PACKET);
  473. break;
  474. }
  475. expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
  476. state = 3 /* State.READ_PAYLOAD */;
  477. } else {
  478. if (totalLength(chunks) < expectedLength) {
  479. break;
  480. }
  481. var data = concatChunks(chunks, expectedLength);
  482. controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
  483. state = 0 /* State.READ_HEADER */;
  484. }
  485. if (expectedLength === 0 || expectedLength > maxPayload) {
  486. controller.enqueue(ERROR_PACKET);
  487. break;
  488. }
  489. }
  490. }
  491. });
  492. }
  493. var protocol$1 = 4;
  494. /**
  495. * Initialize a new `Emitter`.
  496. *
  497. * @api public
  498. */
  499. function Emitter(obj) {
  500. if (obj) return mixin(obj);
  501. }
  502. /**
  503. * Mixin the emitter properties.
  504. *
  505. * @param {Object} obj
  506. * @return {Object}
  507. * @api private
  508. */
  509. function mixin(obj) {
  510. for (var key in Emitter.prototype) {
  511. obj[key] = Emitter.prototype[key];
  512. }
  513. return obj;
  514. }
  515. /**
  516. * Listen on the given `event` with `fn`.
  517. *
  518. * @param {String} event
  519. * @param {Function} fn
  520. * @return {Emitter}
  521. * @api public
  522. */
  523. Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
  524. this._callbacks = this._callbacks || {};
  525. (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
  526. return this;
  527. };
  528. /**
  529. * Adds an `event` listener that will be invoked a single
  530. * time then automatically removed.
  531. *
  532. * @param {String} event
  533. * @param {Function} fn
  534. * @return {Emitter}
  535. * @api public
  536. */
  537. Emitter.prototype.once = function (event, fn) {
  538. function on() {
  539. this.off(event, on);
  540. fn.apply(this, arguments);
  541. }
  542. on.fn = fn;
  543. this.on(event, on);
  544. return this;
  545. };
  546. /**
  547. * Remove the given callback for `event` or all
  548. * registered callbacks.
  549. *
  550. * @param {String} event
  551. * @param {Function} fn
  552. * @return {Emitter}
  553. * @api public
  554. */
  555. Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
  556. this._callbacks = this._callbacks || {};
  557. // all
  558. if (0 == arguments.length) {
  559. this._callbacks = {};
  560. return this;
  561. }
  562. // specific event
  563. var callbacks = this._callbacks['$' + event];
  564. if (!callbacks) return this;
  565. // remove all handlers
  566. if (1 == arguments.length) {
  567. delete this._callbacks['$' + event];
  568. return this;
  569. }
  570. // remove specific handler
  571. var cb;
  572. for (var i = 0; i < callbacks.length; i++) {
  573. cb = callbacks[i];
  574. if (cb === fn || cb.fn === fn) {
  575. callbacks.splice(i, 1);
  576. break;
  577. }
  578. }
  579. // Remove event specific arrays for event types that no
  580. // one is subscribed for to avoid memory leak.
  581. if (callbacks.length === 0) {
  582. delete this._callbacks['$' + event];
  583. }
  584. return this;
  585. };
  586. /**
  587. * Emit `event` with the given args.
  588. *
  589. * @param {String} event
  590. * @param {Mixed} ...
  591. * @return {Emitter}
  592. */
  593. Emitter.prototype.emit = function (event) {
  594. this._callbacks = this._callbacks || {};
  595. var args = new Array(arguments.length - 1),
  596. callbacks = this._callbacks['$' + event];
  597. for (var i = 1; i < arguments.length; i++) {
  598. args[i - 1] = arguments[i];
  599. }
  600. if (callbacks) {
  601. callbacks = callbacks.slice(0);
  602. for (var i = 0, len = callbacks.length; i < len; ++i) {
  603. callbacks[i].apply(this, args);
  604. }
  605. }
  606. return this;
  607. };
  608. // alias used for reserved events (protected method)
  609. Emitter.prototype.emitReserved = Emitter.prototype.emit;
  610. /**
  611. * Return array of callbacks for `event`.
  612. *
  613. * @param {String} event
  614. * @return {Array}
  615. * @api public
  616. */
  617. Emitter.prototype.listeners = function (event) {
  618. this._callbacks = this._callbacks || {};
  619. return this._callbacks['$' + event] || [];
  620. };
  621. /**
  622. * Check if this emitter has `event` handlers.
  623. *
  624. * @param {String} event
  625. * @return {Boolean}
  626. * @api public
  627. */
  628. Emitter.prototype.hasListeners = function (event) {
  629. return !!this.listeners(event).length;
  630. };
  631. var nextTick = function () {
  632. var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
  633. if (isPromiseAvailable) {
  634. return function (cb) {
  635. return Promise.resolve().then(cb);
  636. };
  637. } else {
  638. return function (cb, setTimeoutFn) {
  639. return setTimeoutFn(cb, 0);
  640. };
  641. }
  642. }();
  643. var globalThisShim = function () {
  644. if (typeof self !== "undefined") {
  645. return self;
  646. } else if (typeof window !== "undefined") {
  647. return window;
  648. } else {
  649. return Function("return this")();
  650. }
  651. }();
  652. var defaultBinaryType = "arraybuffer";
  653. function createCookieJar() {}
  654. function pick(obj) {
  655. for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  656. attr[_key - 1] = arguments[_key];
  657. }
  658. return attr.reduce(function (acc, k) {
  659. if (obj.hasOwnProperty(k)) {
  660. acc[k] = obj[k];
  661. }
  662. return acc;
  663. }, {});
  664. }
  665. // Keep a reference to the real timeout functions so they can be used when overridden
  666. var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
  667. var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
  668. function installTimerFunctions(obj, opts) {
  669. if (opts.useNativeTimers) {
  670. obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
  671. obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
  672. } else {
  673. obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
  674. obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
  675. }
  676. }
  677. // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
  678. var BASE64_OVERHEAD = 1.33;
  679. // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
  680. function byteLength(obj) {
  681. if (typeof obj === "string") {
  682. return utf8Length(obj);
  683. }
  684. // arraybuffer or blob
  685. return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
  686. }
  687. function utf8Length(str) {
  688. var c = 0,
  689. length = 0;
  690. for (var i = 0, l = str.length; i < l; i++) {
  691. c = str.charCodeAt(i);
  692. if (c < 0x80) {
  693. length += 1;
  694. } else if (c < 0x800) {
  695. length += 2;
  696. } else if (c < 0xd800 || c >= 0xe000) {
  697. length += 3;
  698. } else {
  699. i++;
  700. length += 4;
  701. }
  702. }
  703. return length;
  704. }
  705. /**
  706. * Generates a random 8-characters string.
  707. */
  708. function randomString() {
  709. return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
  710. }
  711. // imported from https://github.com/galkn/querystring
  712. /**
  713. * Compiles a querystring
  714. * Returns string representation of the object
  715. *
  716. * @param {Object}
  717. * @api private
  718. */
  719. function encode(obj) {
  720. var str = '';
  721. for (var i in obj) {
  722. if (obj.hasOwnProperty(i)) {
  723. if (str.length) str += '&';
  724. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  725. }
  726. }
  727. return str;
  728. }
  729. /**
  730. * Parses a simple querystring into an object
  731. *
  732. * @param {String} qs
  733. * @api private
  734. */
  735. function decode(qs) {
  736. var qry = {};
  737. var pairs = qs.split('&');
  738. for (var i = 0, l = pairs.length; i < l; i++) {
  739. var pair = pairs[i].split('=');
  740. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  741. }
  742. return qry;
  743. }
  744. var TransportError = /*#__PURE__*/function (_Error) {
  745. function TransportError(reason, description, context) {
  746. var _this;
  747. _this = _Error.call(this, reason) || this;
  748. _this.description = description;
  749. _this.context = context;
  750. _this.type = "TransportError";
  751. return _this;
  752. }
  753. _inheritsLoose(TransportError, _Error);
  754. return TransportError;
  755. }( /*#__PURE__*/_wrapNativeSuper(Error));
  756. var Transport = /*#__PURE__*/function (_Emitter) {
  757. /**
  758. * Transport abstract constructor.
  759. *
  760. * @param {Object} opts - options
  761. * @protected
  762. */
  763. function Transport(opts) {
  764. var _this2;
  765. _this2 = _Emitter.call(this) || this;
  766. _this2.writable = false;
  767. installTimerFunctions(_this2, opts);
  768. _this2.opts = opts;
  769. _this2.query = opts.query;
  770. _this2.socket = opts.socket;
  771. _this2.supportsBinary = !opts.forceBase64;
  772. return _this2;
  773. }
  774. /**
  775. * Emits an error.
  776. *
  777. * @param {String} reason
  778. * @param description
  779. * @param context - the error context
  780. * @return {Transport} for chaining
  781. * @protected
  782. */
  783. _inheritsLoose(Transport, _Emitter);
  784. var _proto = Transport.prototype;
  785. _proto.onError = function onError(reason, description, context) {
  786. _Emitter.prototype.emitReserved.call(this, "error", new TransportError(reason, description, context));
  787. return this;
  788. }
  789. /**
  790. * Opens the transport.
  791. */;
  792. _proto.open = function open() {
  793. this.readyState = "opening";
  794. this.doOpen();
  795. return this;
  796. }
  797. /**
  798. * Closes the transport.
  799. */;
  800. _proto.close = function close() {
  801. if (this.readyState === "opening" || this.readyState === "open") {
  802. this.doClose();
  803. this.onClose();
  804. }
  805. return this;
  806. }
  807. /**
  808. * Sends multiple packets.
  809. *
  810. * @param {Array} packets
  811. */;
  812. _proto.send = function send(packets) {
  813. if (this.readyState === "open") {
  814. this.write(packets);
  815. }
  816. }
  817. /**
  818. * Called upon open
  819. *
  820. * @protected
  821. */;
  822. _proto.onOpen = function onOpen() {
  823. this.readyState = "open";
  824. this.writable = true;
  825. _Emitter.prototype.emitReserved.call(this, "open");
  826. }
  827. /**
  828. * Called with data.
  829. *
  830. * @param {String} data
  831. * @protected
  832. */;
  833. _proto.onData = function onData(data) {
  834. var packet = decodePacket(data, this.socket.binaryType);
  835. this.onPacket(packet);
  836. }
  837. /**
  838. * Called with a decoded packet.
  839. *
  840. * @protected
  841. */;
  842. _proto.onPacket = function onPacket(packet) {
  843. _Emitter.prototype.emitReserved.call(this, "packet", packet);
  844. }
  845. /**
  846. * Called upon close.
  847. *
  848. * @protected
  849. */;
  850. _proto.onClose = function onClose(details) {
  851. this.readyState = "closed";
  852. _Emitter.prototype.emitReserved.call(this, "close", details);
  853. }
  854. /**
  855. * Pauses the transport, in order not to lose packets during an upgrade.
  856. *
  857. * @param onPause
  858. */;
  859. _proto.pause = function pause(onPause) {};
  860. _proto.createUri = function createUri(schema) {
  861. var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  862. return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
  863. };
  864. _proto._hostname = function _hostname() {
  865. var hostname = this.opts.hostname;
  866. return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
  867. };
  868. _proto._port = function _port() {
  869. if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) {
  870. return ":" + this.opts.port;
  871. } else {
  872. return "";
  873. }
  874. };
  875. _proto._query = function _query(query) {
  876. var encodedQuery = encode(query);
  877. return encodedQuery.length ? "?" + encodedQuery : "";
  878. };
  879. return Transport;
  880. }(Emitter);
  881. var Polling = /*#__PURE__*/function (_Transport) {
  882. function Polling() {
  883. var _this;
  884. _this = _Transport.apply(this, arguments) || this;
  885. _this._polling = false;
  886. return _this;
  887. }
  888. _inheritsLoose(Polling, _Transport);
  889. var _proto = Polling.prototype;
  890. /**
  891. * Opens the socket (triggers polling). We write a PING message to determine
  892. * when the transport is open.
  893. *
  894. * @protected
  895. */
  896. _proto.doOpen = function doOpen() {
  897. this._poll();
  898. }
  899. /**
  900. * Pauses polling.
  901. *
  902. * @param {Function} onPause - callback upon buffers are flushed and transport is paused
  903. * @package
  904. */;
  905. _proto.pause = function pause(onPause) {
  906. var _this2 = this;
  907. this.readyState = "pausing";
  908. var pause = function pause() {
  909. _this2.readyState = "paused";
  910. onPause();
  911. };
  912. if (this._polling || !this.writable) {
  913. var total = 0;
  914. if (this._polling) {
  915. total++;
  916. this.once("pollComplete", function () {
  917. --total || pause();
  918. });
  919. }
  920. if (!this.writable) {
  921. total++;
  922. this.once("drain", function () {
  923. --total || pause();
  924. });
  925. }
  926. } else {
  927. pause();
  928. }
  929. }
  930. /**
  931. * Starts polling cycle.
  932. *
  933. * @private
  934. */;
  935. _proto._poll = function _poll() {
  936. this._polling = true;
  937. this.doPoll();
  938. this.emitReserved("poll");
  939. }
  940. /**
  941. * Overloads onData to detect payloads.
  942. *
  943. * @protected
  944. */;
  945. _proto.onData = function onData(data) {
  946. var _this3 = this;
  947. var callback = function callback(packet) {
  948. // if its the first message we consider the transport open
  949. if ("opening" === _this3.readyState && packet.type === "open") {
  950. _this3.onOpen();
  951. }
  952. // if its a close packet, we close the ongoing requests
  953. if ("close" === packet.type) {
  954. _this3.onClose({
  955. description: "transport closed by the server"
  956. });
  957. return false;
  958. }
  959. // otherwise bypass onData and handle the message
  960. _this3.onPacket(packet);
  961. };
  962. // decode payload
  963. decodePayload(data, this.socket.binaryType).forEach(callback);
  964. // if an event did not trigger closing
  965. if ("closed" !== this.readyState) {
  966. // if we got data we're not polling
  967. this._polling = false;
  968. this.emitReserved("pollComplete");
  969. if ("open" === this.readyState) {
  970. this._poll();
  971. }
  972. }
  973. }
  974. /**
  975. * For polling, send a close packet.
  976. *
  977. * @protected
  978. */;
  979. _proto.doClose = function doClose() {
  980. var _this4 = this;
  981. var close = function close() {
  982. _this4.write([{
  983. type: "close"
  984. }]);
  985. };
  986. if ("open" === this.readyState) {
  987. close();
  988. } else {
  989. // in case we're trying to close while
  990. // handshaking is in progress (GH-164)
  991. this.once("open", close);
  992. }
  993. }
  994. /**
  995. * Writes a packets payload.
  996. *
  997. * @param {Array} packets - data packets
  998. * @protected
  999. */;
  1000. _proto.write = function write(packets) {
  1001. var _this5 = this;
  1002. this.writable = false;
  1003. encodePayload(packets, function (data) {
  1004. _this5.doWrite(data, function () {
  1005. _this5.writable = true;
  1006. _this5.emitReserved("drain");
  1007. });
  1008. });
  1009. }
  1010. /**
  1011. * Generates uri for connection.
  1012. *
  1013. * @private
  1014. */;
  1015. _proto.uri = function uri() {
  1016. var schema = this.opts.secure ? "https" : "http";
  1017. var query = this.query || {};
  1018. // cache busting is forced
  1019. if (false !== this.opts.timestampRequests) {
  1020. query[this.opts.timestampParam] = randomString();
  1021. }
  1022. if (!this.supportsBinary && !query.sid) {
  1023. query.b64 = 1;
  1024. }
  1025. return this.createUri(schema, query);
  1026. };
  1027. return _createClass(Polling, [{
  1028. key: "name",
  1029. get: function get() {
  1030. return "polling";
  1031. }
  1032. }]);
  1033. }(Transport);
  1034. // imported from https://github.com/component/has-cors
  1035. var value = false;
  1036. try {
  1037. value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
  1038. } catch (err) {
  1039. // if XMLHttp support is disabled in IE then it will throw
  1040. // when trying to create
  1041. }
  1042. var hasCORS = value;
  1043. function empty() {}
  1044. var BaseXHR = /*#__PURE__*/function (_Polling) {
  1045. /**
  1046. * XHR Polling constructor.
  1047. *
  1048. * @param {Object} opts
  1049. * @package
  1050. */
  1051. function BaseXHR(opts) {
  1052. var _this;
  1053. _this = _Polling.call(this, opts) || this;
  1054. if (typeof location !== "undefined") {
  1055. var isSSL = "https:" === location.protocol;
  1056. var port = location.port;
  1057. // some user agents have empty `location.port`
  1058. if (!port) {
  1059. port = isSSL ? "443" : "80";
  1060. }
  1061. _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
  1062. }
  1063. return _this;
  1064. }
  1065. /**
  1066. * Sends data.
  1067. *
  1068. * @param {String} data to send.
  1069. * @param {Function} called upon flush.
  1070. * @private
  1071. */
  1072. _inheritsLoose(BaseXHR, _Polling);
  1073. var _proto = BaseXHR.prototype;
  1074. _proto.doWrite = function doWrite(data, fn) {
  1075. var _this2 = this;
  1076. var req = this.request({
  1077. method: "POST",
  1078. data: data
  1079. });
  1080. req.on("success", fn);
  1081. req.on("error", function (xhrStatus, context) {
  1082. _this2.onError("xhr post error", xhrStatus, context);
  1083. });
  1084. }
  1085. /**
  1086. * Starts a poll cycle.
  1087. *
  1088. * @private
  1089. */;
  1090. _proto.doPoll = function doPoll() {
  1091. var _this3 = this;
  1092. var req = this.request();
  1093. req.on("data", this.onData.bind(this));
  1094. req.on("error", function (xhrStatus, context) {
  1095. _this3.onError("xhr poll error", xhrStatus, context);
  1096. });
  1097. this.pollXhr = req;
  1098. };
  1099. return BaseXHR;
  1100. }(Polling);
  1101. var Request = /*#__PURE__*/function (_Emitter) {
  1102. /**
  1103. * Request constructor
  1104. *
  1105. * @param {Object} options
  1106. * @package
  1107. */
  1108. function Request(createRequest, uri, opts) {
  1109. var _this4;
  1110. _this4 = _Emitter.call(this) || this;
  1111. _this4.createRequest = createRequest;
  1112. installTimerFunctions(_this4, opts);
  1113. _this4._opts = opts;
  1114. _this4._method = opts.method || "GET";
  1115. _this4._uri = uri;
  1116. _this4._data = undefined !== opts.data ? opts.data : null;
  1117. _this4._create();
  1118. return _this4;
  1119. }
  1120. /**
  1121. * Creates the XHR object and sends the request.
  1122. *
  1123. * @private
  1124. */
  1125. _inheritsLoose(Request, _Emitter);
  1126. var _proto2 = Request.prototype;
  1127. _proto2._create = function _create() {
  1128. var _this5 = this;
  1129. var _a;
  1130. var opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  1131. opts.xdomain = !!this._opts.xd;
  1132. var xhr = this._xhr = this.createRequest(opts);
  1133. try {
  1134. xhr.open(this._method, this._uri, true);
  1135. try {
  1136. if (this._opts.extraHeaders) {
  1137. // @ts-ignore
  1138. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  1139. for (var i in this._opts.extraHeaders) {
  1140. if (this._opts.extraHeaders.hasOwnProperty(i)) {
  1141. xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
  1142. }
  1143. }
  1144. }
  1145. } catch (e) {}
  1146. if ("POST" === this._method) {
  1147. try {
  1148. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  1149. } catch (e) {}
  1150. }
  1151. try {
  1152. xhr.setRequestHeader("Accept", "*/*");
  1153. } catch (e) {}
  1154. (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
  1155. // ie6 check
  1156. if ("withCredentials" in xhr) {
  1157. xhr.withCredentials = this._opts.withCredentials;
  1158. }
  1159. if (this._opts.requestTimeout) {
  1160. xhr.timeout = this._opts.requestTimeout;
  1161. }
  1162. xhr.onreadystatechange = function () {
  1163. var _a;
  1164. if (xhr.readyState === 3) {
  1165. (_a = _this5._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(
  1166. // @ts-ignore
  1167. xhr.getResponseHeader("set-cookie"));
  1168. }
  1169. if (4 !== xhr.readyState) return;
  1170. if (200 === xhr.status || 1223 === xhr.status) {
  1171. _this5._onLoad();
  1172. } else {
  1173. // make sure the `error` event handler that's user-set
  1174. // does not throw in the same tick and gets caught here
  1175. _this5.setTimeoutFn(function () {
  1176. _this5._onError(typeof xhr.status === "number" ? xhr.status : 0);
  1177. }, 0);
  1178. }
  1179. };
  1180. xhr.send(this._data);
  1181. } catch (e) {
  1182. // Need to defer since .create() is called directly from the constructor
  1183. // and thus the 'error' event can only be only bound *after* this exception
  1184. // occurs. Therefore, also, we cannot throw here at all.
  1185. this.setTimeoutFn(function () {
  1186. _this5._onError(e);
  1187. }, 0);
  1188. return;
  1189. }
  1190. if (typeof document !== "undefined") {
  1191. this._index = Request.requestsCount++;
  1192. Request.requests[this._index] = this;
  1193. }
  1194. }
  1195. /**
  1196. * Called upon error.
  1197. *
  1198. * @private
  1199. */;
  1200. _proto2._onError = function _onError(err) {
  1201. this.emitReserved("error", err, this._xhr);
  1202. this._cleanup(true);
  1203. }
  1204. /**
  1205. * Cleans up house.
  1206. *
  1207. * @private
  1208. */;
  1209. _proto2._cleanup = function _cleanup(fromError) {
  1210. if ("undefined" === typeof this._xhr || null === this._xhr) {
  1211. return;
  1212. }
  1213. this._xhr.onreadystatechange = empty;
  1214. if (fromError) {
  1215. try {
  1216. this._xhr.abort();
  1217. } catch (e) {}
  1218. }
  1219. if (typeof document !== "undefined") {
  1220. delete Request.requests[this._index];
  1221. }
  1222. this._xhr = null;
  1223. }
  1224. /**
  1225. * Called upon load.
  1226. *
  1227. * @private
  1228. */;
  1229. _proto2._onLoad = function _onLoad() {
  1230. var data = this._xhr.responseText;
  1231. if (data !== null) {
  1232. this.emitReserved("data", data);
  1233. this.emitReserved("success");
  1234. this._cleanup();
  1235. }
  1236. }
  1237. /**
  1238. * Aborts the request.
  1239. *
  1240. * @package
  1241. */;
  1242. _proto2.abort = function abort() {
  1243. this._cleanup();
  1244. };
  1245. return Request;
  1246. }(Emitter);
  1247. Request.requestsCount = 0;
  1248. Request.requests = {};
  1249. /**
  1250. * Aborts pending requests when unloading the window. This is needed to prevent
  1251. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1252. * emitted.
  1253. */
  1254. if (typeof document !== "undefined") {
  1255. // @ts-ignore
  1256. if (typeof attachEvent === "function") {
  1257. // @ts-ignore
  1258. attachEvent("onunload", unloadHandler);
  1259. } else if (typeof addEventListener === "function") {
  1260. var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
  1261. addEventListener(terminationEvent, unloadHandler, false);
  1262. }
  1263. }
  1264. function unloadHandler() {
  1265. for (var i in Request.requests) {
  1266. if (Request.requests.hasOwnProperty(i)) {
  1267. Request.requests[i].abort();
  1268. }
  1269. }
  1270. }
  1271. var hasXHR2 = function () {
  1272. var xhr = newRequest({
  1273. xdomain: false
  1274. });
  1275. return xhr && xhr.responseType !== null;
  1276. }();
  1277. /**
  1278. * HTTP long-polling based on the built-in `XMLHttpRequest` object.
  1279. *
  1280. * Usage: browser
  1281. *
  1282. * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  1283. */
  1284. var XHR = /*#__PURE__*/function (_BaseXHR) {
  1285. function XHR(opts) {
  1286. var _this6;
  1287. _this6 = _BaseXHR.call(this, opts) || this;
  1288. var forceBase64 = opts && opts.forceBase64;
  1289. _this6.supportsBinary = hasXHR2 && !forceBase64;
  1290. return _this6;
  1291. }
  1292. _inheritsLoose(XHR, _BaseXHR);
  1293. var _proto3 = XHR.prototype;
  1294. _proto3.request = function request() {
  1295. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1296. _extends(opts, {
  1297. xd: this.xd
  1298. }, this.opts);
  1299. return new Request(newRequest, this.uri(), opts);
  1300. };
  1301. return XHR;
  1302. }(BaseXHR);
  1303. function newRequest(opts) {
  1304. var xdomain = opts.xdomain;
  1305. // XMLHttpRequest can be disabled on IE
  1306. try {
  1307. if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  1308. return new XMLHttpRequest();
  1309. }
  1310. } catch (e) {}
  1311. if (!xdomain) {
  1312. try {
  1313. return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
  1314. } catch (e) {}
  1315. }
  1316. }
  1317. // detect ReactNative environment
  1318. var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
  1319. var BaseWS = /*#__PURE__*/function (_Transport) {
  1320. function BaseWS() {
  1321. return _Transport.apply(this, arguments) || this;
  1322. }
  1323. _inheritsLoose(BaseWS, _Transport);
  1324. var _proto = BaseWS.prototype;
  1325. _proto.doOpen = function doOpen() {
  1326. var uri = this.uri();
  1327. var protocols = this.opts.protocols;
  1328. // React Native only supports the 'headers' option, and will print a warning if anything else is passed
  1329. var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
  1330. if (this.opts.extraHeaders) {
  1331. opts.headers = this.opts.extraHeaders;
  1332. }
  1333. try {
  1334. this.ws = this.createSocket(uri, protocols, opts);
  1335. } catch (err) {
  1336. return this.emitReserved("error", err);
  1337. }
  1338. this.ws.binaryType = this.socket.binaryType;
  1339. this.addEventListeners();
  1340. }
  1341. /**
  1342. * Adds event listeners to the socket
  1343. *
  1344. * @private
  1345. */;
  1346. _proto.addEventListeners = function addEventListeners() {
  1347. var _this = this;
  1348. this.ws.onopen = function () {
  1349. if (_this.opts.autoUnref) {
  1350. _this.ws._socket.unref();
  1351. }
  1352. _this.onOpen();
  1353. };
  1354. this.ws.onclose = function (closeEvent) {
  1355. return _this.onClose({
  1356. description: "websocket connection closed",
  1357. context: closeEvent
  1358. });
  1359. };
  1360. this.ws.onmessage = function (ev) {
  1361. return _this.onData(ev.data);
  1362. };
  1363. this.ws.onerror = function (e) {
  1364. return _this.onError("websocket error", e);
  1365. };
  1366. };
  1367. _proto.write = function write(packets) {
  1368. var _this2 = this;
  1369. this.writable = false;
  1370. // encodePacket efficient as it uses WS framing
  1371. // no need for encodePayload
  1372. var _loop = function _loop() {
  1373. var packet = packets[i];
  1374. var lastPacket = i === packets.length - 1;
  1375. encodePacket(packet, _this2.supportsBinary, function (data) {
  1376. // Sometimes the websocket has already been closed but the browser didn't
  1377. // have a chance of informing us about it yet, in that case send will
  1378. // throw an error
  1379. try {
  1380. _this2.doWrite(packet, data);
  1381. } catch (e) {}
  1382. if (lastPacket) {
  1383. // fake drain
  1384. // defer to next tick to allow Socket to clear writeBuffer
  1385. nextTick(function () {
  1386. _this2.writable = true;
  1387. _this2.emitReserved("drain");
  1388. }, _this2.setTimeoutFn);
  1389. }
  1390. });
  1391. };
  1392. for (var i = 0; i < packets.length; i++) {
  1393. _loop();
  1394. }
  1395. };
  1396. _proto.doClose = function doClose() {
  1397. if (typeof this.ws !== "undefined") {
  1398. this.ws.close();
  1399. this.ws = null;
  1400. }
  1401. }
  1402. /**
  1403. * Generates uri for connection.
  1404. *
  1405. * @private
  1406. */;
  1407. _proto.uri = function uri() {
  1408. var schema = this.opts.secure ? "wss" : "ws";
  1409. var query = this.query || {};
  1410. // append timestamp to URI
  1411. if (this.opts.timestampRequests) {
  1412. query[this.opts.timestampParam] = randomString();
  1413. }
  1414. // communicate binary support capabilities
  1415. if (!this.supportsBinary) {
  1416. query.b64 = 1;
  1417. }
  1418. return this.createUri(schema, query);
  1419. };
  1420. return _createClass(BaseWS, [{
  1421. key: "name",
  1422. get: function get() {
  1423. return "websocket";
  1424. }
  1425. }]);
  1426. }(Transport);
  1427. var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
  1428. /**
  1429. * WebSocket transport based on the built-in `WebSocket` object.
  1430. *
  1431. * Usage: browser, Node.js (since v21), Deno, Bun
  1432. *
  1433. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
  1434. * @see https://caniuse.com/mdn-api_websocket
  1435. * @see https://nodejs.org/api/globals.html#websocket
  1436. */
  1437. var WS = /*#__PURE__*/function (_BaseWS) {
  1438. function WS() {
  1439. return _BaseWS.apply(this, arguments) || this;
  1440. }
  1441. _inheritsLoose(WS, _BaseWS);
  1442. var _proto2 = WS.prototype;
  1443. _proto2.createSocket = function createSocket(uri, protocols, opts) {
  1444. return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
  1445. };
  1446. _proto2.doWrite = function doWrite(_packet, data) {
  1447. this.ws.send(data);
  1448. };
  1449. return WS;
  1450. }(BaseWS);
  1451. /**
  1452. * WebTransport transport based on the built-in `WebTransport` object.
  1453. *
  1454. * Usage: browser, Node.js (with the `@fails-components/webtransport` package)
  1455. *
  1456. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
  1457. * @see https://caniuse.com/webtransport
  1458. */
  1459. var WT = /*#__PURE__*/function (_Transport) {
  1460. function WT() {
  1461. return _Transport.apply(this, arguments) || this;
  1462. }
  1463. _inheritsLoose(WT, _Transport);
  1464. var _proto = WT.prototype;
  1465. _proto.doOpen = function doOpen() {
  1466. var _this = this;
  1467. try {
  1468. // @ts-ignore
  1469. this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
  1470. } catch (err) {
  1471. return this.emitReserved("error", err);
  1472. }
  1473. this._transport.closed.then(function () {
  1474. _this.onClose();
  1475. })["catch"](function (err) {
  1476. _this.onError("webtransport error", err);
  1477. });
  1478. // note: we could have used async/await, but that would require some additional polyfills
  1479. this._transport.ready.then(function () {
  1480. _this._transport.createBidirectionalStream().then(function (stream) {
  1481. var decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, _this.socket.binaryType);
  1482. var reader = stream.readable.pipeThrough(decoderStream).getReader();
  1483. var encoderStream = createPacketEncoderStream();
  1484. encoderStream.readable.pipeTo(stream.writable);
  1485. _this._writer = encoderStream.writable.getWriter();
  1486. var read = function read() {
  1487. reader.read().then(function (_ref) {
  1488. var done = _ref.done,
  1489. value = _ref.value;
  1490. if (done) {
  1491. return;
  1492. }
  1493. _this.onPacket(value);
  1494. read();
  1495. })["catch"](function (err) {});
  1496. };
  1497. read();
  1498. var packet = {
  1499. type: "open"
  1500. };
  1501. if (_this.query.sid) {
  1502. packet.data = "{\"sid\":\"".concat(_this.query.sid, "\"}");
  1503. }
  1504. _this._writer.write(packet).then(function () {
  1505. return _this.onOpen();
  1506. });
  1507. });
  1508. });
  1509. };
  1510. _proto.write = function write(packets) {
  1511. var _this2 = this;
  1512. this.writable = false;
  1513. var _loop = function _loop() {
  1514. var packet = packets[i];
  1515. var lastPacket = i === packets.length - 1;
  1516. _this2._writer.write(packet).then(function () {
  1517. if (lastPacket) {
  1518. nextTick(function () {
  1519. _this2.writable = true;
  1520. _this2.emitReserved("drain");
  1521. }, _this2.setTimeoutFn);
  1522. }
  1523. });
  1524. };
  1525. for (var i = 0; i < packets.length; i++) {
  1526. _loop();
  1527. }
  1528. };
  1529. _proto.doClose = function doClose() {
  1530. var _a;
  1531. (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
  1532. };
  1533. return _createClass(WT, [{
  1534. key: "name",
  1535. get: function get() {
  1536. return "webtransport";
  1537. }
  1538. }]);
  1539. }(Transport);
  1540. var transports = {
  1541. websocket: WS,
  1542. webtransport: WT,
  1543. polling: XHR
  1544. };
  1545. // imported from https://github.com/galkn/parseuri
  1546. /**
  1547. * Parses a URI
  1548. *
  1549. * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
  1550. *
  1551. * See:
  1552. * - https://developer.mozilla.org/en-US/docs/Web/API/URL
  1553. * - https://caniuse.com/url
  1554. * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
  1555. *
  1556. * History of the parse() method:
  1557. * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
  1558. * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
  1559. * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
  1560. *
  1561. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  1562. * @api private
  1563. */
  1564. var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  1565. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
  1566. function parse(str) {
  1567. if (str.length > 8000) {
  1568. throw "URI too long";
  1569. }
  1570. var src = str,
  1571. b = str.indexOf('['),
  1572. e = str.indexOf(']');
  1573. if (b != -1 && e != -1) {
  1574. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  1575. }
  1576. var m = re.exec(str || ''),
  1577. uri = {},
  1578. i = 14;
  1579. while (i--) {
  1580. uri[parts[i]] = m[i] || '';
  1581. }
  1582. if (b != -1 && e != -1) {
  1583. uri.source = src;
  1584. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  1585. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  1586. uri.ipv6uri = true;
  1587. }
  1588. uri.pathNames = pathNames(uri, uri['path']);
  1589. uri.queryKey = queryKey(uri, uri['query']);
  1590. return uri;
  1591. }
  1592. function pathNames(obj, path) {
  1593. var regx = /\/{2,9}/g,
  1594. names = path.replace(regx, "/").split("/");
  1595. if (path.slice(0, 1) == '/' || path.length === 0) {
  1596. names.splice(0, 1);
  1597. }
  1598. if (path.slice(-1) == '/') {
  1599. names.splice(names.length - 1, 1);
  1600. }
  1601. return names;
  1602. }
  1603. function queryKey(uri, query) {
  1604. var data = {};
  1605. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  1606. if ($1) {
  1607. data[$1] = $2;
  1608. }
  1609. });
  1610. return data;
  1611. }
  1612. var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
  1613. var OFFLINE_EVENT_LISTENERS = [];
  1614. if (withEventListeners) {
  1615. // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the
  1616. // script, so we create one single event listener here which will forward the event to the socket instances
  1617. addEventListener("offline", function () {
  1618. OFFLINE_EVENT_LISTENERS.forEach(function (listener) {
  1619. return listener();
  1620. });
  1621. }, false);
  1622. }
  1623. /**
  1624. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  1625. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  1626. *
  1627. * This class comes without upgrade mechanism, which means that it will keep the first low-level transport that
  1628. * successfully establishes the connection.
  1629. *
  1630. * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
  1631. *
  1632. * @example
  1633. * import { SocketWithoutUpgrade, WebSocket } from "engine.io-client";
  1634. *
  1635. * const socket = new SocketWithoutUpgrade({
  1636. * transports: [WebSocket]
  1637. * });
  1638. *
  1639. * socket.on("open", () => {
  1640. * socket.send("hello");
  1641. * });
  1642. *
  1643. * @see SocketWithUpgrade
  1644. * @see Socket
  1645. */
  1646. var SocketWithoutUpgrade = /*#__PURE__*/function (_Emitter) {
  1647. /**
  1648. * Socket constructor.
  1649. *
  1650. * @param {String|Object} uri - uri or options
  1651. * @param {Object} opts - options
  1652. */
  1653. function SocketWithoutUpgrade(uri, opts) {
  1654. var _this;
  1655. _this = _Emitter.call(this) || this;
  1656. _this.binaryType = defaultBinaryType;
  1657. _this.writeBuffer = [];
  1658. _this._prevBufferLen = 0;
  1659. _this._pingInterval = -1;
  1660. _this._pingTimeout = -1;
  1661. _this._maxPayload = -1;
  1662. /**
  1663. * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the
  1664. * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.
  1665. */
  1666. _this._pingTimeoutTime = Infinity;
  1667. if (uri && "object" === _typeof(uri)) {
  1668. opts = uri;
  1669. uri = null;
  1670. }
  1671. if (uri) {
  1672. var parsedUri = parse(uri);
  1673. opts.hostname = parsedUri.host;
  1674. opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
  1675. opts.port = parsedUri.port;
  1676. if (parsedUri.query) opts.query = parsedUri.query;
  1677. } else if (opts.host) {
  1678. opts.hostname = parse(opts.host).host;
  1679. }
  1680. installTimerFunctions(_this, opts);
  1681. _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
  1682. if (opts.hostname && !opts.port) {
  1683. // if no port is specified manually, use the protocol default
  1684. opts.port = _this.secure ? "443" : "80";
  1685. }
  1686. _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
  1687. _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
  1688. _this.transports = [];
  1689. _this._transportsByName = {};
  1690. opts.transports.forEach(function (t) {
  1691. var transportName = t.prototype.name;
  1692. _this.transports.push(transportName);
  1693. _this._transportsByName[transportName] = t;
  1694. });
  1695. _this.opts = _extends({
  1696. path: "/engine.io",
  1697. agent: false,
  1698. withCredentials: false,
  1699. upgrade: true,
  1700. timestampParam: "t",
  1701. rememberUpgrade: false,
  1702. addTrailingSlash: true,
  1703. rejectUnauthorized: true,
  1704. perMessageDeflate: {
  1705. threshold: 1024
  1706. },
  1707. transportOptions: {},
  1708. closeOnBeforeunload: false
  1709. }, opts);
  1710. _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : "");
  1711. if (typeof _this.opts.query === "string") {
  1712. _this.opts.query = decode(_this.opts.query);
  1713. }
  1714. if (withEventListeners) {
  1715. if (_this.opts.closeOnBeforeunload) {
  1716. // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
  1717. // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
  1718. // closed/reloaded)
  1719. _this._beforeunloadEventListener = function () {
  1720. if (_this.transport) {
  1721. // silently close the transport
  1722. _this.transport.removeAllListeners();
  1723. _this.transport.close();
  1724. }
  1725. };
  1726. addEventListener("beforeunload", _this._beforeunloadEventListener, false);
  1727. }
  1728. if (_this.hostname !== "localhost") {
  1729. _this._offlineEventListener = function () {
  1730. _this._onClose("transport close", {
  1731. description: "network connection lost"
  1732. });
  1733. };
  1734. OFFLINE_EVENT_LISTENERS.push(_this._offlineEventListener);
  1735. }
  1736. }
  1737. if (_this.opts.withCredentials) {
  1738. _this._cookieJar = createCookieJar();
  1739. }
  1740. _this._open();
  1741. return _this;
  1742. }
  1743. /**
  1744. * Creates transport of the given type.
  1745. *
  1746. * @param {String} name - transport name
  1747. * @return {Transport}
  1748. * @private
  1749. */
  1750. _inheritsLoose(SocketWithoutUpgrade, _Emitter);
  1751. var _proto = SocketWithoutUpgrade.prototype;
  1752. _proto.createTransport = function createTransport(name) {
  1753. var query = _extends({}, this.opts.query);
  1754. // append engine.io protocol identifier
  1755. query.EIO = protocol$1;
  1756. // transport name
  1757. query.transport = name;
  1758. // session id if we already have one
  1759. if (this.id) query.sid = this.id;
  1760. var opts = _extends({}, this.opts, {
  1761. query: query,
  1762. socket: this,
  1763. hostname: this.hostname,
  1764. secure: this.secure,
  1765. port: this.port
  1766. }, this.opts.transportOptions[name]);
  1767. return new this._transportsByName[name](opts);
  1768. }
  1769. /**
  1770. * Initializes transport to use and starts probe.
  1771. *
  1772. * @private
  1773. */;
  1774. _proto._open = function _open() {
  1775. var _this2 = this;
  1776. if (this.transports.length === 0) {
  1777. // Emit error on next tick so it can be listened to
  1778. this.setTimeoutFn(function () {
  1779. _this2.emitReserved("error", "No transports available");
  1780. }, 0);
  1781. return;
  1782. }
  1783. var transportName = this.opts.rememberUpgrade && SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
  1784. this.readyState = "opening";
  1785. var transport = this.createTransport(transportName);
  1786. transport.open();
  1787. this.setTransport(transport);
  1788. }
  1789. /**
  1790. * Sets the current transport. Disables the existing one (if any).
  1791. *
  1792. * @private
  1793. */;
  1794. _proto.setTransport = function setTransport(transport) {
  1795. var _this3 = this;
  1796. if (this.transport) {
  1797. this.transport.removeAllListeners();
  1798. }
  1799. // set up transport
  1800. this.transport = transport;
  1801. // set up transport listeners
  1802. transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", function (reason) {
  1803. return _this3._onClose("transport close", reason);
  1804. });
  1805. }
  1806. /**
  1807. * Called when connection is deemed open.
  1808. *
  1809. * @private
  1810. */;
  1811. _proto.onOpen = function onOpen() {
  1812. this.readyState = "open";
  1813. SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
  1814. this.emitReserved("open");
  1815. this.flush();
  1816. }
  1817. /**
  1818. * Handles a packet.
  1819. *
  1820. * @private
  1821. */;
  1822. _proto._onPacket = function _onPacket(packet) {
  1823. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  1824. this.emitReserved("packet", packet);
  1825. // Socket is live - any packet counts
  1826. this.emitReserved("heartbeat");
  1827. switch (packet.type) {
  1828. case "open":
  1829. this.onHandshake(JSON.parse(packet.data));
  1830. break;
  1831. case "ping":
  1832. this._sendPacket("pong");
  1833. this.emitReserved("ping");
  1834. this.emitReserved("pong");
  1835. this._resetPingTimeout();
  1836. break;
  1837. case "error":
  1838. var err = new Error("server error");
  1839. // @ts-ignore
  1840. err.code = packet.data;
  1841. this._onError(err);
  1842. break;
  1843. case "message":
  1844. this.emitReserved("data", packet.data);
  1845. this.emitReserved("message", packet.data);
  1846. break;
  1847. }
  1848. }
  1849. }
  1850. /**
  1851. * Called upon handshake completion.
  1852. *
  1853. * @param {Object} data - handshake obj
  1854. * @private
  1855. */;
  1856. _proto.onHandshake = function onHandshake(data) {
  1857. this.emitReserved("handshake", data);
  1858. this.id = data.sid;
  1859. this.transport.query.sid = data.sid;
  1860. this._pingInterval = data.pingInterval;
  1861. this._pingTimeout = data.pingTimeout;
  1862. this._maxPayload = data.maxPayload;
  1863. this.onOpen();
  1864. // In case open handler closes socket
  1865. if ("closed" === this.readyState) return;
  1866. this._resetPingTimeout();
  1867. }
  1868. /**
  1869. * Sets and resets ping timeout timer based on server pings.
  1870. *
  1871. * @private
  1872. */;
  1873. _proto._resetPingTimeout = function _resetPingTimeout() {
  1874. var _this4 = this;
  1875. this.clearTimeoutFn(this._pingTimeoutTimer);
  1876. var delay = this._pingInterval + this._pingTimeout;
  1877. this._pingTimeoutTime = Date.now() + delay;
  1878. this._pingTimeoutTimer = this.setTimeoutFn(function () {
  1879. _this4._onClose("ping timeout");
  1880. }, delay);
  1881. if (this.opts.autoUnref) {
  1882. this._pingTimeoutTimer.unref();
  1883. }
  1884. }
  1885. /**
  1886. * Called on `drain` event
  1887. *
  1888. * @private
  1889. */;
  1890. _proto._onDrain = function _onDrain() {
  1891. this.writeBuffer.splice(0, this._prevBufferLen);
  1892. // setting prevBufferLen = 0 is very important
  1893. // for example, when upgrading, upgrade packet is sent over,
  1894. // and a nonzero prevBufferLen could cause problems on `drain`
  1895. this._prevBufferLen = 0;
  1896. if (0 === this.writeBuffer.length) {
  1897. this.emitReserved("drain");
  1898. } else {
  1899. this.flush();
  1900. }
  1901. }
  1902. /**
  1903. * Flush write buffers.
  1904. *
  1905. * @private
  1906. */;
  1907. _proto.flush = function flush() {
  1908. if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
  1909. var packets = this._getWritablePackets();
  1910. this.transport.send(packets);
  1911. // keep track of current length of writeBuffer
  1912. // splice writeBuffer and callbackBuffer on `drain`
  1913. this._prevBufferLen = packets.length;
  1914. this.emitReserved("flush");
  1915. }
  1916. }
  1917. /**
  1918. * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
  1919. * long-polling)
  1920. *
  1921. * @private
  1922. */;
  1923. _proto._getWritablePackets = function _getWritablePackets() {
  1924. var shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
  1925. if (!shouldCheckPayloadSize) {
  1926. return this.writeBuffer;
  1927. }
  1928. var payloadSize = 1; // first packet type
  1929. for (var i = 0; i < this.writeBuffer.length; i++) {
  1930. var data = this.writeBuffer[i].data;
  1931. if (data) {
  1932. payloadSize += byteLength(data);
  1933. }
  1934. if (i > 0 && payloadSize > this._maxPayload) {
  1935. return this.writeBuffer.slice(0, i);
  1936. }
  1937. payloadSize += 2; // separator + packet type
  1938. }
  1939. return this.writeBuffer;
  1940. }
  1941. /**
  1942. * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
  1943. *
  1944. * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
  1945. * `write()` method then the message would not be buffered by the Socket.IO client.
  1946. *
  1947. * @return {boolean}
  1948. * @private
  1949. */
  1950. /* private */;
  1951. _proto._hasPingExpired = function _hasPingExpired() {
  1952. var _this5 = this;
  1953. if (!this._pingTimeoutTime) return true;
  1954. var hasExpired = Date.now() > this._pingTimeoutTime;
  1955. if (hasExpired) {
  1956. this._pingTimeoutTime = 0;
  1957. nextTick(function () {
  1958. _this5._onClose("ping timeout");
  1959. }, this.setTimeoutFn);
  1960. }
  1961. return hasExpired;
  1962. }
  1963. /**
  1964. * Sends a message.
  1965. *
  1966. * @param {String} msg - message.
  1967. * @param {Object} options.
  1968. * @param {Function} fn - callback function.
  1969. * @return {Socket} for chaining.
  1970. */;
  1971. _proto.write = function write(msg, options, fn) {
  1972. this._sendPacket("message", msg, options, fn);
  1973. return this;
  1974. }
  1975. /**
  1976. * Sends a message. Alias of {@link Socket#write}.
  1977. *
  1978. * @param {String} msg - message.
  1979. * @param {Object} options.
  1980. * @param {Function} fn - callback function.
  1981. * @return {Socket} for chaining.
  1982. */;
  1983. _proto.send = function send(msg, options, fn) {
  1984. this._sendPacket("message", msg, options, fn);
  1985. return this;
  1986. }
  1987. /**
  1988. * Sends a packet.
  1989. *
  1990. * @param {String} type: packet type.
  1991. * @param {String} data.
  1992. * @param {Object} options.
  1993. * @param {Function} fn - callback function.
  1994. * @private
  1995. */;
  1996. _proto._sendPacket = function _sendPacket(type, data, options, fn) {
  1997. if ("function" === typeof data) {
  1998. fn = data;
  1999. data = undefined;
  2000. }
  2001. if ("function" === typeof options) {
  2002. fn = options;
  2003. options = null;
  2004. }
  2005. if ("closing" === this.readyState || "closed" === this.readyState) {
  2006. return;
  2007. }
  2008. options = options || {};
  2009. options.compress = false !== options.compress;
  2010. var packet = {
  2011. type: type,
  2012. data: data,
  2013. options: options
  2014. };
  2015. this.emitReserved("packetCreate", packet);
  2016. this.writeBuffer.push(packet);
  2017. if (fn) this.once("flush", fn);
  2018. this.flush();
  2019. }
  2020. /**
  2021. * Closes the connection.
  2022. */;
  2023. _proto.close = function close() {
  2024. var _this6 = this;
  2025. var close = function close() {
  2026. _this6._onClose("forced close");
  2027. _this6.transport.close();
  2028. };
  2029. var cleanupAndClose = function cleanupAndClose() {
  2030. _this6.off("upgrade", cleanupAndClose);
  2031. _this6.off("upgradeError", cleanupAndClose);
  2032. close();
  2033. };
  2034. var waitForUpgrade = function waitForUpgrade() {
  2035. // wait for upgrade to finish since we can't send packets while pausing a transport
  2036. _this6.once("upgrade", cleanupAndClose);
  2037. _this6.once("upgradeError", cleanupAndClose);
  2038. };
  2039. if ("opening" === this.readyState || "open" === this.readyState) {
  2040. this.readyState = "closing";
  2041. if (this.writeBuffer.length) {
  2042. this.once("drain", function () {
  2043. if (_this6.upgrading) {
  2044. waitForUpgrade();
  2045. } else {
  2046. close();
  2047. }
  2048. });
  2049. } else if (this.upgrading) {
  2050. waitForUpgrade();
  2051. } else {
  2052. close();
  2053. }
  2054. }
  2055. return this;
  2056. }
  2057. /**
  2058. * Called upon transport error
  2059. *
  2060. * @private
  2061. */;
  2062. _proto._onError = function _onError(err) {
  2063. SocketWithoutUpgrade.priorWebsocketSuccess = false;
  2064. if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
  2065. this.transports.shift();
  2066. return this._open();
  2067. }
  2068. this.emitReserved("error", err);
  2069. this._onClose("transport error", err);
  2070. }
  2071. /**
  2072. * Called upon transport close.
  2073. *
  2074. * @private
  2075. */;
  2076. _proto._onClose = function _onClose(reason, description) {
  2077. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  2078. // clear timers
  2079. this.clearTimeoutFn(this._pingTimeoutTimer);
  2080. // stop event from firing again for transport
  2081. this.transport.removeAllListeners("close");
  2082. // ensure transport won't stay open
  2083. this.transport.close();
  2084. // ignore further transport communication
  2085. this.transport.removeAllListeners();
  2086. if (withEventListeners) {
  2087. if (this._beforeunloadEventListener) {
  2088. removeEventListener("beforeunload", this._beforeunloadEventListener, false);
  2089. }
  2090. if (this._offlineEventListener) {
  2091. var i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
  2092. if (i !== -1) {
  2093. OFFLINE_EVENT_LISTENERS.splice(i, 1);
  2094. }
  2095. }
  2096. }
  2097. // set ready state
  2098. this.readyState = "closed";
  2099. // clear session id
  2100. this.id = null;
  2101. // emit close event
  2102. this.emitReserved("close", reason, description);
  2103. // clean buffers after, so users can still
  2104. // grab the buffers on `close` event
  2105. this.writeBuffer = [];
  2106. this._prevBufferLen = 0;
  2107. }
  2108. };
  2109. return SocketWithoutUpgrade;
  2110. }(Emitter);
  2111. SocketWithoutUpgrade.protocol = protocol$1;
  2112. /**
  2113. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2114. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2115. *
  2116. * This class comes with an upgrade mechanism, which means that once the connection is established with the first
  2117. * low-level transport, it will try to upgrade to a better transport.
  2118. *
  2119. * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
  2120. *
  2121. * @example
  2122. * import { SocketWithUpgrade, WebSocket } from "engine.io-client";
  2123. *
  2124. * const socket = new SocketWithUpgrade({
  2125. * transports: [WebSocket]
  2126. * });
  2127. *
  2128. * socket.on("open", () => {
  2129. * socket.send("hello");
  2130. * });
  2131. *
  2132. * @see SocketWithoutUpgrade
  2133. * @see Socket
  2134. */
  2135. var SocketWithUpgrade = /*#__PURE__*/function (_SocketWithoutUpgrade) {
  2136. function SocketWithUpgrade() {
  2137. var _this7;
  2138. _this7 = _SocketWithoutUpgrade.apply(this, arguments) || this;
  2139. _this7._upgrades = [];
  2140. return _this7;
  2141. }
  2142. _inheritsLoose(SocketWithUpgrade, _SocketWithoutUpgrade);
  2143. var _proto2 = SocketWithUpgrade.prototype;
  2144. _proto2.onOpen = function onOpen() {
  2145. _SocketWithoutUpgrade.prototype.onOpen.call(this);
  2146. if ("open" === this.readyState && this.opts.upgrade) {
  2147. for (var i = 0; i < this._upgrades.length; i++) {
  2148. this._probe(this._upgrades[i]);
  2149. }
  2150. }
  2151. }
  2152. /**
  2153. * Probes a transport.
  2154. *
  2155. * @param {String} name - transport name
  2156. * @private
  2157. */;
  2158. _proto2._probe = function _probe(name) {
  2159. var _this8 = this;
  2160. var transport = this.createTransport(name);
  2161. var failed = false;
  2162. SocketWithoutUpgrade.priorWebsocketSuccess = false;
  2163. var onTransportOpen = function onTransportOpen() {
  2164. if (failed) return;
  2165. transport.send([{
  2166. type: "ping",
  2167. data: "probe"
  2168. }]);
  2169. transport.once("packet", function (msg) {
  2170. if (failed) return;
  2171. if ("pong" === msg.type && "probe" === msg.data) {
  2172. _this8.upgrading = true;
  2173. _this8.emitReserved("upgrading", transport);
  2174. if (!transport) return;
  2175. SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
  2176. _this8.transport.pause(function () {
  2177. if (failed) return;
  2178. if ("closed" === _this8.readyState) return;
  2179. cleanup();
  2180. _this8.setTransport(transport);
  2181. transport.send([{
  2182. type: "upgrade"
  2183. }]);
  2184. _this8.emitReserved("upgrade", transport);
  2185. transport = null;
  2186. _this8.upgrading = false;
  2187. _this8.flush();
  2188. });
  2189. } else {
  2190. var err = new Error("probe error");
  2191. // @ts-ignore
  2192. err.transport = transport.name;
  2193. _this8.emitReserved("upgradeError", err);
  2194. }
  2195. });
  2196. };
  2197. function freezeTransport() {
  2198. if (failed) return;
  2199. // Any callback called by transport should be ignored since now
  2200. failed = true;
  2201. cleanup();
  2202. transport.close();
  2203. transport = null;
  2204. }
  2205. // Handle any error that happens while probing
  2206. var onerror = function onerror(err) {
  2207. var error = new Error("probe error: " + err);
  2208. // @ts-ignore
  2209. error.transport = transport.name;
  2210. freezeTransport();
  2211. _this8.emitReserved("upgradeError", error);
  2212. };
  2213. function onTransportClose() {
  2214. onerror("transport closed");
  2215. }
  2216. // When the socket is closed while we're probing
  2217. function onclose() {
  2218. onerror("socket closed");
  2219. }
  2220. // When the socket is upgraded while we're probing
  2221. function onupgrade(to) {
  2222. if (transport && to.name !== transport.name) {
  2223. freezeTransport();
  2224. }
  2225. }
  2226. // Remove all listeners on the transport and on self
  2227. var cleanup = function cleanup() {
  2228. transport.removeListener("open", onTransportOpen);
  2229. transport.removeListener("error", onerror);
  2230. transport.removeListener("close", onTransportClose);
  2231. _this8.off("close", onclose);
  2232. _this8.off("upgrading", onupgrade);
  2233. };
  2234. transport.once("open", onTransportOpen);
  2235. transport.once("error", onerror);
  2236. transport.once("close", onTransportClose);
  2237. this.once("close", onclose);
  2238. this.once("upgrading", onupgrade);
  2239. if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
  2240. // favor WebTransport
  2241. this.setTimeoutFn(function () {
  2242. if (!failed) {
  2243. transport.open();
  2244. }
  2245. }, 200);
  2246. } else {
  2247. transport.open();
  2248. }
  2249. };
  2250. _proto2.onHandshake = function onHandshake(data) {
  2251. this._upgrades = this._filterUpgrades(data.upgrades);
  2252. _SocketWithoutUpgrade.prototype.onHandshake.call(this, data);
  2253. }
  2254. /**
  2255. * Filters upgrades, returning only those matching client transports.
  2256. *
  2257. * @param {Array} upgrades - server upgrades
  2258. * @private
  2259. */;
  2260. _proto2._filterUpgrades = function _filterUpgrades(upgrades) {
  2261. var filteredUpgrades = [];
  2262. for (var i = 0; i < upgrades.length; i++) {
  2263. if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
  2264. }
  2265. return filteredUpgrades;
  2266. };
  2267. return SocketWithUpgrade;
  2268. }(SocketWithoutUpgrade);
  2269. /**
  2270. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2271. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2272. *
  2273. * This class comes with an upgrade mechanism, which means that once the connection is established with the first
  2274. * low-level transport, it will try to upgrade to a better transport.
  2275. *
  2276. * @example
  2277. * import { Socket } from "engine.io-client";
  2278. *
  2279. * const socket = new Socket();
  2280. *
  2281. * socket.on("open", () => {
  2282. * socket.send("hello");
  2283. * });
  2284. *
  2285. * @see SocketWithoutUpgrade
  2286. * @see SocketWithUpgrade
  2287. */
  2288. var Socket$1 = /*#__PURE__*/function (_SocketWithUpgrade) {
  2289. function Socket(uri) {
  2290. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2291. var o = _typeof(uri) === "object" ? uri : opts;
  2292. if (!o.transports || o.transports && typeof o.transports[0] === "string") {
  2293. o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map(function (transportName) {
  2294. return transports[transportName];
  2295. }).filter(function (t) {
  2296. return !!t;
  2297. });
  2298. }
  2299. return _SocketWithUpgrade.call(this, uri, o) || this;
  2300. }
  2301. _inheritsLoose(Socket, _SocketWithUpgrade);
  2302. return Socket;
  2303. }(SocketWithUpgrade);
  2304. Socket$1.protocol;
  2305. function getDefaultExportFromCjs (x) {
  2306. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2307. }
  2308. var browser = {exports: {}};
  2309. var ms;
  2310. var hasRequiredMs;
  2311. function requireMs() {
  2312. if (hasRequiredMs) return ms;
  2313. hasRequiredMs = 1;
  2314. var s = 1000;
  2315. var m = s * 60;
  2316. var h = m * 60;
  2317. var d = h * 24;
  2318. var w = d * 7;
  2319. var y = d * 365.25;
  2320. /**
  2321. * Parse or format the given `val`.
  2322. *
  2323. * Options:
  2324. *
  2325. * - `long` verbose formatting [false]
  2326. *
  2327. * @param {String|Number} val
  2328. * @param {Object} [options]
  2329. * @throws {Error} throw an error if val is not a non-empty string or a number
  2330. * @return {String|Number}
  2331. * @api public
  2332. */
  2333. ms = function ms(val, options) {
  2334. options = options || {};
  2335. var type = _typeof(val);
  2336. if (type === 'string' && val.length > 0) {
  2337. return parse(val);
  2338. } else if (type === 'number' && isFinite(val)) {
  2339. return options["long"] ? fmtLong(val) : fmtShort(val);
  2340. }
  2341. throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
  2342. };
  2343. /**
  2344. * Parse the given `str` and return milliseconds.
  2345. *
  2346. * @param {String} str
  2347. * @return {Number}
  2348. * @api private
  2349. */
  2350. function parse(str) {
  2351. str = String(str);
  2352. if (str.length > 100) {
  2353. return;
  2354. }
  2355. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
  2356. if (!match) {
  2357. return;
  2358. }
  2359. var n = parseFloat(match[1]);
  2360. var type = (match[2] || 'ms').toLowerCase();
  2361. switch (type) {
  2362. case 'years':
  2363. case 'year':
  2364. case 'yrs':
  2365. case 'yr':
  2366. case 'y':
  2367. return n * y;
  2368. case 'weeks':
  2369. case 'week':
  2370. case 'w':
  2371. return n * w;
  2372. case 'days':
  2373. case 'day':
  2374. case 'd':
  2375. return n * d;
  2376. case 'hours':
  2377. case 'hour':
  2378. case 'hrs':
  2379. case 'hr':
  2380. case 'h':
  2381. return n * h;
  2382. case 'minutes':
  2383. case 'minute':
  2384. case 'mins':
  2385. case 'min':
  2386. case 'm':
  2387. return n * m;
  2388. case 'seconds':
  2389. case 'second':
  2390. case 'secs':
  2391. case 'sec':
  2392. case 's':
  2393. return n * s;
  2394. case 'milliseconds':
  2395. case 'millisecond':
  2396. case 'msecs':
  2397. case 'msec':
  2398. case 'ms':
  2399. return n;
  2400. default:
  2401. return undefined;
  2402. }
  2403. }
  2404. /**
  2405. * Short format for `ms`.
  2406. *
  2407. * @param {Number} ms
  2408. * @return {String}
  2409. * @api private
  2410. */
  2411. function fmtShort(ms) {
  2412. var msAbs = Math.abs(ms);
  2413. if (msAbs >= d) {
  2414. return Math.round(ms / d) + 'd';
  2415. }
  2416. if (msAbs >= h) {
  2417. return Math.round(ms / h) + 'h';
  2418. }
  2419. if (msAbs >= m) {
  2420. return Math.round(ms / m) + 'm';
  2421. }
  2422. if (msAbs >= s) {
  2423. return Math.round(ms / s) + 's';
  2424. }
  2425. return ms + 'ms';
  2426. }
  2427. /**
  2428. * Long format for `ms`.
  2429. *
  2430. * @param {Number} ms
  2431. * @return {String}
  2432. * @api private
  2433. */
  2434. function fmtLong(ms) {
  2435. var msAbs = Math.abs(ms);
  2436. if (msAbs >= d) {
  2437. return plural(ms, msAbs, d, 'day');
  2438. }
  2439. if (msAbs >= h) {
  2440. return plural(ms, msAbs, h, 'hour');
  2441. }
  2442. if (msAbs >= m) {
  2443. return plural(ms, msAbs, m, 'minute');
  2444. }
  2445. if (msAbs >= s) {
  2446. return plural(ms, msAbs, s, 'second');
  2447. }
  2448. return ms + ' ms';
  2449. }
  2450. /**
  2451. * Pluralization helper.
  2452. */
  2453. function plural(ms, msAbs, n, name) {
  2454. var isPlural = msAbs >= n * 1.5;
  2455. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  2456. }
  2457. return ms;
  2458. }
  2459. /**
  2460. * This is the common logic for both the Node.js and web browser
  2461. * implementations of `debug()`.
  2462. */
  2463. function setup(env) {
  2464. createDebug.debug = createDebug;
  2465. createDebug["default"] = createDebug;
  2466. createDebug.coerce = coerce;
  2467. createDebug.disable = disable;
  2468. createDebug.enable = enable;
  2469. createDebug.enabled = enabled;
  2470. createDebug.humanize = requireMs();
  2471. createDebug.destroy = destroy;
  2472. Object.keys(env).forEach(function (key) {
  2473. createDebug[key] = env[key];
  2474. });
  2475. /**
  2476. * The currently active debug mode names, and names to skip.
  2477. */
  2478. createDebug.names = [];
  2479. createDebug.skips = [];
  2480. /**
  2481. * Map of special "%n" handling functions, for the debug "format" argument.
  2482. *
  2483. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  2484. */
  2485. createDebug.formatters = {};
  2486. /**
  2487. * Selects a color for a debug namespace
  2488. * @param {String} namespace The namespace string for the debug instance to be colored
  2489. * @return {Number|String} An ANSI color code for the given namespace
  2490. * @api private
  2491. */
  2492. function selectColor(namespace) {
  2493. var hash = 0;
  2494. for (var i = 0; i < namespace.length; i++) {
  2495. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  2496. hash |= 0; // Convert to 32bit integer
  2497. }
  2498. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  2499. }
  2500. createDebug.selectColor = selectColor;
  2501. /**
  2502. * Create a debugger with the given `namespace`.
  2503. *
  2504. * @param {String} namespace
  2505. * @return {Function}
  2506. * @api public
  2507. */
  2508. function createDebug(namespace) {
  2509. var prevTime;
  2510. var enableOverride = null;
  2511. var namespacesCache;
  2512. var enabledCache;
  2513. function debug() {
  2514. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2515. args[_key] = arguments[_key];
  2516. }
  2517. // Disabled?
  2518. if (!debug.enabled) {
  2519. return;
  2520. }
  2521. var self = debug;
  2522. // Set `diff` timestamp
  2523. var curr = Number(new Date());
  2524. var ms = curr - (prevTime || curr);
  2525. self.diff = ms;
  2526. self.prev = prevTime;
  2527. self.curr = curr;
  2528. prevTime = curr;
  2529. args[0] = createDebug.coerce(args[0]);
  2530. if (typeof args[0] !== 'string') {
  2531. // Anything else let's inspect with %O
  2532. args.unshift('%O');
  2533. }
  2534. // Apply any `formatters` transformations
  2535. var index = 0;
  2536. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  2537. // If we encounter an escaped % then don't increase the array index
  2538. if (match === '%%') {
  2539. return '%';
  2540. }
  2541. index++;
  2542. var formatter = createDebug.formatters[format];
  2543. if (typeof formatter === 'function') {
  2544. var val = args[index];
  2545. match = formatter.call(self, val);
  2546. // Now we need to remove `args[index]` since it's inlined in the `format`
  2547. args.splice(index, 1);
  2548. index--;
  2549. }
  2550. return match;
  2551. });
  2552. // Apply env-specific formatting (colors, etc.)
  2553. createDebug.formatArgs.call(self, args);
  2554. var logFn = self.log || createDebug.log;
  2555. logFn.apply(self, args);
  2556. }
  2557. debug.namespace = namespace;
  2558. debug.useColors = createDebug.useColors();
  2559. debug.color = createDebug.selectColor(namespace);
  2560. debug.extend = extend;
  2561. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  2562. Object.defineProperty(debug, 'enabled', {
  2563. enumerable: true,
  2564. configurable: false,
  2565. get: function get() {
  2566. if (enableOverride !== null) {
  2567. return enableOverride;
  2568. }
  2569. if (namespacesCache !== createDebug.namespaces) {
  2570. namespacesCache = createDebug.namespaces;
  2571. enabledCache = createDebug.enabled(namespace);
  2572. }
  2573. return enabledCache;
  2574. },
  2575. set: function set(v) {
  2576. enableOverride = v;
  2577. }
  2578. });
  2579. // Env-specific initialization logic for debug instances
  2580. if (typeof createDebug.init === 'function') {
  2581. createDebug.init(debug);
  2582. }
  2583. return debug;
  2584. }
  2585. function extend(namespace, delimiter) {
  2586. var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  2587. newDebug.log = this.log;
  2588. return newDebug;
  2589. }
  2590. /**
  2591. * Enables a debug mode by namespaces. This can include modes
  2592. * separated by a colon and wildcards.
  2593. *
  2594. * @param {String} namespaces
  2595. * @api public
  2596. */
  2597. function enable(namespaces) {
  2598. createDebug.save(namespaces);
  2599. createDebug.namespaces = namespaces;
  2600. createDebug.names = [];
  2601. createDebug.skips = [];
  2602. var i;
  2603. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  2604. var len = split.length;
  2605. for (i = 0; i < len; i++) {
  2606. if (!split[i]) {
  2607. // ignore empty strings
  2608. continue;
  2609. }
  2610. namespaces = split[i].replace(/\*/g, '.*?');
  2611. if (namespaces[0] === '-') {
  2612. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  2613. } else {
  2614. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  2615. }
  2616. }
  2617. }
  2618. /**
  2619. * Disable debug output.
  2620. *
  2621. * @return {String} namespaces
  2622. * @api public
  2623. */
  2624. function disable() {
  2625. var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) {
  2626. return '-' + namespace;
  2627. }))).join(',');
  2628. createDebug.enable('');
  2629. return namespaces;
  2630. }
  2631. /**
  2632. * Returns true if the given mode name is enabled, false otherwise.
  2633. *
  2634. * @param {String} name
  2635. * @return {Boolean}
  2636. * @api public
  2637. */
  2638. function enabled(name) {
  2639. if (name[name.length - 1] === '*') {
  2640. return true;
  2641. }
  2642. var i;
  2643. var len;
  2644. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  2645. if (createDebug.skips[i].test(name)) {
  2646. return false;
  2647. }
  2648. }
  2649. for (i = 0, len = createDebug.names.length; i < len; i++) {
  2650. if (createDebug.names[i].test(name)) {
  2651. return true;
  2652. }
  2653. }
  2654. return false;
  2655. }
  2656. /**
  2657. * Convert regexp to namespace
  2658. *
  2659. * @param {RegExp} regxep
  2660. * @return {String} namespace
  2661. * @api private
  2662. */
  2663. function toNamespace(regexp) {
  2664. return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
  2665. }
  2666. /**
  2667. * Coerce `val`.
  2668. *
  2669. * @param {Mixed} val
  2670. * @return {Mixed}
  2671. * @api private
  2672. */
  2673. function coerce(val) {
  2674. if (val instanceof Error) {
  2675. return val.stack || val.message;
  2676. }
  2677. return val;
  2678. }
  2679. /**
  2680. * XXX DO NOT USE. This is a temporary stub function.
  2681. * XXX It WILL be removed in the next major release.
  2682. */
  2683. function destroy() {
  2684. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  2685. }
  2686. createDebug.enable(createDebug.load());
  2687. return createDebug;
  2688. }
  2689. var common = setup;
  2690. /* eslint-env browser */
  2691. browser.exports;
  2692. (function (module, exports) {
  2693. /**
  2694. * This is the web browser implementation of `debug()`.
  2695. */
  2696. exports.formatArgs = formatArgs;
  2697. exports.save = save;
  2698. exports.load = load;
  2699. exports.useColors = useColors;
  2700. exports.storage = localstorage();
  2701. exports.destroy = function () {
  2702. var warned = false;
  2703. return function () {
  2704. if (!warned) {
  2705. warned = true;
  2706. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  2707. }
  2708. };
  2709. }();
  2710. /**
  2711. * Colors.
  2712. */
  2713. exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  2714. /**
  2715. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2716. * and the Firebug extension (any Firefox version) are known
  2717. * to support "%c" CSS customizations.
  2718. *
  2719. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2720. */
  2721. // eslint-disable-next-line complexity
  2722. function useColors() {
  2723. // NB: In an Electron preload script, document will be defined but not fully
  2724. // initialized. Since we know we're in Chrome, we'll just detect this case
  2725. // explicitly
  2726. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  2727. return true;
  2728. }
  2729. // Internet Explorer and Edge do not support colors.
  2730. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  2731. return false;
  2732. }
  2733. // Is webkit? http://stackoverflow.com/a/16459606/376773
  2734. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  2735. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
  2736. // Is firebug? http://stackoverflow.com/a/398120/376773
  2737. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
  2738. // Is firefox >= v31?
  2739. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2740. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 ||
  2741. // Double check webkit in userAgent just in case we are in a worker
  2742. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  2743. }
  2744. /**
  2745. * Colorize log arguments if enabled.
  2746. *
  2747. * @api public
  2748. */
  2749. function formatArgs(args) {
  2750. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  2751. if (!this.useColors) {
  2752. return;
  2753. }
  2754. var c = 'color: ' + this.color;
  2755. args.splice(1, 0, c, 'color: inherit');
  2756. // The final "%c" is somewhat tricky, because there could be other
  2757. // arguments passed either before or after the %c, so we need to
  2758. // figure out the correct index to insert the CSS into
  2759. var index = 0;
  2760. var lastC = 0;
  2761. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  2762. if (match === '%%') {
  2763. return;
  2764. }
  2765. index++;
  2766. if (match === '%c') {
  2767. // We only are interested in the *last* %c
  2768. // (the user may have provided their own)
  2769. lastC = index;
  2770. }
  2771. });
  2772. args.splice(lastC, 0, c);
  2773. }
  2774. /**
  2775. * Invokes `console.debug()` when available.
  2776. * No-op when `console.debug` is not a "function".
  2777. * If `console.debug` is not available, falls back
  2778. * to `console.log`.
  2779. *
  2780. * @api public
  2781. */
  2782. exports.log = console.debug || console.log || function () {};
  2783. /**
  2784. * Save `namespaces`.
  2785. *
  2786. * @param {String} namespaces
  2787. * @api private
  2788. */
  2789. function save(namespaces) {
  2790. try {
  2791. if (namespaces) {
  2792. exports.storage.setItem('debug', namespaces);
  2793. } else {
  2794. exports.storage.removeItem('debug');
  2795. }
  2796. } catch (error) {
  2797. // Swallow
  2798. // XXX (@Qix-) should we be logging these?
  2799. }
  2800. }
  2801. /**
  2802. * Load `namespaces`.
  2803. *
  2804. * @return {String} returns the previously persisted debug modes
  2805. * @api private
  2806. */
  2807. function load() {
  2808. var r;
  2809. try {
  2810. r = exports.storage.getItem('debug');
  2811. } catch (error) {
  2812. // Swallow
  2813. // XXX (@Qix-) should we be logging these?
  2814. }
  2815. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  2816. if (!r && typeof process !== 'undefined' && 'env' in process) {
  2817. r = process.env.DEBUG;
  2818. }
  2819. return r;
  2820. }
  2821. /**
  2822. * Localstorage attempts to return the localstorage.
  2823. *
  2824. * This is necessary because safari throws
  2825. * when a user disables cookies/localstorage
  2826. * and you attempt to access it.
  2827. *
  2828. * @return {LocalStorage}
  2829. * @api private
  2830. */
  2831. function localstorage() {
  2832. try {
  2833. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  2834. // The Browser also has localStorage in the global context.
  2835. return localStorage;
  2836. } catch (error) {
  2837. // Swallow
  2838. // XXX (@Qix-) should we be logging these?
  2839. }
  2840. }
  2841. module.exports = common(exports);
  2842. var formatters = module.exports.formatters;
  2843. /**
  2844. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2845. */
  2846. formatters.j = function (v) {
  2847. try {
  2848. return JSON.stringify(v);
  2849. } catch (error) {
  2850. return '[UnexpectedJSONParseError]: ' + error.message;
  2851. }
  2852. };
  2853. })(browser, browser.exports);
  2854. var browserExports = browser.exports;
  2855. var debugModule = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
  2856. var debug$3 = debugModule("socket.io-client:url"); // debug()
  2857. /**
  2858. * URL parser.
  2859. *
  2860. * @param uri - url
  2861. * @param path - the request path of the connection
  2862. * @param loc - An object meant to mimic window.location.
  2863. * Defaults to window.location.
  2864. * @public
  2865. */
  2866. function url(uri) {
  2867. var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  2868. var loc = arguments.length > 2 ? arguments[2] : undefined;
  2869. var obj = uri;
  2870. // default to window.location
  2871. loc = loc || typeof location !== "undefined" && location;
  2872. if (null == uri) uri = loc.protocol + "//" + loc.host;
  2873. // relative path support
  2874. if (typeof uri === "string") {
  2875. if ("/" === uri.charAt(0)) {
  2876. if ("/" === uri.charAt(1)) {
  2877. uri = loc.protocol + uri;
  2878. } else {
  2879. uri = loc.host + uri;
  2880. }
  2881. }
  2882. if (!/^(https?|wss?):\/\//.test(uri)) {
  2883. debug$3("protocol-less url %s", uri);
  2884. if ("undefined" !== typeof loc) {
  2885. uri = loc.protocol + "//" + uri;
  2886. } else {
  2887. uri = "https://" + uri;
  2888. }
  2889. }
  2890. // parse
  2891. debug$3("parse %s", uri);
  2892. obj = parse(uri);
  2893. }
  2894. // make sure we treat `localhost:80` and `localhost` equally
  2895. if (!obj.port) {
  2896. if (/^(http|ws)$/.test(obj.protocol)) {
  2897. obj.port = "80";
  2898. } else if (/^(http|ws)s$/.test(obj.protocol)) {
  2899. obj.port = "443";
  2900. }
  2901. }
  2902. obj.path = obj.path || "/";
  2903. var ipv6 = obj.host.indexOf(":") !== -1;
  2904. var host = ipv6 ? "[" + obj.host + "]" : obj.host;
  2905. // define unique id
  2906. obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
  2907. // define href
  2908. obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
  2909. return obj;
  2910. }
  2911. var withNativeArrayBuffer = typeof ArrayBuffer === "function";
  2912. var isView = function isView(obj) {
  2913. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
  2914. };
  2915. var toString = Object.prototype.toString;
  2916. var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
  2917. var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
  2918. /**
  2919. * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
  2920. *
  2921. * @private
  2922. */
  2923. function isBinary(obj) {
  2924. return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
  2925. }
  2926. function hasBinary(obj, toJSON) {
  2927. if (!obj || _typeof(obj) !== "object") {
  2928. return false;
  2929. }
  2930. if (Array.isArray(obj)) {
  2931. for (var i = 0, l = obj.length; i < l; i++) {
  2932. if (hasBinary(obj[i])) {
  2933. return true;
  2934. }
  2935. }
  2936. return false;
  2937. }
  2938. if (isBinary(obj)) {
  2939. return true;
  2940. }
  2941. if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
  2942. return hasBinary(obj.toJSON(), true);
  2943. }
  2944. for (var key in obj) {
  2945. if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
  2946. return true;
  2947. }
  2948. }
  2949. return false;
  2950. }
  2951. /**
  2952. * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
  2953. *
  2954. * @param {Object} packet - socket.io event packet
  2955. * @return {Object} with deconstructed packet and list of buffers
  2956. * @public
  2957. */
  2958. function deconstructPacket(packet) {
  2959. var buffers = [];
  2960. var packetData = packet.data;
  2961. var pack = packet;
  2962. pack.data = _deconstructPacket(packetData, buffers);
  2963. pack.attachments = buffers.length; // number of binary 'attachments'
  2964. return {
  2965. packet: pack,
  2966. buffers: buffers
  2967. };
  2968. }
  2969. function _deconstructPacket(data, buffers) {
  2970. if (!data) return data;
  2971. if (isBinary(data)) {
  2972. var placeholder = {
  2973. _placeholder: true,
  2974. num: buffers.length
  2975. };
  2976. buffers.push(data);
  2977. return placeholder;
  2978. } else if (Array.isArray(data)) {
  2979. var newData = new Array(data.length);
  2980. for (var i = 0; i < data.length; i++) {
  2981. newData[i] = _deconstructPacket(data[i], buffers);
  2982. }
  2983. return newData;
  2984. } else if (_typeof(data) === "object" && !(data instanceof Date)) {
  2985. var _newData = {};
  2986. for (var key in data) {
  2987. if (Object.prototype.hasOwnProperty.call(data, key)) {
  2988. _newData[key] = _deconstructPacket(data[key], buffers);
  2989. }
  2990. }
  2991. return _newData;
  2992. }
  2993. return data;
  2994. }
  2995. /**
  2996. * Reconstructs a binary packet from its placeholder packet and buffers
  2997. *
  2998. * @param {Object} packet - event packet with placeholders
  2999. * @param {Array} buffers - binary buffers to put in placeholder positions
  3000. * @return {Object} reconstructed packet
  3001. * @public
  3002. */
  3003. function reconstructPacket(packet, buffers) {
  3004. packet.data = _reconstructPacket(packet.data, buffers);
  3005. delete packet.attachments; // no longer useful
  3006. return packet;
  3007. }
  3008. function _reconstructPacket(data, buffers) {
  3009. if (!data) return data;
  3010. if (data && data._placeholder === true) {
  3011. var isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
  3012. if (isIndexValid) {
  3013. return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  3014. } else {
  3015. throw new Error("illegal attachments");
  3016. }
  3017. } else if (Array.isArray(data)) {
  3018. for (var i = 0; i < data.length; i++) {
  3019. data[i] = _reconstructPacket(data[i], buffers);
  3020. }
  3021. } else if (_typeof(data) === "object") {
  3022. for (var key in data) {
  3023. if (Object.prototype.hasOwnProperty.call(data, key)) {
  3024. data[key] = _reconstructPacket(data[key], buffers);
  3025. }
  3026. }
  3027. }
  3028. return data;
  3029. }
  3030. /**
  3031. * These strings must not be used as event names, as they have a special meaning.
  3032. */
  3033. var RESERVED_EVENTS$1 = ["connect",
  3034. // used on the client side
  3035. "connect_error",
  3036. // used on the client side
  3037. "disconnect",
  3038. // used on both sides
  3039. "disconnecting",
  3040. // used on the server side
  3041. "newListener",
  3042. // used by the Node.js EventEmitter
  3043. "removeListener" // used by the Node.js EventEmitter
  3044. ];
  3045. /**
  3046. * Protocol version.
  3047. *
  3048. * @public
  3049. */
  3050. var protocol = 5;
  3051. var PacketType;
  3052. (function (PacketType) {
  3053. PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
  3054. PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
  3055. PacketType[PacketType["EVENT"] = 2] = "EVENT";
  3056. PacketType[PacketType["ACK"] = 3] = "ACK";
  3057. PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
  3058. PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
  3059. PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
  3060. })(PacketType || (PacketType = {}));
  3061. /**
  3062. * A socket.io Encoder instance
  3063. */
  3064. var Encoder = /*#__PURE__*/function () {
  3065. /**
  3066. * Encoder constructor
  3067. *
  3068. * @param {function} replacer - custom replacer to pass down to JSON.parse
  3069. */
  3070. function Encoder(replacer) {
  3071. this.replacer = replacer;
  3072. }
  3073. /**
  3074. * Encode a packet as a single string if non-binary, or as a
  3075. * buffer sequence, depending on packet type.
  3076. *
  3077. * @param {Object} obj - packet object
  3078. */
  3079. var _proto = Encoder.prototype;
  3080. _proto.encode = function encode(obj) {
  3081. if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
  3082. if (hasBinary(obj)) {
  3083. return this.encodeAsBinary({
  3084. type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
  3085. nsp: obj.nsp,
  3086. data: obj.data,
  3087. id: obj.id
  3088. });
  3089. }
  3090. }
  3091. return [this.encodeAsString(obj)];
  3092. }
  3093. /**
  3094. * Encode packet as string.
  3095. */;
  3096. _proto.encodeAsString = function encodeAsString(obj) {
  3097. // first is type
  3098. var str = "" + obj.type;
  3099. // attachments if we have them
  3100. if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
  3101. str += obj.attachments + "-";
  3102. }
  3103. // if we have a namespace other than `/`
  3104. // we append it followed by a comma `,`
  3105. if (obj.nsp && "/" !== obj.nsp) {
  3106. str += obj.nsp + ",";
  3107. }
  3108. // immediately followed by the id
  3109. if (null != obj.id) {
  3110. str += obj.id;
  3111. }
  3112. // json data
  3113. if (null != obj.data) {
  3114. str += JSON.stringify(obj.data, this.replacer);
  3115. }
  3116. return str;
  3117. }
  3118. /**
  3119. * Encode packet as 'buffer sequence' by removing blobs, and
  3120. * deconstructing packet into object with placeholders and
  3121. * a list of buffers.
  3122. */;
  3123. _proto.encodeAsBinary = function encodeAsBinary(obj) {
  3124. var deconstruction = deconstructPacket(obj);
  3125. var pack = this.encodeAsString(deconstruction.packet);
  3126. var buffers = deconstruction.buffers;
  3127. buffers.unshift(pack); // add packet info to beginning of data list
  3128. return buffers; // write all the buffers
  3129. };
  3130. return Encoder;
  3131. }();
  3132. /**
  3133. * A socket.io Decoder instance
  3134. *
  3135. * @return {Object} decoder
  3136. */
  3137. var Decoder = /*#__PURE__*/function (_Emitter) {
  3138. /**
  3139. * Decoder constructor
  3140. *
  3141. * @param {function} reviver - custom reviver to pass down to JSON.stringify
  3142. */
  3143. function Decoder(reviver) {
  3144. var _this;
  3145. _this = _Emitter.call(this) || this;
  3146. _this.reviver = reviver;
  3147. return _this;
  3148. }
  3149. /**
  3150. * Decodes an encoded packet string into packet JSON.
  3151. *
  3152. * @param {String} obj - encoded packet
  3153. */
  3154. _inheritsLoose(Decoder, _Emitter);
  3155. var _proto2 = Decoder.prototype;
  3156. _proto2.add = function add(obj) {
  3157. var packet;
  3158. if (typeof obj === "string") {
  3159. if (this.reconstructor) {
  3160. throw new Error("got plaintext data when reconstructing a packet");
  3161. }
  3162. packet = this.decodeString(obj);
  3163. var isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
  3164. if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
  3165. packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
  3166. // binary packet's json
  3167. this.reconstructor = new BinaryReconstructor(packet);
  3168. // no attachments, labeled binary but no binary data to follow
  3169. if (packet.attachments === 0) {
  3170. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3171. }
  3172. } else {
  3173. // non-binary full packet
  3174. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3175. }
  3176. } else if (isBinary(obj) || obj.base64) {
  3177. // raw binary data
  3178. if (!this.reconstructor) {
  3179. throw new Error("got binary data when not reconstructing a packet");
  3180. } else {
  3181. packet = this.reconstructor.takeBinaryData(obj);
  3182. if (packet) {
  3183. // received final buffer
  3184. this.reconstructor = null;
  3185. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3186. }
  3187. }
  3188. } else {
  3189. throw new Error("Unknown type: " + obj);
  3190. }
  3191. }
  3192. /**
  3193. * Decode a packet String (JSON data)
  3194. *
  3195. * @param {String} str
  3196. * @return {Object} packet
  3197. */;
  3198. _proto2.decodeString = function decodeString(str) {
  3199. var i = 0;
  3200. // look up type
  3201. var p = {
  3202. type: Number(str.charAt(0))
  3203. };
  3204. if (PacketType[p.type] === undefined) {
  3205. throw new Error("unknown packet type " + p.type);
  3206. }
  3207. // look up attachments if type binary
  3208. if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
  3209. var start = i + 1;
  3210. while (str.charAt(++i) !== "-" && i != str.length) {}
  3211. var buf = str.substring(start, i);
  3212. if (buf != Number(buf) || str.charAt(i) !== "-") {
  3213. throw new Error("Illegal attachments");
  3214. }
  3215. p.attachments = Number(buf);
  3216. }
  3217. // look up namespace (if any)
  3218. if ("/" === str.charAt(i + 1)) {
  3219. var _start = i + 1;
  3220. while (++i) {
  3221. var c = str.charAt(i);
  3222. if ("," === c) break;
  3223. if (i === str.length) break;
  3224. }
  3225. p.nsp = str.substring(_start, i);
  3226. } else {
  3227. p.nsp = "/";
  3228. }
  3229. // look up id
  3230. var next = str.charAt(i + 1);
  3231. if ("" !== next && Number(next) == next) {
  3232. var _start2 = i + 1;
  3233. while (++i) {
  3234. var _c = str.charAt(i);
  3235. if (null == _c || Number(_c) != _c) {
  3236. --i;
  3237. break;
  3238. }
  3239. if (i === str.length) break;
  3240. }
  3241. p.id = Number(str.substring(_start2, i + 1));
  3242. }
  3243. // look up json data
  3244. if (str.charAt(++i)) {
  3245. var payload = this.tryParse(str.substr(i));
  3246. if (Decoder.isPayloadValid(p.type, payload)) {
  3247. p.data = payload;
  3248. } else {
  3249. throw new Error("invalid payload");
  3250. }
  3251. }
  3252. return p;
  3253. };
  3254. _proto2.tryParse = function tryParse(str) {
  3255. try {
  3256. return JSON.parse(str, this.reviver);
  3257. } catch (e) {
  3258. return false;
  3259. }
  3260. };
  3261. Decoder.isPayloadValid = function isPayloadValid(type, payload) {
  3262. switch (type) {
  3263. case PacketType.CONNECT:
  3264. return isObject(payload);
  3265. case PacketType.DISCONNECT:
  3266. return payload === undefined;
  3267. case PacketType.CONNECT_ERROR:
  3268. return typeof payload === "string" || isObject(payload);
  3269. case PacketType.EVENT:
  3270. case PacketType.BINARY_EVENT:
  3271. return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
  3272. case PacketType.ACK:
  3273. case PacketType.BINARY_ACK:
  3274. return Array.isArray(payload);
  3275. }
  3276. }
  3277. /**
  3278. * Deallocates a parser's resources
  3279. */;
  3280. _proto2.destroy = function destroy() {
  3281. if (this.reconstructor) {
  3282. this.reconstructor.finishedReconstruction();
  3283. this.reconstructor = null;
  3284. }
  3285. };
  3286. return Decoder;
  3287. }(Emitter);
  3288. /**
  3289. * A manager of a binary event's 'buffer sequence'. Should
  3290. * be constructed whenever a packet of type BINARY_EVENT is
  3291. * decoded.
  3292. *
  3293. * @param {Object} packet
  3294. * @return {BinaryReconstructor} initialized reconstructor
  3295. */
  3296. var BinaryReconstructor = /*#__PURE__*/function () {
  3297. function BinaryReconstructor(packet) {
  3298. this.packet = packet;
  3299. this.buffers = [];
  3300. this.reconPack = packet;
  3301. }
  3302. /**
  3303. * Method to be called when binary data received from connection
  3304. * after a BINARY_EVENT packet.
  3305. *
  3306. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  3307. * @return {null | Object} returns null if more binary data is expected or
  3308. * a reconstructed packet object if all buffers have been received.
  3309. */
  3310. var _proto3 = BinaryReconstructor.prototype;
  3311. _proto3.takeBinaryData = function takeBinaryData(binData) {
  3312. this.buffers.push(binData);
  3313. if (this.buffers.length === this.reconPack.attachments) {
  3314. // done with buffer list
  3315. var packet = reconstructPacket(this.reconPack, this.buffers);
  3316. this.finishedReconstruction();
  3317. return packet;
  3318. }
  3319. return null;
  3320. }
  3321. /**
  3322. * Cleans up binary packet reconstruction variables.
  3323. */;
  3324. _proto3.finishedReconstruction = function finishedReconstruction() {
  3325. this.reconPack = null;
  3326. this.buffers = [];
  3327. };
  3328. return BinaryReconstructor;
  3329. }();
  3330. function isNamespaceValid(nsp) {
  3331. return typeof nsp === "string";
  3332. }
  3333. // see https://caniuse.com/mdn-javascript_builtins_number_isinteger
  3334. var isInteger = Number.isInteger || function (value) {
  3335. return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  3336. };
  3337. function isAckIdValid(id) {
  3338. return id === undefined || isInteger(id);
  3339. }
  3340. // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
  3341. function isObject(value) {
  3342. return Object.prototype.toString.call(value) === "[object Object]";
  3343. }
  3344. function isDataValid(type, payload) {
  3345. switch (type) {
  3346. case PacketType.CONNECT:
  3347. return payload === undefined || isObject(payload);
  3348. case PacketType.DISCONNECT:
  3349. return payload === undefined;
  3350. case PacketType.EVENT:
  3351. return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
  3352. case PacketType.ACK:
  3353. return Array.isArray(payload);
  3354. case PacketType.CONNECT_ERROR:
  3355. return typeof payload === "string" || isObject(payload);
  3356. default:
  3357. return false;
  3358. }
  3359. }
  3360. function isPacketValid(packet) {
  3361. return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
  3362. }
  3363. var parser = /*#__PURE__*/Object.freeze({
  3364. __proto__: null,
  3365. protocol: protocol,
  3366. get PacketType () { return PacketType; },
  3367. Encoder: Encoder,
  3368. Decoder: Decoder,
  3369. isPacketValid: isPacketValid
  3370. });
  3371. function on(obj, ev, fn) {
  3372. obj.on(ev, fn);
  3373. return function subDestroy() {
  3374. obj.off(ev, fn);
  3375. };
  3376. }
  3377. var debug$2 = debugModule("socket.io-client:socket"); // debug()
  3378. /**
  3379. * Internal events.
  3380. * These events can't be emitted by the user.
  3381. */
  3382. var RESERVED_EVENTS = Object.freeze({
  3383. connect: 1,
  3384. connect_error: 1,
  3385. disconnect: 1,
  3386. disconnecting: 1,
  3387. // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
  3388. newListener: 1,
  3389. removeListener: 1
  3390. });
  3391. /**
  3392. * A Socket is the fundamental class for interacting with the server.
  3393. *
  3394. * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
  3395. *
  3396. * @example
  3397. * const socket = io();
  3398. *
  3399. * socket.on("connect", () => {
  3400. * console.log("connected");
  3401. * });
  3402. *
  3403. * // send an event to the server
  3404. * socket.emit("foo", "bar");
  3405. *
  3406. * socket.on("foobar", () => {
  3407. * // an event was received from the server
  3408. * });
  3409. *
  3410. * // upon disconnection
  3411. * socket.on("disconnect", (reason) => {
  3412. * console.log(`disconnected due to ${reason}`);
  3413. * });
  3414. */
  3415. var Socket = /*#__PURE__*/function (_Emitter) {
  3416. /**
  3417. * `Socket` constructor.
  3418. */
  3419. function Socket(io, nsp, opts) {
  3420. var _this;
  3421. _this = _Emitter.call(this) || this;
  3422. /**
  3423. * Whether the socket is currently connected to the server.
  3424. *
  3425. * @example
  3426. * const socket = io();
  3427. *
  3428. * socket.on("connect", () => {
  3429. * console.log(socket.connected); // true
  3430. * });
  3431. *
  3432. * socket.on("disconnect", () => {
  3433. * console.log(socket.connected); // false
  3434. * });
  3435. */
  3436. _this.connected = false;
  3437. /**
  3438. * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
  3439. * be transmitted by the server.
  3440. */
  3441. _this.recovered = false;
  3442. /**
  3443. * Buffer for packets received before the CONNECT packet
  3444. */
  3445. _this.receiveBuffer = [];
  3446. /**
  3447. * Buffer for packets that will be sent once the socket is connected
  3448. */
  3449. _this.sendBuffer = [];
  3450. /**
  3451. * The queue of packets to be sent with retry in case of failure.
  3452. *
  3453. * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
  3454. * @private
  3455. */
  3456. _this._queue = [];
  3457. /**
  3458. * A sequence to generate the ID of the {@link QueuedPacket}.
  3459. * @private
  3460. */
  3461. _this._queueSeq = 0;
  3462. _this.ids = 0;
  3463. /**
  3464. * A map containing acknowledgement handlers.
  3465. *
  3466. * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
  3467. *
  3468. * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
  3469. * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
  3470. * - `const value = await socket.emitWithAck("test")`
  3471. *
  3472. * From those that don't:
  3473. *
  3474. * - `socket.emit("test", (value) => { ... });`
  3475. *
  3476. * In the first case, the handlers will be called with an error when:
  3477. *
  3478. * - the timeout is reached
  3479. * - the socket gets disconnected
  3480. *
  3481. * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
  3482. * an acknowledgement from the server.
  3483. *
  3484. * @private
  3485. */
  3486. _this.acks = {};
  3487. _this.flags = {};
  3488. _this.io = io;
  3489. _this.nsp = nsp;
  3490. if (opts && opts.auth) {
  3491. _this.auth = opts.auth;
  3492. }
  3493. _this._opts = _extends({}, opts);
  3494. if (_this.io._autoConnect) _this.open();
  3495. return _this;
  3496. }
  3497. /**
  3498. * Whether the socket is currently disconnected
  3499. *
  3500. * @example
  3501. * const socket = io();
  3502. *
  3503. * socket.on("connect", () => {
  3504. * console.log(socket.disconnected); // false
  3505. * });
  3506. *
  3507. * socket.on("disconnect", () => {
  3508. * console.log(socket.disconnected); // true
  3509. * });
  3510. */
  3511. _inheritsLoose(Socket, _Emitter);
  3512. var _proto = Socket.prototype;
  3513. /**
  3514. * Subscribe to open, close and packet events
  3515. *
  3516. * @private
  3517. */
  3518. _proto.subEvents = function subEvents() {
  3519. if (this.subs) return;
  3520. var io = this.io;
  3521. this.subs = [on(io, "open", this.onopen.bind(this)), on(io, "packet", this.onpacket.bind(this)), on(io, "error", this.onerror.bind(this)), on(io, "close", this.onclose.bind(this))];
  3522. }
  3523. /**
  3524. * Whether the Socket will try to reconnect when its Manager connects or reconnects.
  3525. *
  3526. * @example
  3527. * const socket = io();
  3528. *
  3529. * console.log(socket.active); // true
  3530. *
  3531. * socket.on("disconnect", (reason) => {
  3532. * if (reason === "io server disconnect") {
  3533. * // the disconnection was initiated by the server, you need to manually reconnect
  3534. * console.log(socket.active); // false
  3535. * }
  3536. * // else the socket will automatically try to reconnect
  3537. * console.log(socket.active); // true
  3538. * });
  3539. */;
  3540. /**
  3541. * "Opens" the socket.
  3542. *
  3543. * @example
  3544. * const socket = io({
  3545. * autoConnect: false
  3546. * });
  3547. *
  3548. * socket.connect();
  3549. */
  3550. _proto.connect = function connect() {
  3551. if (this.connected) return this;
  3552. this.subEvents();
  3553. if (!this.io["_reconnecting"]) this.io.open(); // ensure open
  3554. if ("open" === this.io._readyState) this.onopen();
  3555. return this;
  3556. }
  3557. /**
  3558. * Alias for {@link connect()}.
  3559. */;
  3560. _proto.open = function open() {
  3561. return this.connect();
  3562. }
  3563. /**
  3564. * Sends a `message` event.
  3565. *
  3566. * This method mimics the WebSocket.send() method.
  3567. *
  3568. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  3569. *
  3570. * @example
  3571. * socket.send("hello");
  3572. *
  3573. * // this is equivalent to
  3574. * socket.emit("message", "hello");
  3575. *
  3576. * @return self
  3577. */;
  3578. _proto.send = function send() {
  3579. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3580. args[_key] = arguments[_key];
  3581. }
  3582. args.unshift("message");
  3583. this.emit.apply(this, args);
  3584. return this;
  3585. }
  3586. /**
  3587. * Override `emit`.
  3588. * If the event is in `events`, it's emitted normally.
  3589. *
  3590. * @example
  3591. * socket.emit("hello", "world");
  3592. *
  3593. * // all serializable datastructures are supported (no need to call JSON.stringify)
  3594. * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  3595. *
  3596. * // with an acknowledgement from the server
  3597. * socket.emit("hello", "world", (val) => {
  3598. * // ...
  3599. * });
  3600. *
  3601. * @return self
  3602. */;
  3603. _proto.emit = function emit(ev) {
  3604. var _a, _b, _c;
  3605. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  3606. throw new Error('"' + ev.toString() + '" is a reserved event name');
  3607. }
  3608. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  3609. args[_key2 - 1] = arguments[_key2];
  3610. }
  3611. args.unshift(ev);
  3612. if (this._opts.retries && !this.flags.fromQueue && !this.flags["volatile"]) {
  3613. this._addToQueue(args);
  3614. return this;
  3615. }
  3616. var packet = {
  3617. type: PacketType.EVENT,
  3618. data: args
  3619. };
  3620. packet.options = {};
  3621. packet.options.compress = this.flags.compress !== false;
  3622. // event ack callback
  3623. if ("function" === typeof args[args.length - 1]) {
  3624. var id = this.ids++;
  3625. debug$2("emitting packet with ack id %d", id);
  3626. var ack = args.pop();
  3627. this._registerAckCallback(id, ack);
  3628. packet.id = id;
  3629. }
  3630. var isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
  3631. var isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
  3632. var discardPacket = this.flags["volatile"] && !isTransportWritable;
  3633. if (discardPacket) {
  3634. debug$2("discard packet as the transport is not currently writable");
  3635. } else if (isConnected) {
  3636. this.notifyOutgoingListeners(packet);
  3637. this.packet(packet);
  3638. } else {
  3639. this.sendBuffer.push(packet);
  3640. }
  3641. this.flags = {};
  3642. return this;
  3643. }
  3644. /**
  3645. * @private
  3646. */;
  3647. _proto._registerAckCallback = function _registerAckCallback(id, ack) {
  3648. var _this2 = this;
  3649. var _a;
  3650. var timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
  3651. if (timeout === undefined) {
  3652. this.acks[id] = ack;
  3653. return;
  3654. }
  3655. // @ts-ignore
  3656. var timer = this.io.setTimeoutFn(function () {
  3657. delete _this2.acks[id];
  3658. for (var i = 0; i < _this2.sendBuffer.length; i++) {
  3659. if (_this2.sendBuffer[i].id === id) {
  3660. debug$2("removing packet with ack id %d from the buffer", id);
  3661. _this2.sendBuffer.splice(i, 1);
  3662. }
  3663. }
  3664. debug$2("event with ack id %d has timed out after %d ms", id, timeout);
  3665. ack.call(_this2, new Error("operation has timed out"));
  3666. }, timeout);
  3667. var fn = function fn() {
  3668. // @ts-ignore
  3669. _this2.io.clearTimeoutFn(timer);
  3670. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  3671. args[_key3] = arguments[_key3];
  3672. }
  3673. ack.apply(_this2, args);
  3674. };
  3675. fn.withError = true;
  3676. this.acks[id] = fn;
  3677. }
  3678. /**
  3679. * Emits an event and waits for an acknowledgement
  3680. *
  3681. * @example
  3682. * // without timeout
  3683. * const response = await socket.emitWithAck("hello", "world");
  3684. *
  3685. * // with a specific timeout
  3686. * try {
  3687. * const response = await socket.timeout(1000).emitWithAck("hello", "world");
  3688. * } catch (err) {
  3689. * // the server did not acknowledge the event in the given delay
  3690. * }
  3691. *
  3692. * @return a Promise that will be fulfilled when the server acknowledges the event
  3693. */;
  3694. _proto.emitWithAck = function emitWithAck(ev) {
  3695. var _this3 = this;
  3696. for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
  3697. args[_key4 - 1] = arguments[_key4];
  3698. }
  3699. return new Promise(function (resolve, reject) {
  3700. var fn = function fn(arg1, arg2) {
  3701. return arg1 ? reject(arg1) : resolve(arg2);
  3702. };
  3703. fn.withError = true;
  3704. args.push(fn);
  3705. _this3.emit.apply(_this3, [ev].concat(args));
  3706. });
  3707. }
  3708. /**
  3709. * Add the packet to the queue.
  3710. * @param args
  3711. * @private
  3712. */;
  3713. _proto._addToQueue = function _addToQueue(args) {
  3714. var _this4 = this;
  3715. var ack;
  3716. if (typeof args[args.length - 1] === "function") {
  3717. ack = args.pop();
  3718. }
  3719. var packet = {
  3720. id: this._queueSeq++,
  3721. tryCount: 0,
  3722. pending: false,
  3723. args: args,
  3724. flags: _extends({
  3725. fromQueue: true
  3726. }, this.flags)
  3727. };
  3728. args.push(function (err) {
  3729. if (packet !== _this4._queue[0]) {
  3730. // the packet has already been acknowledged
  3731. return;
  3732. }
  3733. var hasError = err !== null;
  3734. if (hasError) {
  3735. if (packet.tryCount > _this4._opts.retries) {
  3736. debug$2("packet [%d] is discarded after %d tries", packet.id, packet.tryCount);
  3737. _this4._queue.shift();
  3738. if (ack) {
  3739. ack(err);
  3740. }
  3741. }
  3742. } else {
  3743. debug$2("packet [%d] was successfully sent", packet.id);
  3744. _this4._queue.shift();
  3745. if (ack) {
  3746. for (var _len5 = arguments.length, responseArgs = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
  3747. responseArgs[_key5 - 1] = arguments[_key5];
  3748. }
  3749. ack.apply(void 0, [null].concat(responseArgs));
  3750. }
  3751. }
  3752. packet.pending = false;
  3753. return _this4._drainQueue();
  3754. });
  3755. this._queue.push(packet);
  3756. this._drainQueue();
  3757. }
  3758. /**
  3759. * Send the first packet of the queue, and wait for an acknowledgement from the server.
  3760. * @param force - whether to resend a packet that has not been acknowledged yet
  3761. *
  3762. * @private
  3763. */;
  3764. _proto._drainQueue = function _drainQueue() {
  3765. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  3766. debug$2("draining queue");
  3767. if (!this.connected || this._queue.length === 0) {
  3768. return;
  3769. }
  3770. var packet = this._queue[0];
  3771. if (packet.pending && !force) {
  3772. debug$2("packet [%d] has already been sent and is waiting for an ack", packet.id);
  3773. return;
  3774. }
  3775. packet.pending = true;
  3776. packet.tryCount++;
  3777. debug$2("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
  3778. this.flags = packet.flags;
  3779. this.emit.apply(this, packet.args);
  3780. }
  3781. /**
  3782. * Sends a packet.
  3783. *
  3784. * @param packet
  3785. * @private
  3786. */;
  3787. _proto.packet = function packet(_packet) {
  3788. _packet.nsp = this.nsp;
  3789. this.io._packet(_packet);
  3790. }
  3791. /**
  3792. * Called upon engine `open`.
  3793. *
  3794. * @private
  3795. */;
  3796. _proto.onopen = function onopen() {
  3797. var _this5 = this;
  3798. debug$2("transport is open - connecting");
  3799. if (typeof this.auth == "function") {
  3800. this.auth(function (data) {
  3801. _this5._sendConnectPacket(data);
  3802. });
  3803. } else {
  3804. this._sendConnectPacket(this.auth);
  3805. }
  3806. }
  3807. /**
  3808. * Sends a CONNECT packet to initiate the Socket.IO session.
  3809. *
  3810. * @param data
  3811. * @private
  3812. */;
  3813. _proto._sendConnectPacket = function _sendConnectPacket(data) {
  3814. this.packet({
  3815. type: PacketType.CONNECT,
  3816. data: this._pid ? _extends({
  3817. pid: this._pid,
  3818. offset: this._lastOffset
  3819. }, data) : data
  3820. });
  3821. }
  3822. /**
  3823. * Called upon engine or manager `error`.
  3824. *
  3825. * @param err
  3826. * @private
  3827. */;
  3828. _proto.onerror = function onerror(err) {
  3829. if (!this.connected) {
  3830. this.emitReserved("connect_error", err);
  3831. }
  3832. }
  3833. /**
  3834. * Called upon engine `close`.
  3835. *
  3836. * @param reason
  3837. * @param description
  3838. * @private
  3839. */;
  3840. _proto.onclose = function onclose(reason, description) {
  3841. debug$2("close (%s)", reason);
  3842. this.connected = false;
  3843. delete this.id;
  3844. this.emitReserved("disconnect", reason, description);
  3845. this._clearAcks();
  3846. }
  3847. /**
  3848. * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
  3849. * the server.
  3850. *
  3851. * @private
  3852. */;
  3853. _proto._clearAcks = function _clearAcks() {
  3854. var _this6 = this;
  3855. Object.keys(this.acks).forEach(function (id) {
  3856. var isBuffered = _this6.sendBuffer.some(function (packet) {
  3857. return String(packet.id) === id;
  3858. });
  3859. if (!isBuffered) {
  3860. // note: handlers that do not accept an error as first argument are ignored here
  3861. var ack = _this6.acks[id];
  3862. delete _this6.acks[id];
  3863. if (ack.withError) {
  3864. ack.call(_this6, new Error("socket has been disconnected"));
  3865. }
  3866. }
  3867. });
  3868. }
  3869. /**
  3870. * Called with socket packet.
  3871. *
  3872. * @param packet
  3873. * @private
  3874. */;
  3875. _proto.onpacket = function onpacket(packet) {
  3876. var sameNamespace = packet.nsp === this.nsp;
  3877. if (!sameNamespace) return;
  3878. switch (packet.type) {
  3879. case PacketType.CONNECT:
  3880. if (packet.data && packet.data.sid) {
  3881. this.onconnect(packet.data.sid, packet.data.pid);
  3882. } else {
  3883. this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
  3884. }
  3885. break;
  3886. case PacketType.EVENT:
  3887. case PacketType.BINARY_EVENT:
  3888. this.onevent(packet);
  3889. break;
  3890. case PacketType.ACK:
  3891. case PacketType.BINARY_ACK:
  3892. this.onack(packet);
  3893. break;
  3894. case PacketType.DISCONNECT:
  3895. this.ondisconnect();
  3896. break;
  3897. case PacketType.CONNECT_ERROR:
  3898. this.destroy();
  3899. var err = new Error(packet.data.message);
  3900. // @ts-ignore
  3901. err.data = packet.data.data;
  3902. this.emitReserved("connect_error", err);
  3903. break;
  3904. }
  3905. }
  3906. /**
  3907. * Called upon a server event.
  3908. *
  3909. * @param packet
  3910. * @private
  3911. */;
  3912. _proto.onevent = function onevent(packet) {
  3913. var args = packet.data || [];
  3914. debug$2("emitting event %j", args);
  3915. if (null != packet.id) {
  3916. debug$2("attaching ack callback to event");
  3917. args.push(this.ack(packet.id));
  3918. }
  3919. if (this.connected) {
  3920. this.emitEvent(args);
  3921. } else {
  3922. this.receiveBuffer.push(Object.freeze(args));
  3923. }
  3924. };
  3925. _proto.emitEvent = function emitEvent(args) {
  3926. if (this._anyListeners && this._anyListeners.length) {
  3927. var listeners = this._anyListeners.slice();
  3928. var _iterator = _createForOfIteratorHelper(listeners),
  3929. _step;
  3930. try {
  3931. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  3932. var listener = _step.value;
  3933. listener.apply(this, args);
  3934. }
  3935. } catch (err) {
  3936. _iterator.e(err);
  3937. } finally {
  3938. _iterator.f();
  3939. }
  3940. }
  3941. _Emitter.prototype.emit.apply(this, args);
  3942. if (this._pid && args.length && typeof args[args.length - 1] === "string") {
  3943. this._lastOffset = args[args.length - 1];
  3944. }
  3945. }
  3946. /**
  3947. * Produces an ack callback to emit with an event.
  3948. *
  3949. * @private
  3950. */;
  3951. _proto.ack = function ack(id) {
  3952. var self = this;
  3953. var sent = false;
  3954. return function () {
  3955. // prevent double callbacks
  3956. if (sent) return;
  3957. sent = true;
  3958. for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
  3959. args[_key6] = arguments[_key6];
  3960. }
  3961. debug$2("sending ack %j", args);
  3962. self.packet({
  3963. type: PacketType.ACK,
  3964. id: id,
  3965. data: args
  3966. });
  3967. };
  3968. }
  3969. /**
  3970. * Called upon a server acknowledgement.
  3971. *
  3972. * @param packet
  3973. * @private
  3974. */;
  3975. _proto.onack = function onack(packet) {
  3976. var ack = this.acks[packet.id];
  3977. if (typeof ack !== "function") {
  3978. debug$2("bad ack %s", packet.id);
  3979. return;
  3980. }
  3981. delete this.acks[packet.id];
  3982. debug$2("calling ack %s with %j", packet.id, packet.data);
  3983. // @ts-ignore FIXME ack is incorrectly inferred as 'never'
  3984. if (ack.withError) {
  3985. packet.data.unshift(null);
  3986. }
  3987. // @ts-ignore
  3988. ack.apply(this, packet.data);
  3989. }
  3990. /**
  3991. * Called upon server connect.
  3992. *
  3993. * @private
  3994. */;
  3995. _proto.onconnect = function onconnect(id, pid) {
  3996. debug$2("socket connected with id %s", id);
  3997. this.id = id;
  3998. this.recovered = pid && this._pid === pid;
  3999. this._pid = pid; // defined only if connection state recovery is enabled
  4000. this.connected = true;
  4001. this.emitBuffered();
  4002. this.emitReserved("connect");
  4003. this._drainQueue(true);
  4004. }
  4005. /**
  4006. * Emit buffered events (received and emitted).
  4007. *
  4008. * @private
  4009. */;
  4010. _proto.emitBuffered = function emitBuffered() {
  4011. var _this7 = this;
  4012. this.receiveBuffer.forEach(function (args) {
  4013. return _this7.emitEvent(args);
  4014. });
  4015. this.receiveBuffer = [];
  4016. this.sendBuffer.forEach(function (packet) {
  4017. _this7.notifyOutgoingListeners(packet);
  4018. _this7.packet(packet);
  4019. });
  4020. this.sendBuffer = [];
  4021. }
  4022. /**
  4023. * Called upon server disconnect.
  4024. *
  4025. * @private
  4026. */;
  4027. _proto.ondisconnect = function ondisconnect() {
  4028. debug$2("server disconnect (%s)", this.nsp);
  4029. this.destroy();
  4030. this.onclose("io server disconnect");
  4031. }
  4032. /**
  4033. * Called upon forced client/server side disconnections,
  4034. * this method ensures the manager stops tracking us and
  4035. * that reconnections don't get triggered for this.
  4036. *
  4037. * @private
  4038. */;
  4039. _proto.destroy = function destroy() {
  4040. if (this.subs) {
  4041. // clean subscriptions to avoid reconnections
  4042. this.subs.forEach(function (subDestroy) {
  4043. return subDestroy();
  4044. });
  4045. this.subs = undefined;
  4046. }
  4047. this.io["_destroy"](this);
  4048. }
  4049. /**
  4050. * Disconnects the socket manually. In that case, the socket will not try to reconnect.
  4051. *
  4052. * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
  4053. *
  4054. * @example
  4055. * const socket = io();
  4056. *
  4057. * socket.on("disconnect", (reason) => {
  4058. * // console.log(reason); prints "io client disconnect"
  4059. * });
  4060. *
  4061. * socket.disconnect();
  4062. *
  4063. * @return self
  4064. */;
  4065. _proto.disconnect = function disconnect() {
  4066. if (this.connected) {
  4067. debug$2("performing disconnect (%s)", this.nsp);
  4068. this.packet({
  4069. type: PacketType.DISCONNECT
  4070. });
  4071. }
  4072. // remove socket from pool
  4073. this.destroy();
  4074. if (this.connected) {
  4075. // fire events
  4076. this.onclose("io client disconnect");
  4077. }
  4078. return this;
  4079. }
  4080. /**
  4081. * Alias for {@link disconnect()}.
  4082. *
  4083. * @return self
  4084. */;
  4085. _proto.close = function close() {
  4086. return this.disconnect();
  4087. }
  4088. /**
  4089. * Sets the compress flag.
  4090. *
  4091. * @example
  4092. * socket.compress(false).emit("hello");
  4093. *
  4094. * @param compress - if `true`, compresses the sending data
  4095. * @return self
  4096. */;
  4097. _proto.compress = function compress(_compress) {
  4098. this.flags.compress = _compress;
  4099. return this;
  4100. }
  4101. /**
  4102. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  4103. * ready to send messages.
  4104. *
  4105. * @example
  4106. * socket.volatile.emit("hello"); // the server may or may not receive it
  4107. *
  4108. * @returns self
  4109. */;
  4110. /**
  4111. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  4112. * given number of milliseconds have elapsed without an acknowledgement from the server:
  4113. *
  4114. * @example
  4115. * socket.timeout(5000).emit("my-event", (err) => {
  4116. * if (err) {
  4117. * // the server did not acknowledge the event in the given delay
  4118. * }
  4119. * });
  4120. *
  4121. * @returns self
  4122. */
  4123. _proto.timeout = function timeout(_timeout) {
  4124. this.flags.timeout = _timeout;
  4125. return this;
  4126. }
  4127. /**
  4128. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4129. * callback.
  4130. *
  4131. * @example
  4132. * socket.onAny((event, ...args) => {
  4133. * console.log(`got ${event}`);
  4134. * });
  4135. *
  4136. * @param listener
  4137. */;
  4138. _proto.onAny = function onAny(listener) {
  4139. this._anyListeners = this._anyListeners || [];
  4140. this._anyListeners.push(listener);
  4141. return this;
  4142. }
  4143. /**
  4144. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4145. * callback. The listener is added to the beginning of the listeners array.
  4146. *
  4147. * @example
  4148. * socket.prependAny((event, ...args) => {
  4149. * console.log(`got event ${event}`);
  4150. * });
  4151. *
  4152. * @param listener
  4153. */;
  4154. _proto.prependAny = function prependAny(listener) {
  4155. this._anyListeners = this._anyListeners || [];
  4156. this._anyListeners.unshift(listener);
  4157. return this;
  4158. }
  4159. /**
  4160. * Removes the listener that will be fired when any event is emitted.
  4161. *
  4162. * @example
  4163. * const catchAllListener = (event, ...args) => {
  4164. * console.log(`got event ${event}`);
  4165. * }
  4166. *
  4167. * socket.onAny(catchAllListener);
  4168. *
  4169. * // remove a specific listener
  4170. * socket.offAny(catchAllListener);
  4171. *
  4172. * // or remove all listeners
  4173. * socket.offAny();
  4174. *
  4175. * @param listener
  4176. */;
  4177. _proto.offAny = function offAny(listener) {
  4178. if (!this._anyListeners) {
  4179. return this;
  4180. }
  4181. if (listener) {
  4182. var listeners = this._anyListeners;
  4183. for (var i = 0; i < listeners.length; i++) {
  4184. if (listener === listeners[i]) {
  4185. listeners.splice(i, 1);
  4186. return this;
  4187. }
  4188. }
  4189. } else {
  4190. this._anyListeners = [];
  4191. }
  4192. return this;
  4193. }
  4194. /**
  4195. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  4196. * e.g. to remove listeners.
  4197. */;
  4198. _proto.listenersAny = function listenersAny() {
  4199. return this._anyListeners || [];
  4200. }
  4201. /**
  4202. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4203. * callback.
  4204. *
  4205. * Note: acknowledgements sent to the server are not included.
  4206. *
  4207. * @example
  4208. * socket.onAnyOutgoing((event, ...args) => {
  4209. * console.log(`sent event ${event}`);
  4210. * });
  4211. *
  4212. * @param listener
  4213. */;
  4214. _proto.onAnyOutgoing = function onAnyOutgoing(listener) {
  4215. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  4216. this._anyOutgoingListeners.push(listener);
  4217. return this;
  4218. }
  4219. /**
  4220. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4221. * callback. The listener is added to the beginning of the listeners array.
  4222. *
  4223. * Note: acknowledgements sent to the server are not included.
  4224. *
  4225. * @example
  4226. * socket.prependAnyOutgoing((event, ...args) => {
  4227. * console.log(`sent event ${event}`);
  4228. * });
  4229. *
  4230. * @param listener
  4231. */;
  4232. _proto.prependAnyOutgoing = function prependAnyOutgoing(listener) {
  4233. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  4234. this._anyOutgoingListeners.unshift(listener);
  4235. return this;
  4236. }
  4237. /**
  4238. * Removes the listener that will be fired when any event is emitted.
  4239. *
  4240. * @example
  4241. * const catchAllListener = (event, ...args) => {
  4242. * console.log(`sent event ${event}`);
  4243. * }
  4244. *
  4245. * socket.onAnyOutgoing(catchAllListener);
  4246. *
  4247. * // remove a specific listener
  4248. * socket.offAnyOutgoing(catchAllListener);
  4249. *
  4250. * // or remove all listeners
  4251. * socket.offAnyOutgoing();
  4252. *
  4253. * @param [listener] - the catch-all listener (optional)
  4254. */;
  4255. _proto.offAnyOutgoing = function offAnyOutgoing(listener) {
  4256. if (!this._anyOutgoingListeners) {
  4257. return this;
  4258. }
  4259. if (listener) {
  4260. var listeners = this._anyOutgoingListeners;
  4261. for (var i = 0; i < listeners.length; i++) {
  4262. if (listener === listeners[i]) {
  4263. listeners.splice(i, 1);
  4264. return this;
  4265. }
  4266. }
  4267. } else {
  4268. this._anyOutgoingListeners = [];
  4269. }
  4270. return this;
  4271. }
  4272. /**
  4273. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  4274. * e.g. to remove listeners.
  4275. */;
  4276. _proto.listenersAnyOutgoing = function listenersAnyOutgoing() {
  4277. return this._anyOutgoingListeners || [];
  4278. }
  4279. /**
  4280. * Notify the listeners for each packet sent
  4281. *
  4282. * @param packet
  4283. *
  4284. * @private
  4285. */;
  4286. _proto.notifyOutgoingListeners = function notifyOutgoingListeners(packet) {
  4287. if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
  4288. var listeners = this._anyOutgoingListeners.slice();
  4289. var _iterator2 = _createForOfIteratorHelper(listeners),
  4290. _step2;
  4291. try {
  4292. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  4293. var listener = _step2.value;
  4294. listener.apply(this, packet.data);
  4295. }
  4296. } catch (err) {
  4297. _iterator2.e(err);
  4298. } finally {
  4299. _iterator2.f();
  4300. }
  4301. }
  4302. };
  4303. return _createClass(Socket, [{
  4304. key: "disconnected",
  4305. get: function get() {
  4306. return !this.connected;
  4307. }
  4308. }, {
  4309. key: "active",
  4310. get: function get() {
  4311. return !!this.subs;
  4312. }
  4313. }, {
  4314. key: "volatile",
  4315. get: function get() {
  4316. this.flags["volatile"] = true;
  4317. return this;
  4318. }
  4319. }]);
  4320. }(Emitter);
  4321. /**
  4322. * Initialize backoff timer with `opts`.
  4323. *
  4324. * - `min` initial timeout in milliseconds [100]
  4325. * - `max` max timeout [10000]
  4326. * - `jitter` [0]
  4327. * - `factor` [2]
  4328. *
  4329. * @param {Object} opts
  4330. * @api public
  4331. */
  4332. function Backoff(opts) {
  4333. opts = opts || {};
  4334. this.ms = opts.min || 100;
  4335. this.max = opts.max || 10000;
  4336. this.factor = opts.factor || 2;
  4337. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  4338. this.attempts = 0;
  4339. }
  4340. /**
  4341. * Return the backoff duration.
  4342. *
  4343. * @return {Number}
  4344. * @api public
  4345. */
  4346. Backoff.prototype.duration = function () {
  4347. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  4348. if (this.jitter) {
  4349. var rand = Math.random();
  4350. var deviation = Math.floor(rand * this.jitter * ms);
  4351. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  4352. }
  4353. return Math.min(ms, this.max) | 0;
  4354. };
  4355. /**
  4356. * Reset the number of attempts.
  4357. *
  4358. * @api public
  4359. */
  4360. Backoff.prototype.reset = function () {
  4361. this.attempts = 0;
  4362. };
  4363. /**
  4364. * Set the minimum duration
  4365. *
  4366. * @api public
  4367. */
  4368. Backoff.prototype.setMin = function (min) {
  4369. this.ms = min;
  4370. };
  4371. /**
  4372. * Set the maximum duration
  4373. *
  4374. * @api public
  4375. */
  4376. Backoff.prototype.setMax = function (max) {
  4377. this.max = max;
  4378. };
  4379. /**
  4380. * Set the jitter
  4381. *
  4382. * @api public
  4383. */
  4384. Backoff.prototype.setJitter = function (jitter) {
  4385. this.jitter = jitter;
  4386. };
  4387. var debug$1 = debugModule("socket.io-client:manager"); // debug()
  4388. var Manager = /*#__PURE__*/function (_Emitter) {
  4389. function Manager(uri, opts) {
  4390. var _this;
  4391. var _a;
  4392. _this = _Emitter.call(this) || this;
  4393. _this.nsps = {};
  4394. _this.subs = [];
  4395. if (uri && "object" === _typeof(uri)) {
  4396. opts = uri;
  4397. uri = undefined;
  4398. }
  4399. opts = opts || {};
  4400. opts.path = opts.path || "/socket.io";
  4401. _this.opts = opts;
  4402. installTimerFunctions(_this, opts);
  4403. _this.reconnection(opts.reconnection !== false);
  4404. _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  4405. _this.reconnectionDelay(opts.reconnectionDelay || 1000);
  4406. _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  4407. _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  4408. _this.backoff = new Backoff({
  4409. min: _this.reconnectionDelay(),
  4410. max: _this.reconnectionDelayMax(),
  4411. jitter: _this.randomizationFactor()
  4412. });
  4413. _this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  4414. _this._readyState = "closed";
  4415. _this.uri = uri;
  4416. var _parser = opts.parser || parser;
  4417. _this.encoder = new _parser.Encoder();
  4418. _this.decoder = new _parser.Decoder();
  4419. _this._autoConnect = opts.autoConnect !== false;
  4420. if (_this._autoConnect) _this.open();
  4421. return _this;
  4422. }
  4423. _inheritsLoose(Manager, _Emitter);
  4424. var _proto = Manager.prototype;
  4425. _proto.reconnection = function reconnection(v) {
  4426. if (!arguments.length) return this._reconnection;
  4427. this._reconnection = !!v;
  4428. if (!v) {
  4429. this.skipReconnect = true;
  4430. }
  4431. return this;
  4432. };
  4433. _proto.reconnectionAttempts = function reconnectionAttempts(v) {
  4434. if (v === undefined) return this._reconnectionAttempts;
  4435. this._reconnectionAttempts = v;
  4436. return this;
  4437. };
  4438. _proto.reconnectionDelay = function reconnectionDelay(v) {
  4439. var _a;
  4440. if (v === undefined) return this._reconnectionDelay;
  4441. this._reconnectionDelay = v;
  4442. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  4443. return this;
  4444. };
  4445. _proto.randomizationFactor = function randomizationFactor(v) {
  4446. var _a;
  4447. if (v === undefined) return this._randomizationFactor;
  4448. this._randomizationFactor = v;
  4449. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  4450. return this;
  4451. };
  4452. _proto.reconnectionDelayMax = function reconnectionDelayMax(v) {
  4453. var _a;
  4454. if (v === undefined) return this._reconnectionDelayMax;
  4455. this._reconnectionDelayMax = v;
  4456. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  4457. return this;
  4458. };
  4459. _proto.timeout = function timeout(v) {
  4460. if (!arguments.length) return this._timeout;
  4461. this._timeout = v;
  4462. return this;
  4463. }
  4464. /**
  4465. * Starts trying to reconnect if reconnection is enabled and we have not
  4466. * started reconnecting yet
  4467. *
  4468. * @private
  4469. */;
  4470. _proto.maybeReconnectOnOpen = function maybeReconnectOnOpen() {
  4471. // Only try to reconnect if it's the first time we're connecting
  4472. if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
  4473. // keeps reconnection from firing twice for the same reconnection loop
  4474. this.reconnect();
  4475. }
  4476. }
  4477. /**
  4478. * Sets the current transport `socket`.
  4479. *
  4480. * @param {Function} fn - optional, callback
  4481. * @return self
  4482. * @public
  4483. */;
  4484. _proto.open = function open(fn) {
  4485. var _this2 = this;
  4486. debug$1("readyState %s", this._readyState);
  4487. if (~this._readyState.indexOf("open")) return this;
  4488. debug$1("opening %s", this.uri);
  4489. this.engine = new Socket$1(this.uri, this.opts);
  4490. var socket = this.engine;
  4491. var self = this;
  4492. this._readyState = "opening";
  4493. this.skipReconnect = false;
  4494. // emit `open`
  4495. var openSubDestroy = on(socket, "open", function () {
  4496. self.onopen();
  4497. fn && fn();
  4498. });
  4499. var onError = function onError(err) {
  4500. debug$1("error");
  4501. _this2.cleanup();
  4502. _this2._readyState = "closed";
  4503. _this2.emitReserved("error", err);
  4504. if (fn) {
  4505. fn(err);
  4506. } else {
  4507. // Only do this if there is no fn to handle the error
  4508. _this2.maybeReconnectOnOpen();
  4509. }
  4510. };
  4511. // emit `error`
  4512. var errorSub = on(socket, "error", onError);
  4513. if (false !== this._timeout) {
  4514. var timeout = this._timeout;
  4515. debug$1("connect attempt will timeout after %d", timeout);
  4516. // set timer
  4517. var timer = this.setTimeoutFn(function () {
  4518. debug$1("connect attempt timed out after %d", timeout);
  4519. openSubDestroy();
  4520. onError(new Error("timeout"));
  4521. socket.close();
  4522. }, timeout);
  4523. if (this.opts.autoUnref) {
  4524. timer.unref();
  4525. }
  4526. this.subs.push(function () {
  4527. _this2.clearTimeoutFn(timer);
  4528. });
  4529. }
  4530. this.subs.push(openSubDestroy);
  4531. this.subs.push(errorSub);
  4532. return this;
  4533. }
  4534. /**
  4535. * Alias for open()
  4536. *
  4537. * @return self
  4538. * @public
  4539. */;
  4540. _proto.connect = function connect(fn) {
  4541. return this.open(fn);
  4542. }
  4543. /**
  4544. * Called upon transport open.
  4545. *
  4546. * @private
  4547. */;
  4548. _proto.onopen = function onopen() {
  4549. debug$1("open");
  4550. // clear old subs
  4551. this.cleanup();
  4552. // mark as open
  4553. this._readyState = "open";
  4554. this.emitReserved("open");
  4555. // add new subs
  4556. var socket = this.engine;
  4557. this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)),
  4558. // @ts-ignore
  4559. on(this.decoder, "decoded", this.ondecoded.bind(this)));
  4560. }
  4561. /**
  4562. * Called upon a ping.
  4563. *
  4564. * @private
  4565. */;
  4566. _proto.onping = function onping() {
  4567. this.emitReserved("ping");
  4568. }
  4569. /**
  4570. * Called with data.
  4571. *
  4572. * @private
  4573. */;
  4574. _proto.ondata = function ondata(data) {
  4575. try {
  4576. this.decoder.add(data);
  4577. } catch (e) {
  4578. this.onclose("parse error", e);
  4579. }
  4580. }
  4581. /**
  4582. * Called when parser fully decodes a packet.
  4583. *
  4584. * @private
  4585. */;
  4586. _proto.ondecoded = function ondecoded(packet) {
  4587. var _this3 = this;
  4588. // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
  4589. nextTick(function () {
  4590. _this3.emitReserved("packet", packet);
  4591. }, this.setTimeoutFn);
  4592. }
  4593. /**
  4594. * Called upon socket error.
  4595. *
  4596. * @private
  4597. */;
  4598. _proto.onerror = function onerror(err) {
  4599. debug$1("error", err);
  4600. this.emitReserved("error", err);
  4601. }
  4602. /**
  4603. * Creates a new socket for the given `nsp`.
  4604. *
  4605. * @return {Socket}
  4606. * @public
  4607. */;
  4608. _proto.socket = function socket(nsp, opts) {
  4609. var socket = this.nsps[nsp];
  4610. if (!socket) {
  4611. socket = new Socket(this, nsp, opts);
  4612. this.nsps[nsp] = socket;
  4613. } else if (this._autoConnect && !socket.active) {
  4614. socket.connect();
  4615. }
  4616. return socket;
  4617. }
  4618. /**
  4619. * Called upon a socket close.
  4620. *
  4621. * @param socket
  4622. * @private
  4623. */;
  4624. _proto._destroy = function _destroy(socket) {
  4625. var nsps = Object.keys(this.nsps);
  4626. for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) {
  4627. var nsp = _nsps[_i];
  4628. var _socket = this.nsps[nsp];
  4629. if (_socket.active) {
  4630. debug$1("socket %s is still active, skipping close", nsp);
  4631. return;
  4632. }
  4633. }
  4634. this._close();
  4635. }
  4636. /**
  4637. * Writes a packet.
  4638. *
  4639. * @param packet
  4640. * @private
  4641. */;
  4642. _proto._packet = function _packet(packet) {
  4643. debug$1("writing packet %j", packet);
  4644. var encodedPackets = this.encoder.encode(packet);
  4645. for (var i = 0; i < encodedPackets.length; i++) {
  4646. this.engine.write(encodedPackets[i], packet.options);
  4647. }
  4648. }
  4649. /**
  4650. * Clean up transport subscriptions and packet buffer.
  4651. *
  4652. * @private
  4653. */;
  4654. _proto.cleanup = function cleanup() {
  4655. debug$1("cleanup");
  4656. this.subs.forEach(function (subDestroy) {
  4657. return subDestroy();
  4658. });
  4659. this.subs.length = 0;
  4660. this.decoder.destroy();
  4661. }
  4662. /**
  4663. * Close the current socket.
  4664. *
  4665. * @private
  4666. */;
  4667. _proto._close = function _close() {
  4668. debug$1("disconnect");
  4669. this.skipReconnect = true;
  4670. this._reconnecting = false;
  4671. this.onclose("forced close");
  4672. }
  4673. /**
  4674. * Alias for close()
  4675. *
  4676. * @private
  4677. */;
  4678. _proto.disconnect = function disconnect() {
  4679. return this._close();
  4680. }
  4681. /**
  4682. * Called when:
  4683. *
  4684. * - the low-level engine is closed
  4685. * - the parser encountered a badly formatted packet
  4686. * - all sockets are disconnected
  4687. *
  4688. * @private
  4689. */;
  4690. _proto.onclose = function onclose(reason, description) {
  4691. var _a;
  4692. debug$1("closed due to %s", reason);
  4693. this.cleanup();
  4694. (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
  4695. this.backoff.reset();
  4696. this._readyState = "closed";
  4697. this.emitReserved("close", reason, description);
  4698. if (this._reconnection && !this.skipReconnect) {
  4699. this.reconnect();
  4700. }
  4701. }
  4702. /**
  4703. * Attempt a reconnection.
  4704. *
  4705. * @private
  4706. */;
  4707. _proto.reconnect = function reconnect() {
  4708. var _this4 = this;
  4709. if (this._reconnecting || this.skipReconnect) return this;
  4710. var self = this;
  4711. if (this.backoff.attempts >= this._reconnectionAttempts) {
  4712. debug$1("reconnect failed");
  4713. this.backoff.reset();
  4714. this.emitReserved("reconnect_failed");
  4715. this._reconnecting = false;
  4716. } else {
  4717. var delay = this.backoff.duration();
  4718. debug$1("will wait %dms before reconnect attempt", delay);
  4719. this._reconnecting = true;
  4720. var timer = this.setTimeoutFn(function () {
  4721. if (self.skipReconnect) return;
  4722. debug$1("attempting reconnect");
  4723. _this4.emitReserved("reconnect_attempt", self.backoff.attempts);
  4724. // check again for the case socket closed in above events
  4725. if (self.skipReconnect) return;
  4726. self.open(function (err) {
  4727. if (err) {
  4728. debug$1("reconnect attempt error");
  4729. self._reconnecting = false;
  4730. self.reconnect();
  4731. _this4.emitReserved("reconnect_error", err);
  4732. } else {
  4733. debug$1("reconnect success");
  4734. self.onreconnect();
  4735. }
  4736. });
  4737. }, delay);
  4738. if (this.opts.autoUnref) {
  4739. timer.unref();
  4740. }
  4741. this.subs.push(function () {
  4742. _this4.clearTimeoutFn(timer);
  4743. });
  4744. }
  4745. }
  4746. /**
  4747. * Called upon successful reconnect.
  4748. *
  4749. * @private
  4750. */;
  4751. _proto.onreconnect = function onreconnect() {
  4752. var attempt = this.backoff.attempts;
  4753. this._reconnecting = false;
  4754. this.backoff.reset();
  4755. this.emitReserved("reconnect", attempt);
  4756. };
  4757. return Manager;
  4758. }(Emitter);
  4759. var debug = debugModule("socket.io-client"); // debug()
  4760. /**
  4761. * Managers cache.
  4762. */
  4763. var cache = {};
  4764. function lookup(uri, opts) {
  4765. if (_typeof(uri) === "object") {
  4766. opts = uri;
  4767. uri = undefined;
  4768. }
  4769. opts = opts || {};
  4770. var parsed = url(uri, opts.path || "/socket.io");
  4771. var source = parsed.source;
  4772. var id = parsed.id;
  4773. var path = parsed.path;
  4774. var sameNamespace = cache[id] && path in cache[id]["nsps"];
  4775. var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
  4776. var io;
  4777. if (newConnection) {
  4778. debug("ignoring socket cache for %s", source);
  4779. io = new Manager(source, opts);
  4780. } else {
  4781. if (!cache[id]) {
  4782. debug("new io instance for %s", source);
  4783. cache[id] = new Manager(source, opts);
  4784. }
  4785. io = cache[id];
  4786. }
  4787. if (parsed.query && !opts.query) {
  4788. opts.query = parsed.queryKey;
  4789. }
  4790. return io.socket(parsed.path, opts);
  4791. }
  4792. // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
  4793. // namespace (e.g. `io.connect(...)`), for backward compatibility
  4794. _extends(lookup, {
  4795. Manager: Manager,
  4796. Socket: Socket,
  4797. io: lookup,
  4798. connect: lookup
  4799. });
  4800. return lookup;
  4801. }));
  4802. //# sourceMappingURL=socket.io.js.map