@cosyte/mllp 0.1.5 → 0.1.7

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
@@ -244,7 +244,7 @@ var FrameReader = class {
244
244
  );
245
245
  this._frameStartOffset = this._byteOffset;
246
246
  this._state = "READING_PAYLOAD";
247
- this._appendByte(byte);
247
+ this._readPayload(byte);
248
248
  return;
249
249
  }
250
250
  const snippet = Buffer.from([byte]);
@@ -700,7 +700,10 @@ function assertUsableDhParameters(dhParameters) {
700
700
  createSecureContext({ dhparam: dhParameters });
701
701
  } catch (err) {
702
702
  throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_REJECTED, {
703
- cause: err instanceof Error ? err : new Error(String(err))
703
+ cause: err instanceof Error ? err : (
704
+ /* v8 ignore next -- createSecureContext throws only Error */
705
+ new Error(String(err))
706
+ )
704
707
  });
705
708
  }
706
709
  }
@@ -718,7 +721,10 @@ function resolveTlsCipherPolicy(opts, side) {
718
721
  createSecureContext({ ciphers });
719
722
  } catch (err) {
720
723
  throw new MllpTlsConfigurationError(MLLP_TLS_CIPHER_LIST_REJECTED, {
721
- cause: err instanceof Error ? err : new Error(String(err))
724
+ cause: err instanceof Error ? err : (
725
+ /* v8 ignore next -- createSecureContext throws only Error */
726
+ new Error(String(err))
727
+ )
722
728
  });
723
729
  }
724
730
  }
