index.js 1.5 KB

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