@cosyte/mllp 0.1.14 → 0.1.16

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
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var buffer = require('buffer');
3
4
  var tls = require('tls');
4
5
  var events = require('events');
5
6
  var crypto = require('crypto');
@@ -16,8 +17,6 @@ function createWarning(code, byteOffset, message) {
16
17
  timestamp: /* @__PURE__ */ new Date()
17
18
  });
18
19
  }
19
-
20
- // src/framing/error.ts
21
20
  var MAX_SNIPPET_BYTES = 64;
22
21
  var MllpFramingError = class _MllpFramingError extends Error {
23
22
  name = "MllpFramingError";
@@ -52,7 +51,7 @@ var MllpFramingError = class _MllpFramingError extends Error {
52
51
  super(message ?? `MLLP framing error: ${code} at byte offset ${byteOffset}`);
53
52
  this.code = code;
54
53
  this.byteOffset = byteOffset;
55
- this.snippet = Buffer.from(snippet.subarray(0, MAX_SNIPPET_BYTES));
54
+ this.snippet = buffer.Buffer.from(snippet.subarray(0, MAX_SNIPPET_BYTES));
56
55
  if (Error.captureStackTrace) {
57
56
  Error.captureStackTrace(this, _MllpFramingError);
58
57
  }
@@ -67,9 +66,9 @@ var LF = 10;
67
66
  var DEFAULT_MAX_FRAME_SIZE = 16 * 1024 * 1024;
68
67
 
69
68
  // src/framing/encoder.ts
70
- function encodeFrame(payload, opts) {
71
- const allow = opts?.allowDelimiterBytesInPayload === true;
72
- const onWarning = opts?.onWarning;
69
+ function encodeFrame(payload, options = {}) {
70
+ const allow = options.allowDelimiterBytesInPayload === true;
71
+ const onWarning = options.onWarning;
73
72
  if (!(payload instanceof Uint8Array)) {
74
73
  scanEachByte(payload, allow, onWarning);
75
74
  } else if (!allow || onWarning !== void 0) {
@@ -83,7 +82,7 @@ function encodeFrame(payload, opts) {
83
82
  else fs = payload.indexOf(FS, i + 1);
84
83
  }
85
84
  }
86
- const frame = Buffer.allocUnsafe(payload.length + 3);
85
+ const frame = buffer.Buffer.allocUnsafe(payload.length + 3);
87
86
  frame[0] = VT;
88
87
  payload.copy(frame, 1);
89
88
  frame[payload.length + 1] = FS;
@@ -100,7 +99,7 @@ function scanEachByte(payload, allow, onWarning) {
100
99
  function delimiterAt(byte, i, allow, onWarning) {
101
100
  const code = byte === VT ? "MLLP_PAYLOAD_CONTAINS_VT" : "MLLP_PAYLOAD_CONTAINS_FS";
102
101
  if (!allow) {
103
- throw new MllpFramingError(code, i, Buffer.from([byte]));
102
+ throw new MllpFramingError(code, i, buffer.Buffer.from([byte]));
104
103
  }
105
104
  if (onWarning !== void 0) {
106
105
  const byteHex = byte === VT ? "0x0B" : "0x1C";
@@ -115,16 +114,14 @@ function delimiterAt(byte, i, allow, onWarning) {
115
114
  }
116
115
  }
117
116
  }
118
-
119
- // src/framing/decoder.ts
120
117
  var BLOCK_SIZE = 4096;
121
- var EMPTY_SNIPPET = Buffer.alloc(0);
118
+ var EMPTY_SNIPPET = buffer.Buffer.alloc(0);
122
119
  var FrameReader = class {
123
120
  _opts;
124
121
  _maxFrameSize;
125
122
  _state = "SCANNING_FOR_VT";
126
123
  /** Reusable 4 KiB block the current frame's latest bytes are gathered in. */
127
- _accumulator = Buffer.allocUnsafe(BLOCK_SIZE);
124
+ _accumulator = buffer.Buffer.allocUnsafe(BLOCK_SIZE);
128
125
  /** Number of the current frame's bytes in `_accumulator`. */
129
126
  _blockUsed = 0;
130
127
  /**
@@ -181,7 +178,7 @@ var FrameReader = class {
181
178
  if (nextVt !== -1 && nextVt < stop) stop = nextVt;
182
179
  if (stop > i) {
183
180
  if (this._writePos === 0 && stop === nextFs && stop + 1 < end && chunk[stop + 1] === CR && stop - i <= this._room()) {
184
- const payload = Buffer.from(chunk.subarray(i, stop));
181
+ const payload = buffer.Buffer.from(chunk.subarray(i, stop));
185
182
  this._byteOffset += stop - i + 1;
186
183
  this._state = "EXPECTING_CR";
187
184
  this._deliver(payload);
@@ -256,10 +253,10 @@ var FrameReader = class {
256
253
  }
257
254
  if (at < end) {
258
255
  this._parts.push(this._accumulator);
259
- this._accumulator = Buffer.allocUnsafe(BLOCK_SIZE);
256
+ this._accumulator = buffer.Buffer.allocUnsafe(BLOCK_SIZE);
260
257
  const rest = end - at;
261
258
  if (rest >= BLOCK_SIZE) {
262
- this._parts.push(Buffer.from(src.subarray(at, end)));
259
+ this._parts.push(buffer.Buffer.from(src.subarray(at, end)));
263
260
  this._blockUsed = 0;
264
261
  } else {
265
262
  this._accumulator.set(src.subarray(at, end), 0);
@@ -326,7 +323,7 @@ var FrameReader = class {
326
323
  if (isWhitespace) {
327
324
  if (this._opts.allowLeadingWhitespace === true) {
328
325
  if (this._opts.strict === true) {
329
- const snippet3 = Buffer.from([byte]);
326
+ const snippet3 = buffer.Buffer.from([byte]);
330
327
  throw new MllpFramingError(
331
328
  "MLLP_MISSING_LEADING_VT",
332
329
  this._byteOffset,
@@ -340,7 +337,7 @@ var FrameReader = class {
340
337
  this._wsCount++;
341
338
  return;
342
339
  }
343
- const snippet2 = Buffer.from([byte]);
340
+ const snippet2 = buffer.Buffer.from([byte]);
344
341
  throw new MllpFramingError(
345
342
  "MLLP_MISSING_LEADING_VT",
346
343
  this._byteOffset,
@@ -359,7 +356,7 @@ var FrameReader = class {
359
356
  }
360
357
  if (this._opts.allowMissingLeadingVt === true) {
361
358
  if (this._opts.strict === true) {
362
- const snippet2 = Buffer.from([byte]);
359
+ const snippet2 = buffer.Buffer.from([byte]);
363
360
  throw new MllpFramingError(
364
361
  "MLLP_MISSING_LEADING_VT",
365
362
  this._byteOffset,
@@ -377,7 +374,7 @@ var FrameReader = class {
377
374
  this._readPayload(byte);
378
375
  return;
379
376
  }
380
- const snippet = Buffer.from([byte]);
377
+ const snippet = buffer.Buffer.from([byte]);
381
378
  throw new MllpFramingError(
382
379
  "MLLP_MISSING_LEADING_VT",
383
380
  this._byteOffset,
@@ -398,14 +395,12 @@ var FrameReader = class {
398
395
  return;
399
396
  }
400
397
  if (byte === VT) {
401
- this._emitWarning(
402
- "MLLP_TRAILING_BYTES",
398
+ this._refuse(
399
+ "MLLP_PAYLOAD_CONTAINS_VT",
403
400
  this._byteOffset,
404
- `Unexpected VT (0x0B) mid-payload at offset ${this._byteOffset}; discarding ${this._writePos} accumulated bytes`
401
+ VT,
402
+ `VT (0x0B) inside a frame at offset ${this._byteOffset}; the frame is refused whole`
405
403
  );
406
- this._discard();
407
- this._state = "READING_PAYLOAD";
408
- return;
409
404
  }
410
405
  if (this._writePos >= this._maxFrameSize) this._throwTooLarge();
411
406
  this._appendByte(byte);
@@ -419,7 +414,7 @@ var FrameReader = class {
419
414
  if (byte === LF) {
420
415
  if (this._opts.allowLfAfterFs === true) {
421
416
  if (this._opts.strict === true) {
422
- const snippet3 = Buffer.from([byte]);
417
+ const snippet3 = buffer.Buffer.from([byte]);
423
418
  throw new MllpFramingError(
424
419
  "MLLP_LF_AFTER_FS",
425
420
  this._byteOffset,
@@ -436,7 +431,7 @@ var FrameReader = class {
436
431
  this._state = "SCANNING_FOR_VT";
437
432
  return;
438
433
  }
439
- const snippet2 = Buffer.from([byte]);
434
+ const snippet2 = buffer.Buffer.from([byte]);
440
435
  throw new MllpFramingError(
441
436
  "MLLP_LF_AFTER_FS",
442
437
  this._byteOffset,
@@ -447,7 +442,7 @@ var FrameReader = class {
447
442
  if (byte === VT) {
448
443
  if (this._opts.allowFsOnly === true) {
449
444
  if (this._opts.strict === true) {
450
- const snippet3 = Buffer.from([byte]);
445
+ const snippet3 = buffer.Buffer.from([byte]);
451
446
  throw new MllpFramingError(
452
447
  "MLLP_FS_WITHOUT_CR",
453
448
  this._byteOffset,
@@ -464,7 +459,7 @@ var FrameReader = class {
464
459
  this._state = "READING_PAYLOAD";
465
460
  return;
466
461
  }
467
- const snippet2 = Buffer.from([byte]);
462
+ const snippet2 = buffer.Buffer.from([byte]);
468
463
  throw new MllpFramingError(
469
464
  "MLLP_FS_WITHOUT_CR",
470
465
  this._byteOffset,
@@ -474,7 +469,7 @@ var FrameReader = class {
474
469
  }
475
470
  if (this._opts.allowFsOnly === true) {
476
471
  if (this._opts.strict === true) {
477
- const snippet2 = Buffer.from([byte]);
472
+ const snippet2 = buffer.Buffer.from([byte]);
478
473
  throw new MllpFramingError(
479
474
  "MLLP_FS_WITHOUT_CR",
480
475
  this._byteOffset,
@@ -482,16 +477,14 @@ var FrameReader = class {
482
477
  `Strict mode: FS without CR at offset ${this._byteOffset}`
483
478
  );
484
479
  }
485
- this._emitWarning(
486
- "MLLP_FS_WITHOUT_CR",
487
- this._byteOffset,
488
- `FS not followed by CR at offset ${this._byteOffset}; got 0x${byte.toString(16).padStart(2, "0")} (dropped)`
480
+ this._refuse(
481
+ "MLLP_PAYLOAD_CONTAINS_FS",
482
+ this._byteOffset - 1,
483
+ FS,
484
+ `FS (0x1C) inside a frame at offset ${this._byteOffset - 1}; the frame is refused whole`
489
485
  );
490
- this._deliverFrame();
491
- this._state = "SCANNING_FOR_VT";
492
- return;
493
486
  }
494
- const snippet = Buffer.from([byte]);
487
+ const snippet = buffer.Buffer.from([byte]);
495
488
  throw new MllpFramingError(
496
489
  "MLLP_FS_WITHOUT_CR",
497
490
  this._byteOffset,
@@ -503,7 +496,7 @@ var FrameReader = class {
503
496
  _appendByte(byte) {
504
497
  if (this._blockUsed === BLOCK_SIZE) {
505
498
  this._parts.push(this._accumulator);
506
- this._accumulator = Buffer.allocUnsafe(BLOCK_SIZE);
499
+ this._accumulator = buffer.Buffer.allocUnsafe(BLOCK_SIZE);
507
500
  this._blockUsed = 0;
508
501
  }
509
502
  this._accumulator[this._blockUsed++] = byte;
@@ -516,11 +509,11 @@ var FrameReader = class {
516
509
  _deliverFrame() {
517
510
  const block = this._accumulator.subarray(0, this._blockUsed);
518
511
  if (this._parts.length === 0) {
519
- this._deliver(Buffer.from(block));
512
+ this._deliver(buffer.Buffer.from(block));
520
513
  return;
521
514
  }
522
515
  this._parts.push(block);
523
- this._deliver(Buffer.concat(this._parts, this._writePos));
516
+ this._deliver(buffer.Buffer.concat(this._parts, this._writePos));
524
517
  }
525
518
  /**
526
519
  * Deliver `payload` via `onFrame` with this frame's start offset and warnings, the frame's
@@ -533,6 +526,17 @@ var FrameReader = class {
533
526
  this._frameWarnings = [];
534
527
  this._opts.onFrame(payload, frameStart, frameWarnings);
535
528
  }
529
+ /**
530
+ * Refuse the current frame whole: forget its bytes and its warnings, go back to scanning for a
531
+ * VT, and throw. The error names the framing byte (`delimiter`) and its offset, never a byte of
532
+ * the frame's content, and nothing of the frame is delivered.
533
+ */
534
+ _refuse(code, byteOffset, delimiter, message) {
535
+ this._discard();
536
+ this._frameWarnings = [];
537
+ this._state = "SCANNING_FOR_VT";
538
+ throw new MllpFramingError(code, byteOffset, buffer.Buffer.from([delimiter]), message);
539
+ }
536
540
  /** Emit a warning via the `onWarning` callback, swallowing any handler exceptions. */
537
541
  _emitWarning(code, byteOffset, message) {
538
542
  const warning = createWarning(code, byteOffset, message);
@@ -682,19 +686,17 @@ var MllpTlsConfigurationError = class _MllpTlsConfigurationError extends Error {
682
686
  * Construct a TLS configuration error.
683
687
  *
684
688
  * @param code - The stable configuration-error code; also selects the message.
685
- * @param opts - Optional underlying `cause` from the TLS library.
689
+ * @param options - Optional underlying `cause` from the TLS library.
686
690
  */
687
- constructor(code, opts) {
691
+ constructor(code, options = {}) {
688
692
  super(tlsConfigurationMessage(code));
689
693
  this.code = code;
690
- this.cause = opts?.cause;
694
+ this.cause = options.cause;
691
695
  if (Error.captureStackTrace) {
692
696
  Error.captureStackTrace(this, _MllpTlsConfigurationError);
693
697
  }
694
698
  }
695
699
  };
696
-
697
- // src/transport/dh-parameters.ts
698
700
  var BEGIN_BOUNDARY = "-----BEGIN DH PARAMETERS-----";
699
701
  var END_BOUNDARY = "-----END DH PARAMETERS-----";
700
702
  var BOM_SPELLINGS = [
@@ -750,7 +752,7 @@ function magnitudeOf(der, element) {
750
752
  }
751
753
  function compareMagnitudes(left, right) {
752
754
  if (left.length !== right.length) return left.length < right.length ? -1 : 1;
753
- return Buffer.compare(left, right);
755
+ return buffer.Buffer.compare(left, right);
754
756
  }
755
757
  function isOneBelow(value, oddPrime) {
756
758
  if (value.length !== oddPrime.length) return false;
@@ -804,7 +806,7 @@ function isDhParametersPem(input) {
804
806
  const body = readArmouredBody(text);
805
807
  if (body === null) return false;
806
808
  if (body.length % 4 !== 0 || !BASE64_BODY.test(body)) return false;
807
- const der = Buffer.from(body, "base64");
809
+ const der = buffer.Buffer.from(body, "base64");
808
810
  const sequence = readDerElement(der, 0);
809
811
  if (sequence === null || sequence.tag !== DER_SEQUENCE) return false;
810
812
  if (sequence.contentEnd !== der.length) return false;
@@ -1023,6 +1025,20 @@ var Connection = class extends events.EventEmitter {
1023
1025
  _leftDraining = new Promise((resolve) => {
1024
1026
  this._leaveDraining = resolve;
1025
1027
  });
1028
+ /**
1029
+ * Work answering a frame this connection delivered, still running, with what it owes the peer.
1030
+ * See {@link Connection.holdOpenFor}.
1031
+ */
1032
+ _answering = /* @__PURE__ */ new Map();
1033
+ /**
1034
+ * Set once a fatal framing error has been met, or {@link Connection.stopReading} called: from
1035
+ * then on no byte the peer sends is read.
1036
+ */
1037
+ _refusing = false;
1038
+ /** When the `close()` drain began (`Date.now()`), or `undefined` when no `close()` is draining. */
1039
+ _closeBegan;
1040
+ /** Ends the wait after a fatal framing error: destroys the transport once the bound passes. */
1041
+ _refusalBound;
1026
1042
  /**
1027
1043
  * beforeClose hook, no-op default that resolves immediately.
1028
1044
  *
@@ -1054,6 +1070,7 @@ var Connection = class extends events.EventEmitter {
1054
1070
  }
1055
1071
  });
1056
1072
  this._transport.onData((chunk) => {
1073
+ if (this._refusing) return;
1057
1074
  this._bytesIn += chunk.length;
1058
1075
  this._lastByteInAt = /* @__PURE__ */ new Date();
1059
1076
  try {
@@ -1149,9 +1166,13 @@ var Connection = class extends events.EventEmitter {
1149
1166
  *
1150
1167
  * - If `CONNECTING` or `RECONNECTING`: cancels the pending attempt, transitions
1151
1168
  * directly to `CLOSED`, and calls `transport.destroy()`.
1152
- * - If `CONNECTED`: transitions to `DRAINING`, calls `beforeClose(drainTimeoutMs)`,
1153
- * then `DRAINING → DISCONNECTED` once the hook resolves, or `DRAINING → CLOSED`
1154
- * if the drain timeout elapses first.
1169
+ * - If `CONNECTED`: transitions to `DRAINING`, calls `beforeClose(drainTimeoutMs)` and
1170
+ * waits for it and for every piece of work passed to {@link Connection.holdOpenFor} that is
1171
+ * still running, then `DRAINING → DISCONNECTED` and ends the transport gracefully, so what
1172
+ * that work wrote reaches the peer. If the drain timeout elapses first: `DRAINING → CLOSED`
1173
+ * and the transport is destroyed. Work still running when the drain ends that way (the
1174
+ * timeout or a `destroy()`) is abandoned, and an `MllpConnectionError` with `phase: 'close'`
1175
+ * on `'error'` says how many were left and that what they would write is not sent.
1155
1176
  * - If `DRAINING`: waits for the existing drain to complete (idempotent).
1156
1177
  *
1157
1178
  * Every pending `close()` resolves as soon as the connection leaves `DRAINING`, by whatever
@@ -1159,15 +1180,15 @@ var Connection = class extends events.EventEmitter {
1159
1180
  * `destroy()` during a long drain therefore ends the wait at once, not at the drain timeout.
1160
1181
  * - If `CLOSED` or `DISCONNECTED`: no-op.
1161
1182
  *
1162
- * @param opts.drainTimeoutMs - Override drain timeout (default: `opts.drainTimeoutMs ?? 30_000`).
1183
+ * @param options.drainTimeoutMs - Override drain timeout (default: `options.drainTimeoutMs ?? 30_000`).
1163
1184
  *
1164
1185
  * @example
1165
1186
  * ```typescript
1166
1187
  * await conn.close({ drainTimeoutMs: 5_000 });
1167
1188
  * ```
1168
1189
  */
1169
- async close(opts) {
1170
- const timeout = opts?.drainTimeoutMs ?? this._opts.drainTimeoutMs ?? 3e4;
1190
+ async close(options = {}) {
1191
+ const timeout = options.drainTimeoutMs ?? this._opts.drainTimeoutMs ?? 3e4;
1171
1192
  if (this._state === "CLOSED" || this._state === "DISCONNECTED") return;
1172
1193
  if (this._state === "CONNECTING" || this._state === "RECONNECTING") {
1173
1194
  this._transition("CLOSED", "close() during " + this._state);
@@ -1177,6 +1198,7 @@ var Connection = class extends events.EventEmitter {
1177
1198
  if (this._state === "DRAINING") {
1178
1199
  return this._drainPromise ?? Promise.resolve();
1179
1200
  }
1201
+ this._closeBegan = Date.now();
1180
1202
  this._transition("DRAINING");
1181
1203
  this._drainPromise = this._drainWithTimeout(timeout).finally(() => {
1182
1204
  this._drainPromise = null;
@@ -1184,13 +1206,13 @@ var Connection = class extends events.EventEmitter {
1184
1206
  return this._drainPromise;
1185
1207
  }
1186
1208
  /**
1187
- * Race `beforeClose()` against the drain timeout.
1209
+ * Race `beforeClose()` and the held work against the drain timeout.
1188
1210
  *
1189
1211
  * On normal completion: `DRAINING → DISCONNECTED` + `transport.close()`.
1190
1212
  * On timeout: `DRAINING → CLOSED` + `transport.destroy()`.
1191
1213
  */
1192
1214
  async _drainWithTimeout(timeoutMs) {
1193
- const drainPromise = this.beforeClose(timeoutMs);
1215
+ const drainPromise = Promise.all([this.beforeClose(timeoutMs), this._heldWorkSettled()]);
1194
1216
  let handle;
1195
1217
  const timeoutPromise = new Promise((resolve) => {
1196
1218
  handle = setTimeout(() => {
@@ -1206,6 +1228,7 @@ var Connection = class extends events.EventEmitter {
1206
1228
  ]);
1207
1229
  if (this._state !== "DRAINING") return;
1208
1230
  if (result === "timeout") {
1231
+ this._reportAbandonedAfter("drain timeout");
1209
1232
  this._transition("CLOSED", "drain timeout");
1210
1233
  this._transport.destroy();
1211
1234
  } else {
@@ -1232,9 +1255,75 @@ var Connection = class extends events.EventEmitter {
1232
1255
  */
1233
1256
  destroy(reason) {
1234
1257
  if (this._state === "CLOSED") return;
1258
+ if (this._state === "DRAINING") {
1259
+ this._reportAbandonedAfter(reason?.message ?? "destroy()");
1260
+ }
1235
1261
  this._transition("CLOSED", reason?.message ?? "destroy()");
1236
1262
  this._transport.destroy(reason);
1237
1263
  }
1264
+ /**
1265
+ * Hold the connection open, on `close()` or a fatal framing error, until `work` settles.
1266
+ *
1267
+ * Pass the work that answers a frame this connection delivered: the handler and the write of
1268
+ * its acknowledgement. A `close()` waits for every piece of work passed here to settle before
1269
+ * it ends the transport, so an acknowledgement written by that work still goes out. When a
1270
+ * later frame on the same connection has a fatal framing error, the connection reads nothing
1271
+ * more, waits the same way, and only then closes, so the acknowledgement of a frame delivered
1272
+ * before the refused one still goes out. Either wait is bounded by `drainTimeoutMs` (default 30
1273
+ * seconds): work that has not settled by then is abandoned and the connection is destroyed.
1274
+ * `MllpServer` passes every message's work here itself; a caller driving a bare `Connection`
1275
+ * may do the same.
1276
+ *
1277
+ * `options.kind` says what the work owes the peer, which decides whether `close()` waits for it
1278
+ * and how an abandoned piece is reported:
1279
+ *
1280
+ * - `'ack'` (the default): the work writes the frame's acknowledgement as its last step, so
1281
+ * while it runs the acknowledgement has not been sent. `close()` waits for it; abandoned, it is
1282
+ * counted as a message delivered whose acknowledgement was not sent.
1283
+ * - `'manual'`: the work writes the acknowledgement itself at a point of its own choosing (a
1284
+ * manual-mode handler). `close()` waits for it until it settles; abandoned, it is counted as a
1285
+ * handler whose acknowledgement may not have been sent.
1286
+ * - `'observer'`: the work writes no acknowledgement (an `onMessage` observer in custom-ACK
1287
+ * mode). `close()` does not wait for it; still running when a `close()` is abandoned, it is
1288
+ * named separately as an observer still running. A fatal framing error still waits for it.
1289
+ *
1290
+ * A rejection of `work` is not reported here; it only ends the wait for it.
1291
+ *
1292
+ * @param work - The work answering one delivered frame.
1293
+ * @param options - `kind`: what the work owes the peer (default `'ack'`).
1294
+ *
1295
+ * @example
1296
+ * ```typescript
1297
+ * conn.on('message', ({ payload }) => {
1298
+ * conn.holdOpenFor(commit(payload).then(() => conn.send(encodeFrame(ackFor(payload)))));
1299
+ * });
1300
+ * ```
1301
+ */
1302
+ holdOpenFor(work, options) {
1303
+ const done = () => {
1304
+ this._answering.delete(work);
1305
+ };
1306
+ this._answering.set(work, options?.kind ?? "ack");
1307
+ work.then(done, done);
1308
+ }
1309
+ /**
1310
+ * Read nothing more from the peer: every byte that arrives from now on is dropped unread, and
1311
+ * no further frame is delivered. It cannot be undone.
1312
+ *
1313
+ * `MllpServer.close()` calls this on each connection before closing it, so no new message
1314
+ * reaches a handler while the ones already running finish and their acknowledgements are
1315
+ * written. A client must not call it before a `close()` that waits for acknowledgements, since
1316
+ * it would then never read them.
1317
+ *
1318
+ * @example
1319
+ * ```typescript
1320
+ * conn.stopReading();
1321
+ * await conn.close();
1322
+ * ```
1323
+ */
1324
+ stopReading() {
1325
+ this._refusing = true;
1326
+ }
1238
1327
  /**
1239
1328
  * Return a JSON-serializable observability snapshot.
1240
1329
  *
@@ -1272,6 +1361,61 @@ var Connection = class extends events.EventEmitter {
1272
1361
  // ---------------------------------------------------------------------------
1273
1362
  // Private FSM helpers
1274
1363
  // ---------------------------------------------------------------------------
1364
+ /**
1365
+ * Settle once no work passed to {@link Connection.holdOpenFor} that owes an acknowledgement is
1366
+ * running; an `'observer'` is not waited for. Work registered while waiting (a frame decoded
1367
+ * from bytes already read) is waited for too.
1368
+ */
1369
+ async _heldWorkSettled() {
1370
+ for (; ; ) {
1371
+ const owing = [...this._answering].filter(([, kind]) => kind !== "observer");
1372
+ if (owing.length === 0) return;
1373
+ await Promise.allSettled(owing.map(([work]) => work));
1374
+ }
1375
+ }
1376
+ /**
1377
+ * Report, on `'error'`, the held work a `close()` drain abandons because the drain ended before
1378
+ * that work settled. It counts per delivered message: work that would have written an
1379
+ * acknowledgement (not sent), a manual-mode handler (its acknowledgement may not have been
1380
+ * sent), and, separately, observers that owe none. Nothing is reported when no `close()` is
1381
+ * draining or nothing is still running.
1382
+ *
1383
+ * @param how - How the drain ended, as it reads after "close() ended ".
1384
+ * @param reason - What ended it, the message of the report's `cause`.
1385
+ */
1386
+ _reportAbandonedWork(how, reason) {
1387
+ if (this._closeBegan === void 0) return;
1388
+ const count = { ack: 0, manual: 0, observer: 0 };
1389
+ for (const kind of this._answering.values()) count[kind] += 1;
1390
+ const parts = [];
1391
+ if (count.ack > 0) {
1392
+ parts.push(
1393
+ count.ack === 1 ? "1 message was delivered and its acknowledgement was not sent" : `${String(count.ack)} messages were delivered and their acknowledgements were not sent`
1394
+ );
1395
+ }
1396
+ if (count.manual > 0) {
1397
+ parts.push(
1398
+ count.manual === 1 ? "1 manual-mode handler was still running, so its acknowledgement may not have been sent" : `${String(count.manual)} manual-mode handlers were still running, so their acknowledgements may not have been sent`
1399
+ );
1400
+ }
1401
+ if (count.observer > 0) {
1402
+ parts.push(
1403
+ count.observer === 1 ? "1 observer that owes no acknowledgement was still running" : `${String(count.observer)} observers that owe no acknowledgement were still running`
1404
+ );
1405
+ }
1406
+ if (count.ack + count.manual === 0) return;
1407
+ this._emitErrorIfListened(
1408
+ new MllpConnectionError(`close() ended ${how}: ${parts.join("; ")}`, {
1409
+ cause: new Error(reason),
1410
+ phase: "close"
1411
+ })
1412
+ );
1413
+ }
1414
+ /** Report the work a `close()` drain abandons at the bound or on a `destroy()`. */
1415
+ _reportAbandonedAfter(reason) {
1416
+ const elapsedMs = Date.now() - (this._closeBegan ?? Date.now());
1417
+ this._reportAbandonedWork(`after ${String(elapsedMs)} ms (${reason})`, reason);
1418
+ }
1275
1419
  _transition(to, reason) {
1276
1420
  const from = this._state;
1277
1421
  const legal = LEGAL_TRANSITIONS.get(from);
@@ -1303,7 +1447,9 @@ var Connection = class extends events.EventEmitter {
1303
1447
  }
1304
1448
  }
1305
1449
  _onTransportClose() {
1450
+ clearTimeout(this._refusalBound);
1306
1451
  if (this._state === "DRAINING") {
1452
+ this._reportAbandonedWork("when the sender closed the connection", "peer closed");
1307
1453
  this._transition("DISCONNECTED");
1308
1454
  return;
1309
1455
  }
@@ -1338,7 +1484,7 @@ var Connection = class extends events.EventEmitter {
1338
1484
  }
1339
1485
  }
1340
1486
  /**
1341
- * Handle a fatal framing error thrown out of `FrameReader.push` (FRAME-FATAL).
1487
+ * Handle a fatal framing error thrown out of `FrameReader.push`.
1342
1488
  *
1343
1489
  * Contract: surface it as a connection `'error'` (frozen payload, `phase: 'receive'`,
1344
1490
  * `connectionCause: 'framing-fatal'`, the original `MllpFramingError` preserved as `cause` so
@@ -1356,8 +1502,21 @@ var Connection = class extends events.EventEmitter {
1356
1502
  * forever, and the backoff would become an unbounded reconnect storm against an interface
1357
1503
  * engine that is already unwell. A compatibility failure is not a network blip.
1358
1504
  *
1359
- * If a peer's quirk is *expected* (trailing junk, keepalive bytes, a missing leading VT), the
1360
- * decoder's tolerance opt-ins are the supported answer, they turn the throw into a warning.
1505
+ * Frames delivered before the refused one are still answered. Their handlers may still be
1506
+ * running (an acknowledgement is written after its handler settles, so even a synchronous
1507
+ * handler's is not out yet), and closing at once dropped every one of those acknowledgements:
1508
+ * the sender resent a message already committed, and it was processed twice. So when work
1509
+ * passed to {@link Connection.holdOpenFor} is still running, the connection reads nothing
1510
+ * more, moves to `DRAINING`, waits for that work to settle, then closes gracefully (`CLOSED`,
1511
+ * the transport ended so the acknowledgements written are flushed). The wait is bounded by
1512
+ * `drainTimeoutMs`: past it the connection is destroyed, settled or not, so a handler that never
1513
+ * settles cannot hold the socket open. With nothing running it is destroyed at once.
1514
+ *
1515
+ * If a peer's quirk is *expected*, the decoder's tolerance opt-ins are the supported answer:
1516
+ * `allowLeadingWhitespace` (padding or keepalive bytes before a frame), `allowMissingLeadingVt`,
1517
+ * `allowFsOnly` (a bare FS that the next frame's VT follows) and `allowLfAfterFs` turn their
1518
+ * throw into a warning. No opt-in accepts other bytes between frames, or a stray FS or VT inside
1519
+ * one: those are always refused.
1361
1520
  */
1362
1521
  _onFatalFramingError(err) {
1363
1522
  if (this._state === "CLOSED") return;
@@ -1368,7 +1527,24 @@ var Connection = class extends events.EventEmitter {
1368
1527
  connectionCause: "framing-fatal"
1369
1528
  })
1370
1529
  );
1371
- this.destroy(err);
1530
+ if (this._answering.size === 0 || this._state !== "CONNECTED") {
1531
+ this.destroy(err);
1532
+ return;
1533
+ }
1534
+ this._refusing = true;
1535
+ const boundMs = this._opts.drainTimeoutMs ?? 3e4;
1536
+ this._transition("DRAINING", err.message);
1537
+ this._drainPromise = this._leftDraining.then(() => void 0);
1538
+ this._refusalBound = setTimeout(() => {
1539
+ this._transition("CLOSED", err.message);
1540
+ this._transport.destroy(err);
1541
+ }, boundMs);
1542
+ this._refusalBound.unref();
1543
+ void Promise.allSettled([...this._answering.keys()]).then(() => {
1544
+ if (this._state !== "DRAINING") return;
1545
+ this._transition("CLOSED", err.message);
1546
+ this._transport.close();
1547
+ });
1372
1548
  }
1373
1549
  /**
1374
1550
  * Backstop for a NON-framing throw escaping `FrameReader.push`, i.e. our own bug, or a
@@ -1391,6 +1567,7 @@ var Connection = class extends events.EventEmitter {
1391
1567
  const phase = this._state === "CONNECTING" ? "connect" : this._state === "RECONNECTING" ? "reconnect" : this._state === "DRAINING" ? "close" : "receive";
1392
1568
  if (this._state === "CLOSED" || this._state === "DISCONNECTED") return;
1393
1569
  this._emitErrorIfListened(new MllpConnectionError(err.message, { cause: err, phase }));
1570
+ this._reportAbandonedWork(`when the connection failed (${err.message})`, err.message);
1394
1571
  const target = this._state === "CONNECTING" || this._state === "RECONNECTING" ? "CLOSED" : "DISCONNECTED";
1395
1572
  this._transition(target, `error: ${err.message}`);
1396
1573
  }
@@ -1475,7 +1652,7 @@ function tlsOptionNames() {
1475
1652
  return Object.values(names);
1476
1653
  }
1477
1654
  function copyValue(value) {
1478
- return ArrayBuffer.isView(value) ? Buffer.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) : value;
1655
+ return ArrayBuffer.isView(value) ? buffer.Buffer.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) : value;
1479
1656
  }
1480
1657
  function isOptionsObject(value) {
1481
1658
  if (typeof value !== "object" || value === null) return false;
@@ -1630,13 +1807,13 @@ var MllpAckError = class extends Error {
1630
1807
  ackCode;
1631
1808
  /**
1632
1809
  * @param message - Diagnostic text for the thrower. Never placed on the wire (may carry PHI).
1633
- * @param opts.ackCode - Negative code to return. Default `'AE'`.
1634
- * @param opts.cause - Underlying error, preserved on `.cause`.
1810
+ * @param options.ackCode - Negative code to return. Default `'AE'`.
1811
+ * @param options.cause - Underlying error, preserved on `.cause`.
1635
1812
  */
1636
- constructor(message, opts) {
1637
- super(message, opts?.cause !== void 0 ? { cause: opts.cause } : void 0);
1813
+ constructor(message, options = {}) {
1814
+ super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
1638
1815
  this.name = "MllpAckError";
1639
- this.ackCode = opts?.ackCode ?? "AE";
1816
+ this.ackCode = options.ackCode ?? "AE";
1640
1817
  }
1641
1818
  };
1642
1819
  function resolveNackCode(err) {
@@ -1690,7 +1867,7 @@ function buildRawAckFrom(inbound, code) {
1690
1867
  const s2 = DEFAULT_FIELD_SEPARATOR;
1691
1868
  const e = DEFAULT_ENCODING_CHARACTERS;
1692
1869
  const tail = code === "AE" || code === "AR" ? `${s2}${NACK_TEXT[code]}` : "";
1693
- return Buffer.from(
1870
+ return buffer.Buffer.from(
1694
1871
  `MSH${s2}${e}${s2}${s2}${s2}${s2}${s2}${now}${s2}${s2}ACK${s2}${newControlId}${s2}P${s2}2.3\rMSA${s2}${code}${s2}${tail}\r`,
1695
1872
  "latin1"
1696
1873
  );
@@ -1709,7 +1886,7 @@ function buildRawAckFrom(inbound, code) {
1709
1886
  const version = fields[11] ?? "2.3";
1710
1887
  const msaTail = code === "AE" || code === "AR" ? `${s}${NACK_TEXT[code]}` : "";
1711
1888
  const ackStr = `MSH${s}${encodingChars}${s}${receivingApp}${s}${receivingFacility}${s}${sendingApp}${s}${sendingFacility}${s}${now}${s}${s}ACK${s}${newControlId}${s}${processingId}${s}${version}\rMSA${s}${code}${s}${inboundControlId}${msaTail}\r`;
1712
- return Buffer.from(ackStr, "latin1");
1889
+ return buffer.Buffer.from(ackStr, "latin1");
1713
1890
  }
1714
1891
  function timestamp14() {
1715
1892
  const d = /* @__PURE__ */ new Date();
@@ -1764,8 +1941,8 @@ var ORIGINAL_MODE = Object.freeze({
1764
1941
  acceptCondition: "NE",
1765
1942
  applicationCondition: "AL",
1766
1943
  awaitsApplicationAck: false,
1767
- acceptFieldUnrecognised: false,
1768
- applicationFieldUnrecognised: false
1944
+ acceptFieldUnrecognized: false,
1945
+ applicationFieldUnrecognized: false
1769
1946
  });
1770
1947
  function classifyOutboundAckMode(msh) {
1771
1948
  if (msh === null) return ORIGINAL_MODE;
@@ -1779,8 +1956,8 @@ function classifyOutboundAckMode(msh) {
1779
1956
  acceptCondition: accept.kind === "code" ? accept.code : "NE",
1780
1957
  applicationCondition,
1781
1958
  awaitsApplicationAck: applicationCondition !== "NE",
1782
- acceptFieldUnrecognised: accept.kind === "unrecognised",
1783
- applicationFieldUnrecognised: application.kind === "unrecognised"
1959
+ acceptFieldUnrecognized: accept.kind === "unrecognised",
1960
+ applicationFieldUnrecognized: application.kind === "unrecognised"
1784
1961
  });
1785
1962
  }
1786
1963
  function readAcceptCondition(msh) {
@@ -1893,6 +2070,11 @@ var MllpServer = class extends events.EventEmitter {
1893
2070
  /** `true` when `ServerOptions.tls` is set, `_netServer` is actually a `tls.Server`. */
1894
2071
  _isTls;
1895
2072
  _listening = false;
2073
+ /**
2074
+ * `true` from a `close()` until the next `listen()`: a socket accepted meanwhile (a TLS
2075
+ * handshake that began before the close and finished during it) is closed at once, never served.
2076
+ */
2077
+ _closing = false;
1896
2078
  /** Single-flight guard: `true` while a `listen()` call is settling. */
1897
2079
  _listenInFlight = false;
1898
2080
  /**
@@ -2148,6 +2330,7 @@ var MllpServer = class extends events.EventEmitter {
2148
2330
  );
2149
2331
  }
2150
2332
  this._listenInFlight = true;
2333
+ this._closing = false;
2151
2334
  return new Promise((resolve, reject) => {
2152
2335
  let settled = false;
2153
2336
  const settle = (outcome, opts) => {
@@ -2274,10 +2457,23 @@ var MllpServer = class extends events.EventEmitter {
2274
2457
  * Stop accepting new connections and gracefully close all active connections.
2275
2458
  *
2276
2459
  * Sequence:
2277
- * 1. `net.Server.close()`, stops accepting new connections immediately
2460
+ * 1. `net.Server.close()`, stops accepting new connections immediately. A socket the listener
2461
+ * still hands over (a TLS handshake that began before `close()` and ends during it) is
2462
+ * destroyed at once, before any byte of it is read.
2278
2463
  * 2. If `_connections` is empty: resolves immediately (no drain needed)
2279
- * 3. Calls `_drainAll(drainTimeoutMs)`, Promise.all + side-effect setTimeout
2280
- * that force-destroys stragglers after the drain window
2464
+ * 3. Every connection stops reading: bytes the peer sends from now on are dropped unread, so no
2465
+ * new message reaches a handler.
2466
+ * 4. Every connection waits for its handlers still running and the acknowledgements they write
2467
+ * (`AA`, a negative ACK for a handler that rejects, a custom builder's bytes), then ends its
2468
+ * socket gracefully so those acknowledgements reach the sender. In manual mode the wait lasts
2469
+ * until the handler's promise settles: a `conn.send()` made after that is not waited for. In
2470
+ * custom-ACK mode the `onMessage` observer is not waited for: it writes no acknowledgement.
2471
+ * 5. The wait is bounded by `drainTimeoutMs`. A connection still waiting then is destroyed, and
2472
+ * the server's `'error'` event carries an `MllpConnectionError` with `phase: 'close'` saying
2473
+ * how many messages were delivered without their acknowledgement being sent, how many
2474
+ * manual-mode handlers may not have sent theirs, and how many observers were still running.
2475
+ * The same report is made when the sender closes the connection, or half-closes it (the
2476
+ * server's sockets are not half-open, so our side ends with it), before that work settles.
2281
2477
  *
2282
2478
  * Calling `close()` while a `listen()` is still in flight proactively
2283
2479
  * settles that `listen()` with a typed `MllpConnectionError` rejection
@@ -2289,8 +2485,8 @@ var MllpServer = class extends events.EventEmitter {
2289
2485
  * the server and does NOT settle the in-flight `listen()`, which simply
2290
2486
  * continues and settles on its own bind outcome.
2291
2487
  *
2292
- * @param opts.drainTimeoutMs - Override drain timeout (default: `opts.drainTimeoutMs ?? 30_000`).
2293
- * @param opts.signal - AbortSignal to cancel the close operation. On abort, all
2488
+ * @param options.drainTimeoutMs - Override drain timeout (default: `options.drainTimeoutMs ?? 30_000`).
2489
+ * @param options.signal - AbortSignal to cancel the close operation. On abort, all
2294
2490
  * active connections are destroyed and the promise rejects with AbortError.
2295
2491
  *
2296
2492
  * @example
@@ -2298,12 +2494,13 @@ var MllpServer = class extends events.EventEmitter {
2298
2494
  * await server.close({ drainTimeoutMs: 5_000 });
2299
2495
  * ```
2300
2496
  */
2301
- async close(opts) {
2302
- const signal = opts?.signal;
2497
+ async close(options = {}) {
2498
+ const signal = options.signal;
2303
2499
  if (signal?.aborted) {
2304
2500
  return Promise.reject(new DOMException("Aborted", "AbortError"));
2305
2501
  }
2306
2502
  this._pendingListenSettle?.();
2503
+ this._closing = true;
2307
2504
  this._netServer.close();
2308
2505
  this._listening = false;
2309
2506
  if (this._connections.size === 0) {
@@ -2321,7 +2518,7 @@ var MllpServer = class extends events.EventEmitter {
2321
2518
  signal.addEventListener("abort", abortHandler, { once: true });
2322
2519
  }) : null;
2323
2520
  try {
2324
- const drainTimeoutMs = opts?.drainTimeoutMs ?? this._opts.drainTimeoutMs ?? 3e4;
2521
+ const drainTimeoutMs = options.drainTimeoutMs ?? this._opts.drainTimeoutMs ?? 3e4;
2325
2522
  if (abortPromise !== null) {
2326
2523
  await Promise.race([this._drainAll(drainTimeoutMs), abortPromise]);
2327
2524
  } else {
@@ -2346,10 +2543,13 @@ var MllpServer = class extends events.EventEmitter {
2346
2543
  */
2347
2544
  async _drainAll(drainTimeoutMs) {
2348
2545
  const snapshot = [...this._connections];
2349
- const closePromises = snapshot.map((conn) => conn.close({ drainTimeoutMs }));
2546
+ const closePromises = snapshot.map((conn) => {
2547
+ conn.stopReading();
2548
+ return conn.close({ drainTimeoutMs });
2549
+ });
2350
2550
  const timeoutHandle = setTimeout(() => {
2351
2551
  for (const conn of this._connections) {
2352
- conn.destroy();
2552
+ conn.destroy(new Error("drain timeout"));
2353
2553
  }
2354
2554
  }, drainTimeoutMs);
2355
2555
  timeoutHandle.unref();
@@ -2436,6 +2636,10 @@ var MllpServer = class extends events.EventEmitter {
2436
2636
  // Private: per-socket setup
2437
2637
  // ---------------------------------------------------------------------------
2438
2638
  _onSocketAccepted(socket) {
2639
+ if (this._closing) {
2640
+ socket.destroy();
2641
+ return;
2642
+ }
2439
2643
  if (this._opts.keepaliveIntervalMs !== void 0) {
2440
2644
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
2441
2645
  }
@@ -2446,10 +2650,12 @@ var MllpServer = class extends events.EventEmitter {
2446
2650
  ...this._opts.framing ?? {}
2447
2651
  };
2448
2652
  const connOpts = this._opts.onWarning !== void 0 ? { transport, framing: mergedFraming, onWarning: this._opts.onWarning } : { transport, framing: mergedFraming };
2449
- const conn = new Connection(connOpts);
2653
+ const conn = new Connection({
2654
+ ...connOpts,
2655
+ drainTimeoutMs: this._opts.drainTimeoutMs ?? 3e4
2656
+ });
2450
2657
  const release = this._capRelease.get(socket);
2451
2658
  if (release !== void 0) socket.once("close", release);
2452
- conn.beforeClose = () => Promise.resolve();
2453
2659
  conn.on("error", (errEvent) => {
2454
2660
  this._emitErrorIfListened(errEvent);
2455
2661
  });
@@ -2503,12 +2709,12 @@ var MllpServer = class extends events.EventEmitter {
2503
2709
  }
2504
2710
  const autoAck = this._opts.autoAck;
2505
2711
  if (autoAck === "AA") {
2506
- void this._sendCommitAck(payload, meta, conn);
2712
+ conn.holdOpenFor(this._sendCommitAck(payload, meta, conn));
2507
2713
  } else if (autoAck !== void 0) {
2508
- this._observeMessage(payload, meta, conn);
2509
- void this._sendCustomAck(autoAck, payload, meta, conn);
2714
+ this._observeMessage(payload, meta, conn, "observer");
2715
+ conn.holdOpenFor(this._sendCustomAck(autoAck, payload, meta, conn));
2510
2716
  } else {
2511
- this._observeMessage(payload, meta, conn);
2717
+ this._observeMessage(payload, meta, conn, "manual");
2512
2718
  }
2513
2719
  }
2514
2720
  );
@@ -2575,7 +2781,7 @@ var MllpServer = class extends events.EventEmitter {
2575
2781
  if (handler === void 0) {
2576
2782
  this._dispatchAck(
2577
2783
  conn,
2578
- buildRawAckFrom(inbound, this._resolveAutoAckPositive(inbound, meta, conn, selectCode))
2784
+ buildRawAckFrom(inbound, this._resolveAutoAckPositive(inbound, conn, selectCode))
2579
2785
  );
2580
2786
  return;
2581
2787
  }
@@ -2584,7 +2790,7 @@ var MllpServer = class extends events.EventEmitter {
2584
2790
  try {
2585
2791
  await handler(payload, meta, conn);
2586
2792
  settled = readInbound(payload);
2587
- code = this._resolveAutoAckPositive(settled, meta, conn, selectCode);
2793
+ code = this._resolveAutoAckPositive(settled, conn, selectCode);
2588
2794
  } catch (err) {
2589
2795
  const nack = resolveNackCode(err);
2590
2796
  code = selectCode(nack);
@@ -2607,30 +2813,18 @@ var MllpServer = class extends events.EventEmitter {
2607
2813
  * cannot carry a correlatable positive ACK, so `AA` never names a control ID the sender
2608
2814
  * cannot match (→ timeout → resend → **duplicate clinical message**).
2609
2815
  *
2610
- * Two independent disqualifiers, one from the bytes and one from the frame:
2611
- *
2612
- * - **`rawAckUncorrelatable(payload)`**, no readable `MSH`, an empty MSH-10, or a
2613
- * batch/concatenated-message shape. This is the SAME predicate `buildRawAck` enforces
2614
- * on the wire; it is re-checked here so the downgrade is **observable** (a `'nack'`
2615
- * event) rather than a silent code change inside the builder.
2616
- * - **`MLLP_TRAILING_BYTES`** in the frame's warnings, a mid-payload `VT` made the
2617
- * decoder discard accumulated bytes and deliver only the fragment after it. The
2618
- * clinical message was destroyed in transit, so even a fragment that happens to carry
2619
- * a readable MSH must not be positively acknowledged. This condition is invisible to
2620
- * `buildRawAck` (it sees only the fragment), which is why it lives here. The code is
2621
- * **reserved** for that discard (see the decoder's `_readPayload`) and is emitted while
2622
- * accumulating the delivered frame, so it is frame-scoped: it names *this* payload's own
2623
- * discard, never a neighbouring frame's trailing junk.
2624
- *
2625
- * `'discarded-bytes'` takes precedence in the reason when both hold, it is the root cause.
2816
+ * The disqualifier is **`rawAckUncorrelatable(payload)`**: no readable `MSH`, an empty
2817
+ * MSH-10, or a batch/concatenated-message shape. This is the SAME predicate `buildRawAck`
2818
+ * enforces on the wire; it is re-checked here so the downgrade is **observable** (a `'nack'`
2819
+ * event) rather than a silent code change inside the builder. A frame with a `VT` or a stray
2820
+ * `FS` inside it never gets here: the decoder refuses it whole and the connection closes.
2626
2821
  *
2627
2822
  * `selectCode` puts the resolved disposition in the half of HL7 Table 0008 the inbound
2628
2823
  * asked for; it is the identity for a message that asked for nothing.
2629
2824
  */
2630
- _resolveAutoAckPositive(inbound, meta, conn, selectCode) {
2631
- const discarded = meta.warnings.some((w) => w.code === "MLLP_TRAILING_BYTES");
2632
- if (!discarded && !uncorrelatable(inbound)) return selectCode("AA");
2633
- const reason = discarded ? "discarded-bytes" : "uncorrelatable-inbound";
2825
+ _resolveAutoAckPositive(inbound, conn, selectCode) {
2826
+ if (!uncorrelatable(inbound)) return selectCode("AA");
2827
+ const reason = "uncorrelatable-inbound";
2634
2828
  const code = selectCode("AE");
2635
2829
  this._emitContained(
2636
2830
  "nack",
@@ -2706,13 +2900,14 @@ var MllpServer = class extends events.EventEmitter {
2706
2900
  * connection (a handler error never crashes the server) rather than escaping as
2707
2901
  * an unhandled rejection. The error text is never placed on the wire.
2708
2902
  */
2709
- _observeMessage(payload, meta, conn) {
2903
+ _observeMessage(payload, meta, conn, kind) {
2710
2904
  const handler = this._opts.onMessage;
2711
2905
  if (handler === void 0) return;
2712
- void Promise.resolve().then(() => handler(payload, meta, conn)).catch((err) => {
2906
+ const work = Promise.resolve().then(() => handler(payload, meta, conn)).catch((err) => {
2713
2907
  const connErr = err instanceof Error ? err : new Error(String(err));
2714
2908
  safeEmitError(conn, Object.freeze({ connectionId: conn.connectionId, error: connErr }));
2715
2909
  });
2910
+ conn.holdOpenFor(work, { kind });
2716
2911
  }
2717
2912
  /**
2718
2913
  * The custom-builder path for `autoAck: fn`. Awaits the builder and dispatches its
@@ -2729,10 +2924,12 @@ var MllpServer = class extends events.EventEmitter {
2729
2924
  }
2730
2925
  }
2731
2926
  /**
2732
- * Frame an ACK payload and write it to the connection. `Connection.send()` returns
2733
- * `false` under backpressure (socket write buffer full); that drops the ACK and emits
2734
- * a `MllpConnectionError({ phase: 'send' })` on the connection, the peer will
2735
- * time out waiting and may retry. The server never crashes.
2927
+ * Frame an ACK payload and write it to the connection. When the connection has already
2928
+ * closed (a handler that settled after `server.close()` gave up on it, or after the peer
2929
+ * left), the ACK is not sent and a `MllpConnectionError({ phase: 'send' })` saying so is
2930
+ * emitted on the connection. `Connection.send()` returns `false` under backpressure (socket
2931
+ * write buffer full); that is reported the same way, as backpressure. Either way the peer
2932
+ * will time out waiting and may retry. The server never crashes.
2736
2933
  */
2737
2934
  _dispatchAck(conn, ackPayload) {
2738
2935
  let framed;
@@ -2749,6 +2946,19 @@ var MllpServer = class extends events.EventEmitter {
2749
2946
  );
2750
2947
  return;
2751
2948
  }
2949
+ if (conn.state === "CLOSED" || conn.state === "DISCONNECTED") {
2950
+ safeEmitError(
2951
+ conn,
2952
+ Object.freeze({
2953
+ connectionId: conn.connectionId,
2954
+ error: new MllpConnectionError(
2955
+ "ACK not sent: the connection closed before the handler settled",
2956
+ { cause: new Error("connection closed"), phase: "send" }
2957
+ )
2958
+ })
2959
+ );
2960
+ return;
2961
+ }
2752
2962
  const sent = conn.send(framed);
2753
2963
  if (!sent) {
2754
2964
  safeEmitError(
@@ -3760,8 +3970,8 @@ var MllpClient = class extends events.EventEmitter {
3760
3970
  * await client.connect({ signal: ac.signal });
3761
3971
  * ```
3762
3972
  */
3763
- connect(opts) {
3764
- const signal = opts?.signal;
3973
+ connect(options = {}) {
3974
+ const signal = options.signal;
3765
3975
  if (signal?.aborted) {
3766
3976
  return Promise.reject(new DOMException("Aborted", "AbortError"));
3767
3977
  }
@@ -4106,7 +4316,7 @@ var MllpClient = class extends events.EventEmitter {
4106
4316
  const err = new MllpFramingError(
4107
4317
  "MLLP_ACK_UNMATCHED_CONTROL_ID",
4108
4318
  0,
4109
- Buffer.alloc(0),
4319
+ buffer.Buffer.alloc(0),
4110
4320
  ackDiagnosticMessage("MLLP_ACK_UNMATCHED_CONTROL_ID")
4111
4321
  );
4112
4322
  safeEmitError(
@@ -4640,21 +4850,22 @@ var MllpClient = class extends events.EventEmitter {
4640
4850
  * @example
4641
4851
  * ```typescript
4642
4852
  * const ack = await client.send(payloadBuffer);
4643
- * logger.info({ ack: ack.toString('utf8') });
4853
+ * // Log the acknowledgement's size, never its bytes: they echo your MSH-10.
4854
+ * logger.info({ ackBytes: ack.length });
4644
4855
  * ```
4645
4856
  *
4646
4857
  * @param payload Raw bytes; MLLP framing is added internally via `encodeFrame`.
4647
- * @param opts.signal AbortSignal, aborting cancels the ACK wait.
4648
- * @param opts.ackTimeoutMs This send's bound on the wait for its acknowledgement, from the
4858
+ * @param options.signal AbortSignal, aborting cancels the ACK wait.
4859
+ * @param options.ackTimeoutMs This send's bound on the wait for its acknowledgement, from the
4649
4860
  * moment its bytes are flushed, in place of the client's `ackTimeoutMs`. Under
4650
4861
  * `onBackpressure: "wait"` it also bounds the wait for queue room, and the
4651
4862
  * acknowledgement wait then starts afresh once the send is written.
4652
- * @param opts.applicationAckTimeoutMs Per-send override of the second wait's bound.
4653
- * @param opts.onCommitAck Called with the commit disposition when the peer commits the
4863
+ * @param options.applicationAckTimeoutMs Per-send override of the second wait's bound.
4864
+ * @param options.onCommitAck Called with the commit disposition when the peer commits the
4654
4865
  * message ahead of its application acknowledgement. See {@link CommitAckReport}.
4655
4866
  */
4656
- send(payload, opts) {
4657
- const signal = opts?.signal;
4867
+ send(payload, options = {}) {
4868
+ const signal = options.signal;
4658
4869
  if (signal?.aborted === true) {
4659
4870
  return Promise.reject(new DOMException("Aborted", "AbortError"));
4660
4871
  }
@@ -4669,7 +4880,7 @@ var MllpClient = class extends events.EventEmitter {
4669
4880
  const msh = readMshSegment(payload);
4670
4881
  const controlId = this._correlateByControlId ? controlIdFromMsh(msh) : null;
4671
4882
  const ackMode = classifyOutboundAckMode(msh);
4672
- const twoPhase = this._twoPhaseStateFor(ackMode, opts);
4883
+ const twoPhase = this._twoPhaseStateFor(ackMode, options);
4673
4884
  const correlator = this._correlator;
4674
4885
  const conn = this._connection;
4675
4886
  const frame = encodeFrame(payload);
@@ -4700,10 +4911,10 @@ var MllpClient = class extends events.EventEmitter {
4700
4911
  return this._waitThenSend(
4701
4912
  payload,
4702
4913
  { byteCount: frame.length, messageControlIdBytes: controlId?.length },
4703
- opts
4914
+ options
4704
4915
  );
4705
4916
  }
4706
- const sendAckTimeoutMs = opts?.ackTimeoutMs;
4917
+ const sendAckTimeoutMs = options.ackTimeoutMs;
4707
4918
  return new Promise((resolve, reject) => {
4708
4919
  let abortListener = null;
4709
4920
  let ackDeadline;
@@ -4744,7 +4955,7 @@ var MllpClient = class extends events.EventEmitter {
4744
4955
  wrappedReject(neverDelivered());
4745
4956
  return;
4746
4957
  }
4747
- this.send(payload, opts).then(wrappedResolve, wrappedReject);
4958
+ this.send(payload, options).then(wrappedResolve, wrappedReject);
4748
4959
  };
4749
4960
  parked.cancel = () => {
4750
4961
  this.off("drain", onDrain);
@@ -4804,10 +5015,10 @@ var MllpClient = class extends events.EventEmitter {
4804
5015
  */
4805
5016
  _twoPhaseStateFor(ackMode, opts) {
4806
5017
  if (!ackMode.enhanced) return null;
4807
- if (ackMode.acceptFieldUnrecognised) {
5018
+ if (ackMode.acceptFieldUnrecognized) {
4808
5019
  this._emitAckModeWarning("MLLP_ACK_ACCEPT_TYPE_UNRECOGNISED", OUTBOUND_WARNING_CONTEXT);
4809
5020
  }
4810
- if (ackMode.applicationFieldUnrecognised) {
5021
+ if (ackMode.applicationFieldUnrecognized) {
4811
5022
  this._emitAckModeWarning("MLLP_ACK_APPLICATION_TYPE_UNRECOGNISED", OUTBOUND_WARNING_CONTEXT);
4812
5023
  }
4813
5024
  if (!this._correlateByControlId) {
@@ -5121,8 +5332,8 @@ var MllpClient = class extends events.EventEmitter {
5121
5332
  * await client.close({ drainTimeoutMs: 5_000 });
5122
5333
  * ```
5123
5334
  */
5124
- async close(opts) {
5125
- const signal = opts?.signal;
5335
+ async close(options = {}) {
5336
+ const signal = options.signal;
5126
5337
  if (signal?.aborted) {
5127
5338
  return Promise.reject(new DOMException("Aborted", "AbortError"));
5128
5339
  }
@@ -5137,7 +5348,7 @@ var MllpClient = class extends events.EventEmitter {
5137
5348
  return;
5138
5349
  }
5139
5350
  this._installDrainHook(conn);
5140
- const closeOpts = opts?.drainTimeoutMs !== void 0 ? { drainTimeoutMs: opts.drainTimeoutMs } : void 0;
5351
+ const closeOpts = options.drainTimeoutMs !== void 0 ? { drainTimeoutMs: options.drainTimeoutMs } : void 0;
5141
5352
  if (signal === void 0) {
5142
5353
  try {
5143
5354
  await conn.close(closeOpts);
@@ -5307,8 +5518,6 @@ async function createStarterClient(opts) {
5307
5518
  await client.connect();
5308
5519
  return client;
5309
5520
  }
5310
-
5311
- // src/differential/corpus.ts
5312
5521
  var SEGMENT_SEPARATOR = "\r";
5313
5522
  var ADT_A01_SEGMENTS = [
5314
5523
  "MSH|^~\\&|SENDING_APP|SENDING_FAC|RECV_APP|RECV_FAC|20260709120000||ADT^A01|MSG00001|P|2.5",
@@ -5327,7 +5536,7 @@ var ACK_AA_SEGMENTS = [
5327
5536
  "MSA|AA|MSG00001"
5328
5537
  ];
5329
5538
  function messageBytes(segments) {
5330
- return Buffer.from(segments.join(SEGMENT_SEPARATOR), CONTROL_ID_ENCODING);
5539
+ return buffer.Buffer.from(segments.join(SEGMENT_SEPARATOR), CONTROL_ID_ENCODING);
5331
5540
  }
5332
5541
  function canonicalExchanges() {
5333
5542
  return Object.freeze([
@@ -5475,7 +5684,7 @@ async function runExchange(exchange, settings) {
5475
5684
  transport.onData((chunk) => {
5476
5685
  if (settled) return;
5477
5686
  responseByteCount += chunk.length;
5478
- chunks.push(Buffer.from(chunk));
5687
+ chunks.push(buffer.Buffer.from(chunk));
5479
5688
  try {
5480
5689
  reader.push(chunk);
5481
5690
  } catch (err) {
@@ -5537,7 +5746,7 @@ function classifyFrame(exchange, payload, frameStart, chunks, deviations, finish
5537
5746
  recordWarning(deviations, w, frameStart + 1);
5538
5747
  }
5539
5748
  });
5540
- const received = Buffer.concat([...chunks]);
5749
+ const received = buffer.Buffer.concat([...chunks]);
5541
5750
  const parityMatch = deviations.length === 0 && frameStart === 0 && received.length >= canonical.length && received.subarray(0, canonical.length).equals(canonical);
5542
5751
  const acknowledged = extractMsaControlId(payload);
5543
5752
  let correlation;
@@ -5604,7 +5813,7 @@ async function runDifferential(options = {}) {
5604
5813
  }
5605
5814
 
5606
5815
  // src/index.ts
5607
- var VERSION = "0.1.14";
5816
+ var VERSION = "0.1.16";
5608
5817
 
5609
5818
  exports.ATNA_CIPHER_LIST = ATNA_CIPHER_LIST;
5610
5819
  exports.ATNA_CIPHER_SUITES = ATNA_CIPHER_SUITES;