index.js 1.4 KB

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