mllp-node-sl7 2.1.6 → 2.2.0

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/README.md CHANGED
@@ -1,36 +1,86 @@
1
1
  mllp
2
2
  ====
3
+
3
4
  Fork, for original Readme see below!
4
5
 
5
6
  # Install:
7
+
6
8
  [![NPM](https://nodei.co/npm/mllp-node-sl7.png)](https://nodei.co/npm/mllp-node-sl7/)
7
9
 
8
10
  Changes:
11
+
9
12
  - Multi Message Support on a single Socket Connection
10
- - Basic Character Encoding Support
13
+ - Character set from MSH-18, otherwise the default character set of the server (5th constructor
14
+ argument in MSH-18 notation such as `8859/1`, default `UNICODE UTF-8`); decoding is done by
15
+ sb-sl7. `ISO IR6`, `ISO IR100` and `ISO IR192` count as `ASCII`, `8859/1` and `UNICODE UTF-8`. A
16
+ message that cannot be decoded is read as UTF-8 and reported to the logger as a warning without
17
+ content; an MSH-18 value that is not a character set of HL7 table 0211 is shown as
18
+ `<invalid MSH-18>`. A default character set that is not supported is reported once when the
19
+ server is created, and messages without MSH-18 are then read as UTF-8.
20
+ - Responses (ACKs) are always sent as UTF-8, whatever the character set of the message.
11
21
  - Timeout with Auto-Response
12
22
  - Supports bind to all Interfaces (0.0.0.0)
13
- - Using Package [sb-sl7](https://github.com/sourceblock-ug/sb-sl7) for Message parsing
23
+ - Using Package [sb-sl7](https://github.com/sourceblock-ug/sb-sl7) for Message parsing
14
24
 
15
- Sample (see example.js):
16
- ```javascript
17
- var mllp = require('mllp-node');
18
- var timeout = 600; // ms
19
- var server = new mllp.MLLPServer('0.0.0.0', 1234, timeout);
25
+ ## Usage
20
26
 
21
- // Subscribe to inbound messages
22
- server.on('hl7', function (data){
23
- console.log('received payload:', data);
24
- });
27
+ ```typescript
28
+ import { MLLPServer, mllpSendMessage } from "mllp-node-sl7";
25
29
 
26
- // Send outbound messages
27
- server.send('127.0.0.1', 4321, 'outbound-hl7-message', function (err, ackData) {
28
- // async callback code here
30
+ // Optional, see "Logging". Without a logger nothing is logged. This one has no
31
+ // `trace`, so message content is never logged.
32
+ const logger = { info: console.info, warn: console.warn, error: console.error };
33
+
34
+ const server = new MLLPServer("0.0.0.0", 1234, logger, 600);
35
+
36
+ // Inbound messages. Without a response the default ACK is sent after the timeout.
37
+ server.on("hl7", (event) => {
38
+ // event.id (MSH-10), event.msg (decoded text), event.hl7 (parsed sb-sl7 Message)
39
+ server.sendResponse(event.id, "AA");
29
40
  });
41
+
42
+ // Outbound messages
43
+ mllpSendMessage(
44
+ "127.0.0.1",
45
+ 4321,
46
+ "outbound-hl7-message",
47
+ (err, ack, response) => {
48
+ // ack is the MSA segment, response the complete answer
49
+ },
50
+ );
30
51
  ```
31
52
 
32
- Original Readme:
53
+ Errors of a connection and of the server itself (a port that is already in use, for example) are
54
+ emitted as `hl7-error`. If listening fails, `hl7-ready` is not emitted. An error of the server is
55
+ logged only if nobody listens for `hl7-error`.
33
56
 
57
+ ## Logging
58
+
59
+ The library never writes to the console. Pass a logger as third constructor argument (and as
60
+ last argument of `mllpSendMessage`); without one nothing is logged.
61
+
62
+ - An object with `trace`, `debug`, `info`, `warn` and `error` methods (`MllpLogger`) gets every
63
+ entry on its level. Message content is passed to `trace` only; all other levels carry
64
+ technical data such as the message id (MSH-10), the message type and remote addresses. A level
65
+ the object does not have is silent.
66
+ - A plain function `(msg, ...data) => void` is still accepted. It receives everything except
67
+ the `trace` output and therefore never sees message content.
68
+
69
+ HL7 messages usually contain patient data, so only enable `trace` where that is acceptable.
70
+
71
+ ## Development
72
+
73
+ Development requires Node.js 22.13 or newer, or 24 (Vitest 5 and ESLint 10); the library itself
74
+ runs on Node.js 20 or newer.
75
+
76
+ ```bash
77
+ npm install
78
+ npm test # Vitest
79
+ npm run lint # type check (npm run typecheck), ESLint and Prettier
80
+ npm run build # compiles to dist/
81
+ ```
82
+
83
+ Original Readme:
34
84
 
35
85
  [![NPM](https://nodei.co/npm/mllp-node.png)](https://nodei.co/npm/mllp-node/)
36
86
 
@@ -39,16 +89,14 @@ Original Readme:
39
89
 
40
90
  HL7's MLLP (Minimum Lower Layer Protocol) server implementation in Node.js.
41
91
 
42
-
43
92
  Listen on predefined port for HL7 messages in format:
44
93
 
45
94
  ```
46
95
  <VT>[HL7 Message]<FS><CR>
47
96
  ```
48
97
 
49
- * [HL7 MLP minimul layer protocol defined](http://www.hl7standards.com/blog/2007/05/02/hl7-mlp-minimum-layer-protocol-defined/)
50
- * [ACK message](http://www.hl7standards.com/blog/2007/02/01/ack-message-original-mode-acknowledgement/)
51
-
98
+ - [HL7 MLP minimul layer protocol defined](http://www.hl7standards.com/blog/2007/05/02/hl7-mlp-minimum-layer-protocol-defined/)
99
+ - [ACK message](http://www.hl7standards.com/blog/2007/02/01/ack-message-original-mode-acknowledgement/)
52
100
 
53
101
  ## Quick up and running guide
54
102
 
@@ -70,18 +118,18 @@ grunt
70
118
  See `example.js`:
71
119
 
72
120
  ```javascript
73
- var mllp = require('mllp-node');
121
+ var mllp = require("mllp-node");
74
122
 
75
- var server = new mllp.MLLPServer('127.0.0.1', 1234);
123
+ var server = new mllp.MLLPServer("127.0.0.1", 1234);
76
124
 
77
125
  // Subscribe to inbound messages
78
- server.on('hl7', function (data){
79
- console.log('received payload:', data);
126
+ server.on("hl7", function (data) {
127
+ console.log("received payload:", data);
80
128
  });
81
129
 
82
130
  // Send outbound messages
83
- server.send('127.0.0.1', 4321, 'outbound-hl7-message', function (err, ackData) {
84
- // async callback code here
131
+ server.send("127.0.0.1", 4321, "outbound-hl7-message", function (err, ackData) {
132
+ // async callback code here
85
133
  });
86
134
  ```
87
135
 
@@ -0,0 +1,19 @@
1
+ /** Stands in for an MSH-18 value that is not a character set of table 0211. */
2
+ export declare const INVALID_MSH18 = "<invalid MSH-18>";
3
+ /**
4
+ * The name sb-sl7 understands for the given character set: an alias is
5
+ * replaced, any other name is passed on unchanged.
6
+ */
7
+ export declare function resolveCharset(name: string): string;
8
+ /**
9
+ * The character set of MSH-18 as it may be logged above TRACE. MSH-18 comes
10
+ * from the sender, so only a name of HL7 table 0211 is logged; any other
11
+ * value could be message content and is replaced by {@link INVALID_MSH18}.
12
+ */
13
+ export declare function describeMessageCharset(name: string): string;
14
+ /**
15
+ * The configured default character set as it may be logged: a configuration
16
+ * value, but still shortened to something that looks like a name.
17
+ */
18
+ export declare function describeConfiguredCharset(name: string): string;
19
+ //# sourceMappingURL=charset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"charset.d.ts","sourceRoot":"","sources":["../src/charset.ts"],"names":[],"mappings":"AA8BA,+EAA+E;AAC/E,eAAO,MAAM,aAAa,qBAAqB,CAAC;AAMhD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAK3D;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9D"}
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INVALID_MSH18 = void 0;
4
+ exports.resolveCharset = resolveCharset;
5
+ exports.describeMessageCharset = describeMessageCharset;
6
+ exports.describeConfiguredCharset = describeConfiguredCharset;
7
+ /**
8
+ * Names of character sets that sb-sl7 does not know, although they name a
9
+ * character set it supports: the ISO registrations of ASCII, Latin-1 and
10
+ * UTF-8.
11
+ */
12
+ const ALIASES = {
13
+ "ISO IR6": "ASCII",
14
+ "ISO IR100": "8859/1",
15
+ "ISO IR192": "UNICODE UTF-8",
16
+ };
17
+ /** Character sets of HL7 table 0211, apart from `8859/<n>`. */
18
+ const TABLE_0211 = new Set([
19
+ "ASCII",
20
+ "ISO IR6",
21
+ "ISO IR14",
22
+ "ISO IR87",
23
+ "ISO IR100",
24
+ "ISO IR159",
25
+ "ISO IR192",
26
+ "GB 18030-2000",
27
+ "KS X 1001",
28
+ "CNS 11643-1992",
29
+ "BIG-5",
30
+ "UNICODE",
31
+ "UNICODE UTF-8",
32
+ "UNICODE UTF-16",
33
+ "UNICODE UTF-32",
34
+ ]);
35
+ /** Stands in for an MSH-18 value that is not a character set of table 0211. */
36
+ exports.INVALID_MSH18 = "<invalid MSH-18>";
37
+ function normalise(name) {
38
+ return `${name}`.trim().toUpperCase();
39
+ }
40
+ /**
41
+ * The name sb-sl7 understands for the given character set: an alias is
42
+ * replaced, any other name is passed on unchanged.
43
+ */
44
+ function resolveCharset(name) {
45
+ return ALIASES[normalise(name)] ?? name;
46
+ }
47
+ /**
48
+ * The character set of MSH-18 as it may be logged above TRACE. MSH-18 comes
49
+ * from the sender, so only a name of HL7 table 0211 is logged; any other
50
+ * value could be message content and is replaced by {@link INVALID_MSH18}.
51
+ */
52
+ function describeMessageCharset(name) {
53
+ const normalised = normalise(name);
54
+ return TABLE_0211.has(normalised) || /^8859\/\d{1,2}$/.test(normalised)
55
+ ? normalised
56
+ : exports.INVALID_MSH18;
57
+ }
58
+ /**
59
+ * The configured default character set as it may be logged: a configuration
60
+ * value, but still shortened to something that looks like a name.
61
+ */
62
+ function describeConfiguredCharset(name) {
63
+ return /^[A-Za-z0-9 /_.-]{1,32}$/.test(name) ? name : "<invalid name>";
64
+ }
65
+ //# sourceMappingURL=charset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"charset.js","sourceRoot":"","sources":["../src/charset.ts"],"names":[],"mappings":";;;AAyCA,wCAEC;AAOD,wDAKC;AAMD,8DAEC;AA/DD;;;;GAIG;AACH,MAAM,OAAO,GAA2B;IACtC,SAAS,EAAE,OAAO;IAClB,WAAW,EAAE,QAAQ;IACrB,WAAW,EAAE,eAAe;CAC7B,CAAC;AAEF,+DAA+D;AAC/D,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,OAAO;IACP,SAAS;IACT,UAAU;IACV,UAAU;IACV,WAAW;IACX,WAAW;IACX,WAAW;IACX,eAAe;IACf,WAAW;IACX,gBAAgB;IAChB,OAAO;IACP,SAAS;IACT,eAAe;IACf,gBAAgB;IAChB,gBAAgB;CACjB,CAAC,CAAC;AAEH,+EAA+E;AAClE,QAAA,aAAa,GAAG,kBAAkB,CAAC;AAEhD,SAAS,SAAS,CAAC,IAAY;IAC7B,OAAO,GAAG,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACxC,CAAC;AAED;;;GAGG;AACH,SAAgB,cAAc,CAAC,IAAY;IACzC,OAAO,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC;AAC1C,CAAC;AAED;;;;GAIG;AACH,SAAgB,sBAAsB,CAAC,IAAY;IACjD,MAAM,UAAU,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IACnC,OAAO,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,iBAAiB,CAAC,IAAI,CAAC,UAAU,CAAC;QACrE,CAAC,CAAC,UAAU;QACZ,CAAC,CAAC,qBAAa,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,IAAY;IACpD,OAAO,0BAA0B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC;AACzE,CAAC"}
@@ -1,15 +1,14 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
1
  import net from "net";
5
2
  import EventEmitter from "events";
6
3
  import { Message } from "@sourceblock-ug/sb-sl7";
4
+ import type { MllpLogFunction, MllpLogger } from "./logger";
5
+ export type { MllpLogFunction, MllpLogger } from "./logger";
7
6
  export interface Renderable {
8
7
  render(): string | Buffer;
9
8
  }
10
9
  export declare const cleanupString: (msg: string, removeParts: string[]) => string;
11
10
  export declare const cleanup: (msg: string) => string;
12
- export declare function mllpSendMessage(receivingHost: string, receivingPort: number, hl7Data: Buffer | Renderable | string, callback: (err: Error | null, response: string | null, responseMessage: string | null) => void, logger?: (msg: string) => void): void;
11
+ export declare function mllpSendMessage(receivingHost: string, receivingPort: number, hl7Data: Buffer | Renderable | string, callback: (err: Error | null, response: string | null, responseMessage: string | null) => void, logger?: Partial<MllpLogger> | MllpLogFunction): void;
13
12
  export interface MessageResponseEvent {
14
13
  id: string;
15
14
  ack: string | Renderable | unknown;
@@ -29,9 +28,15 @@ export interface MLLPConnectionState {
29
28
  * @constructor MLLPServer
30
29
  * @param {string} host a resolvable hostname or IP Address
31
30
  * @param {number} port a valid free port for the server to listen on.
32
- * @param defaultLogger
31
+ * @param defaultLogger logger with level methods, or a plain log function.
32
+ * Message content is only ever passed to `trace`; a plain function never
33
+ * receives it. A level the logger does not have is silent. Without a logger
34
+ * nothing is logged.
33
35
  * @param {number} timeout after which the answer is sended.
34
- * @param {string} defaultCharset for Message decoding
36
+ * @param {string} defaultCharset character set (MSH-18 notation, such as
37
+ * `8859/1`) of messages without MSH-18. Default `UNICODE UTF-8`. A character
38
+ * set that is not supported is reported once as a warning; such messages
39
+ * are then read as UTF-8.
35
40
  * @param {string} timeoutAck like AA or AE - default is AA
36
41
  *
37
42
  * @fires MLLPServer#hl7
@@ -54,7 +59,7 @@ export declare class MLLPServer extends EventEmitter {
54
59
  protected readonly HOST: string;
55
60
  protected readonly PORT: number;
56
61
  protected readonly TIMEOUT: number;
57
- protected logger: (msg: string, ...data: unknown[]) => void;
62
+ protected logger: MllpLogger;
58
63
  protected charset: string;
59
64
  private readonly TIMEOUTS;
60
65
  private readonly openEvents;
@@ -62,7 +67,19 @@ export declare class MLLPServer extends EventEmitter {
62
67
  protected connectionEventState: MLLPConnectionState;
63
68
  private readonly openConnections;
64
69
  private readonly timeoutAck;
65
- constructor(host: string, port: number, defaultLogger?: (msg: string) => void, timeout?: number, defaultCharset?: string, timeoutAck?: string);
70
+ constructor(host: string, port: number, defaultLogger?: Partial<MllpLogger> | MllpLogFunction, timeout?: number, defaultCharset?: string, timeoutAck?: string);
71
+ /**
72
+ * Checks the default character set once, so a name that is not supported
73
+ * is reported at the start instead of with every message without MSH-18.
74
+ * Such messages are read as UTF-8, as sb-sl7 would do anyway.
75
+ */
76
+ private checkDefaultCharset;
77
+ /**
78
+ * Reported by sb-sl7 when a message could not be decoded with its character
79
+ * set and was read as UTF-8 instead. MSH-18 comes from the sender, so only
80
+ * a character set of HL7 table 0211 is named above TRACE.
81
+ */
82
+ private readonly onDecodeError;
66
83
  private handleIncomingMessage;
67
84
  private updateState;
68
85
  private addSocket;
@@ -78,3 +95,4 @@ export declare class MLLPServer extends EventEmitter {
78
95
  close(done?: (err?: Error) => void): void;
79
96
  private static closeSocket;
80
97
  }
98
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"}
@@ -3,11 +3,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MLLPServer = exports.mllpSendMessage = exports.cleanup = exports.cleanupString = void 0;
6
+ exports.MLLPServer = exports.cleanup = exports.cleanupString = void 0;
7
+ exports.mllpSendMessage = mllpSendMessage;
7
8
  const net_1 = __importDefault(require("net"));
8
9
  const events_1 = __importDefault(require("events"));
9
10
  const sb_sl7_1 = require("@sourceblock-ug/sb-sl7");
10
- const decoder_1 = __importDefault(require("./decoder"));
11
+ const charset_1 = require("./charset");
12
+ const logger_1 = require("./logger");
11
13
  // The header is a vertical tab character <VT> its hex value is 0x0b.
12
14
  // The trailer is a field separator character <FS> (hex 0x1c) immediately followed by a carriage return <CR> (hex 0x0d)
13
15
  const VT = String.fromCharCode(0x0b);
@@ -16,11 +18,13 @@ const FS = String.fromCharCode(0x1c); // const FSi = 0x1c;
16
18
  const CR = String.fromCharCode(0x0d); // const CRi = 0x0d; > \r
17
19
  function isARenderable(obj) {
18
20
  return (typeof obj === "object" &&
19
- Object.prototype.hasOwnProperty.call(obj, "render") &&
21
+ obj !== null &&
22
+ !Buffer.isBuffer(obj) &&
23
+ "render" in obj &&
20
24
  typeof obj.render === "function");
21
25
  }
22
26
  function getPayload(hl7Data) {
23
- if (typeof hl7Data === "object" && isARenderable(hl7Data)) {
27
+ if (isARenderable(hl7Data)) {
24
28
  return hl7Data.render();
25
29
  }
26
30
  return hl7Data;
@@ -37,14 +41,14 @@ const cleanup = (msg) => {
37
41
  exports.cleanup = cleanup;
38
42
  function mllpSendMessage(receivingHost, receivingPort, hl7Data, callback, logger) {
39
43
  // Render Message if it is an object:
40
- const log = logger || console.log;
44
+ const log = (0, logger_1.toLogger)(logger);
41
45
  const payload = getPayload(hl7Data);
42
46
  // Continue with Sending:
43
47
  const sendingClient = net_1.default.connect({
44
48
  host: receivingHost,
45
49
  port: receivingPort,
46
50
  }, () => {
47
- log(`Sending data to ${receivingHost}:${receivingPort}`);
51
+ log.debug(`Sending data to ${receivingHost}:${receivingPort}`);
48
52
  sendingClient.write(VT, () => {
49
53
  sendingClient.write(payload, () => {
50
54
  sendingClient.write(FS + CR);
@@ -52,31 +56,36 @@ function mllpSendMessage(receivingHost, receivingPort, hl7Data, callback, logger
52
56
  });
53
57
  });
54
58
  const terminate = () => {
55
- log(`closing connection with ${receivingHost}:${receivingPort}`);
59
+ log.debug(`closing connection with ${receivingHost}:${receivingPort}`);
56
60
  sendingClient.end();
57
61
  };
58
62
  sendingClient.on("data", (rawAckData) => {
59
- log(`${receivingHost}:${receivingPort} ACKED data`);
63
+ log.debug(`${receivingHost}:${receivingPort} ACKED data`);
60
64
  const responseMessage = rawAckData.toString().replace(VT, "");
61
65
  const ackData = responseMessage.split("\r")[1]; // Ack data
62
66
  callback(null, (0, exports.cleanup)(ackData), (0, exports.cleanup)(responseMessage));
63
67
  terminate();
64
68
  });
65
69
  sendingClient.on("error", (error) => {
66
- log(`${receivingHost}:${receivingPort} couldn't process data`);
70
+ log.warn(`${receivingHost}:${receivingPort} couldn't process data`, error);
67
71
  callback(error, null, null);
68
72
  terminate();
69
73
  });
70
74
  }
71
- exports.mllpSendMessage = mllpSendMessage;
72
75
  // noinspection JSUnusedGlobalSymbols
73
76
  /**
74
77
  * @constructor MLLPServer
75
78
  * @param {string} host a resolvable hostname or IP Address
76
79
  * @param {number} port a valid free port for the server to listen on.
77
- * @param defaultLogger
80
+ * @param defaultLogger logger with level methods, or a plain log function.
81
+ * Message content is only ever passed to `trace`; a plain function never
82
+ * receives it. A level the logger does not have is silent. Without a logger
83
+ * nothing is logged.
78
84
  * @param {number} timeout after which the answer is sended.
79
- * @param {string} defaultCharset for Message decoding
85
+ * @param {string} defaultCharset character set (MSH-18 notation, such as
86
+ * `8859/1`) of messages without MSH-18. Default `UNICODE UTF-8`. A character
87
+ * set that is not supported is reported once as a warning; such messages
88
+ * are then read as UTF-8.
80
89
  * @param {string} timeoutAck like AA or AE - default is AA
81
90
  *
82
91
  * @fires MLLPServer#hl7
@@ -96,21 +105,30 @@ exports.mllpSendMessage = mllpSendMessage;
96
105
  *
97
106
  */
98
107
  class MLLPServer extends events_1.default {
108
+ HOST;
109
+ PORT;
110
+ TIMEOUT;
111
+ logger;
112
+ charset;
113
+ TIMEOUTS;
114
+ openEvents;
115
+ Server;
116
+ connectionEventState;
117
+ openConnections = [];
118
+ timeoutAck;
99
119
  constructor(host, port, defaultLogger, timeout, defaultCharset, timeoutAck) {
100
120
  super();
101
- this.openConnections = [];
102
121
  this.HOST = host || "127.0.0.1";
103
122
  this.PORT = port || 6969;
104
123
  this.TIMEOUT = timeout || 600;
105
- this.logger = defaultLogger || console.log;
124
+ this.logger = (0, logger_1.toLogger)(defaultLogger);
106
125
  this.TIMEOUTS = {};
107
126
  this.openEvents = {};
108
127
  this.timeoutAck =
109
128
  typeof timeoutAck === "string" && timeoutAck.length === 2
110
129
  ? timeoutAck.toUpperCase()
111
130
  : "AA";
112
- this.charset =
113
- defaultCharset !== undefined ? `${defaultCharset}` : "UNICODE UTF-8";
131
+ this.charset = this.checkDefaultCharset(defaultCharset !== undefined ? `${defaultCharset}` : "UNICODE UTF-8");
114
132
  this.connectionEventState = {
115
133
  host: this.HOST,
116
134
  port: this.PORT,
@@ -120,12 +138,12 @@ class MLLPServer extends events_1.default {
120
138
  try {
121
139
  this.Server = net_1.default.createServer((sock) => {
122
140
  let message = Buffer.from("", "binary");
123
- this.logger(`CONNECTED: ${sock.remoteAddress}:${sock.remotePort}`);
141
+ this.logger.debug(`CONNECTED: ${sock.remoteAddress}:${sock.remotePort}`);
124
142
  this.addSocket(sock);
125
143
  sock.on("end", () => {
126
144
  // This should not happen, but if it does, tell everyone who is interested
127
145
  this.emit("hl7-closed", this.updateState());
128
- this.logger("server disconnected", this.HOST, this.PORT);
146
+ this.logger.debug(`server disconnected ${this.HOST}:${this.PORT}`);
129
147
  this.removeSocket(sock);
130
148
  });
131
149
  /*
@@ -153,7 +171,7 @@ class MLLPServer extends events_1.default {
153
171
  this.emit("hl7-error", err);
154
172
  });
155
173
  sock.on("close", () => {
156
- this.logger(`CLOSED: ${sock.remoteAddress} ${sock.remotePort}`);
174
+ this.logger.debug(`CLOSED: ${sock.remoteAddress} ${sock.remotePort}`);
157
175
  // Tell the outside world out connection state:
158
176
  this.removeSocket(sock);
159
177
  this.emit("hl7-disconnected", this.updateState());
@@ -161,7 +179,7 @@ class MLLPServer extends events_1.default {
161
179
  });
162
180
  if (this.HOST !== "0.0.0.0") {
163
181
  this.Server.listen(this.PORT, this.HOST, () => {
164
- this.logger(`Listen now to ${this.HOST}:${this.PORT}`);
182
+ this.logger.info(`Listen now to ${this.HOST}:${this.PORT}`);
165
183
  setImmediate(() => {
166
184
  this.emit("hl7-ready", this.updateState());
167
185
  });
@@ -169,7 +187,7 @@ class MLLPServer extends events_1.default {
169
187
  }
170
188
  else {
171
189
  this.Server.listen(this.PORT, () => {
172
- this.logger(`Listen now to [any]:${this.PORT}`);
190
+ this.logger.info(`Listen now to [any]:${this.PORT}`);
173
191
  setImmediate(() => {
174
192
  this.emit("hl7-ready", this.updateState());
175
193
  });
@@ -179,33 +197,76 @@ class MLLPServer extends events_1.default {
179
197
  this.emit("hl7-closed", { port: this.PORT, host: this.HOST });
180
198
  });
181
199
  this.Server.on("error", (err) => {
182
- this.logger(`Error during MLLP Connection`, err);
200
+ // Listening fails asynchronously (a port in use, for example), so it
201
+ // cannot be thrown from the constructor. Without this event a caller
202
+ // waiting for "hl7-ready" would never learn about it. Reported once:
203
+ // whoever listens for the event reports it, otherwise it is logged.
204
+ if (!this.emit("hl7-error", err)) {
205
+ this.logger.error(`Error during MLLP Connection`, err);
206
+ }
183
207
  });
184
208
  }
185
209
  catch (e) {
186
- this.logger(`Error Listen to ${this.HOST}:${this.PORT}`, e);
187
- throw new Error(`Error Listen to ${this.HOST}:${this.PORT}`);
210
+ this.logger.error(`Error Listen to ${this.HOST}:${this.PORT}`, e);
211
+ throw new Error(`Error Listen to ${this.HOST}:${this.PORT}`, {
212
+ cause: e,
213
+ });
188
214
  }
189
215
  }
190
- handleIncomingMessage(messageBuffer, sock) {
191
- let messageString = messageBuffer.toString();
192
- let data2 = new sb_sl7_1.Message(messageString);
193
- let msgId = data2.getString("MSH-10");
194
- let encoding = data2.getString("MSH-18");
195
- if (encoding === undefined || encoding === null || encoding === "") {
196
- // use Default:
197
- encoding = this.charset;
216
+ /**
217
+ * Checks the default character set once, so a name that is not supported
218
+ * is reported at the start instead of with every message without MSH-18.
219
+ * Such messages are read as UTF-8, as sb-sl7 would do anyway.
220
+ */
221
+ checkDefaultCharset(name) {
222
+ const charset = (0, charset_1.resolveCharset)(name);
223
+ let supported = true;
224
+ (0, sb_sl7_1.decode)(Buffer.from("MSH"), charset, () => {
225
+ supported = false;
226
+ });
227
+ if (supported) {
228
+ return charset;
229
+ }
230
+ this.logger.warn(`Default character set ${(0, charset_1.describeConfiguredCharset)(name)} is not supported, messages without MSH-18 are read as UTF-8`);
231
+ return "UNICODE UTF-8";
232
+ }
233
+ /**
234
+ * Reported by sb-sl7 when a message could not be decoded with its character
235
+ * set and was read as UTF-8 instead. MSH-18 comes from the sender, so only
236
+ * a character set of HL7 table 0211 is named above TRACE.
237
+ */
238
+ onDecodeError = (error, charset) => {
239
+ const name = (0, charset_1.describeMessageCharset)(charset);
240
+ if (name !== charset_1.INVALID_MSH18) {
241
+ this.logger.warn(`Could not decode message as ${name}, falling back to UTF-8`, error);
242
+ return;
198
243
  }
199
- if (encoding !== "UNICODE UTF-8") {
200
- // Decoding needed:
201
- messageString = (0, decoder_1.default)(messageBuffer, encoding);
244
+ // The value, and the error that may repeat it, could be message content.
245
+ this.logger.warn(`Could not decode message as ${name}, falling back to UTF-8`);
246
+ this.logger.trace(`Character set (MSH-18) that could not be decoded: ${JSON.stringify(charset)}`, error);
247
+ };
248
+ handleIncomingMessage(messageBuffer, sock) {
249
+ // MSH-18 is read from the message as UTF-8, which is enough for the MSH
250
+ // segment. Without MSH-18 the default character set of the server applies.
251
+ // The ISO names of ASCII, Latin-1 and UTF-8 are passed on as HL7 names.
252
+ // `new Message(buffer)` of sb-sl7 cannot be used: it has no default
253
+ // character set and does not return the decoded text, and rendering the
254
+ // message instead would change its segment separators.
255
+ const utf8 = messageBuffer.toString();
256
+ let data2 = new sb_sl7_1.Message(utf8);
257
+ const charset = (0, charset_1.resolveCharset)(data2.getString("MSH-18") || this.charset);
258
+ const messageString = (0, sb_sl7_1.decode)(messageBuffer, charset, this.onDecodeError);
259
+ if (messageString !== utf8) {
202
260
  data2 = new sb_sl7_1.Message(messageString);
203
- msgId = data2.getString("MSH-10");
204
261
  }
205
- this.logger(`Message:\r\n${messageString.replace(/\r/g, "\n")}\r\n\r\n`);
262
+ let msgId = data2.getString("MSH-10");
206
263
  if (msgId === "") {
207
264
  msgId = Math.random().toString(36).substring(2);
208
265
  }
266
+ // Only the id is logged. The content may hold patient data and goes to
267
+ // TRACE exclusively.
268
+ this.logger.info(`Received message ${msgId} (${data2.getString("MSH-9")})`);
269
+ this.logger.trace(`Message ${msgId}:\r\n${messageString.replace(/\r/g, "\n")}\r\n\r\n`);
209
270
  const event = {
210
271
  id: msgId,
211
272
  ack: this.timeoutAck,
@@ -218,7 +279,9 @@ class MLLPServer extends events_1.default {
218
279
  this.TIMEOUTS[msgId] = setTimeout(() => {
219
280
  this.handleAck(event, "timeout");
220
281
  }, this.TIMEOUT);
221
- this.openEvents[msgId] = { sock, org: messageBuffer }; // save socket and Message for Response
282
+ // Socket and message are kept for the response. The decoded text is
283
+ // kept too, so the response is built from the same text as the event.
284
+ this.openEvents[msgId] = { sock, org: messageBuffer, msg: messageString };
222
285
  /**
223
286
  * MLLP HL7 Event. Fired when a HL7 Message is received.
224
287
  * @event MLLPServer#hl7
@@ -303,20 +366,27 @@ class MLLPServer extends events_1.default {
303
366
  return true;
304
367
  }
305
368
  catch (e) {
306
- this.logger(`Error sending response in mode ${mode}`, e);
369
+ this.logger.error(`Error sending response for message ${event.id} in mode ${mode}`, e);
307
370
  }
308
371
  }
309
372
  else {
310
- this.logger(`Response already send! Cannot process another response in mode ${mode}`, event);
373
+ this.logger.warn(`Response for message ${event.id} already send! Cannot process another response in mode ${mode}`);
311
374
  }
312
375
  return false;
313
376
  }
314
377
  response(event) {
315
378
  if (this.openEvents[event.id] !== undefined) {
316
379
  const inMsg = this.openEvents[event.id];
317
- return this.handleAck(Object.assign({ hl7: new sb_sl7_1.Message(inMsg.org), msg: inMsg.org.toString(), buffer: inMsg.org }, event), "direct");
380
+ return this.handleAck({
381
+ // Parsed from the decoded text: the raw buffer would be read
382
+ // without the default character set of the server.
383
+ hl7: new sb_sl7_1.Message(inMsg.msg),
384
+ msg: inMsg.msg,
385
+ buffer: inMsg.org,
386
+ ...event,
387
+ }, "direct");
318
388
  }
319
- this.logger(`Response already send! Cannot process another response directly.`, event);
389
+ this.logger.warn(`Response for message ${event.id} already send! Cannot process another response directly.`);
320
390
  return false;
321
391
  }
322
392
  sendResponse(msgId, ack) {
@@ -347,3 +417,4 @@ class MLLPServer extends events_1.default {
347
417
  }
348
418
  }
349
419
  exports.MLLPServer = MLLPServer;
420
+ //# sourceMappingURL=index.js.map