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