index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { url } from "./url.js";
  2. import { Manager } from "./manager.js";
  3. import { Socket } from "./socket.js";
  4. import debugModule from "debug"; // debug()
  5. const debug = debugModule("socket.io-client"); // debug()
  6. /**
  7. * Managers cache.
  8. */
  9. const cache = {};
  10. function lookup(uri, opts) {
  11. if (typeof uri === "object") {
  12. opts = uri;
  13. uri = undefined;
  14. }
  15. opts = opts || {};
  16. const parsed = url(uri, opts.path || "/socket.io");
  17. const source = parsed.source;
  18. const id = parsed.id;
  19. const path = parsed.path;
  20. const sameNamespace = cache[id] && path in cache[id]["nsps"];
  21. const newConnection = opts.forceNew ||
  22. opts["force new connection"] ||
  23. false === opts.multiplex ||
  24. sameNamespace;
  25. let io;
  26. if (newConnection) {
  27. debug("ignoring socket cache for %s", source);
  28. io = new Manager(source, opts);
  29. }
  30. else {
  31. if (!cache[id]) {
  32. debug("new io instance for %s", source);
  33. cache[id] = new Manager(source, opts);
  34. }
  35. io = cache[id];
  36. }
  37. if (parsed.query && !opts.query) {
  38. opts.query = parsed.queryKey;
  39. }
  40. return io.socket(parsed.path, opts);
  41. }
  42. // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
  43. // namespace (e.g. `io.connect(...)`), for backward compatibility
  44. Object.assign(lookup, {
  45. Manager,
  46. Socket,
  47. io: lookup,
  48. connect: lookup,
  49. });
  50. /**
  51. * Protocol version.
  52. *
  53. * @public
  54. */
  55. export { protocol } from "socket.io-parser";
  56. /**
  57. * Expose constructors for standalone build.
  58. *
  59. * @public
  60. */
  61. export { Manager, Socket, lookup as io, lookup as connect, lookup as default, };