@cosyte/mllp 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -644,13 +644,21 @@ var MLLP_BIND_ALL_INTERFACES = "MLLP_BIND_ALL_INTERFACES";
644
644
  var MLLP_TLS_CIPHER_LIST_REJECTED = "MLLP_TLS_CIPHER_LIST_REJECTED";
645
645
  var MLLP_TLS_CIPHER_OPTION_CONFLICT = "MLLP_TLS_CIPHER_OPTION_CONFLICT";
646
646
  var MLLP_TLS_DH_PARAMETERS_REJECTED = "MLLP_TLS_DH_PARAMETERS_REJECTED";
647
- var TLS_CONFIGURATION_MESSAGES = Object.freeze({
648
- [MLLP_TLS_CIPHER_LIST_REJECTED]: "the TLS library rejected the configured cipher-suite list; no connection was opened and no fallback to the runtime default list was made",
649
- [MLLP_TLS_CIPHER_OPTION_CONFLICT]: "tls.atnaTransportSecurity and tls.ciphers both declare the offered cipher-suite list; set exactly one of them",
650
- [MLLP_TLS_DH_PARAMETERS_REJECTED]: "the configured ephemeral Diffie-Hellman parameters are not usable; nothing was bound and no fallback to a server without Diffie-Hellman parameters was made"
651
- });
647
+ var MLLP_TLS_CIPHER_LIST_UNENFORCEABLE = "MLLP_TLS_CIPHER_LIST_UNENFORCEABLE";
648
+ var MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE = "MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE";
649
+ var MLLP_TLS_PFX_REJECTED = "MLLP_TLS_PFX_REJECTED";
650
+ var MLLP_TLS_CREDENTIAL_CONFLICT = "MLLP_TLS_CREDENTIAL_CONFLICT";
652
651
  function tlsConfigurationMessage(code) {
653
- return TLS_CONFIGURATION_MESSAGES[code];
652
+ const messages = {
653
+ [MLLP_TLS_CIPHER_LIST_REJECTED]: "the TLS library rejected the configured cipher-suite list; no connection was opened and no fallback to the runtime default list was made",
654
+ [MLLP_TLS_CIPHER_OPTION_CONFLICT]: "tls.atnaTransportSecurity and tls.ciphers both declare the offered cipher-suite list; set exactly one of them",
655
+ [MLLP_TLS_DH_PARAMETERS_REJECTED]: "the configured ephemeral Diffie-Hellman parameters are not usable; nothing was bound and no fallback to a server without Diffie-Hellman parameters was made",
656
+ [MLLP_TLS_CIPHER_LIST_UNENFORCEABLE]: "this runtime's TLS library does not enforce a configured cipher-suite list; no connection was opened, rather than one offering a list other than the one configured",
657
+ [MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE]: "this runtime's TLS library does not enforce server Diffie-Hellman parameters; nothing was bound, rather than a server running without the parameters configured",
658
+ [MLLP_TLS_PFX_REJECTED]: "tls.pfx could not be loaded with tls.passphrase: the passphrase is wrong, the file is not PKCS#12, or it uses a legacy encryption (RC2-40, as `openssl pkcs12 -export -legacy` and older exports write it) that OpenSSL 3 does not load, so re-export it with AES-256; no socket was opened",
659
+ [MLLP_TLS_CREDENTIAL_CONFLICT]: "tls.pfx was set together with tls.cert or tls.key; the PKCS#12 file carries its own certificate and key, so set either cert and key or pfx, not both"
660
+ };
661
+ return messages[code];
654
662
  }
