@cosyte/mllp 0.1.11 → 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) {
@@ -3319,6 +3473,15 @@ var MllpClient = class extends EventEmitter {
3319
3473
  _connectSignal;
3320
3474
  /** Set when close()/destroy()/abort fires; reconnect handler short-circuits. */
3321
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;
3322
3485
  /**
3323
3486
  * Sends parked inside the client with nothing written for them. See {@link ParkedSend}.
3324
3487
  * Every entry removes itself the moment its own wait ends, however it ends.
@@ -3381,6 +3544,7 @@ var MllpClient = class extends EventEmitter {
3381
3544
  "ClientOptions.connectTimeoutMs must be an integer from 1 to 2147483647, or left unset for no bound"
3382
3545
  );
3383
3546
  }
3547
+ checkCredentialMix(opts.tls);
3384
3548
  this._opts = opts;
3385
3549
  this._ackTimeoutMs = opts.ackTimeoutMs ?? 3e4;
3386
3550
  this._applicationAckTimeoutMs = opts.applicationAckTimeoutMs;
@@ -3427,10 +3591,22 @@ var MllpClient = class extends EventEmitter {
3427
3591
  * - `MllpConnectionError({ phase: 'connect', connectionCause: 'connect-timeout' })` if
3428
3592
  * {@link ClientOptions.connectTimeoutMs} is set and the TCP connect, or the TLS handshake
3429
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.
3430
3603
  * - `MllpTlsConfigurationError` if the configured cipher-suite list cannot be
3431
- * honoured (the runtime rejects it, or `atnaTransportSecurity` and `ciphers`
3432
- * both declare one). Raised **before** a socket is opened, so nothing is left
3433
- * 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.
3434
3610
  *
3435
3611
  * **Dual failure signal on initial connect:** the Connection's transport
3436
3612
  * error handler is attached before this promise's own error listener, so a
@@ -3471,12 +3647,14 @@ var MllpClient = class extends EventEmitter {
3471
3647
  if (signal !== void 0) {
3472
3648
  this._captureConnectSignal(signal);
3473
3649
  }
3650
+ this._destroyReason = null;
3474
3651
  return new Promise((resolve, reject) => {
3475
3652
  let aborted = false;
3476
3653
  const { socket, transport } = this._createSocketAndTransport();
3477
3654
  if (this._opts.keepaliveIntervalMs !== void 0) {
3478
3655
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
3479
3656
  }
3657
+ socket.setNoDelay(this._opts.noDelay !== false);
3480
3658
  this._socket = socket;
3481
3659
  const connOpts = this._opts.framing !== void 0 ? { transport, framing: this._opts.framing } : { transport };
3482
3660
  if (this._opts.drainTimeoutMs !== void 0) {
@@ -3492,6 +3670,7 @@ var MllpClient = class extends EventEmitter {
3492
3670
  }
3493
3671
  socket.removeListener(connectEventName, onSocketConnect);
3494
3672
  socket.removeListener("error", onSocketError);
3673
+ socket.removeListener("close", onSocketClose);
3495
3674
  };
3496
3675
  const abortHandler = () => {
3497
3676
  aborted = true;
@@ -3516,13 +3695,28 @@ var MllpClient = class extends EventEmitter {
3516
3695
  const onSocketError = (err) => {
3517
3696
  if (aborted) return;
3518
3697
  cleanup();
3698
+ if (err === this._destroyReason) {
3699
+ this._destroyReason = null;
3700
+ reject(new MllpConnectionError(err.message, { cause: err, phase: "connect" }));
3701
+ return;
3702
+ }
3519
3703
  reject(this._wrapConnectError(err, "connect"));
3520
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
+ };
3521
3714
  if (signal !== void 0) {
3522
3715
  signal.addEventListener("abort", abortHandler, { once: true });
3523
3716
  }
3524
3717
  socket.once(connectEventName, onSocketConnect);
3525
3718
  socket.once("error", onSocketError);
3719
+ socket.once("close", onSocketClose);
3526
3720
  });
3527
3721
  }
3528
3722
  /**
@@ -3545,6 +3739,7 @@ var MllpClient = class extends EventEmitter {
3545
3739
  }
3546
3740
  const tlsOpts = tlsOpt === true ? {} : tlsOpt;
3547
3741
  const cipherPolicy = resolveTlsCipherPolicy(tlsOpts, "client");
3742
+ checkPfx(tlsOpts.pfx, tlsOpts.passphrase);
3548
3743
  const socket = connect({
3549
3744
  host: this._opts.host,
3550
3745
  port: this._opts.port,
@@ -3553,6 +3748,7 @@ var MllpClient = class extends EventEmitter {
3553
3748
  ...tlsOpts.cert !== void 0 ? { cert: tlsOpts.cert } : {},
3554
3749
  ...tlsOpts.key !== void 0 ? { key: tlsOpts.key } : {},
3555
3750
  ...tlsOpts.passphrase !== void 0 ? { passphrase: tlsOpts.passphrase } : {},
3751
+ pfx: tlsOpts.pfx,
3556
3752
  minVersion: tlsOpts.minVersion ?? "TLSv1.2",
3557
3753
  ...tlsOpts.maxVersion !== void 0 ? { maxVersion: tlsOpts.maxVersion } : {},
3558
3754
  ...cipherPolicy,
@@ -4084,6 +4280,7 @@ var MllpClient = class extends EventEmitter {
4084
4280
  if (this._opts.keepaliveIntervalMs !== void 0) {
4085
4281
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
4086
4282
  }
4283
+ socket.setNoDelay(this._opts.noDelay !== false);
4087
4284
  this._socket = socket;
4088
4285
  const connOpts = this._opts.framing !== void 0 ? { transport, framing: this._opts.framing } : { transport };
4089
4286
  if (this._opts.drainTimeoutMs !== void 0) {
@@ -4272,8 +4469,8 @@ var MllpClient = class extends EventEmitter {
4272
4469
  *
4273
4470
  * Resolves with the ACK Buffer (framing stripped). Rejects with:
4274
4471
  * - `DOMException('Aborted', 'AbortError')` if `signal` aborts before the ACK.
4275
- * - `MllpTimeoutError` if no ACK arrives within `ackTimeoutMs`.
4276
- * 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
4277
4474
  * the `send()` call.
4278
4475
  * - `MllpConnectionError({ phase: 'send' })` if the client is not connected.
4279
4476
  *
@@ -4302,7 +4499,10 @@ var MllpClient = class extends EventEmitter {
4302
4499
  *
4303
4500
  * @param payload Raw bytes; MLLP framing is added internally via `encodeFrame`.
4304
4501
  * @param opts.signal AbortSignal, aborting cancels the ACK wait.
4305
- * @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.
4306
4506
  * @param opts.applicationAckTimeoutMs Per-send override of the second wait's bound.
4307
4507
  * @param opts.onCommitAck Called with the commit disposition when the peer commits the
4308
4508
  * message ahead of its application acknowledgement. See {@link CommitAckReport}.
@@ -4357,21 +4557,34 @@ var MllpClient = class extends EventEmitter {
4357
4557
  opts
4358
4558
  );
4359
4559
  }
4560
+ const sendAckTimeoutMs = opts?.ackTimeoutMs;
4360
4561
  return new Promise((resolve, reject) => {
4361
4562
  let abortListener = null;
4362
- const wrappedResolve = (ack) => {
4563
+ let ackDeadline;
4564
+ let settled = false;
4565
+ const settle = () => {
4566
+ settled = true;
4363
4567
  if (signal !== void 0 && abortListener !== null) {
4364
4568
  signal.removeEventListener("abort", abortListener);
4365
4569
  }
4570
+ clearTimeout(ackDeadline);
4571
+ };
4572
+ const wrappedResolve = (ack) => {
4573
+ settle();
4366
4574
  resolve(ack);
4367
4575
  };
4368
4576
  const wrappedReject = (err) => {
4369
- if (signal !== void 0 && abortListener !== null) {
4370
- signal.removeEventListener("abort", abortListener);
4371
- }
4577
+ settle();
4372
4578
  reject(err);
4373
4579
  };
4374
- 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
+ );
4375
4588
  if (key === null) {
4376
4589
  const parked = { cancel: () => void 0 };
4377
4590
  const neverDelivered = () => new MllpNeverDeliveredError({
@@ -4413,6 +4626,12 @@ var MllpClient = class extends EventEmitter {
4413
4626
  }
4414
4627
  conn.send(frame);
4415
4628
  correlator.markFlushed(key, Date.now());
4629
+ if (sendAckTimeoutMs !== void 0 && !settled) {
4630
+ ackDeadline = setTimeout(() => {
4631
+ correlator.expireDue();
4632
+ }, sendAckTimeoutMs);
4633
+ ackDeadline.unref();
4634
+ }
4416
4635
  this._sentTotal += 1;
4417
4636
  });
4418
4637
  }
@@ -4809,6 +5028,12 @@ var MllpClient = class extends EventEmitter {
4809
5028
  * ever written for it; that is a statement about the bytes, not about how the client was
4810
5029
  * shut down, so it holds on this path too.
4811
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
+ *
4812
5037
  * @example
4813
5038
  * ```typescript
4814
5039
  * client.destroy(new Error('shutting down'));
@@ -4829,6 +5054,7 @@ var MllpClient = class extends EventEmitter {
4829
5054
  this._teardownCorrelator(teardownReason);
4830
5055
  const conn = this._connection;
4831
5056
  if (conn === null) return;
5057
+ if (conn.state === "CONNECTING") this._destroyReason = reason ?? null;
4832
5058
  conn.destroy(reason);
4833
5059
  }
4834
5060
  /**
@@ -4909,6 +5135,7 @@ async function createStarterClient(opts) {
4909
5135
  ...opts.retryStrategy !== void 0 ? { retryStrategy: opts.retryStrategy } : {},
4910
5136
  ...opts.keepaliveIntervalMs !== void 0 ? { keepaliveIntervalMs: opts.keepaliveIntervalMs } : {},
4911
5137
  ...opts.deadPeerTimeoutMs !== void 0 ? { deadPeerTimeoutMs: opts.deadPeerTimeoutMs } : {},
5138
+ noDelay: opts.noDelay !== false,
4912
5139
  ...opts.connectTimeoutMs !== void 0 ? { connectTimeoutMs: opts.connectTimeoutMs } : {},
4913
5140
  ...opts.tls !== void 0 ? { tls: opts.tls } : {}
4914
5141
  };
@@ -5230,8 +5457,8 @@ async function runDifferential(options = {}) {
5230
5457
  }
5231
5458
 
5232
5459
  // src/index.ts
5233
- var VERSION = "0.1.11";
5460
+ var VERSION = "0.1.12";
5234
5461
 
5235
- 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 };
5236
5463
  //# sourceMappingURL=index.mjs.map
5237
5464
  //# sourceMappingURL=index.mjs.map