engine.io.js 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064
  1. /*!
  2. * Engine.IO v6.6.4
  3. * (c) 2014-2025 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.eio = 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 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
  199. var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
  200. // ArrayBuffer.isView method is not defined in IE10
  201. var isView = 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 && data instanceof Blob) {
  208. if (supportsBinary) {
  209. return callback(data);
  210. } else {
  211. return encodeBlobAsBase64(data, callback);
  212. }
  213. } else if (withNativeArrayBuffer$1 && (data instanceof ArrayBuffer || isView(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 && packet.data instanceof Blob) {
  243. return packet.data.arrayBuffer().then(toArray).then(callback);
  244. } else if (withNativeArrayBuffer$1 && (packet.data instanceof ArrayBuffer || isView(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 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  258. for (var i = 0; i < chars.length; i++) {
  259. lookup[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[base64.charCodeAt(i)];
  280. encoded2 = lookup[base64.charCodeAt(i + 1)];
  281. encoded3 = lookup[base64.charCodeAt(i + 2)];
  282. encoded4 = lookup[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 = 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) {
  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 = 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. function getDefaultExportFromCjs (x) {
  745. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  746. }
  747. var browser = {exports: {}};
  748. var ms;
  749. var hasRequiredMs;
  750. function requireMs() {
  751. if (hasRequiredMs) return ms;
  752. hasRequiredMs = 1;
  753. var s = 1000;
  754. var m = s * 60;
  755. var h = m * 60;
  756. var d = h * 24;
  757. var w = d * 7;
  758. var y = d * 365.25;
  759. /**
  760. * Parse or format the given `val`.
  761. *
  762. * Options:
  763. *
  764. * - `long` verbose formatting [false]
  765. *
  766. * @param {String|Number} val
  767. * @param {Object} [options]
  768. * @throws {Error} throw an error if val is not a non-empty string or a number
  769. * @return {String|Number}
  770. * @api public
  771. */
  772. ms = function ms(val, options) {
  773. options = options || {};
  774. var type = _typeof(val);
  775. if (type === 'string' && val.length > 0) {
  776. return parse(val);
  777. } else if (type === 'number' && isFinite(val)) {
  778. return options["long"] ? fmtLong(val) : fmtShort(val);
  779. }
  780. throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
  781. };
  782. /**
  783. * Parse the given `str` and return milliseconds.
  784. *
  785. * @param {String} str
  786. * @return {Number}
  787. * @api private
  788. */
  789. function parse(str) {
  790. str = String(str);
  791. if (str.length > 100) {
  792. return;
  793. }
  794. 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);
  795. if (!match) {
  796. return;
  797. }
  798. var n = parseFloat(match[1]);
  799. var type = (match[2] || 'ms').toLowerCase();
  800. switch (type) {
  801. case 'years':
  802. case 'year':
  803. case 'yrs':
  804. case 'yr':
  805. case 'y':
  806. return n * y;
  807. case 'weeks':
  808. case 'week':
  809. case 'w':
  810. return n * w;
  811. case 'days':
  812. case 'day':
  813. case 'd':
  814. return n * d;
  815. case 'hours':
  816. case 'hour':
  817. case 'hrs':
  818. case 'hr':
  819. case 'h':
  820. return n * h;
  821. case 'minutes':
  822. case 'minute':
  823. case 'mins':
  824. case 'min':
  825. case 'm':
  826. return n * m;
  827. case 'seconds':
  828. case 'second':
  829. case 'secs':
  830. case 'sec':
  831. case 's':
  832. return n * s;
  833. case 'milliseconds':
  834. case 'millisecond':
  835. case 'msecs':
  836. case 'msec':
  837. case 'ms':
  838. return n;
  839. default:
  840. return undefined;
  841. }
  842. }
  843. /**
  844. * Short format for `ms`.
  845. *
  846. * @param {Number} ms
  847. * @return {String}
  848. * @api private
  849. */
  850. function fmtShort(ms) {
  851. var msAbs = Math.abs(ms);
  852. if (msAbs >= d) {
  853. return Math.round(ms / d) + 'd';
  854. }
  855. if (msAbs >= h) {
  856. return Math.round(ms / h) + 'h';
  857. }
  858. if (msAbs >= m) {
  859. return Math.round(ms / m) + 'm';
  860. }
  861. if (msAbs >= s) {
  862. return Math.round(ms / s) + 's';
  863. }
  864. return ms + 'ms';
  865. }
  866. /**
  867. * Long format for `ms`.
  868. *
  869. * @param {Number} ms
  870. * @return {String}
  871. * @api private
  872. */
  873. function fmtLong(ms) {
  874. var msAbs = Math.abs(ms);
  875. if (msAbs >= d) {
  876. return plural(ms, msAbs, d, 'day');
  877. }
  878. if (msAbs >= h) {
  879. return plural(ms, msAbs, h, 'hour');
  880. }
  881. if (msAbs >= m) {
  882. return plural(ms, msAbs, m, 'minute');
  883. }
  884. if (msAbs >= s) {
  885. return plural(ms, msAbs, s, 'second');
  886. }
  887. return ms + ' ms';
  888. }
  889. /**
  890. * Pluralization helper.
  891. */
  892. function plural(ms, msAbs, n, name) {
  893. var isPlural = msAbs >= n * 1.5;
  894. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  895. }
  896. return ms;
  897. }
  898. /**
  899. * This is the common logic for both the Node.js and web browser
  900. * implementations of `debug()`.
  901. */
  902. function setup(env) {
  903. createDebug.debug = createDebug;
  904. createDebug["default"] = createDebug;
  905. createDebug.coerce = coerce;
  906. createDebug.disable = disable;
  907. createDebug.enable = enable;
  908. createDebug.enabled = enabled;
  909. createDebug.humanize = requireMs();
  910. createDebug.destroy = destroy;
  911. Object.keys(env).forEach(function (key) {
  912. createDebug[key] = env[key];
  913. });
  914. /**
  915. * The currently active debug mode names, and names to skip.
  916. */
  917. createDebug.names = [];
  918. createDebug.skips = [];
  919. /**
  920. * Map of special "%n" handling functions, for the debug "format" argument.
  921. *
  922. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  923. */
  924. createDebug.formatters = {};
  925. /**
  926. * Selects a color for a debug namespace
  927. * @param {String} namespace The namespace string for the debug instance to be colored
  928. * @return {Number|String} An ANSI color code for the given namespace
  929. * @api private
  930. */
  931. function selectColor(namespace) {
  932. var hash = 0;
  933. for (var i = 0; i < namespace.length; i++) {
  934. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  935. hash |= 0; // Convert to 32bit integer
  936. }
  937. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  938. }
  939. createDebug.selectColor = selectColor;
  940. /**
  941. * Create a debugger with the given `namespace`.
  942. *
  943. * @param {String} namespace
  944. * @return {Function}
  945. * @api public
  946. */
  947. function createDebug(namespace) {
  948. var prevTime;
  949. var enableOverride = null;
  950. var namespacesCache;
  951. var enabledCache;
  952. function debug() {
  953. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  954. args[_key] = arguments[_key];
  955. }
  956. // Disabled?
  957. if (!debug.enabled) {
  958. return;
  959. }
  960. var self = debug;
  961. // Set `diff` timestamp
  962. var curr = Number(new Date());
  963. var ms = curr - (prevTime || curr);
  964. self.diff = ms;
  965. self.prev = prevTime;
  966. self.curr = curr;
  967. prevTime = curr;
  968. args[0] = createDebug.coerce(args[0]);
  969. if (typeof args[0] !== 'string') {
  970. // Anything else let's inspect with %O
  971. args.unshift('%O');
  972. }
  973. // Apply any `formatters` transformations
  974. var index = 0;
  975. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  976. // If we encounter an escaped % then don't increase the array index
  977. if (match === '%%') {
  978. return '%';
  979. }
  980. index++;
  981. var formatter = createDebug.formatters[format];
  982. if (typeof formatter === 'function') {
  983. var val = args[index];
  984. match = formatter.call(self, val);
  985. // Now we need to remove `args[index]` since it's inlined in the `format`
  986. args.splice(index, 1);
  987. index--;
  988. }
  989. return match;
  990. });
  991. // Apply env-specific formatting (colors, etc.)
  992. createDebug.formatArgs.call(self, args);
  993. var logFn = self.log || createDebug.log;
  994. logFn.apply(self, args);
  995. }
  996. debug.namespace = namespace;
  997. debug.useColors = createDebug.useColors();
  998. debug.color = createDebug.selectColor(namespace);
  999. debug.extend = extend;
  1000. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  1001. Object.defineProperty(debug, 'enabled', {
  1002. enumerable: true,
  1003. configurable: false,
  1004. get: function get() {
  1005. if (enableOverride !== null) {
  1006. return enableOverride;
  1007. }
  1008. if (namespacesCache !== createDebug.namespaces) {
  1009. namespacesCache = createDebug.namespaces;
  1010. enabledCache = createDebug.enabled(namespace);
  1011. }
  1012. return enabledCache;
  1013. },
  1014. set: function set(v) {
  1015. enableOverride = v;
  1016. }
  1017. });
  1018. // Env-specific initialization logic for debug instances
  1019. if (typeof createDebug.init === 'function') {
  1020. createDebug.init(debug);
  1021. }
  1022. return debug;
  1023. }
  1024. function extend(namespace, delimiter) {
  1025. var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  1026. newDebug.log = this.log;
  1027. return newDebug;
  1028. }
  1029. /**
  1030. * Enables a debug mode by namespaces. This can include modes
  1031. * separated by a colon and wildcards.
  1032. *
  1033. * @param {String} namespaces
  1034. * @api public
  1035. */
  1036. function enable(namespaces) {
  1037. createDebug.save(namespaces);
  1038. createDebug.namespaces = namespaces;
  1039. createDebug.names = [];
  1040. createDebug.skips = [];
  1041. var split = (typeof namespaces === 'string' ? namespaces : '').trim().replace(/\s+/g, ',').split(',').filter(Boolean);
  1042. var _iterator = _createForOfIteratorHelper(split),
  1043. _step;
  1044. try {
  1045. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1046. var ns = _step.value;
  1047. if (ns[0] === '-') {
  1048. createDebug.skips.push(ns.slice(1));
  1049. } else {
  1050. createDebug.names.push(ns);
  1051. }
  1052. }
  1053. } catch (err) {
  1054. _iterator.e(err);
  1055. } finally {
  1056. _iterator.f();
  1057. }
  1058. }
  1059. /**
  1060. * Checks if the given string matches a namespace template, honoring
  1061. * asterisks as wildcards.
  1062. *
  1063. * @param {String} search
  1064. * @param {String} template
  1065. * @return {Boolean}
  1066. */
  1067. function matchesTemplate(search, template) {
  1068. var searchIndex = 0;
  1069. var templateIndex = 0;
  1070. var starIndex = -1;
  1071. var matchIndex = 0;
  1072. while (searchIndex < search.length) {
  1073. if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
  1074. // Match character or proceed with wildcard
  1075. if (template[templateIndex] === '*') {
  1076. starIndex = templateIndex;
  1077. matchIndex = searchIndex;
  1078. templateIndex++; // Skip the '*'
  1079. } else {
  1080. searchIndex++;
  1081. templateIndex++;
  1082. }
  1083. } else if (starIndex !== -1) {
  1084. // eslint-disable-line no-negated-condition
  1085. // Backtrack to the last '*' and try to match more characters
  1086. templateIndex = starIndex + 1;
  1087. matchIndex++;
  1088. searchIndex = matchIndex;
  1089. } else {
  1090. return false; // No match
  1091. }
  1092. }
  1093. // Handle trailing '*' in template
  1094. while (templateIndex < template.length && template[templateIndex] === '*') {
  1095. templateIndex++;
  1096. }
  1097. return templateIndex === template.length;
  1098. }
  1099. /**
  1100. * Disable debug output.
  1101. *
  1102. * @return {String} namespaces
  1103. * @api public
  1104. */
  1105. function disable() {
  1106. var namespaces = [].concat(_toConsumableArray(createDebug.names), _toConsumableArray(createDebug.skips.map(function (namespace) {
  1107. return '-' + namespace;
  1108. }))).join(',');
  1109. createDebug.enable('');
  1110. return namespaces;
  1111. }
  1112. /**
  1113. * Returns true if the given mode name is enabled, false otherwise.
  1114. *
  1115. * @param {String} name
  1116. * @return {Boolean}
  1117. * @api public
  1118. */
  1119. function enabled(name) {
  1120. var _iterator2 = _createForOfIteratorHelper(createDebug.skips),
  1121. _step2;
  1122. try {
  1123. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  1124. var skip = _step2.value;
  1125. if (matchesTemplate(name, skip)) {
  1126. return false;
  1127. }
  1128. }
  1129. } catch (err) {
  1130. _iterator2.e(err);
  1131. } finally {
  1132. _iterator2.f();
  1133. }
  1134. var _iterator3 = _createForOfIteratorHelper(createDebug.names),
  1135. _step3;
  1136. try {
  1137. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  1138. var ns = _step3.value;
  1139. if (matchesTemplate(name, ns)) {
  1140. return true;
  1141. }
  1142. }
  1143. } catch (err) {
  1144. _iterator3.e(err);
  1145. } finally {
  1146. _iterator3.f();
  1147. }
  1148. return false;
  1149. }
  1150. /**
  1151. * Coerce `val`.
  1152. *
  1153. * @param {Mixed} val
  1154. * @return {Mixed}
  1155. * @api private
  1156. */
  1157. function coerce(val) {
  1158. if (val instanceof Error) {
  1159. return val.stack || val.message;
  1160. }
  1161. return val;
  1162. }
  1163. /**
  1164. * XXX DO NOT USE. This is a temporary stub function.
  1165. * XXX It WILL be removed in the next major release.
  1166. */
  1167. function destroy() {
  1168. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  1169. }
  1170. createDebug.enable(createDebug.load());
  1171. return createDebug;
  1172. }
  1173. var common = setup;
  1174. /* eslint-env browser */
  1175. browser.exports;
  1176. (function (module, exports) {
  1177. /**
  1178. * This is the web browser implementation of `debug()`.
  1179. */
  1180. exports.formatArgs = formatArgs;
  1181. exports.save = save;
  1182. exports.load = load;
  1183. exports.useColors = useColors;
  1184. exports.storage = localstorage();
  1185. exports.destroy = function () {
  1186. var warned = false;
  1187. return function () {
  1188. if (!warned) {
  1189. warned = true;
  1190. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  1191. }
  1192. };
  1193. }();
  1194. /**
  1195. * Colors.
  1196. */
  1197. 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'];
  1198. /**
  1199. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1200. * and the Firebug extension (any Firefox version) are known
  1201. * to support "%c" CSS customizations.
  1202. *
  1203. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1204. */
  1205. // eslint-disable-next-line complexity
  1206. function useColors() {
  1207. // NB: In an Electron preload script, document will be defined but not fully
  1208. // initialized. Since we know we're in Chrome, we'll just detect this case
  1209. // explicitly
  1210. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  1211. return true;
  1212. }
  1213. // Internet Explorer and Edge do not support colors.
  1214. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  1215. return false;
  1216. }
  1217. var m;
  1218. // Is webkit? http://stackoverflow.com/a/16459606/376773
  1219. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  1220. // eslint-disable-next-line no-return-assign
  1221. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
  1222. // Is firebug? http://stackoverflow.com/a/398120/376773
  1223. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
  1224. // Is firefox >= v31?
  1225. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1226. typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 ||
  1227. // Double check webkit in userAgent just in case we are in a worker
  1228. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  1229. }
  1230. /**
  1231. * Colorize log arguments if enabled.
  1232. *
  1233. * @api public
  1234. */
  1235. function formatArgs(args) {
  1236. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  1237. if (!this.useColors) {
  1238. return;
  1239. }
  1240. var c = 'color: ' + this.color;
  1241. args.splice(1, 0, c, 'color: inherit');
  1242. // The final "%c" is somewhat tricky, because there could be other
  1243. // arguments passed either before or after the %c, so we need to
  1244. // figure out the correct index to insert the CSS into
  1245. var index = 0;
  1246. var lastC = 0;
  1247. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  1248. if (match === '%%') {
  1249. return;
  1250. }
  1251. index++;
  1252. if (match === '%c') {
  1253. // We only are interested in the *last* %c
  1254. // (the user may have provided their own)
  1255. lastC = index;
  1256. }
  1257. });
  1258. args.splice(lastC, 0, c);
  1259. }
  1260. /**
  1261. * Invokes `console.debug()` when available.
  1262. * No-op when `console.debug` is not a "function".
  1263. * If `console.debug` is not available, falls back
  1264. * to `console.log`.
  1265. *
  1266. * @api public
  1267. */
  1268. exports.log = console.debug || console.log || function () {};
  1269. /**
  1270. * Save `namespaces`.
  1271. *
  1272. * @param {String} namespaces
  1273. * @api private
  1274. */
  1275. function save(namespaces) {
  1276. try {
  1277. if (namespaces) {
  1278. exports.storage.setItem('debug', namespaces);
  1279. } else {
  1280. exports.storage.removeItem('debug');
  1281. }
  1282. } catch (error) {
  1283. // Swallow
  1284. // XXX (@Qix-) should we be logging these?
  1285. }
  1286. }
  1287. /**
  1288. * Load `namespaces`.
  1289. *
  1290. * @return {String} returns the previously persisted debug modes
  1291. * @api private
  1292. */
  1293. function load() {
  1294. var r;
  1295. try {
  1296. r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG');
  1297. } catch (error) {
  1298. // Swallow
  1299. // XXX (@Qix-) should we be logging these?
  1300. }
  1301. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  1302. if (!r && typeof process !== 'undefined' && 'env' in process) {
  1303. r = process.env.DEBUG;
  1304. }
  1305. return r;
  1306. }
  1307. /**
  1308. * Localstorage attempts to return the localstorage.
  1309. *
  1310. * This is necessary because safari throws
  1311. * when a user disables cookies/localstorage
  1312. * and you attempt to access it.
  1313. *
  1314. * @return {LocalStorage}
  1315. * @api private
  1316. */
  1317. function localstorage() {
  1318. try {
  1319. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  1320. // The Browser also has localStorage in the global context.
  1321. return localStorage;
  1322. } catch (error) {
  1323. // Swallow
  1324. // XXX (@Qix-) should we be logging these?
  1325. }
  1326. }
  1327. module.exports = common(exports);
  1328. var formatters = module.exports.formatters;
  1329. /**
  1330. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1331. */
  1332. formatters.j = function (v) {
  1333. try {
  1334. return JSON.stringify(v);
  1335. } catch (error) {
  1336. return '[UnexpectedJSONParseError]: ' + error.message;
  1337. }
  1338. };
  1339. })(browser, browser.exports);
  1340. var browserExports = browser.exports;
  1341. var debugModule = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
  1342. var debug$5 = debugModule("engine.io-client:transport"); // debug()
  1343. var TransportError = /*#__PURE__*/function (_Error) {
  1344. function TransportError(reason, description, context) {
  1345. var _this;
  1346. _this = _Error.call(this, reason) || this;
  1347. _this.description = description;
  1348. _this.context = context;
  1349. _this.type = "TransportError";
  1350. return _this;
  1351. }
  1352. _inheritsLoose(TransportError, _Error);
  1353. return TransportError;
  1354. }( /*#__PURE__*/_wrapNativeSuper(Error));
  1355. var Transport = /*#__PURE__*/function (_Emitter) {
  1356. /**
  1357. * Transport abstract constructor.
  1358. *
  1359. * @param {Object} opts - options
  1360. * @protected
  1361. */
  1362. function Transport(opts) {
  1363. var _this2;
  1364. _this2 = _Emitter.call(this) || this;
  1365. _this2.writable = false;
  1366. installTimerFunctions(_this2, opts);
  1367. _this2.opts = opts;
  1368. _this2.query = opts.query;
  1369. _this2.socket = opts.socket;
  1370. _this2.supportsBinary = !opts.forceBase64;
  1371. return _this2;
  1372. }
  1373. /**
  1374. * Emits an error.
  1375. *
  1376. * @param {String} reason
  1377. * @param description
  1378. * @param context - the error context
  1379. * @return {Transport} for chaining
  1380. * @protected
  1381. */
  1382. _inheritsLoose(Transport, _Emitter);
  1383. var _proto = Transport.prototype;
  1384. _proto.onError = function onError(reason, description, context) {
  1385. _Emitter.prototype.emitReserved.call(this, "error", new TransportError(reason, description, context));
  1386. return this;
  1387. }
  1388. /**
  1389. * Opens the transport.
  1390. */;
  1391. _proto.open = function open() {
  1392. this.readyState = "opening";
  1393. this.doOpen();
  1394. return this;
  1395. }
  1396. /**
  1397. * Closes the transport.
  1398. */;
  1399. _proto.close = function close() {
  1400. if (this.readyState === "opening" || this.readyState === "open") {
  1401. this.doClose();
  1402. this.onClose();
  1403. }
  1404. return this;
  1405. }
  1406. /**
  1407. * Sends multiple packets.
  1408. *
  1409. * @param {Array} packets
  1410. */;
  1411. _proto.send = function send(packets) {
  1412. if (this.readyState === "open") {
  1413. this.write(packets);
  1414. } else {
  1415. // this might happen if the transport was silently closed in the beforeunload event handler
  1416. debug$5("transport is not open, discarding packets");
  1417. }
  1418. }
  1419. /**
  1420. * Called upon open
  1421. *
  1422. * @protected
  1423. */;
  1424. _proto.onOpen = function onOpen() {
  1425. this.readyState = "open";
  1426. this.writable = true;
  1427. _Emitter.prototype.emitReserved.call(this, "open");
  1428. }
  1429. /**
  1430. * Called with data.
  1431. *
  1432. * @param {String} data
  1433. * @protected
  1434. */;
  1435. _proto.onData = function onData(data) {
  1436. var packet = decodePacket(data, this.socket.binaryType);
  1437. this.onPacket(packet);
  1438. }
  1439. /**
  1440. * Called with a decoded packet.
  1441. *
  1442. * @protected
  1443. */;
  1444. _proto.onPacket = function onPacket(packet) {
  1445. _Emitter.prototype.emitReserved.call(this, "packet", packet);
  1446. }
  1447. /**
  1448. * Called upon close.
  1449. *
  1450. * @protected
  1451. */;
  1452. _proto.onClose = function onClose(details) {
  1453. this.readyState = "closed";
  1454. _Emitter.prototype.emitReserved.call(this, "close", details);
  1455. }
  1456. /**
  1457. * Pauses the transport, in order not to lose packets during an upgrade.
  1458. *
  1459. * @param onPause
  1460. */;
  1461. _proto.pause = function pause(onPause) {};
  1462. _proto.createUri = function createUri(schema) {
  1463. var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1464. return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
  1465. };
  1466. _proto._hostname = function _hostname() {
  1467. var hostname = this.opts.hostname;
  1468. return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
  1469. };
  1470. _proto._port = function _port() {
  1471. if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) {
  1472. return ":" + this.opts.port;
  1473. } else {
  1474. return "";
  1475. }
  1476. };
  1477. _proto._query = function _query(query) {
  1478. var encodedQuery = encode(query);
  1479. return encodedQuery.length ? "?" + encodedQuery : "";
  1480. };
  1481. return Transport;
  1482. }(Emitter);
  1483. var debug$4 = debugModule("engine.io-client:polling"); // debug()
  1484. var Polling = /*#__PURE__*/function (_Transport) {
  1485. function Polling() {
  1486. var _this;
  1487. _this = _Transport.apply(this, arguments) || this;
  1488. _this._polling = false;
  1489. return _this;
  1490. }
  1491. _inheritsLoose(Polling, _Transport);
  1492. var _proto = Polling.prototype;
  1493. /**
  1494. * Opens the socket (triggers polling). We write a PING message to determine
  1495. * when the transport is open.
  1496. *
  1497. * @protected
  1498. */
  1499. _proto.doOpen = function doOpen() {
  1500. this._poll();
  1501. }
  1502. /**
  1503. * Pauses polling.
  1504. *
  1505. * @param {Function} onPause - callback upon buffers are flushed and transport is paused
  1506. * @package
  1507. */;
  1508. _proto.pause = function pause(onPause) {
  1509. var _this2 = this;
  1510. this.readyState = "pausing";
  1511. var pause = function pause() {
  1512. debug$4("paused");
  1513. _this2.readyState = "paused";
  1514. onPause();
  1515. };
  1516. if (this._polling || !this.writable) {
  1517. var total = 0;
  1518. if (this._polling) {
  1519. debug$4("we are currently polling - waiting to pause");
  1520. total++;
  1521. this.once("pollComplete", function () {
  1522. debug$4("pre-pause polling complete");
  1523. --total || pause();
  1524. });
  1525. }
  1526. if (!this.writable) {
  1527. debug$4("we are currently writing - waiting to pause");
  1528. total++;
  1529. this.once("drain", function () {
  1530. debug$4("pre-pause writing complete");
  1531. --total || pause();
  1532. });
  1533. }
  1534. } else {
  1535. pause();
  1536. }
  1537. }
  1538. /**
  1539. * Starts polling cycle.
  1540. *
  1541. * @private
  1542. */;
  1543. _proto._poll = function _poll() {
  1544. debug$4("polling");
  1545. this._polling = true;
  1546. this.doPoll();
  1547. this.emitReserved("poll");
  1548. }
  1549. /**
  1550. * Overloads onData to detect payloads.
  1551. *
  1552. * @protected
  1553. */;
  1554. _proto.onData = function onData(data) {
  1555. var _this3 = this;
  1556. debug$4("polling got data %s", data);
  1557. var callback = function callback(packet) {
  1558. // if its the first message we consider the transport open
  1559. if ("opening" === _this3.readyState && packet.type === "open") {
  1560. _this3.onOpen();
  1561. }
  1562. // if its a close packet, we close the ongoing requests
  1563. if ("close" === packet.type) {
  1564. _this3.onClose({
  1565. description: "transport closed by the server"
  1566. });
  1567. return false;
  1568. }
  1569. // otherwise bypass onData and handle the message
  1570. _this3.onPacket(packet);
  1571. };
  1572. // decode payload
  1573. decodePayload(data, this.socket.binaryType).forEach(callback);
  1574. // if an event did not trigger closing
  1575. if ("closed" !== this.readyState) {
  1576. // if we got data we're not polling
  1577. this._polling = false;
  1578. this.emitReserved("pollComplete");
  1579. if ("open" === this.readyState) {
  1580. this._poll();
  1581. } else {
  1582. debug$4('ignoring poll - transport state "%s"', this.readyState);
  1583. }
  1584. }
  1585. }
  1586. /**
  1587. * For polling, send a close packet.
  1588. *
  1589. * @protected
  1590. */;
  1591. _proto.doClose = function doClose() {
  1592. var _this4 = this;
  1593. var close = function close() {
  1594. debug$4("writing close packet");
  1595. _this4.write([{
  1596. type: "close"
  1597. }]);
  1598. };
  1599. if ("open" === this.readyState) {
  1600. debug$4("transport open - closing");
  1601. close();
  1602. } else {
  1603. // in case we're trying to close while
  1604. // handshaking is in progress (GH-164)
  1605. debug$4("transport not open - deferring close");
  1606. this.once("open", close);
  1607. }
  1608. }
  1609. /**
  1610. * Writes a packets payload.
  1611. *
  1612. * @param {Array} packets - data packets
  1613. * @protected
  1614. */;
  1615. _proto.write = function write(packets) {
  1616. var _this5 = this;
  1617. this.writable = false;
  1618. encodePayload(packets, function (data) {
  1619. _this5.doWrite(data, function () {
  1620. _this5.writable = true;
  1621. _this5.emitReserved("drain");
  1622. });
  1623. });
  1624. }
  1625. /**
  1626. * Generates uri for connection.
  1627. *
  1628. * @private
  1629. */;
  1630. _proto.uri = function uri() {
  1631. var schema = this.opts.secure ? "https" : "http";
  1632. var query = this.query || {};
  1633. // cache busting is forced
  1634. if (false !== this.opts.timestampRequests) {
  1635. query[this.opts.timestampParam] = randomString();
  1636. }
  1637. if (!this.supportsBinary && !query.sid) {
  1638. query.b64 = 1;
  1639. }
  1640. return this.createUri(schema, query);
  1641. };
  1642. return _createClass(Polling, [{
  1643. key: "name",
  1644. get: function get() {
  1645. return "polling";
  1646. }
  1647. }]);
  1648. }(Transport);
  1649. // imported from https://github.com/component/has-cors
  1650. var value = false;
  1651. try {
  1652. value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
  1653. } catch (err) {
  1654. // if XMLHttp support is disabled in IE then it will throw
  1655. // when trying to create
  1656. }
  1657. var hasCORS = value;
  1658. var debug$3 = debugModule("engine.io-client:polling"); // debug()
  1659. function empty() {}
  1660. var BaseXHR = /*#__PURE__*/function (_Polling) {
  1661. /**
  1662. * XHR Polling constructor.
  1663. *
  1664. * @param {Object} opts
  1665. * @package
  1666. */
  1667. function BaseXHR(opts) {
  1668. var _this;
  1669. _this = _Polling.call(this, opts) || this;
  1670. if (typeof location !== "undefined") {
  1671. var isSSL = "https:" === location.protocol;
  1672. var port = location.port;
  1673. // some user agents have empty `location.port`
  1674. if (!port) {
  1675. port = isSSL ? "443" : "80";
  1676. }
  1677. _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
  1678. }
  1679. return _this;
  1680. }
  1681. /**
  1682. * Sends data.
  1683. *
  1684. * @param {String} data to send.
  1685. * @param {Function} called upon flush.
  1686. * @private
  1687. */
  1688. _inheritsLoose(BaseXHR, _Polling);
  1689. var _proto = BaseXHR.prototype;
  1690. _proto.doWrite = function doWrite(data, fn) {
  1691. var _this2 = this;
  1692. var req = this.request({
  1693. method: "POST",
  1694. data: data
  1695. });
  1696. req.on("success", fn);
  1697. req.on("error", function (xhrStatus, context) {
  1698. _this2.onError("xhr post error", xhrStatus, context);
  1699. });
  1700. }
  1701. /**
  1702. * Starts a poll cycle.
  1703. *
  1704. * @private
  1705. */;
  1706. _proto.doPoll = function doPoll() {
  1707. var _this3 = this;
  1708. debug$3("xhr poll");
  1709. var req = this.request();
  1710. req.on("data", this.onData.bind(this));
  1711. req.on("error", function (xhrStatus, context) {
  1712. _this3.onError("xhr poll error", xhrStatus, context);
  1713. });
  1714. this.pollXhr = req;
  1715. };
  1716. return BaseXHR;
  1717. }(Polling);
  1718. var Request = /*#__PURE__*/function (_Emitter) {
  1719. /**
  1720. * Request constructor
  1721. *
  1722. * @param {Object} options
  1723. * @package
  1724. */
  1725. function Request(createRequest, uri, opts) {
  1726. var _this4;
  1727. _this4 = _Emitter.call(this) || this;
  1728. _this4.createRequest = createRequest;
  1729. installTimerFunctions(_this4, opts);
  1730. _this4._opts = opts;
  1731. _this4._method = opts.method || "GET";
  1732. _this4._uri = uri;
  1733. _this4._data = undefined !== opts.data ? opts.data : null;
  1734. _this4._create();
  1735. return _this4;
  1736. }
  1737. /**
  1738. * Creates the XHR object and sends the request.
  1739. *
  1740. * @private
  1741. */
  1742. _inheritsLoose(Request, _Emitter);
  1743. var _proto2 = Request.prototype;
  1744. _proto2._create = function _create() {
  1745. var _this5 = this;
  1746. var _a;
  1747. var opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  1748. opts.xdomain = !!this._opts.xd;
  1749. var xhr = this._xhr = this.createRequest(opts);
  1750. try {
  1751. debug$3("xhr open %s: %s", this._method, this._uri);
  1752. xhr.open(this._method, this._uri, true);
  1753. try {
  1754. if (this._opts.extraHeaders) {
  1755. // @ts-ignore
  1756. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  1757. for (var i in this._opts.extraHeaders) {
  1758. if (this._opts.extraHeaders.hasOwnProperty(i)) {
  1759. xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
  1760. }
  1761. }
  1762. }
  1763. } catch (e) {}
  1764. if ("POST" === this._method) {
  1765. try {
  1766. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  1767. } catch (e) {}
  1768. }
  1769. try {
  1770. xhr.setRequestHeader("Accept", "*/*");
  1771. } catch (e) {}
  1772. (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
  1773. // ie6 check
  1774. if ("withCredentials" in xhr) {
  1775. xhr.withCredentials = this._opts.withCredentials;
  1776. }
  1777. if (this._opts.requestTimeout) {
  1778. xhr.timeout = this._opts.requestTimeout;
  1779. }
  1780. xhr.onreadystatechange = function () {
  1781. var _a;
  1782. if (xhr.readyState === 3) {
  1783. (_a = _this5._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(
  1784. // @ts-ignore
  1785. xhr.getResponseHeader("set-cookie"));
  1786. }
  1787. if (4 !== xhr.readyState) return;
  1788. if (200 === xhr.status || 1223 === xhr.status) {
  1789. _this5._onLoad();
  1790. } else {
  1791. // make sure the `error` event handler that's user-set
  1792. // does not throw in the same tick and gets caught here
  1793. _this5.setTimeoutFn(function () {
  1794. _this5._onError(typeof xhr.status === "number" ? xhr.status : 0);
  1795. }, 0);
  1796. }
  1797. };
  1798. debug$3("xhr data %s", this._data);
  1799. xhr.send(this._data);
  1800. } catch (e) {
  1801. // Need to defer since .create() is called directly from the constructor
  1802. // and thus the 'error' event can only be only bound *after* this exception
  1803. // occurs. Therefore, also, we cannot throw here at all.
  1804. this.setTimeoutFn(function () {
  1805. _this5._onError(e);
  1806. }, 0);
  1807. return;
  1808. }
  1809. if (typeof document !== "undefined") {
  1810. this._index = Request.requestsCount++;
  1811. Request.requests[this._index] = this;
  1812. }
  1813. }
  1814. /**
  1815. * Called upon error.
  1816. *
  1817. * @private
  1818. */;
  1819. _proto2._onError = function _onError(err) {
  1820. this.emitReserved("error", err, this._xhr);
  1821. this._cleanup(true);
  1822. }
  1823. /**
  1824. * Cleans up house.
  1825. *
  1826. * @private
  1827. */;
  1828. _proto2._cleanup = function _cleanup(fromError) {
  1829. if ("undefined" === typeof this._xhr || null === this._xhr) {
  1830. return;
  1831. }
  1832. this._xhr.onreadystatechange = empty;
  1833. if (fromError) {
  1834. try {
  1835. this._xhr.abort();
  1836. } catch (e) {}
  1837. }
  1838. if (typeof document !== "undefined") {
  1839. delete Request.requests[this._index];
  1840. }
  1841. this._xhr = null;
  1842. }
  1843. /**
  1844. * Called upon load.
  1845. *
  1846. * @private
  1847. */;
  1848. _proto2._onLoad = function _onLoad() {
  1849. var data = this._xhr.responseText;
  1850. if (data !== null) {
  1851. this.emitReserved("data", data);
  1852. this.emitReserved("success");
  1853. this._cleanup();
  1854. }
  1855. }
  1856. /**
  1857. * Aborts the request.
  1858. *
  1859. * @package
  1860. */;
  1861. _proto2.abort = function abort() {
  1862. this._cleanup();
  1863. };
  1864. return Request;
  1865. }(Emitter);
  1866. Request.requestsCount = 0;
  1867. Request.requests = {};
  1868. /**
  1869. * Aborts pending requests when unloading the window. This is needed to prevent
  1870. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1871. * emitted.
  1872. */
  1873. if (typeof document !== "undefined") {
  1874. // @ts-ignore
  1875. if (typeof attachEvent === "function") {
  1876. // @ts-ignore
  1877. attachEvent("onunload", unloadHandler);
  1878. } else if (typeof addEventListener === "function") {
  1879. var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
  1880. addEventListener(terminationEvent, unloadHandler, false);
  1881. }
  1882. }
  1883. function unloadHandler() {
  1884. for (var i in Request.requests) {
  1885. if (Request.requests.hasOwnProperty(i)) {
  1886. Request.requests[i].abort();
  1887. }
  1888. }
  1889. }
  1890. var hasXHR2 = function () {
  1891. var xhr = newRequest({
  1892. xdomain: false
  1893. });
  1894. return xhr && xhr.responseType !== null;
  1895. }();
  1896. /**
  1897. * HTTP long-polling based on the built-in `XMLHttpRequest` object.
  1898. *
  1899. * Usage: browser
  1900. *
  1901. * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  1902. */
  1903. var XHR = /*#__PURE__*/function (_BaseXHR) {
  1904. function XHR(opts) {
  1905. var _this6;
  1906. _this6 = _BaseXHR.call(this, opts) || this;
  1907. var forceBase64 = opts && opts.forceBase64;
  1908. _this6.supportsBinary = hasXHR2 && !forceBase64;
  1909. return _this6;
  1910. }
  1911. _inheritsLoose(XHR, _BaseXHR);
  1912. var _proto3 = XHR.prototype;
  1913. _proto3.request = function request() {
  1914. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1915. _extends(opts, {
  1916. xd: this.xd
  1917. }, this.opts);
  1918. return new Request(newRequest, this.uri(), opts);
  1919. };
  1920. return XHR;
  1921. }(BaseXHR);
  1922. function newRequest(opts) {
  1923. var xdomain = opts.xdomain;
  1924. // XMLHttpRequest can be disabled on IE
  1925. try {
  1926. if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  1927. return new XMLHttpRequest();
  1928. }
  1929. } catch (e) {}
  1930. if (!xdomain) {
  1931. try {
  1932. return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
  1933. } catch (e) {}
  1934. }
  1935. }
  1936. var debug$2 = debugModule("engine.io-client:websocket"); // debug()
  1937. // detect ReactNative environment
  1938. var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
  1939. var BaseWS = /*#__PURE__*/function (_Transport) {
  1940. function BaseWS() {
  1941. return _Transport.apply(this, arguments) || this;
  1942. }
  1943. _inheritsLoose(BaseWS, _Transport);
  1944. var _proto = BaseWS.prototype;
  1945. _proto.doOpen = function doOpen() {
  1946. var uri = this.uri();
  1947. var protocols = this.opts.protocols;
  1948. // React Native only supports the 'headers' option, and will print a warning if anything else is passed
  1949. var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
  1950. if (this.opts.extraHeaders) {
  1951. opts.headers = this.opts.extraHeaders;
  1952. }
  1953. try {
  1954. this.ws = this.createSocket(uri, protocols, opts);
  1955. } catch (err) {
  1956. return this.emitReserved("error", err);
  1957. }
  1958. this.ws.binaryType = this.socket.binaryType;
  1959. this.addEventListeners();
  1960. }
  1961. /**
  1962. * Adds event listeners to the socket
  1963. *
  1964. * @private
  1965. */;
  1966. _proto.addEventListeners = function addEventListeners() {
  1967. var _this = this;
  1968. this.ws.onopen = function () {
  1969. if (_this.opts.autoUnref) {
  1970. _this.ws._socket.unref();
  1971. }
  1972. _this.onOpen();
  1973. };
  1974. this.ws.onclose = function (closeEvent) {
  1975. return _this.onClose({
  1976. description: "websocket connection closed",
  1977. context: closeEvent
  1978. });
  1979. };
  1980. this.ws.onmessage = function (ev) {
  1981. return _this.onData(ev.data);
  1982. };
  1983. this.ws.onerror = function (e) {
  1984. return _this.onError("websocket error", e);
  1985. };
  1986. };
  1987. _proto.write = function write(packets) {
  1988. var _this2 = this;
  1989. this.writable = false;
  1990. // encodePacket efficient as it uses WS framing
  1991. // no need for encodePayload
  1992. var _loop = function _loop() {
  1993. var packet = packets[i];
  1994. var lastPacket = i === packets.length - 1;
  1995. encodePacket(packet, _this2.supportsBinary, function (data) {
  1996. // Sometimes the websocket has already been closed but the browser didn't
  1997. // have a chance of informing us about it yet, in that case send will
  1998. // throw an error
  1999. try {
  2000. _this2.doWrite(packet, data);
  2001. } catch (e) {
  2002. debug$2("websocket closed before onclose event");
  2003. }
  2004. if (lastPacket) {
  2005. // fake drain
  2006. // defer to next tick to allow Socket to clear writeBuffer
  2007. nextTick(function () {
  2008. _this2.writable = true;
  2009. _this2.emitReserved("drain");
  2010. }, _this2.setTimeoutFn);
  2011. }
  2012. });
  2013. };
  2014. for (var i = 0; i < packets.length; i++) {
  2015. _loop();
  2016. }
  2017. };
  2018. _proto.doClose = function doClose() {
  2019. if (typeof this.ws !== "undefined") {
  2020. this.ws.onerror = function () {};
  2021. this.ws.close();
  2022. this.ws = null;
  2023. }
  2024. }
  2025. /**
  2026. * Generates uri for connection.
  2027. *
  2028. * @private
  2029. */;
  2030. _proto.uri = function uri() {
  2031. var schema = this.opts.secure ? "wss" : "ws";
  2032. var query = this.query || {};
  2033. // append timestamp to URI
  2034. if (this.opts.timestampRequests) {
  2035. query[this.opts.timestampParam] = randomString();
  2036. }
  2037. // communicate binary support capabilities
  2038. if (!this.supportsBinary) {
  2039. query.b64 = 1;
  2040. }
  2041. return this.createUri(schema, query);
  2042. };
  2043. return _createClass(BaseWS, [{
  2044. key: "name",
  2045. get: function get() {
  2046. return "websocket";
  2047. }
  2048. }]);
  2049. }(Transport);
  2050. var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
  2051. /**
  2052. * WebSocket transport based on the built-in `WebSocket` object.
  2053. *
  2054. * Usage: browser, Node.js (since v21), Deno, Bun
  2055. *
  2056. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
  2057. * @see https://caniuse.com/mdn-api_websocket
  2058. * @see https://nodejs.org/api/globals.html#websocket
  2059. */
  2060. var WS = /*#__PURE__*/function (_BaseWS) {
  2061. function WS() {
  2062. return _BaseWS.apply(this, arguments) || this;
  2063. }
  2064. _inheritsLoose(WS, _BaseWS);
  2065. var _proto2 = WS.prototype;
  2066. _proto2.createSocket = function createSocket(uri, protocols, opts) {
  2067. return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
  2068. };
  2069. _proto2.doWrite = function doWrite(_packet, data) {
  2070. this.ws.send(data);
  2071. };
  2072. return WS;
  2073. }(BaseWS);
  2074. var debug$1 = debugModule("engine.io-client:webtransport"); // debug()
  2075. /**
  2076. * WebTransport transport based on the built-in `WebTransport` object.
  2077. *
  2078. * Usage: browser, Node.js (with the `@fails-components/webtransport` package)
  2079. *
  2080. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
  2081. * @see https://caniuse.com/webtransport
  2082. */
  2083. var WT = /*#__PURE__*/function (_Transport) {
  2084. function WT() {
  2085. return _Transport.apply(this, arguments) || this;
  2086. }
  2087. _inheritsLoose(WT, _Transport);
  2088. var _proto = WT.prototype;
  2089. _proto.doOpen = function doOpen() {
  2090. var _this = this;
  2091. try {
  2092. // @ts-ignore
  2093. this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
  2094. } catch (err) {
  2095. return this.emitReserved("error", err);
  2096. }
  2097. this._transport.closed.then(function () {
  2098. debug$1("transport closed gracefully");
  2099. _this.onClose();
  2100. })["catch"](function (err) {
  2101. debug$1("transport closed due to %s", err);
  2102. _this.onError("webtransport error", err);
  2103. });
  2104. // note: we could have used async/await, but that would require some additional polyfills
  2105. this._transport.ready.then(function () {
  2106. _this._transport.createBidirectionalStream().then(function (stream) {
  2107. var decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, _this.socket.binaryType);
  2108. var reader = stream.readable.pipeThrough(decoderStream).getReader();
  2109. var encoderStream = createPacketEncoderStream();
  2110. encoderStream.readable.pipeTo(stream.writable);
  2111. _this._writer = encoderStream.writable.getWriter();
  2112. var read = function read() {
  2113. reader.read().then(function (_ref) {
  2114. var done = _ref.done,
  2115. value = _ref.value;
  2116. if (done) {
  2117. debug$1("session is closed");
  2118. return;
  2119. }
  2120. debug$1("received chunk: %o", value);
  2121. _this.onPacket(value);
  2122. read();
  2123. })["catch"](function (err) {
  2124. debug$1("an error occurred while reading: %s", err);
  2125. });
  2126. };
  2127. read();
  2128. var packet = {
  2129. type: "open"
  2130. };
  2131. if (_this.query.sid) {
  2132. packet.data = "{\"sid\":\"".concat(_this.query.sid, "\"}");
  2133. }
  2134. _this._writer.write(packet).then(function () {
  2135. return _this.onOpen();
  2136. });
  2137. });
  2138. });
  2139. };
  2140. _proto.write = function write(packets) {
  2141. var _this2 = this;
  2142. this.writable = false;
  2143. var _loop = function _loop() {
  2144. var packet = packets[i];
  2145. var lastPacket = i === packets.length - 1;
  2146. _this2._writer.write(packet).then(function () {
  2147. if (lastPacket) {
  2148. nextTick(function () {
  2149. _this2.writable = true;
  2150. _this2.emitReserved("drain");
  2151. }, _this2.setTimeoutFn);
  2152. }
  2153. });
  2154. };
  2155. for (var i = 0; i < packets.length; i++) {
  2156. _loop();
  2157. }
  2158. };
  2159. _proto.doClose = function doClose() {
  2160. var _a;
  2161. (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
  2162. };
  2163. return _createClass(WT, [{
  2164. key: "name",
  2165. get: function get() {
  2166. return "webtransport";
  2167. }
  2168. }]);
  2169. }(Transport);
  2170. var transports = {
  2171. websocket: WS,
  2172. webtransport: WT,
  2173. polling: XHR
  2174. };
  2175. // imported from https://github.com/galkn/parseuri
  2176. /**
  2177. * Parses a URI
  2178. *
  2179. * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
  2180. *
  2181. * See:
  2182. * - https://developer.mozilla.org/en-US/docs/Web/API/URL
  2183. * - https://caniuse.com/url
  2184. * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
  2185. *
  2186. * History of the parse() method:
  2187. * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
  2188. * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
  2189. * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
  2190. *
  2191. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  2192. * @api private
  2193. */
  2194. var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  2195. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
  2196. function parse(str) {
  2197. if (str.length > 8000) {
  2198. throw "URI too long";
  2199. }
  2200. var src = str,
  2201. b = str.indexOf('['),
  2202. e = str.indexOf(']');
  2203. if (b != -1 && e != -1) {
  2204. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  2205. }
  2206. var m = re.exec(str || ''),
  2207. uri = {},
  2208. i = 14;
  2209. while (i--) {
  2210. uri[parts[i]] = m[i] || '';
  2211. }
  2212. if (b != -1 && e != -1) {
  2213. uri.source = src;
  2214. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  2215. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  2216. uri.ipv6uri = true;
  2217. }
  2218. uri.pathNames = pathNames(uri, uri['path']);
  2219. uri.queryKey = queryKey(uri, uri['query']);
  2220. return uri;
  2221. }
  2222. function pathNames(obj, path) {
  2223. var regx = /\/{2,9}/g,
  2224. names = path.replace(regx, "/").split("/");
  2225. if (path.slice(0, 1) == '/' || path.length === 0) {
  2226. names.splice(0, 1);
  2227. }
  2228. if (path.slice(-1) == '/') {
  2229. names.splice(names.length - 1, 1);
  2230. }
  2231. return names;
  2232. }
  2233. function queryKey(uri, query) {
  2234. var data = {};
  2235. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  2236. if ($1) {
  2237. data[$1] = $2;
  2238. }
  2239. });
  2240. return data;
  2241. }
  2242. var debug = debugModule("engine.io-client:socket"); // debug()
  2243. var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
  2244. var OFFLINE_EVENT_LISTENERS = [];
  2245. if (withEventListeners) {
  2246. // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the
  2247. // script, so we create one single event listener here which will forward the event to the socket instances
  2248. addEventListener("offline", function () {
  2249. debug("closing %d connection(s) because the network was lost", OFFLINE_EVENT_LISTENERS.length);
  2250. OFFLINE_EVENT_LISTENERS.forEach(function (listener) {
  2251. return listener();
  2252. });
  2253. }, false);
  2254. }
  2255. /**
  2256. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2257. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2258. *
  2259. * This class comes without upgrade mechanism, which means that it will keep the first low-level transport that
  2260. * successfully establishes the connection.
  2261. *
  2262. * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
  2263. *
  2264. * @example
  2265. * import { SocketWithoutUpgrade, WebSocket } from "engine.io-client";
  2266. *
  2267. * const socket = new SocketWithoutUpgrade({
  2268. * transports: [WebSocket]
  2269. * });
  2270. *
  2271. * socket.on("open", () => {
  2272. * socket.send("hello");
  2273. * });
  2274. *
  2275. * @see SocketWithUpgrade
  2276. * @see Socket
  2277. */
  2278. var SocketWithoutUpgrade = /*#__PURE__*/function (_Emitter) {
  2279. /**
  2280. * Socket constructor.
  2281. *
  2282. * @param {String|Object} uri - uri or options
  2283. * @param {Object} opts - options
  2284. */
  2285. function SocketWithoutUpgrade(uri, opts) {
  2286. var _this;
  2287. _this = _Emitter.call(this) || this;
  2288. _this.binaryType = defaultBinaryType;
  2289. _this.writeBuffer = [];
  2290. _this._prevBufferLen = 0;
  2291. _this._pingInterval = -1;
  2292. _this._pingTimeout = -1;
  2293. _this._maxPayload = -1;
  2294. /**
  2295. * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the
  2296. * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.
  2297. */
  2298. _this._pingTimeoutTime = Infinity;
  2299. if (uri && "object" === _typeof(uri)) {
  2300. opts = uri;
  2301. uri = null;
  2302. }
  2303. if (uri) {
  2304. var parsedUri = parse(uri);
  2305. opts.hostname = parsedUri.host;
  2306. opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
  2307. opts.port = parsedUri.port;
  2308. if (parsedUri.query) opts.query = parsedUri.query;
  2309. } else if (opts.host) {
  2310. opts.hostname = parse(opts.host).host;
  2311. }
  2312. installTimerFunctions(_this, opts);
  2313. _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
  2314. if (opts.hostname && !opts.port) {
  2315. // if no port is specified manually, use the protocol default
  2316. opts.port = _this.secure ? "443" : "80";
  2317. }
  2318. _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
  2319. _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
  2320. _this.transports = [];
  2321. _this._transportsByName = {};
  2322. opts.transports.forEach(function (t) {
  2323. var transportName = t.prototype.name;
  2324. _this.transports.push(transportName);
  2325. _this._transportsByName[transportName] = t;
  2326. });
  2327. _this.opts = _extends({
  2328. path: "/engine.io",
  2329. agent: false,
  2330. withCredentials: false,
  2331. upgrade: true,
  2332. timestampParam: "t",
  2333. rememberUpgrade: false,
  2334. addTrailingSlash: true,
  2335. rejectUnauthorized: true,
  2336. perMessageDeflate: {
  2337. threshold: 1024
  2338. },
  2339. transportOptions: {},
  2340. closeOnBeforeunload: false
  2341. }, opts);
  2342. _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : "");
  2343. if (typeof _this.opts.query === "string") {
  2344. _this.opts.query = decode(_this.opts.query);
  2345. }
  2346. if (withEventListeners) {
  2347. if (_this.opts.closeOnBeforeunload) {
  2348. // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
  2349. // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
  2350. // closed/reloaded)
  2351. _this._beforeunloadEventListener = function () {
  2352. if (_this.transport) {
  2353. // silently close the transport
  2354. _this.transport.removeAllListeners();
  2355. _this.transport.close();
  2356. }
  2357. };
  2358. addEventListener("beforeunload", _this._beforeunloadEventListener, false);
  2359. }
  2360. if (_this.hostname !== "localhost") {
  2361. debug("adding listener for the 'offline' event");
  2362. _this._offlineEventListener = function () {
  2363. _this._onClose("transport close", {
  2364. description: "network connection lost"
  2365. });
  2366. };
  2367. OFFLINE_EVENT_LISTENERS.push(_this._offlineEventListener);
  2368. }
  2369. }
  2370. if (_this.opts.withCredentials) {
  2371. _this._cookieJar = createCookieJar();
  2372. }
  2373. _this._open();
  2374. return _this;
  2375. }
  2376. /**
  2377. * Creates transport of the given type.
  2378. *
  2379. * @param {String} name - transport name
  2380. * @return {Transport}
  2381. * @private
  2382. */
  2383. _inheritsLoose(SocketWithoutUpgrade, _Emitter);
  2384. var _proto = SocketWithoutUpgrade.prototype;
  2385. _proto.createTransport = function createTransport(name) {
  2386. debug('creating transport "%s"', name);
  2387. var query = _extends({}, this.opts.query);
  2388. // append engine.io protocol identifier
  2389. query.EIO = protocol;
  2390. // transport name
  2391. query.transport = name;
  2392. // session id if we already have one
  2393. if (this.id) query.sid = this.id;
  2394. var opts = _extends({}, this.opts, {
  2395. query: query,
  2396. socket: this,
  2397. hostname: this.hostname,
  2398. secure: this.secure,
  2399. port: this.port
  2400. }, this.opts.transportOptions[name]);
  2401. debug("options: %j", opts);
  2402. return new this._transportsByName[name](opts);
  2403. }
  2404. /**
  2405. * Initializes transport to use and starts probe.
  2406. *
  2407. * @private
  2408. */;
  2409. _proto._open = function _open() {
  2410. var _this2 = this;
  2411. if (this.transports.length === 0) {
  2412. // Emit error on next tick so it can be listened to
  2413. this.setTimeoutFn(function () {
  2414. _this2.emitReserved("error", "No transports available");
  2415. }, 0);
  2416. return;
  2417. }
  2418. var transportName = this.opts.rememberUpgrade && SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
  2419. this.readyState = "opening";
  2420. var transport = this.createTransport(transportName);
  2421. transport.open();
  2422. this.setTransport(transport);
  2423. }
  2424. /**
  2425. * Sets the current transport. Disables the existing one (if any).
  2426. *
  2427. * @private
  2428. */;
  2429. _proto.setTransport = function setTransport(transport) {
  2430. var _this3 = this;
  2431. debug("setting transport %s", transport.name);
  2432. if (this.transport) {
  2433. debug("clearing existing transport %s", this.transport.name);
  2434. this.transport.removeAllListeners();
  2435. }
  2436. // set up transport
  2437. this.transport = transport;
  2438. // set up transport listeners
  2439. transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", function (reason) {
  2440. return _this3._onClose("transport close", reason);
  2441. });
  2442. }
  2443. /**
  2444. * Called when connection is deemed open.
  2445. *
  2446. * @private
  2447. */;
  2448. _proto.onOpen = function onOpen() {
  2449. debug("socket open");
  2450. this.readyState = "open";
  2451. SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
  2452. this.emitReserved("open");
  2453. this.flush();
  2454. }
  2455. /**
  2456. * Handles a packet.
  2457. *
  2458. * @private
  2459. */;
  2460. _proto._onPacket = function _onPacket(packet) {
  2461. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  2462. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  2463. this.emitReserved("packet", packet);
  2464. // Socket is live - any packet counts
  2465. this.emitReserved("heartbeat");
  2466. switch (packet.type) {
  2467. case "open":
  2468. this.onHandshake(JSON.parse(packet.data));
  2469. break;
  2470. case "ping":
  2471. this._sendPacket("pong");
  2472. this.emitReserved("ping");
  2473. this.emitReserved("pong");
  2474. this._resetPingTimeout();
  2475. break;
  2476. case "error":
  2477. var err = new Error("server error");
  2478. // @ts-ignore
  2479. err.code = packet.data;
  2480. this._onError(err);
  2481. break;
  2482. case "message":
  2483. this.emitReserved("data", packet.data);
  2484. this.emitReserved("message", packet.data);
  2485. break;
  2486. }
  2487. } else {
  2488. debug('packet received with socket readyState "%s"', this.readyState);
  2489. }
  2490. }
  2491. /**
  2492. * Called upon handshake completion.
  2493. *
  2494. * @param {Object} data - handshake obj
  2495. * @private
  2496. */;
  2497. _proto.onHandshake = function onHandshake(data) {
  2498. this.emitReserved("handshake", data);
  2499. this.id = data.sid;
  2500. this.transport.query.sid = data.sid;
  2501. this._pingInterval = data.pingInterval;
  2502. this._pingTimeout = data.pingTimeout;
  2503. this._maxPayload = data.maxPayload;
  2504. this.onOpen();
  2505. // In case open handler closes socket
  2506. if ("closed" === this.readyState) return;
  2507. this._resetPingTimeout();
  2508. }
  2509. /**
  2510. * Sets and resets ping timeout timer based on server pings.
  2511. *
  2512. * @private
  2513. */;
  2514. _proto._resetPingTimeout = function _resetPingTimeout() {
  2515. var _this4 = this;
  2516. this.clearTimeoutFn(this._pingTimeoutTimer);
  2517. var delay = this._pingInterval + this._pingTimeout;
  2518. this._pingTimeoutTime = Date.now() + delay;
  2519. this._pingTimeoutTimer = this.setTimeoutFn(function () {
  2520. _this4._onClose("ping timeout");
  2521. }, delay);
  2522. if (this.opts.autoUnref) {
  2523. this._pingTimeoutTimer.unref();
  2524. }
  2525. }
  2526. /**
  2527. * Called on `drain` event
  2528. *
  2529. * @private
  2530. */;
  2531. _proto._onDrain = function _onDrain() {
  2532. this.writeBuffer.splice(0, this._prevBufferLen);
  2533. // setting prevBufferLen = 0 is very important
  2534. // for example, when upgrading, upgrade packet is sent over,
  2535. // and a nonzero prevBufferLen could cause problems on `drain`
  2536. this._prevBufferLen = 0;
  2537. if (0 === this.writeBuffer.length) {
  2538. this.emitReserved("drain");
  2539. } else {
  2540. this.flush();
  2541. }
  2542. }
  2543. /**
  2544. * Flush write buffers.
  2545. *
  2546. * @private
  2547. */;
  2548. _proto.flush = function flush() {
  2549. if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
  2550. var packets = this._getWritablePackets();
  2551. debug("flushing %d packets in socket", packets.length);
  2552. this.transport.send(packets);
  2553. // keep track of current length of writeBuffer
  2554. // splice writeBuffer and callbackBuffer on `drain`
  2555. this._prevBufferLen = packets.length;
  2556. this.emitReserved("flush");
  2557. }
  2558. }
  2559. /**
  2560. * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
  2561. * long-polling)
  2562. *
  2563. * @private
  2564. */;
  2565. _proto._getWritablePackets = function _getWritablePackets() {
  2566. var shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
  2567. if (!shouldCheckPayloadSize) {
  2568. return this.writeBuffer;
  2569. }
  2570. var payloadSize = 1; // first packet type
  2571. for (var i = 0; i < this.writeBuffer.length; i++) {
  2572. var data = this.writeBuffer[i].data;
  2573. if (data) {
  2574. payloadSize += byteLength(data);
  2575. }
  2576. if (i > 0 && payloadSize > this._maxPayload) {
  2577. debug("only send %d out of %d packets", i, this.writeBuffer.length);
  2578. return this.writeBuffer.slice(0, i);
  2579. }
  2580. payloadSize += 2; // separator + packet type
  2581. }
  2582. debug("payload size is %d (max: %d)", payloadSize, this._maxPayload);
  2583. return this.writeBuffer;
  2584. }
  2585. /**
  2586. * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
  2587. *
  2588. * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
  2589. * `write()` method then the message would not be buffered by the Socket.IO client.
  2590. *
  2591. * @return {boolean}
  2592. * @private
  2593. */
  2594. /* private */;
  2595. _proto._hasPingExpired = function _hasPingExpired() {
  2596. var _this5 = this;
  2597. if (!this._pingTimeoutTime) return true;
  2598. var hasExpired = Date.now() > this._pingTimeoutTime;
  2599. if (hasExpired) {
  2600. debug("throttled timer detected, scheduling connection close");
  2601. this._pingTimeoutTime = 0;
  2602. nextTick(function () {
  2603. _this5._onClose("ping timeout");
  2604. }, this.setTimeoutFn);
  2605. }
  2606. return hasExpired;
  2607. }
  2608. /**
  2609. * Sends a message.
  2610. *
  2611. * @param {String} msg - message.
  2612. * @param {Object} options.
  2613. * @param {Function} fn - callback function.
  2614. * @return {Socket} for chaining.
  2615. */;
  2616. _proto.write = function write(msg, options, fn) {
  2617. this._sendPacket("message", msg, options, fn);
  2618. return this;
  2619. }
  2620. /**
  2621. * Sends a message. Alias of {@link Socket#write}.
  2622. *
  2623. * @param {String} msg - message.
  2624. * @param {Object} options.
  2625. * @param {Function} fn - callback function.
  2626. * @return {Socket} for chaining.
  2627. */;
  2628. _proto.send = function send(msg, options, fn) {
  2629. this._sendPacket("message", msg, options, fn);
  2630. return this;
  2631. }
  2632. /**
  2633. * Sends a packet.
  2634. *
  2635. * @param {String} type: packet type.
  2636. * @param {String} data.
  2637. * @param {Object} options.
  2638. * @param {Function} fn - callback function.
  2639. * @private
  2640. */;
  2641. _proto._sendPacket = function _sendPacket(type, data, options, fn) {
  2642. if ("function" === typeof data) {
  2643. fn = data;
  2644. data = undefined;
  2645. }
  2646. if ("function" === typeof options) {
  2647. fn = options;
  2648. options = null;
  2649. }
  2650. if ("closing" === this.readyState || "closed" === this.readyState) {
  2651. return;
  2652. }
  2653. options = options || {};
  2654. options.compress = false !== options.compress;
  2655. var packet = {
  2656. type: type,
  2657. data: data,
  2658. options: options
  2659. };
  2660. this.emitReserved("packetCreate", packet);
  2661. this.writeBuffer.push(packet);
  2662. if (fn) this.once("flush", fn);
  2663. this.flush();
  2664. }
  2665. /**
  2666. * Closes the connection.
  2667. */;
  2668. _proto.close = function close() {
  2669. var _this6 = this;
  2670. var close = function close() {
  2671. _this6._onClose("forced close");
  2672. debug("socket closing - telling transport to close");
  2673. _this6.transport.close();
  2674. };
  2675. var cleanupAndClose = function cleanupAndClose() {
  2676. _this6.off("upgrade", cleanupAndClose);
  2677. _this6.off("upgradeError", cleanupAndClose);
  2678. close();
  2679. };
  2680. var waitForUpgrade = function waitForUpgrade() {
  2681. // wait for upgrade to finish since we can't send packets while pausing a transport
  2682. _this6.once("upgrade", cleanupAndClose);
  2683. _this6.once("upgradeError", cleanupAndClose);
  2684. };
  2685. if ("opening" === this.readyState || "open" === this.readyState) {
  2686. this.readyState = "closing";
  2687. if (this.writeBuffer.length) {
  2688. this.once("drain", function () {
  2689. if (_this6.upgrading) {
  2690. waitForUpgrade();
  2691. } else {
  2692. close();
  2693. }
  2694. });
  2695. } else if (this.upgrading) {
  2696. waitForUpgrade();
  2697. } else {
  2698. close();
  2699. }
  2700. }
  2701. return this;
  2702. }
  2703. /**
  2704. * Called upon transport error
  2705. *
  2706. * @private
  2707. */;
  2708. _proto._onError = function _onError(err) {
  2709. debug("socket error %j", err);
  2710. SocketWithoutUpgrade.priorWebsocketSuccess = false;
  2711. if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
  2712. debug("trying next transport");
  2713. this.transports.shift();
  2714. return this._open();
  2715. }
  2716. this.emitReserved("error", err);
  2717. this._onClose("transport error", err);
  2718. }
  2719. /**
  2720. * Called upon transport close.
  2721. *
  2722. * @private
  2723. */;
  2724. _proto._onClose = function _onClose(reason, description) {
  2725. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  2726. debug('socket close with reason: "%s"', reason);
  2727. // clear timers
  2728. this.clearTimeoutFn(this._pingTimeoutTimer);
  2729. // stop event from firing again for transport
  2730. this.transport.removeAllListeners("close");
  2731. // ensure transport won't stay open
  2732. this.transport.close();
  2733. // ignore further transport communication
  2734. this.transport.removeAllListeners();
  2735. if (withEventListeners) {
  2736. if (this._beforeunloadEventListener) {
  2737. removeEventListener("beforeunload", this._beforeunloadEventListener, false);
  2738. }
  2739. if (this._offlineEventListener) {
  2740. var i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
  2741. if (i !== -1) {
  2742. debug("removing listener for the 'offline' event");
  2743. OFFLINE_EVENT_LISTENERS.splice(i, 1);
  2744. }
  2745. }
  2746. }
  2747. // set ready state
  2748. this.readyState = "closed";
  2749. // clear session id
  2750. this.id = null;
  2751. // emit close event
  2752. this.emitReserved("close", reason, description);
  2753. // clean buffers after, so users can still
  2754. // grab the buffers on `close` event
  2755. this.writeBuffer = [];
  2756. this._prevBufferLen = 0;
  2757. }
  2758. };
  2759. return SocketWithoutUpgrade;
  2760. }(Emitter);
  2761. SocketWithoutUpgrade.protocol = protocol;
  2762. /**
  2763. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2764. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2765. *
  2766. * This class comes with an upgrade mechanism, which means that once the connection is established with the first
  2767. * low-level transport, it will try to upgrade to a better transport.
  2768. *
  2769. * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
  2770. *
  2771. * @example
  2772. * import { SocketWithUpgrade, WebSocket } from "engine.io-client";
  2773. *
  2774. * const socket = new SocketWithUpgrade({
  2775. * transports: [WebSocket]
  2776. * });
  2777. *
  2778. * socket.on("open", () => {
  2779. * socket.send("hello");
  2780. * });
  2781. *
  2782. * @see SocketWithoutUpgrade
  2783. * @see Socket
  2784. */
  2785. var SocketWithUpgrade = /*#__PURE__*/function (_SocketWithoutUpgrade) {
  2786. function SocketWithUpgrade() {
  2787. var _this7;
  2788. _this7 = _SocketWithoutUpgrade.apply(this, arguments) || this;
  2789. _this7._upgrades = [];
  2790. return _this7;
  2791. }
  2792. _inheritsLoose(SocketWithUpgrade, _SocketWithoutUpgrade);
  2793. var _proto2 = SocketWithUpgrade.prototype;
  2794. _proto2.onOpen = function onOpen() {
  2795. _SocketWithoutUpgrade.prototype.onOpen.call(this);
  2796. if ("open" === this.readyState && this.opts.upgrade) {
  2797. debug("starting upgrade probes");
  2798. for (var i = 0; i < this._upgrades.length; i++) {
  2799. this._probe(this._upgrades[i]);
  2800. }
  2801. }
  2802. }
  2803. /**
  2804. * Probes a transport.
  2805. *
  2806. * @param {String} name - transport name
  2807. * @private
  2808. */;
  2809. _proto2._probe = function _probe(name) {
  2810. var _this8 = this;
  2811. debug('probing transport "%s"', name);
  2812. var transport = this.createTransport(name);
  2813. var failed = false;
  2814. SocketWithoutUpgrade.priorWebsocketSuccess = false;
  2815. var onTransportOpen = function onTransportOpen() {
  2816. if (failed) return;
  2817. debug('probe transport "%s" opened', name);
  2818. transport.send([{
  2819. type: "ping",
  2820. data: "probe"
  2821. }]);
  2822. transport.once("packet", function (msg) {
  2823. if (failed) return;
  2824. if ("pong" === msg.type && "probe" === msg.data) {
  2825. debug('probe transport "%s" pong', name);
  2826. _this8.upgrading = true;
  2827. _this8.emitReserved("upgrading", transport);
  2828. if (!transport) return;
  2829. SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
  2830. debug('pausing current transport "%s"', _this8.transport.name);
  2831. _this8.transport.pause(function () {
  2832. if (failed) return;
  2833. if ("closed" === _this8.readyState) return;
  2834. debug("changing transport and sending upgrade packet");
  2835. cleanup();
  2836. _this8.setTransport(transport);
  2837. transport.send([{
  2838. type: "upgrade"
  2839. }]);
  2840. _this8.emitReserved("upgrade", transport);
  2841. transport = null;
  2842. _this8.upgrading = false;
  2843. _this8.flush();
  2844. });
  2845. } else {
  2846. debug('probe transport "%s" failed', name);
  2847. var err = new Error("probe error");
  2848. // @ts-ignore
  2849. err.transport = transport.name;
  2850. _this8.emitReserved("upgradeError", err);
  2851. }
  2852. });
  2853. };
  2854. function freezeTransport() {
  2855. if (failed) return;
  2856. // Any callback called by transport should be ignored since now
  2857. failed = true;
  2858. cleanup();
  2859. transport.close();
  2860. transport = null;
  2861. }
  2862. // Handle any error that happens while probing
  2863. var onerror = function onerror(err) {
  2864. var error = new Error("probe error: " + err);
  2865. // @ts-ignore
  2866. error.transport = transport.name;
  2867. freezeTransport();
  2868. debug('probe transport "%s" failed because of error: %s', name, err);
  2869. _this8.emitReserved("upgradeError", error);
  2870. };
  2871. function onTransportClose() {
  2872. onerror("transport closed");
  2873. }
  2874. // When the socket is closed while we're probing
  2875. function onclose() {
  2876. onerror("socket closed");
  2877. }
  2878. // When the socket is upgraded while we're probing
  2879. function onupgrade(to) {
  2880. if (transport && to.name !== transport.name) {
  2881. debug('"%s" works - aborting "%s"', to.name, transport.name);
  2882. freezeTransport();
  2883. }
  2884. }
  2885. // Remove all listeners on the transport and on self
  2886. var cleanup = function cleanup() {
  2887. transport.removeListener("open", onTransportOpen);
  2888. transport.removeListener("error", onerror);
  2889. transport.removeListener("close", onTransportClose);
  2890. _this8.off("close", onclose);
  2891. _this8.off("upgrading", onupgrade);
  2892. };
  2893. transport.once("open", onTransportOpen);
  2894. transport.once("error", onerror);
  2895. transport.once("close", onTransportClose);
  2896. this.once("close", onclose);
  2897. this.once("upgrading", onupgrade);
  2898. if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
  2899. // favor WebTransport
  2900. this.setTimeoutFn(function () {
  2901. if (!failed) {
  2902. transport.open();
  2903. }
  2904. }, 200);
  2905. } else {
  2906. transport.open();
  2907. }
  2908. };
  2909. _proto2.onHandshake = function onHandshake(data) {
  2910. this._upgrades = this._filterUpgrades(data.upgrades);
  2911. _SocketWithoutUpgrade.prototype.onHandshake.call(this, data);
  2912. }
  2913. /**
  2914. * Filters upgrades, returning only those matching client transports.
  2915. *
  2916. * @param {Array} upgrades - server upgrades
  2917. * @private
  2918. */;
  2919. _proto2._filterUpgrades = function _filterUpgrades(upgrades) {
  2920. var filteredUpgrades = [];
  2921. for (var i = 0; i < upgrades.length; i++) {
  2922. if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
  2923. }
  2924. return filteredUpgrades;
  2925. };
  2926. return SocketWithUpgrade;
  2927. }(SocketWithoutUpgrade);
  2928. /**
  2929. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2930. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2931. *
  2932. * This class comes with an upgrade mechanism, which means that once the connection is established with the first
  2933. * low-level transport, it will try to upgrade to a better transport.
  2934. *
  2935. * @example
  2936. * import { Socket } from "engine.io-client";
  2937. *
  2938. * const socket = new Socket();
  2939. *
  2940. * socket.on("open", () => {
  2941. * socket.send("hello");
  2942. * });
  2943. *
  2944. * @see SocketWithoutUpgrade
  2945. * @see SocketWithUpgrade
  2946. */
  2947. var Socket = /*#__PURE__*/function (_SocketWithUpgrade) {
  2948. function Socket(uri) {
  2949. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2950. var o = _typeof(uri) === "object" ? uri : opts;
  2951. if (!o.transports || o.transports && typeof o.transports[0] === "string") {
  2952. o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map(function (transportName) {
  2953. return transports[transportName];
  2954. }).filter(function (t) {
  2955. return !!t;
  2956. });
  2957. }
  2958. return _SocketWithUpgrade.call(this, uri, o) || this;
  2959. }
  2960. _inheritsLoose(Socket, _SocketWithUpgrade);
  2961. return Socket;
  2962. }(SocketWithUpgrade);
  2963. var browserEntrypoint = (function (uri, opts) {
  2964. return new Socket(uri, opts);
  2965. });
  2966. return browserEntrypoint;
  2967. }));
  2968. //# sourceMappingURL=engine.io.js.map