phoenix.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. "use strict";
  2. var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
  3. var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
  4. (function (root, factory) {
  5. if (typeof define === "function" && define.amd) {
  6. return define(["phoenix"], factory);
  7. } else if (typeof exports === "object") {
  8. return factory(exports);
  9. } else {
  10. root.Phoenix = {};
  11. return factory.call(root, root.Phoenix);
  12. }
  13. })(Function("return this")(), function (exports) {
  14. var root = this;
  15. var SOCKET_STATES = { connecting: 0, open: 1, closing: 2, closed: 3 };
  16. exports.Channel = (function () {
  17. function Channel(topic, message, callback, socket) {
  18. _classCallCheck(this, Channel);
  19. this.topic = topic;
  20. this.message = message;
  21. this.callback = callback;
  22. this.socket = socket;
  23. this.bindings = null;
  24. this.reset();
  25. }
  26. _prototypeProperties(Channel, null, {
  27. reset: {
  28. value: function reset() {
  29. this.bindings = [];
  30. },
  31. writable: true,
  32. configurable: true
  33. },
  34. on: {
  35. value: function on(event, callback) {
  36. this.bindings.push({ event: event, callback: callback });
  37. },
  38. writable: true,
  39. configurable: true
  40. },
  41. isMember: {
  42. value: function isMember(topic) {
  43. return this.topic === topic;
  44. },
  45. writable: true,
  46. configurable: true
  47. },
  48. off: {
  49. value: function off(event) {
  50. this.bindings = this.bindings.filter(function (bind) {
  51. return bind.event !== event;
  52. });
  53. },
  54. writable: true,
  55. configurable: true
  56. },
  57. trigger: {
  58. value: function trigger(triggerEvent, msg) {
  59. this.bindings.filter(function (bind) {
  60. return bind.event === triggerEvent;
  61. }).map(function (bind) {
  62. return bind.callback(msg);
  63. });
  64. },
  65. writable: true,
  66. configurable: true
  67. },
  68. send: {
  69. value: function send(event, payload) {
  70. this.socket.send({ topic: this.topic, event: event, payload: payload });
  71. },
  72. writable: true,
  73. configurable: true
  74. },
  75. leave: {
  76. value: function leave() {
  77. var message = arguments[0] === undefined ? {} : arguments[0];
  78. this.socket.leave(this.topic, message);
  79. this.reset();
  80. },
  81. writable: true,
  82. configurable: true
  83. }
  84. });
  85. return Channel;
  86. })();
  87. exports.Socket = (function () {
  88. // Initializes the Socket
  89. //
  90. // endPoint - The string WebSocket endpoint, ie, "ws://example.com/ws",
  91. // "wss://example.com"
  92. // "/ws" (inherited host & protocol)
  93. // opts - Optional configuration
  94. // transport - The Websocket Transport, ie WebSocket, Phoenix.LongPoller.
  95. // Defaults to WebSocket with automatic LongPoller fallback.
  96. // heartbeatIntervalMs - The millisecond interval to send a heartbeat message
  97. // logger - The optional function for specialized logging, ie:
  98. // `logger: (msg) -> console.log(msg)`
  99. //
  100. function Socket(endPoint) {
  101. var opts = arguments[1] === undefined ? {} : arguments[1];
  102. _classCallCheck(this, Socket);
  103. this.states = SOCKET_STATES;
  104. this.stateChangeCallbacks = { open: [], close: [], error: [], message: [] };
  105. this.flushEveryMs = 50;
  106. this.reconnectTimer = null;
  107. this.reconnectAfterMs = 5000;
  108. this.heartbeatIntervalMs = 30000;
  109. this.channels = [];
  110. this.sendBuffer = [];
  111. this.transport = opts.transport || root.WebSocket || exports.LongPoller;
  112. this.heartbeatIntervalMs = opts.heartbeatIntervalMs || this.heartbeatIntervalMs;
  113. this.logger = opts.logger || function () {}; // noop
  114. this.endPoint = this.expandEndpoint(endPoint);
  115. this.resetBufferTimer();
  116. this.reconnect();
  117. }
  118. _prototypeProperties(Socket, null, {
  119. protocol: {
  120. value: function protocol() {
  121. return location.protocol.match(/^https/) ? "wss" : "ws";
  122. },
  123. writable: true,
  124. configurable: true
  125. },
  126. expandEndpoint: {
  127. value: function expandEndpoint(endPoint) {
  128. if (endPoint.charAt(0) !== "/") {
  129. return endPoint;
  130. }
  131. if (endPoint.charAt(1) === "/") {
  132. return "" + this.protocol() + ":" + endPoint;
  133. }
  134. return "" + this.protocol() + "://" + location.host + "" + endPoint;
  135. },
  136. writable: true,
  137. configurable: true
  138. },
  139. close: {
  140. value: function close(callback, code, reason) {
  141. if (this.conn) {
  142. this.conn.onclose = function () {}; // noop
  143. if (code) {
  144. this.conn.close(code, reason || "");
  145. } else {
  146. this.conn.close();
  147. }
  148. this.conn = null;
  149. }
  150. callback && callback();
  151. },
  152. writable: true,
  153. configurable: true
  154. },
  155. reconnect: {
  156. value: function reconnect() {
  157. var _this = this;
  158. this.close(function () {
  159. _this.conn = new _this.transport(_this.endPoint);
  160. _this.conn.onopen = function () {
  161. return _this.onConnOpen();
  162. };
  163. _this.conn.onerror = function (error) {
  164. return _this.onConnError(error);
  165. };
  166. _this.conn.onmessage = function (event) {
  167. return _this.onConnMessage(event);
  168. };
  169. _this.conn.onclose = function (event) {
  170. return _this.onConnClose(event);
  171. };
  172. });
  173. },
  174. writable: true,
  175. configurable: true
  176. },
  177. resetBufferTimer: {
  178. value: function resetBufferTimer() {
  179. var _this = this;
  180. clearTimeout(this.sendBufferTimer);
  181. this.sendBufferTimer = setTimeout(function () {
  182. return _this.flushSendBuffer();
  183. }, this.flushEveryMs);
  184. },
  185. writable: true,
  186. configurable: true
  187. },
  188. log: {
  189. // Logs the message. Override `this.logger` for specialized logging. noops by default
  190. value: function log(msg) {
  191. this.logger(msg);
  192. },
  193. writable: true,
  194. configurable: true
  195. },
  196. onOpen: {
  197. // Registers callbacks for connection state change events
  198. //
  199. // Examples
  200. //
  201. // socket.onError (error) -> alert("An error occurred")
  202. //
  203. value: function onOpen(callback) {
  204. this.stateChangeCallbacks.open.push(callback);
  205. },
  206. writable: true,
  207. configurable: true
  208. },
  209. onClose: {
  210. value: function onClose(callback) {
  211. this.stateChangeCallbacks.close.push(callback);
  212. },
  213. writable: true,
  214. configurable: true
  215. },
  216. onError: {
  217. value: function onError(callback) {
  218. this.stateChangeCallbacks.error.push(callback);
  219. },
  220. writable: true,
  221. configurable: true
  222. },
  223. onMessage: {
  224. value: function onMessage(callback) {
  225. this.stateChangeCallbacks.message.push(callback);
  226. },
  227. writable: true,
  228. configurable: true
  229. },
  230. onConnOpen: {
  231. value: function onConnOpen() {
  232. var _this = this;
  233. clearInterval(this.reconnectTimer);
  234. if (!this.transport.skipHeartbeat) {
  235. this.heartbeatTimer = setInterval(function () {
  236. return _this.sendHeartbeat();
  237. }, this.heartbeatIntervalMs);
  238. }
  239. this.rejoinAll();
  240. this.stateChangeCallbacks.open.forEach(function (callback) {
  241. return callback();
  242. });
  243. },
  244. writable: true,
  245. configurable: true
  246. },
  247. onConnClose: {
  248. value: function onConnClose(event) {
  249. var _this = this;
  250. this.log("WS close:");
  251. this.log(event);
  252. clearInterval(this.reconnectTimer);
  253. clearInterval(this.heartbeatTimer);
  254. this.reconnectTimer = setInterval(function () {
  255. return _this.reconnect();
  256. }, this.reconnectAfterMs);
  257. this.stateChangeCallbacks.close.forEach(function (callback) {
  258. return callback(event);
  259. });
  260. },
  261. writable: true,
  262. configurable: true
  263. },
  264. onConnError: {
  265. value: function onConnError(error) {
  266. this.log("WS error:");
  267. this.log(error);
  268. this.stateChangeCallbacks.error.forEach(function (callback) {
  269. return callback(error);
  270. });
  271. },
  272. writable: true,
  273. configurable: true
  274. },
  275. connectionState: {
  276. value: function connectionState() {
  277. switch (this.conn && this.conn.readyState) {
  278. case this.states.connecting:
  279. return "connecting";
  280. case this.states.open:
  281. return "open";
  282. case this.states.closing:
  283. return "closing";
  284. default:
  285. return "closed";
  286. }
  287. },
  288. writable: true,
  289. configurable: true
  290. },
  291. isConnected: {
  292. value: function isConnected() {
  293. return this.connectionState() === "open";
  294. },
  295. writable: true,
  296. configurable: true
  297. },
  298. rejoinAll: {
  299. value: function rejoinAll() {
  300. var _this = this;
  301. this.channels.forEach(function (chan) {
  302. return _this.rejoin(chan);
  303. });
  304. },
  305. writable: true,
  306. configurable: true
  307. },
  308. rejoin: {
  309. value: function rejoin(chan) {
  310. chan.reset();
  311. this.send({ topic: chan.topic, event: "join", payload: chan.message });
  312. chan.callback(chan);
  313. },
  314. writable: true,
  315. configurable: true
  316. },
  317. join: {
  318. value: function join(topic, message, callback) {
  319. var chan = new exports.Channel(topic, message, callback, this);
  320. this.channels.push(chan);
  321. if (this.isConnected()) {
  322. this.rejoin(chan);
  323. }
  324. },
  325. writable: true,
  326. configurable: true
  327. },
  328. leave: {
  329. value: function leave(topic) {
  330. var message = arguments[1] === undefined ? {} : arguments[1];
  331. this.send({ topic: topic, event: "leave", payload: message });
  332. this.channels = this.channels.filter(function (c) {
  333. return !c.isMember(topic);
  334. });
  335. },
  336. writable: true,
  337. configurable: true
  338. },
  339. send: {
  340. value: function send(data) {
  341. var _this = this;
  342. var callback = function () {
  343. return _this.conn.send(root.JSON.stringify(data));
  344. };
  345. if (this.isConnected()) {
  346. callback();
  347. } else {
  348. this.sendBuffer.push(callback);
  349. }
  350. },
  351. writable: true,
  352. configurable: true
  353. },
  354. sendHeartbeat: {
  355. value: function sendHeartbeat() {
  356. this.send({ topic: "phoenix", event: "heartbeat", payload: {} });
  357. },
  358. writable: true,
  359. configurable: true
  360. },
  361. flushSendBuffer: {
  362. value: function flushSendBuffer() {
  363. if (this.isConnected() && this.sendBuffer.length > 0) {
  364. this.sendBuffer.forEach(function (callback) {
  365. return callback();
  366. });
  367. this.sendBuffer = [];
  368. }
  369. this.resetBufferTimer();
  370. },
  371. writable: true,
  372. configurable: true
  373. },
  374. onConnMessage: {
  375. value: function onConnMessage(rawMessage) {
  376. this.log("message received:");
  377. this.log(rawMessage);
  378. var _root$JSON$parse = root.JSON.parse(rawMessage.data);
  379. var topic = _root$JSON$parse.topic;
  380. var event = _root$JSON$parse.event;
  381. var payload = _root$JSON$parse.payload;
  382. this.channels.filter(function (chan) {
  383. return chan.isMember(topic);
  384. }).forEach(function (chan) {
  385. return chan.trigger(event, payload);
  386. });
  387. this.stateChangeCallbacks.message.forEach(function (callback) {
  388. callback(topic, event, payload);
  389. });
  390. },
  391. writable: true,
  392. configurable: true
  393. }
  394. });
  395. return Socket;
  396. })();
  397. exports.LongPoller = (function () {
  398. function LongPoller(endPoint) {
  399. _classCallCheck(this, LongPoller);
  400. this.retryInMs = 5000;
  401. this.endPoint = null;
  402. this.token = null;
  403. this.sig = null;
  404. this.skipHeartbeat = true;
  405. this.onopen = function () {}; // noop
  406. this.onerror = function () {}; // noop
  407. this.onmessage = function () {}; // noop
  408. this.onclose = function () {}; // noop
  409. this.states = SOCKET_STATES;
  410. this.upgradeEndpoint = this.normalizeEndpoint(endPoint);
  411. this.pollEndpoint = this.upgradeEndpoint + (/\/$/.test(endPoint) ? "poll" : "/poll");
  412. this.readyState = this.states.connecting;
  413. this.poll();
  414. }
  415. _prototypeProperties(LongPoller, null, {
  416. normalizeEndpoint: {
  417. value: function normalizeEndpoint(endPoint) {
  418. return endPoint.replace("ws://", "http://").replace("wss://", "https://");
  419. },
  420. writable: true,
  421. configurable: true
  422. },
  423. endpointURL: {
  424. value: function endpointURL() {
  425. return this.pollEndpoint + ("?token=" + encodeURIComponent(this.token) + "&sig=" + encodeURIComponent(this.sig));
  426. },
  427. writable: true,
  428. configurable: true
  429. },
  430. closeAndRetry: {
  431. value: function closeAndRetry() {
  432. this.close();
  433. this.readyState = this.states.connecting;
  434. },
  435. writable: true,
  436. configurable: true
  437. },
  438. ontimeout: {
  439. value: function ontimeout() {
  440. this.onerror("timeout");
  441. this.closeAndRetry();
  442. },
  443. writable: true,
  444. configurable: true
  445. },
  446. poll: {
  447. value: function poll() {
  448. var _this = this;
  449. if (!(this.readyState === this.states.open || this.readyState === this.states.connecting)) {
  450. return;
  451. }
  452. exports.Ajax.request("GET", this.endpointURL(), "application/json", null, this.ontimeout.bind(this), function (status, resp) {
  453. if (resp && resp !== "") {
  454. var _root$JSON$parse = root.JSON.parse(resp);
  455. var token = _root$JSON$parse.token;
  456. var sig = _root$JSON$parse.sig;
  457. var messages = _root$JSON$parse.messages;
  458. _this.token = token;
  459. _this.sig = sig;
  460. }
  461. switch (status) {
  462. case 200:
  463. messages.forEach(function (msg) {
  464. return _this.onmessage({ data: root.JSON.stringify(msg) });
  465. });
  466. _this.poll();
  467. break;
  468. case 204:
  469. _this.poll();
  470. break;
  471. case 410:
  472. _this.readyState = _this.states.open;
  473. _this.onopen();
  474. _this.poll();
  475. break;
  476. case 0:
  477. case 500:
  478. _this.onerror();
  479. _this.closeAndRetry();
  480. break;
  481. default:
  482. throw "unhandled poll status " + status;
  483. }
  484. });
  485. },
  486. writable: true,
  487. configurable: true
  488. },
  489. send: {
  490. value: function send(body) {
  491. var _this = this;
  492. exports.Ajax.request("POST", this.endpointURL(), "application/json", body, this.onerror.bind(this, "timeout"), function (status, resp) {
  493. if (status !== 200) {
  494. _this.onerror(status);
  495. }
  496. });
  497. },
  498. writable: true,
  499. configurable: true
  500. },
  501. close: {
  502. value: function close(code, reason) {
  503. this.readyState = this.states.closed;
  504. this.onclose();
  505. },
  506. writable: true,
  507. configurable: true
  508. }
  509. });
  510. return LongPoller;
  511. })();
  512. exports.Ajax = {
  513. states: { complete: 4 },
  514. request: function (method, endPoint, accept, body, ontimeout, callback) {
  515. var _this = this;
  516. var req = root.XMLHttpRequest ? new root.XMLHttpRequest() : // IE7+, Firefox, Chrome, Opera, Safari
  517. new root.ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
  518. req.open(method, endPoint, true);
  519. req.setRequestHeader("Content-type", accept);
  520. req.onerror = function () {
  521. callback && callback(500, null);
  522. };
  523. req.onreadystatechange = function () {
  524. if (req.readyState === _this.states.complete && callback) {
  525. callback(req.status, req.responseText);
  526. }
  527. };
  528. if (ontimeout) {
  529. req.ontimeout = ontimeout;
  530. }
  531. req.send(body);
  532. }
  533. };
  534. });