@@ -808,6 +814,17 @@ var Connection = class extends EventEmitter {
808
814
  _warningsTruncated = false;
809
815
  _onWarningFn = null;
810
816
  _drainPromise = null;
817
+ /** Resolves {@link Connection._leftDraining}; called on the transition out of `DRAINING`. */
818
+ _leaveDraining;
819
+ /**
820
+ * Settles when the connection leaves `DRAINING` by any route: the drain finishing, the drain
821
+ * timeout, a `destroy()`, or the peer closing. A connection enters `DRAINING` at most once, so
822
+ * one promise per connection is enough. The drain races it, so a `close()` never outlives the
823
+ * drain it waits on.
824
+ */
825
+ _leftDraining = new Promise((resolve) => {
826
+ this._leaveDraining = resolve;
827
+ });
811
828
  /**
812
829
  * beforeClose hook, no-op default that resolves immediately.
813
830
  *
@@ -884,7 +901,9 @@ var Connection = class extends EventEmitter {
884
901
  * Notify the connection that the transport handshake has completed.
885
902
  *
886
903
  * Transitions `CONNECTING → CONNECTED` and emits the `'connect'` event.
887
- * Called externally by Server/Client after the socket connects.
904
+ * Called externally by Server/Client after the socket connects. In any other state it does
905
+ * nothing: a connection closed before its socket connected stays `CLOSED` and emits no
906
+ * `'connect'`, and a second call on a `CONNECTED` connection emits no second one.
888
907
  *
889
908
  * @param remoteAddress - Remote peer IP address, or `null` if unavailable.
890
909
  * @param remotePort - Remote peer port, or `null` if unavailable.
@@ -897,6 +916,7 @@ var Connection = class extends EventEmitter {
897
916
  * ```
898
917
  */
899
918
  notifyConnect(remoteAddress, remotePort) {
919
+ if (this._state !== "CONNECTING") return;
900
920
  this._remoteAddress = remoteAddress;
901
921
  this._remotePort = remotePort;
902
922
  this._connectedAt = /* @__PURE__ */ new Date();
@@ -935,6 +955,10 @@ var Connection = class extends EventEmitter {
935
955
  * then `DRAINING → DISCONNECTED` once the hook resolves, or `DRAINING → CLOSED`
936
956
  * if the drain timeout elapses first.
937
957
  * - If `DRAINING`: waits for the existing drain to complete (idempotent).
958
+ *
959
+ * Every pending `close()` resolves as soon as the connection leaves `DRAINING`, by whatever
960
+ * route: the hook resolving, the drain timeout, a `destroy()`, or the peer closing. A
961
+ * `destroy()` during a long drain therefore ends the wait at once, not at the drain timeout.
938
962
  * - If `CLOSED` or `DISCONNECTED`: no-op.
939
963
  *
940
964
  * @param opts.drainTimeoutMs - Override drain timeout (default: `opts.drainTimeoutMs ?? 30_000`).
@@ -969,23 +993,29 @@ var Connection = class extends EventEmitter {
969
993
  */
970
994
  async _drainWithTimeout(timeoutMs) {
971
995
  const drainPromise = this.beforeClose(timeoutMs);
996
+ let handle;
972
997
  const timeoutPromise = new Promise((resolve) => {
973
- const handle = setTimeout(() => {
998
+ handle = setTimeout(() => {
974
999
  resolve("timeout");
975
1000
  }, timeoutMs);
976
1001
  handle.unref();
977
1002
  });
978
- const result = await Promise.race([drainPromise.then(() => "done"), timeoutPromise]);
979
- if (result === "timeout") {
980
- if (this._state === "DRAINING") {
1003
+ try {
1004
+ const result = await Promise.race([
1005
+ drainPromise.then(() => "done"),
1006
+ timeoutPromise,
1007
+ this._leftDraining
1008
+ ]);
1009
+ if (this._state !== "DRAINING") return;
1010
+ if (result === "timeout") {
981
1011
  this._transition("CLOSED", "drain timeout");
982
1012
  this._transport.destroy();
983
- }
984
- } else {
985
- if (this._state === "DRAINING") {
1013
+ } else {
986
1014
  this._transition("DISCONNECTED");
987
1015
  this._transport.close();
988
1016
  }
1017
+ } finally {
1018
+ clearTimeout(handle);
989
1019
  }
990
1020
  }
991
1021
  /**
@@ -1057,6 +1087,7 @@ var Connection = class extends EventEmitter {
1057
1087
  this._dispatchContained(() => {
1058
1088
  this.emit("stateChange", event);
1059
1089
  });
1090
+ if (from === "DRAINING") this._leaveDraining("left");
1060
1091
  if (to === "DISCONNECTED") {
1061
1092
  this._dispatchContained(() => {
1062
1093
  this.emit("disconnect", Object.freeze({ connectionId: this.connectionId }));
@@ -2132,6 +2163,7 @@ var MllpServer = class extends EventEmitter {
2132
2163
  return Object.freeze({
2133
2164
  subjectCN: asCn(cert.subject?.CN),
2134
2165
  issuerCN: asCn(cert.issuer?.CN),
2166
+ /* v8 ignore next -- Node.js always reports valid_to for a parsed certificate */
2135
2167
  validTo: cert.valid_to ?? null,
2136
2168
  // Verification outcome, under 'WANT' a certificate can be present yet
2137
2169
  // UNVERIFIED (see PeerCertificateSummary.authorized JSDoc).
@@ -3053,7 +3085,7 @@ var MllpClient = class extends EventEmitter {
3053
3085
  * the Correlator is timer-free. Cleared on close/destroy.
3054
3086
  */
3055
3087
  _ackSweepTimer = null;
3056
- // ── Reconnect state (Plan 04, CLIENT-05/06/12/17/18) ─────────────────────
3088
+ // ── Reconnect state: backoff, the retry strategy and the reconnect cycle ─────────
3057
3089
  _autoReconnect;
3058
3090
  _initialDelayMs;
3059
3091
  _maxDelayMs;
@@ -3076,7 +3108,7 @@ var MllpClient = class extends EventEmitter {
3076
3108
  _backoffTimer = null;
3077
3109
  /** Last delay (ms) used by the strategy. Surfaced via RetryContext.lastDelayMs. */
3078
3110
  _lastDelayMs = 0;
3079
- // ── Backpressure + pipeline state (Plan 05, CLIENT-07/CLIENT-19, D-23) ───
3111
+ // ── Backpressure and pipeline state: the high-water mark and the in-flight set ───
3080
3112
  /** Count cap; `Number.POSITIVE_INFINITY` when only bytes configured. */
3081
3113
  _hwmCount;
3082
3114
  /** Byte cap; `Number.POSITIVE_INFINITY` when only count configured. */
@@ -3125,7 +3157,7 @@ var MllpClient = class extends EventEmitter {
3125
3157
  * @internal
3126
3158
  */
3127
3159
  _reconnectFactory = null;
3128
- // ── PLAN-06, observability counters for getStats (OBS-01, D-26) ─────────
3160
+ // ── Observability counters for getStats() ─────────────────────────────────
3129
3161
  /** Total successful `conn.send()` flushes since construction. */
3130
3162
  _sentTotal = 0;
3131
3163
  /** Total ACKs resolved since construction. */
@@ -3391,6 +3423,7 @@ var MllpClient = class extends EventEmitter {
3391
3423
  ackCode: ctx.ackCode,
3392
3424
  controlIdBytes: ctx.controlIdBytes,
3393
3425
  elapsedSinceSendMs: ctx.elapsedSinceSendMs,
3426
+ /* v8 ignore next -- send() refuses before any warning when no connection is attached, so one always is here */
3394
3427
  connectionId: this._connection?.connectionId ?? conn?.connectionId,
3395
3428
  timestamp: /* @__PURE__ */ new Date()
3396
3429
  });
@@ -3494,7 +3527,7 @@ var MllpClient = class extends EventEmitter {
3494
3527
  this._correlator = new Correlator({
3495
3528
  mode: this._correlateByControlId ? "controlId" : "fifo",
3496
3529
  ackTimeoutMs: this._ackTimeoutMs,
3497
- // Plan 05, pipeline:false collapses the in-flight set to ≤1 (D-06).
3530
+ // pipeline:false collapses the in-flight set to at most one.
3498
3531
  maxInFlight: this._pipeline ? Number.POSITIVE_INFINITY : 1,
3499
3532
  onWarning: (code, ctx) => {
3500
3533
  this._aggregatedWarningsByCode[code] = (this._aggregatedWarningsByCode[code] ?? 0) + 1;
@@ -3504,6 +3537,7 @@ var MllpClient = class extends EventEmitter {
3504
3537
  message: ackDiagnosticMessage(code),
3505
3538
  controlIdBytes: ctx.controlIdBytes,
3506
3539
  elapsedSinceSendMs: ctx.elapsedSinceSendMs,
3540
+ /* v8 ignore next -- correlator callbacks run only after attach has stored this connection */
3507
3541
  connectionId: this._connection?.connectionId ?? conn.connectionId,
3508
3542
  timestamp: /* @__PURE__ */ new Date()
3509
3543
  });
@@ -3520,6 +3554,7 @@ var MllpClient = class extends EventEmitter {
3520
3554
  safeEmitError(
3521
3555
  this,
3522
3556
  Object.freeze({
3557
+ /* v8 ignore next -- correlator callbacks run only after attach has stored this connection */
3523
3558
  connectionId: this._connection?.connectionId ?? conn.connectionId,
3524
3559
  error: err,
3525
3560
  // The peer's MSA-2 byte LENGTH. The bytes themselves used to be
@@ -3535,6 +3570,7 @@ var MllpClient = class extends EventEmitter {
3535
3570
  new MllpTimeoutError(`ACK timeout after ${elapsedMs}ms`, {
3536
3571
  messageControlIdBytes: entry.controlId?.length,
3537
3572
  elapsedMs,
3573
+ /* v8 ignore next -- only flushed sends can time out, so sentAt is set */
3538
3574
  sentAt: entry.sentAt ?? 0
3539
3575
  })
3540
3576
  );
@@ -3566,6 +3602,7 @@ var MllpClient = class extends EventEmitter {
3566
3602
  safeEmitError(
3567
3603
  this,
3568
3604
  Object.freeze({
3605
+ /* v8 ignore next -- correlator callbacks run only after attach has stored this connection */
3569
3606
  connectionId: this._connection?.connectionId ?? conn.connectionId,
3570
3607
  error: err instanceof Error ? err : new Error(String(err))
3571
3608
  })
@@ -3744,6 +3781,7 @@ var MllpClient = class extends EventEmitter {
3744
3781
  safeEmitError(
3745
3782
  this,
3746
3783
  Object.freeze({
3784
+ /* v8 ignore next -- a disconnect always arrives from an attached connection, so one is stored */
3747
3785
  connectionId: this._connection?.connectionId ?? "<none>",
3748
3786
  error: this._lastError
3749
3787
  })
@@ -3761,6 +3799,7 @@ var MllpClient = class extends EventEmitter {
3761
3799
  this._emitContained(
3762
3800
  "reconnecting",
3763
3801
  Object.freeze({
3802
+ /* v8 ignore next -- a disconnect always arrives from an attached connection, so one is stored */
3764
3803
  connectionId: this._connection?.connectionId ?? "<none>",
3765
3804
  attempt: this._attempt,
3766
3805
  delayMs: delay
@@ -4006,7 +4045,7 @@ var MllpClient = class extends EventEmitter {
4006
4045
  *
4007
4046
  * Emits a frozen `'ack'` event on every successful match.
4008
4047
  *
4009
- * ## Enhanced acknowledgement mode
4048
+ * **Enhanced acknowledgement mode**
4010
4049
  *
4011
4050
  * A message whose MSH-15 or MSH-16 is not null asks for the two-part protocol of HL7
4012
4051
  * v2.5.1 §2.9, and on a client correlating by control ID this method delivers it: the
@@ -4884,6 +4923,7 @@ function recordWarning(into, warning, offsetBase = 0) {
4884
4923
  function classifyFrame(exchange, payload, frameStart, chunks, deviations, finish) {
4885
4924
  const canonical = encodeFrame(payload, {
4886
4925
  allowDelimiterBytesInPayload: true,
4926
+ /* v8 ignore next 3 -- no delivered payload holds VT or FS, so the encoder never warns here */
4887
4927
  onWarning: (w) => {
4888
4928
  recordWarning(deviations, w, frameStart + 1);
4889
4929
  }
@@ -4955,7 +4995,7 @@ async function runDifferential(options = {}) {
4955
4995
  }
4956
4996
 
4957
4997
  // src/index.ts
4958
- var VERSION = "0.1.5";
4998
+ var VERSION = "0.1.7";
4959
4999
 
4960
5000
  export { ATNA_CIPHER_LIST, ATNA_CIPHER_SUITES, Connection, FrameReader, MLLP_BIND_ALL_INTERFACES, 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 };
4961
5001
  //# sourceMappingURL=index.mjs.map