655
663
  var MllpTlsConfigurationError = class _MllpTlsConfigurationError extends Error {
656
664
  name = "MllpTlsConfigurationError";
@@ -660,7 +668,8 @@ var MllpTlsConfigurationError = class _MllpTlsConfigurationError extends Error {
660
668
  */
661
669
  code;
662
670
  /**
663
- * The TLS library's own error, when the runtime is what refused the list.
671
+ * The TLS library's own error, when the runtime is what refused the input
672
+ * (or, for an `_UNENFORCEABLE` code, refused one of the probes).
664
673
  * `undefined` when this package refused the configuration itself.
665
674
  */
666
675
  cause;
@@ -824,6 +833,47 @@ var ATNA_CIPHER_LIST = [
824
833
  ...TLS13_DEFAULT_CIPHER_SUITES,
825
834
  ...ATNA_CIPHER_SUITES
826
835
  ].join(":");
836
+ function refusalOf(options) {
837
+ try {
838
+ createSecureContext(options);
839
+ } catch (err) {
840
+ return err instanceof Error ? err : new Error(String(err));
841
+ }
842
+ return null;
843
+ }
844
+ var probeResults = /* @__PURE__ */ new Map();
845
+ function probeRefusal(probe) {
846
+ const key = "ciphers" in probe ? `ciphers=${probe.ciphers}` : `dhparam=${probe.dhparam}`;
847
+ const found = probeResults.get(key);
848
+ if (found !== void 0) return found;
849
+ const refusal = refusalOf(probe);
850
+ probeResults.set(key, refusal);
851
+ return refusal;
852
+ }
853
+ function assertCipherListEnforced(atna) {
854
+ if (probeRefusal({ ciphers: "ECDHE-RSA-AES128-GCM-SHA256:!ECDHE-RSA-AES128-GCM-SHA256" }) === null) {
855
+ throw new MllpTlsConfigurationError(MLLP_TLS_CIPHER_LIST_UNENFORCEABLE);
856
+ }
857
+ if (!atna) return;
858
+ for (const suite of ATNA_CIPHER_SUITES) {
859
+ const refusal = probeRefusal({ ciphers: suite });
860
+ if (refusal !== null) {
861
+ throw new MllpTlsConfigurationError(MLLP_TLS_CIPHER_LIST_UNENFORCEABLE, { cause: refusal });
862
+ }
863
+ }
864
+ }
865
+ function assertDhParametersEnforced() {
866
+ const autoRefusal = probeRefusal({ dhparam: "auto" });
867
+ if (autoRefusal !== null) {
868
+ throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE, {
869
+ cause: autoRefusal
870
+ });
871
+ }
872
+ const undersized = "-----BEGIN DH PARAMETERS-----\nMAYCARcCAQU=\n-----END DH PARAMETERS-----\n";
873
+ if (probeRefusal({ dhparam: undersized }) === null) {
874
+ throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE);
875
+ }
876
+ }
827
877
  function assertUsableDhParameters(dhParameters) {
828
878
  if (!isDhParametersPem(dhParameters)) {
829
879
  throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_REJECTED);
@@ -848,7 +898,9 @@ function resolveTlsCipherPolicy(opts, side) {
848
898
  const supplied = side === "server" ? opts.dhParameters : void 0;
849
899
  if (supplied !== void 0) assertUsableDhParameters(supplied);
850
900
  const dhparam = supplied ?? (atna && side === "server" ? "auto" : void 0);
901
+ if (dhparam !== void 0) assertDhParametersEnforced();
851
902
  if (ciphers !== void 0) {
903
+ assertCipherListEnforced(atna);
852
904
  try {
853
905
  createSecureContext({ ciphers });
854
906
  } catch (err) {
@@ -1371,6 +1423,20 @@ var Connection = class extends EventEmitter {
1371
1423
  });
1372
1424
  }
1373
1425
  };
1426
+ function checkCredentialMix(tls) {
1427
+ if (typeof tls !== "object" || tls.pfx === void 0) return;
1428
+ if (tls.cert !== void 0 || tls.key !== void 0) {
1429
+ throw new MllpTlsConfigurationError(MLLP_TLS_CREDENTIAL_CONFLICT);
1430
+ }
1431
+ }
1432
+ function checkPfx(pfx, passphrase) {
1433
+ if (pfx === void 0) return;
1434
+ try {
1435
+ createSecureContext({ pfx, passphrase });
1436
+ } catch (err) {
1437
+ throw new MllpTlsConfigurationError(MLLP_TLS_PFX_REJECTED, { cause: err });
1438
+ }
1439
+ }
1374
1440
 
1375
1441
  // src/internal/control-id.ts
1376
1442
  var ASCII_M = 77;
@@ -1609,6 +1675,9 @@ function trimSpaces(value) {
1609
1675
  while (end > start && value.charAt(end - 1) === SPACE) end--;
1610
1676
  return value.substring(start, end);
1611
1677
  }
1678
+ function readConditionField(raw, delimiters) {
1679
+ return readTableField(raw, delimiters, TABLE_0155);
1680
+ }
1612
1681
  function readTableField(raw, delimiters, table) {
1613
1682
  if (raw === void 0) return { kind: "null", byteLength: 0 };
1614
1683
  const byteLength = raw.length;
@@ -1770,6 +1839,18 @@ var MllpServer = class extends EventEmitter {
1770
1839
  _host = null;
1771
1840
  _acceptedTotal = 0;
1772
1841
  _closedTotal = 0;
1842
+ /**
1843
+ * Sockets accepted and not yet closed, counted only when {@link ServerOptions.maxConnections} is
1844
+ * set: the number the cap is compared against.
1845
+ */
1846
+ _openSockets = 0;
1847
+ /** Sockets the connection cap closed at accept, so a runtime's report of them is recognised. */
1848
+ _closedAtAccept = /* @__PURE__ */ new WeakSet();
1849
+ /**
1850
+ * For each socket the connection cap counted, what gives its place back. Released once, however
1851
+ * many times it is called.
1852
+ */
1853
+ _capRelease = /* @__PURE__ */ new WeakMap();
1773
1854
  /** Count of `'tlsClientError'` events since listen(). */
1774
1855
  _tlsClientErrorsTotal = 0;
1775
1856
  /**
@@ -1796,11 +1877,17 @@ var MllpServer = class extends EventEmitter {
1796
1877
  "ServerOptions.maxConnections must be a positive integer, or left unset for no cap"
1797
1878
  );
1798
1879
  }
1880
+ const tlsInput = opts.tls;
1881
+ checkCredentialMix(tlsInput);
1882
+ if (tlsInput !== void 0 && tlsInput.pfx === void 0 && (tlsInput.cert === void 0 || tlsInput.key === void 0)) {
1883
+ throw new TypeError("ServerOptions.tls needs cert and key, or pfx");
1884
+ }
1799
1885
  this._opts = opts;
1800
1886
  this._isTls = opts.tls !== void 0;
1801
1887
  let cipherPolicy = null;
1802
1888
  if (opts.tls !== void 0) {
1803
1889
  try {
1890
+ checkPfx(opts.tls.pfx, opts.tls.passphrase);
1804
1891
  cipherPolicy = resolveTlsCipherPolicy(opts.tls, "server");
1805
1892
  } catch (err) {
1806
1893
  if (!(err instanceof MllpTlsConfigurationError)) throw err;
@@ -1815,6 +1902,7 @@ var MllpServer = class extends EventEmitter {
1815
1902
  const tlsServer = createServer$2({
1816
1903
  cert: tlsOpts.cert,
1817
1904
  key: tlsOpts.key,
1905
+ pfx: tlsOpts.pfx,
1818
1906
  ...tlsOpts.ca !== void 0 ? { ca: tlsOpts.ca } : {},
1819
1907
  ...tlsOpts.passphrase !== void 0 ? { passphrase: tlsOpts.passphrase } : {},
1820
1908
  minVersion: tlsOpts.minVersion ?? "TLSv1.2",
@@ -1828,6 +1916,7 @@ var MllpServer = class extends EventEmitter {
1828
1916
  this._onSocketAccepted(socket);
1829
1917
  });
1830
1918
  tlsServer.on("tlsClientError", (err, socket) => {
1919
+ if (this._closedAtAccept.has(socket)) return;
1831
1920
  this._tlsClientErrorsTotal += 1;
1832
1921
  const nodeErr = err;
1833
1922
  const event = Object.freeze({
@@ -1852,26 +1941,67 @@ var MllpServer = class extends EventEmitter {
1852
1941
  this.emit("error", err);
1853
1942
  }
1854
1943
  });
1855
- if (maxConnections !== void 0) {
1856
- this._netServer.maxConnections = maxConnections;
1857
- this._netServer.on("drop", (data) => {
1858
- this._onConnectionOverCap(maxConnections, data);
1859
- });
1860
- }
1944
+ if (maxConnections !== void 0) this._gateConnections(maxConnections);
1945
+ }
1946
+ /**
1947
+ * Enforce {@link ServerOptions.maxConnections} by counting sockets here, at accept.
1948
+ *
1949
+ * WHY NOT THE LISTENER'S OWN `maxConnections`. Node's `net.Server` enforces a cap of its own and
1950
+ * reports each refusal on `'drop'`, but that report is the runtime's to make, and Deno's
1951
+ * `node:net` closes the socket without emitting `'drop'` (measured: Deno 2.9.8), so the cap held
1952
+ * and `'connectionRejected'` never fired. Counting here makes the cap and its event a property of
1953
+ * this package on every runtime.
1954
+ *
1955
+ * The gate sits IN FRONT of every `'connection'` listener the server already has, and replaces
1956
+ * them: for a plaintext server that is this class's own accept handler, and for a TLS server it
1957
+ * is the runtime's, which wraps the raw socket and starts the handshake. An over-cap socket is
1958
+ * destroyed before either runs, so it never becomes a `Connection`, costs no handshake, and is
1959
+ * not a `'tlsClientError'`. The count is of open sockets, the number that bounds file
1960
+ * descriptors: a socket counts from accept until its `'close'`, handshake in flight included.
1961
+ *
1962
+ * @param maxConnections - The validated cap.
1963
+ */
1964
+ _gateConnections(maxConnections) {
1965
+ const server = this._netServer;
1966
+ const downstream = server.listeners("connection");
1967
+ server.removeAllListeners("connection");
1968
+ server.on("connection", (socket) => {
1969
+ if (this._openSockets >= maxConnections) {
1970
+ const remoteAddress = socket.remoteAddress ?? null;
1971
+ const remotePort = socket.remotePort ?? null;
1972
+ this._closedAtAccept.add(socket);
1973
+ socket.destroy();
1974
+ this._onConnectionOverCap(maxConnections, remoteAddress, remotePort);
1975
+ return;
1976
+ }
1977
+ this._openSockets += 1;
1978
+ let released = false;
1979
+ const release = () => {
1980
+ if (released) return;
1981
+ released = true;
1982
+ this._openSockets -= 1;
1983
+ };
1984
+ this._capRelease.set(socket, release);
1985
+ try {
1986
+ for (const listener of downstream) listener.call(server, socket);
1987
+ } finally {
1988
+ socket.once("close", release);
1989
+ }
1990
+ });
1861
1991
  }
1862
1992
  /**
1863
- * Report a connection the listener closed at accept because the cap was full.
1993
+ * Report a connection closed at accept because the cap was full.
1864
1994
  *
1865
- * Contained: this runs inside the listener's own 'drop' callback, so a throwing subscriber would
1866
- * otherwise unwind into the accept path. The throw is surfaced on 'error' instead.
1995
+ * Contained: this runs inside the listener's own 'connection' callback, so a throwing subscriber
1996
+ * would otherwise unwind into the accept path. The throw is surfaced on 'error' instead.
1867
1997
  */
1868
- _onConnectionOverCap(maxConnections, data) {
1998
+ _onConnectionOverCap(maxConnections, remoteAddress, remotePort) {
1869
1999
  const event = Object.freeze({
1870
2000
  code: MLLP_CONNECTION_LIMIT_REACHED,
1871
2001
  message: CONNECTION_LIMIT_MESSAGE,
1872
2002
  maxConnections,
1873
- remoteAddress: data?.remoteAddress ?? null,
1874
- remotePort: data?.remotePort ?? null,
2003
+ remoteAddress,
2004
+ remotePort,
1875
2005
  timestamp: /* @__PURE__ */ new Date()
1876
2006
  });
1877
2007
  this._emitContained("connectionRejected", event);
@@ -2241,6 +2371,7 @@ var MllpServer = class extends EventEmitter {
2241
2371
  if (this._opts.keepaliveIntervalMs !== void 0) {
2242
2372
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
2243
2373
  }
2374
+ socket.setNoDelay(this._opts.noDelay !== false);
2244
2375
  const transport = this._isTls ? new TlsTransport(socket) : new NetTransport(socket);
2245
2376
  const mergedFraming = {
2246
2377
  ...SERVER_DEFAULT_FRAMING,
@@ -2248,6 +2379,8 @@ var MllpServer = class extends EventEmitter {
2248
2379
  };
2249
2380
  const connOpts = this._opts.onWarning !== void 0 ? { transport, framing: mergedFraming, onWarning: this._opts.onWarning } : { transport, framing: mergedFraming };
2250
2381
  const conn = new Connection(connOpts);
2382
+ const release = this._capRelease.get(socket);
2383
+ if (release !== void 0) socket.once("close", release);
2251
2384
  conn.beforeClose = () => Promise.resolve();
2252
2385
  conn.on("error", (errEvent) => {
2253
2386
  this._emitErrorIfListened(errEvent);
@@ -2587,6 +2720,24 @@ async function createStarterServer(opts) {
2587
2720
  return server;
2588
2721
  }
2589
2722
 
2723
+ // src/server/ack-code.ts
2724
+ function selectAckCode(input) {
2725
+ const { outcome } = input;
2726
+ if (outcome !== "AA" && outcome !== "AE" && outcome !== "AR") {
2727
+ throw new RangeError("selectAckCode: outcome must be one of AA, AE or AR");
2728
+ }
2729
+ const delimiters = delimitersFrom(input.encodingCharacters ?? "^~\\&");
2730
+ const accept = readConditionField(input.msh15, delimiters);
2731
+ const application = readConditionField(input.msh16, delimiters);
2732
+ return Object.freeze({
2733
+ code: acceptAckRequested(accept, outcome) ? acceptModeCounterpart(outcome) : outcome,
2734
+ mode: accept.kind === "null" && application.kind === "null" ? "original" : "enhanced",
2735
+ applicationAckRequested: application.kind !== "code" || acceptAckRequested(application, outcome),
2736
+ acceptTypeUnrecognised: accept.kind === "unrecognised",
2737
+ applicationTypeUnrecognised: application.kind === "unrecognised"
2738
+ });
2739
+ }
2740
+
2590
2741
  // src/client/correlator.ts
2591
2742
  var Correlator = class {
2592
2743
  _opts;
@@ -2656,8 +2807,11 @@ var Correlator = class {
2656
2807
  * `twoPhase` is the enhanced-mode state for a send being correlated by control ID.
2657
2808
  * Omitting it (or passing `null`) is what every other send does, and such an entry is
2658
2809
  * settled by the first acknowledgement matched to it, exactly as before.
2810
+ *
2811
+ * `ackTimeoutMs` is this send's own bound on the wait for its acknowledgement. Omitting it
2812
+ * gives the entry the correlator-wide `ackTimeoutMs`.
2659
2813
  */
2660
- enqueue(frame, controlIdOrNull, resolve, reject, twoPhase = null) {
2814
+ enqueue(frame, controlIdOrNull, resolve, reject, twoPhase = null, ackTimeoutMs) {
2661
2815
  if (this._pending.size >= this._opts.maxInFlight) return null;
2662
2816
  const key = this._opts.mode === "controlId" ? controlIdOrNull ?? `__seq-${++this._sendSeq}` : ++this._sendSeq;
2663
2817
  const entry = {
@@ -2666,6 +2820,7 @@ var Correlator = class {
2666
2820
  controlId: controlIdOrNull,
2667
2821
  byteCount: frame.length,
2668
2822
  sentAt: null,
2823
+ ackTimeoutMs: ackTimeoutMs ?? this._opts.ackTimeoutMs,
2669
2824
  resolve,
2670
2825
  reject,
2671
2826
  twoPhase
@@ -2842,7 +2997,7 @@ var Correlator = class {
2842
2997
  return null;
2843
2998
  }
2844
2999
  /**
2845
- * Sweep live entries; expire those past `sentAt + ackTimeoutMs`.
3000
+ * Sweep live entries; expire those past `sentAt` plus their own `ackTimeoutMs`.
2846
3001
  * Fires `onTimeout(entry, elapsedMs)`; entries move to graveyard.
2847
3002
  * Driven externally by `MllpClient`'s periodic sweep tick, Correlator
2848
3003
  * itself owns no timers.
@@ -2854,7 +3009,6 @@ var Correlator = class {
2854
3009
  */
2855
3010
  expireDue(now) {
2856
3011
  const t = now ?? this._opts.now();
2857
- const ackTimeoutMs = this._opts.ackTimeoutMs;
2858
3012
  for (const [key, entry] of this._pending) {
2859
3013
  if (entry.sentAt === null) continue;
2860
3014
  const twoPhase = entry.twoPhase;
@@ -2872,7 +3026,7 @@ var Correlator = class {
2872
3026
  }
2873
3027
  continue;
2874
3028
  }
2875
- if (entry.sentAt + ackTimeoutMs <= t) {
3029
+ if (entry.sentAt + entry.ackTimeoutMs <= t) {
2876
3030
  const elapsed = t - entry.sentAt;
2877
3031
  this._removeExpired(key, entry);
2878
3032
  if (twoPhase !== null) {
@@ -3237,6 +3391,14 @@ var OUTBOUND_WARNING_CONTEXT = Object.freeze({
3237
3391
  byteOffset: 0,
3238
3392
  elapsedSinceSendMs: 0
3239
3393
  });
3394
+ var MAX_CONNECT_TIMEOUT_MS = 2147483647;
3395
+ var CONNECT_TIMEOUT_MESSAGE = "connect timed out: the connection, including its TLS handshake when TLS is on, was not established within connectTimeoutMs";
3396
+ var ConnectTimeoutCause = class extends Error {
3397
+ code = "ETIMEDOUT";
3398
+ constructor() {
3399
+ super(CONNECT_TIMEOUT_MESSAGE);
3400
+ }
3401
+ };
3240
3402
  function identityOptions(host, servername) {
3241
3403
  const target = servername ?? host;
3242
3404
  if (isIP(target) === 0) return { servername: target };
@@ -3311,6 +3473,15 @@ var MllpClient = class extends EventEmitter {
3311
3473
  _connectSignal;
3312
3474
  /** Set when close()/destroy()/abort fires; reconnect handler short-circuits. */
3313
3475
  _userClosed = false;
3476
+ /**
3477
+ * The reason passed to the `destroy(reason)` that closed a connection still connecting, `null`
3478
+ * otherwise. The socket hands it back on `'error'`, and `connect()` compares by identity so the
3479
+ * caller's own reason is carried as the cause and never sorted into a TLS `connectionCause`.
3480
+ * Only the call that reaches the socket records it: a later `destroy()` finds the connection
3481
+ * already CLOSED and leaves it alone. Cleared once matched and at the start of `connect()`, so
3482
+ * the client does not keep the caller's object alive.
3483
+ */
3484
+ _destroyReason = null;
3314
3485
  /**
3315
3486
  * Sends parked inside the client with nothing written for them. See {@link ParkedSend}.
3316
3487
  * Every entry removes itself the moment its own wait ends, however it ends.
@@ -3367,6 +3538,13 @@ var MllpClient = class extends EventEmitter {
3367
3538
  */
3368
3539
  constructor(opts) {
3369
3540
  super();
3541
+ const connectTimeoutMs = opts.connectTimeoutMs;
3542
+ if (connectTimeoutMs !== void 0 && !(Number.isInteger(connectTimeoutMs) && connectTimeoutMs >= 1 && connectTimeoutMs <= MAX_CONNECT_TIMEOUT_MS)) {
3543
+ throw new RangeError(
3544
+ "ClientOptions.connectTimeoutMs must be an integer from 1 to 2147483647, or left unset for no bound"
3545
+ );
3546
+ }
3547
+ checkCredentialMix(opts.tls);
3370
3548
  this._opts = opts;
3371
3549
  this._ackTimeoutMs = opts.ackTimeoutMs ?? 3e4;
3372
3550
  this._applicationAckTimeoutMs = opts.applicationAckTimeoutMs;
@@ -3410,10 +3588,25 @@ var MllpClient = class extends EventEmitter {
3410
3588
  * TLS failures carry a `connectionCause`: `'tls-verify'` for certificate
3411
3589
  * verification failures, `'tls-handshake'` for TLS-protocol-shaped failures
3412
3590
  * ({@link isTlsProtocolError}); pure TCP failures carry none.
3591
+ * - `MllpConnectionError({ phase: 'connect', connectionCause: 'connect-timeout' })` if
3592
+ * {@link ClientOptions.connectTimeoutMs} is set and the TCP connect, or the TLS handshake
3593
+ * after it, did not complete in time. The socket is destroyed; nothing was written.
3594
+ * - `MllpConnectionError({ phase: 'connect' })` if {@link MllpClient.destroy} is called while
3595
+ * `connect()` is still connecting, over TCP or TLS, before or during the handshake. Its
3596
+ * `cause` is the reason passed to `destroy(reason)`, as it is, and its message is that
3597
+ * reason's; with no reason the cause is an `Error` whose message is `closed before connect`,
3598
+ * the same as for any socket that closes before connecting with no error. It carries no
3599
+ * `connectionCause` either way: a reason is the caller's own, so one whose message or `code`
3600
+ * reads like a TLS failure (`alert`, `ERR_SSL_*`, `EPROTO`, a certificate code) is never
3601
+ * sorted into `'tls-handshake'` or `'tls-verify'`. The first `destroy()` decides: a second
3602
+ * call before `connect()` settles, with a reason or without one, changes nothing.
3413
3603
  * - `MllpTlsConfigurationError` if the configured cipher-suite list cannot be
3414
- * honoured (the runtime rejects it, or `atnaTransportSecurity` and `ciphers`
3415
- * both declare one). Raised **before** a socket is opened, so nothing is left
3416
- * connected; identify it by `instanceof` plus its stable `code`.
3604
+ * honoured (the runtime rejects it, the runtime does not enforce cipher lists
3605
+ * at all, or `atnaTransportSecurity` and `ciphers` both declare one). Raised
3606
+ * **before** a socket is opened, so nothing is left connected; identify it by
3607
+ * `instanceof` plus its stable `code`.
3608
+ * - `MllpTlsConfigurationError` with `MLLP_TLS_PFX_REJECTED` if `tls.pfx` cannot be loaded
3609
+ * with `tls.passphrase` (see {@link TlsOptions.pfx}), also before a socket is opened.
3417
3610
  *
3418
3611
  * **Dual failure signal on initial connect:** the Connection's transport
3419
3612
  * error handler is attached before this promise's own error listener, so a
@@ -3454,12 +3647,14 @@ var MllpClient = class extends EventEmitter {
3454
3647
  if (signal !== void 0) {
3455
3648
  this._captureConnectSignal(signal);
3456
3649
  }
3650
+ this._destroyReason = null;
3457
3651
  return new Promise((resolve, reject) => {
3458
3652
  let aborted = false;
3459
3653
  const { socket, transport } = this._createSocketAndTransport();
3460
3654
  if (this._opts.keepaliveIntervalMs !== void 0) {
3461
3655
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
3462
3656
  }
3657
+ socket.setNoDelay(this._opts.noDelay !== false);
3463
3658
  this._socket = socket;
3464
3659
  const connOpts = this._opts.framing !== void 0 ? { transport, framing: this._opts.framing } : { transport };
3465
3660
  if (this._opts.drainTimeoutMs !== void 0) {
@@ -3468,12 +3663,14 @@ var MllpClient = class extends EventEmitter {
3468
3663
  const conn = new Connection(connOpts);
3469
3664
  this._attachConnection(conn);
3470
3665
  const connectEventName = this._opts.tls !== void 0 ? "secureConnect" : "connect";
3666
+ this._armConnectTimeout(socket, connectEventName);
3471
3667
  const cleanup = () => {
3472
3668
  if (signal !== void 0) {
3473
3669
  signal.removeEventListener("abort", abortHandler);
3474
3670
  }
3475
3671
  socket.removeListener(connectEventName, onSocketConnect);
3476
3672
  socket.removeListener("error", onSocketError);
3673
+ socket.removeListener("close", onSocketClose);
3477
3674
  };
3478
3675
  const abortHandler = () => {
3479
3676
  aborted = true;
@@ -3498,13 +3695,28 @@ var MllpClient = class extends EventEmitter {
3498
3695
  const onSocketError = (err) => {
3499
3696
  if (aborted) return;
3500
3697
  cleanup();
3698
+ if (err === this._destroyReason) {
3699
+ this._destroyReason = null;
3700
+ reject(new MllpConnectionError(err.message, { cause: err, phase: "connect" }));
3701
+ return;
3702
+ }
3501
3703
  reject(this._wrapConnectError(err, "connect"));
3502
3704
  };
3705
+ const onSocketClose = () => {
3706
+ cleanup();
3707
+ reject(
3708
+ new MllpConnectionError("connection closed before it was established", {
3709
+ cause: new Error("closed before connect"),
3710
+ phase: "connect"
3711
+ })
3712
+ );
3713
+ };
3503
3714
  if (signal !== void 0) {
3504
3715
  signal.addEventListener("abort", abortHandler, { once: true });
3505
3716
  }
3506
3717
  socket.once(connectEventName, onSocketConnect);
3507
3718
  socket.once("error", onSocketError);
3719
+ socket.once("close", onSocketClose);
3508
3720
  });
3509
3721
  }
3510
3722
  /**
@@ -3527,6 +3739,7 @@ var MllpClient = class extends EventEmitter {
3527
3739
  }
3528
3740
  const tlsOpts = tlsOpt === true ? {} : tlsOpt;
3529
3741
  const cipherPolicy = resolveTlsCipherPolicy(tlsOpts, "client");
3742
+ checkPfx(tlsOpts.pfx, tlsOpts.passphrase);
3530
3743
  const socket = connect({
3531
3744
  host: this._opts.host,
3532
3745
  port: this._opts.port,
@@ -3535,6 +3748,7 @@ var MllpClient = class extends EventEmitter {
3535
3748
  ...tlsOpts.cert !== void 0 ? { cert: tlsOpts.cert } : {},
3536
3749
  ...tlsOpts.key !== void 0 ? { key: tlsOpts.key } : {},
3537
3750
  ...tlsOpts.passphrase !== void 0 ? { passphrase: tlsOpts.passphrase } : {},
3751
+ pfx: tlsOpts.pfx,
3538
3752
  minVersion: tlsOpts.minVersion ?? "TLSv1.2",
3539
3753
  ...tlsOpts.maxVersion !== void 0 ? { maxVersion: tlsOpts.maxVersion } : {},
3540
3754
  ...cipherPolicy,
@@ -3542,6 +3756,29 @@ var MllpClient = class extends EventEmitter {
3542
3756
  });
3543
3757
  return { socket, transport: new TlsTransport(socket) };
3544
3758
  }
3759
+ /**
3760
+ * Bound one connection attempt by {@link ClientOptions.connectTimeoutMs}, when it is set.
3761
+ *
3762
+ * Armed after the `Connection` has registered its own socket listeners (its set-once
3763
+ * `onClose`/`onError` would otherwise remove ours). The timer stops at the socket's connect
3764
+ * event (`'secureConnect'` for TLS, so the handshake is inside the bound) or at its `'close'`,
3765
+ * whichever comes first; a refused connect or an abort therefore leaves no timer behind. On
3766
+ * expiry the socket is destroyed with a {@link ConnectTimeoutCause}, which reaches the same
3767
+ * `'error'` listeners as any other connect failure: `connect()` rejects, and a reconnect
3768
+ * attempt hands it to the reconnect classifier.
3769
+ */
3770
+ _armConnectTimeout(socket, connectEventName) {
3771
+ const timeoutMs = this._opts.connectTimeoutMs;
3772
+ if (timeoutMs === void 0) return;
3773
+ const timer = setTimeout(() => {
3774
+ socket.destroy(new ConnectTimeoutCause());
3775
+ }, timeoutMs);
3776
+ const stop = () => {
3777
+ clearTimeout(timer);
3778
+ };
3779
+ socket.once(connectEventName, stop);
3780
+ socket.once("close", stop);
3781
+ }
3545
3782
  /**
3546
3783
  * Wrap a connect-phase socket error as `MllpConnectionError`, classifying
3547
3784
  * TLS failures into the additive `connectionCause`:
@@ -3556,6 +3793,13 @@ var MllpClient = class extends EventEmitter {
3556
3793
  * same shape as plaintext connect failures.
3557
3794
  */
3558
3795
  _wrapConnectError(err, phase) {
3796
+ if (err instanceof ConnectTimeoutCause) {
3797
+ return new MllpConnectionError(err.message, {
3798
+ cause: err,
3799
+ phase,
3800
+ connectionCause: "connect-timeout"
3801
+ });
3802
+ }
3559
3803
  if (this._opts.tls === void 0) {
3560
3804
  return new MllpConnectionError(err.message, { cause: err, phase });
3561
3805
  }
@@ -4036,6 +4280,7 @@ var MllpClient = class extends EventEmitter {
4036
4280
  if (this._opts.keepaliveIntervalMs !== void 0) {
4037
4281
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
4038
4282
  }
4283
+ socket.setNoDelay(this._opts.noDelay !== false);
4039
4284
  this._socket = socket;
4040
4285
  const connOpts = this._opts.framing !== void 0 ? { transport, framing: this._opts.framing } : { transport };
4041
4286
  if (this._opts.drainTimeoutMs !== void 0) {
@@ -4048,6 +4293,7 @@ var MllpClient = class extends EventEmitter {
4048
4293
  this._emitNegotiatedTlsParameters(socket);
4049
4294
  };
4050
4295
  const connectEventName = this._opts.tls !== void 0 ? "secureConnect" : "connect";
4296
+ this._armConnectTimeout(socket, connectEventName);
4051
4297
  socket.once("error", (sErr) => {
4052
4298
  if (this._lastError === null || this._lastError.message !== sErr.message) {
4053
4299
  this._lastError = sErr;
@@ -4223,8 +4469,8 @@ var MllpClient = class extends EventEmitter {
4223
4469
  *
4224
4470
  * Resolves with the ACK Buffer (framing stripped). Rejects with:
4225
4471
  * - `DOMException('Aborted', 'AbortError')` if `signal` aborts before the ACK.
4226
- * - `MllpTimeoutError` if no ACK arrives within `ackTimeoutMs`.
4227
- * The clock starts at the underlying `write()` flush callback, NOT at
4472
+ * - `MllpTimeoutError` if no ACK arrives within `ackTimeoutMs` (this send's own, else the
4473
+ * client's). The clock starts at the underlying `write()` flush callback, NOT at
4228
4474
  * the `send()` call.
4229
4475
  * - `MllpConnectionError({ phase: 'send' })` if the client is not connected.
4230
4476
  *
@@ -4253,7 +4499,10 @@ var MllpClient = class extends EventEmitter {
4253
4499
  *
4254
4500
  * @param payload Raw bytes; MLLP framing is added internally via `encodeFrame`.
4255
4501
  * @param opts.signal AbortSignal, aborting cancels the ACK wait.
4256
- * @param opts.ackTimeoutMs Per-send override of the backpressure wait budget.
4502
+ * @param opts.ackTimeoutMs This send's bound on the wait for its acknowledgement, from the
4503
+ * moment its bytes are flushed, in place of the client's `ackTimeoutMs`. Under
4504
+ * `onBackpressure: "wait"` it also bounds the wait for queue room, and the
4505
+ * acknowledgement wait then starts afresh once the send is written.
4257
4506
  * @param opts.applicationAckTimeoutMs Per-send override of the second wait's bound.
4258
4507
  * @param opts.onCommitAck Called with the commit disposition when the peer commits the
4259
4508
  * message ahead of its application acknowledgement. See {@link CommitAckReport}.
@@ -4308,21 +4557,34 @@ var MllpClient = class extends EventEmitter {
4308
4557
  opts
4309
4558
  );
4310
4559
  }
4560
+ const sendAckTimeoutMs = opts?.ackTimeoutMs;
4311
4561
  return new Promise((resolve, reject) => {
4312
4562
  let abortListener = null;
4313
- const wrappedResolve = (ack) => {
4563
+ let ackDeadline;
4564
+ let settled = false;
4565
+ const settle = () => {
4566
+ settled = true;
4314
4567
  if (signal !== void 0 && abortListener !== null) {
4315
4568
  signal.removeEventListener("abort", abortListener);
4316
4569
  }
4570
+ clearTimeout(ackDeadline);
4571
+ };
4572
+ const wrappedResolve = (ack) => {
4573
+ settle();
4317
4574
  resolve(ack);
4318
4575
  };
4319
4576
  const wrappedReject = (err) => {
4320
- if (signal !== void 0 && abortListener !== null) {
4321
- signal.removeEventListener("abort", abortListener);
4322
- }
4577
+ settle();
4323
4578
  reject(err);
4324
4579
  };
4325
- const key = correlator.enqueue(frame, controlId, wrappedResolve, wrappedReject, twoPhase);
4580
+ const key = correlator.enqueue(
4581
+ frame,
4582
+ controlId,
4583
+ wrappedResolve,
4584
+ wrappedReject,
4585
+ twoPhase,
4586
+ sendAckTimeoutMs
4587
+ );
4326
4588
  if (key === null) {
4327
4589
  const parked = { cancel: () => void 0 };
4328
4590
  const neverDelivered = () => new MllpNeverDeliveredError({
@@ -4364,6 +4626,12 @@ var MllpClient = class extends EventEmitter {
4364
4626
  }
4365
4627
  conn.send(frame);
4366
4628
  correlator.markFlushed(key, Date.now());
4629
+ if (sendAckTimeoutMs !== void 0 && !settled) {
4630
+ ackDeadline = setTimeout(() => {
4631
+ correlator.expireDue();
4632
+ }, sendAckTimeoutMs);
4633
+ ackDeadline.unref();
4634
+ }
4367
4635
  this._sentTotal += 1;
4368
4636
  });
4369
4637
  }
@@ -4760,6 +5028,12 @@ var MllpClient = class extends EventEmitter {
4760
5028
  * ever written for it; that is a statement about the bytes, not about how the client was
4761
5029
  * shut down, so it holds on this path too.
4762
5030
  *
5031
+ * A {@link MllpClient.connect} still connecting rejects with an `MllpConnectionError` whose
5032
+ * `phase` is `'connect'` and no `connectionCause`. Its `cause` is `reason` when one is given,
5033
+ * never classified as a TLS failure whatever its message or `code`, and otherwise an `Error`
5034
+ * whose message is `closed before connect`. Only the first call reaches the socket, so a
5035
+ * second `destroy()` before `connect()` settles, with or without a reason, changes nothing.
5036
+ *
4763
5037
  * @example
4764
5038
  * ```typescript
4765
5039
  * client.destroy(new Error('shutting down'));
@@ -4780,6 +5054,7 @@ var MllpClient = class extends EventEmitter {
4780
5054
  this._teardownCorrelator(teardownReason);
4781
5055
  const conn = this._connection;
4782
5056
  if (conn === null) return;
5057
+ if (conn.state === "CONNECTING") this._destroyReason = reason ?? null;
4783
5058
  conn.destroy(reason);
4784
5059
  }
4785
5060
  /**
@@ -4860,6 +5135,8 @@ async function createStarterClient(opts) {
4860
5135
  ...opts.retryStrategy !== void 0 ? { retryStrategy: opts.retryStrategy } : {},
4861
5136
  ...opts.keepaliveIntervalMs !== void 0 ? { keepaliveIntervalMs: opts.keepaliveIntervalMs } : {},
4862
5137
  ...opts.deadPeerTimeoutMs !== void 0 ? { deadPeerTimeoutMs: opts.deadPeerTimeoutMs } : {},
5138
+ noDelay: opts.noDelay !== false,
5139
+ ...opts.connectTimeoutMs !== void 0 ? { connectTimeoutMs: opts.connectTimeoutMs } : {},
4863
5140
  ...opts.tls !== void 0 ? { tls: opts.tls } : {}
4864
5141
  };
4865
5142
  const client = createClient(clientOpts);
@@ -5180,8 +5457,8 @@ async function runDifferential(options = {}) {
5180
5457
  }
5181
5458
 
5182
5459
  // src/index.ts
5183
- var VERSION = "0.1.10";
5460
+ var VERSION = "0.1.12";
5184
5461
 
5185
- export { ATNA_CIPHER_LIST, ATNA_CIPHER_SUITES, Connection, FrameReader, MLLP_BIND_ALL_INTERFACES, MLLP_CONNECTION_LIMIT_REACHED, MLLP_DIFF_PEER_UNPARSEABLE, MLLP_TLS_CIPHER_LIST_REJECTED, MLLP_TLS_CIPHER_OPTION_CONFLICT, MLLP_TLS_DH_PARAMETERS_REJECTED, MLLP_TLS_VERIFY_DISABLED, MllpAckError, MllpApplicationAckError, MllpBackpressureError, MllpClient, MllpCommitRejectedError, MllpConnectionError, MllpDifferentialConfigurationError, MllpFramingError, MllpNeverDeliveredError, MllpServer, MllpTimeoutError, MllpTlsConfigurationError, MllpUnknownFateError, NetTransport, TLS13_DEFAULT_CIPHER_SUITES, TlsTransport, VERSION, ackDiagnosticMessage, ackModeDiagnosticMessage, buildRawAck, canonicalAcknowledgement, canonicalExchanges, createClient, createServer, createStarterClient, createStarterServer, createWarning, differentialConfigurationMessage, encodeFrame, isTlsProtocolError, isTlsVerificationErrorCode, isTransientConnectionError, rawAckUncorrelatable, readNegotiatedTlsParameters, resolveDifferentialPeer, resolveNackCode, resolveTlsCipherPolicy, runDifferential, tlsConfigurationMessage };
5462
+ export { ATNA_CIPHER_LIST, ATNA_CIPHER_SUITES, Connection, FrameReader, MLLP_BIND_ALL_INTERFACES, MLLP_CONNECTION_LIMIT_REACHED, MLLP_DIFF_PEER_UNPARSEABLE, MLLP_TLS_CIPHER_LIST_REJECTED, MLLP_TLS_CIPHER_LIST_UNENFORCEABLE, MLLP_TLS_CIPHER_OPTION_CONFLICT, MLLP_TLS_CREDENTIAL_CONFLICT, MLLP_TLS_DH_PARAMETERS_REJECTED, MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE, MLLP_TLS_PFX_REJECTED, MLLP_TLS_VERIFY_DISABLED, MllpAckError, MllpApplicationAckError, MllpBackpressureError, MllpClient, MllpCommitRejectedError, MllpConnectionError, MllpDifferentialConfigurationError, MllpFramingError, MllpNeverDeliveredError, MllpServer, MllpTimeoutError, MllpTlsConfigurationError, MllpUnknownFateError, NetTransport, TLS13_DEFAULT_CIPHER_SUITES, TlsTransport, VERSION, ackDiagnosticMessage, ackModeDiagnosticMessage, buildRawAck, canonicalAcknowledgement, canonicalExchanges, createClient, createServer, createStarterClient, createStarterServer, createWarning, differentialConfigurationMessage, encodeFrame, isTlsProtocolError, isTlsVerificationErrorCode, isTransientConnectionError, rawAckUncorrelatable, readNegotiatedTlsParameters, resolveDifferentialPeer, resolveNackCode, resolveTlsCipherPolicy, runDifferential, selectAckCode, tlsConfigurationMessage };
5186
5463
  //# sourceMappingURL=index.mjs.map
5187
5464
  //# sourceMappingURL=index.mjs.map