index.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const tls_1 = require("tls");
  4. const deferToConnect = (socket, fn) => {
  5. let listeners;
  6. if (typeof fn === 'function') {
  7. const connect = fn;
  8. listeners = { connect };
  9. }
  10. else {
  11. listeners = fn;
  12. }
  13. const hasConnectListener = typeof listeners.connect === 'function';
  14. const hasSecureConnectListener = typeof listeners.secureConnect === 'function';
  15. const hasCloseListener = typeof listeners.close === 'function';
  16. const onConnect = () => {
  17. if (hasConnectListener) {
  18. listeners.connect();
  19. }
  20. if (socket instanceof tls_1.TLSSocket && hasSecureConnectListener) {
  21. if (socket.authorized) {
  22. listeners.secureConnect();
  23. }
  24. else if (!socket.authorizationError) {
  25. socket.once('secureConnect', listeners.secureConnect);
  26. }
  27. }
  28. if (hasCloseListener) {
  29. socket.once('close', listeners.close);
  30. }
  31. };
  32. if (socket.writable && !socket.connecting) {
  33. onConnect();
  34. }
  35. else if (socket.connecting) {
  36. socket.once('connect', onConnect);
  37. }
  38. else if (socket.destroyed && hasCloseListener) {
  39. listeners.close(socket._hadError);
  40. }
  41. };
  42. exports.default = deferToConnect;
  43. // For CommonJS default export support
  44. module.exports = deferToConnect;
  45. module.exports.default = deferToConnect;