@astm-e1394/core 0.0.0-stage → 1.0.0-beta.1

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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +132 -2
  3. package/astm-component.d.ts +55 -0
  4. package/astm-component.js +138 -0
  5. package/astm-error.d.ts +42 -0
  6. package/astm-error.js +49 -0
  7. package/astm-field.d.ts +44 -0
  8. package/astm-field.js +95 -0
  9. package/astm-message-node.d.ts +22 -0
  10. package/astm-message-node.js +38 -0
  11. package/astm-message-object.d.ts +9 -0
  12. package/astm-message-object.js +69 -0
  13. package/astm-message.d.ts +111 -0
  14. package/astm-message.js +263 -0
  15. package/astm-path.d.ts +40 -0
  16. package/astm-path.js +80 -0
  17. package/astm-record-object.d.ts +8 -0
  18. package/astm-record-object.js +84 -0
  19. package/astm-record.d.ts +44 -0
  20. package/astm-record.js +110 -0
  21. package/astm-repeat.d.ts +31 -0
  22. package/astm-repeat.js +78 -0
  23. package/astm-validator.d.ts +32 -0
  24. package/astm-validator.js +144 -0
  25. package/constants.d.ts +7 -0
  26. package/constants.js +8 -0
  27. package/index.d.ts +19 -0
  28. package/index.js +19 -0
  29. package/link/astm-connection.d.ts +25 -0
  30. package/link/astm-connection.js +1 -0
  31. package/link/astm-link-error.d.ts +27 -0
  32. package/link/astm-link-error.js +34 -0
  33. package/link/astm-link.d.ts +251 -0
  34. package/link/astm-link.js +641 -0
  35. package/link/astm-router.d.ts +76 -0
  36. package/link/astm-router.js +118 -0
  37. package/link/control-chars.d.ts +9 -0
  38. package/link/control-chars.js +10 -0
  39. package/link/frame.d.ts +51 -0
  40. package/link/frame.js +144 -0
  41. package/link/memory-connection.d.ts +21 -0
  42. package/link/memory-connection.js +54 -0
  43. package/package.json +44 -3
  44. package/utils/astm-escape.d.ts +13 -0
  45. package/utils/astm-escape.js +61 -0
  46. package/utils/astm-hierarchy.d.ts +15 -0
  47. package/utils/astm-hierarchy.js +84 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Panates
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,133 @@
1
- # Temporary Holding Version
1
+ # @astm-e1394/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Parses, builds and serializes ASTM E1394 (LIS2-A2) messages, and runs the ASTM E1381 (LIS1-A) protocol over any connection.
4
+
5
+ [![NPM Version][npm-image]][npm-url]
6
+ [![NPM Downloads][downloads-image]][downloads-url]
7
+ [![CI Tests][ci-test-image]][ci-test-url]
8
+ [![Test Coverage][coveralls-image]][coveralls-url]
9
+
10
+ [npm-image]: https://img.shields.io/npm/v/@astm-e1394/core
11
+ [npm-url]: https://npmjs.org/package/@astm-e1394/core
12
+ [downloads-image]: https://img.shields.io/npm/dm/@astm-e1394/core.svg
13
+ [downloads-url]: https://npmjs.org/package/@astm-e1394/core
14
+ [ci-test-image]: https://github.com/panates/astm-e1394/actions/workflows/test.yml/badge.svg
15
+ [ci-test-url]: https://github.com/panates/astm-e1394/actions/workflows/test.yml
16
+ [coveralls-image]: https://img.shields.io/coveralls/panates/astm-e1394/dev.svg
17
+ [coveralls-url]: https://coveralls.io/r/panates/astm-e1394
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install @astm-e1394/core@beta
23
+ ```
24
+
25
+ ## Messages
26
+
27
+ ```typescript
28
+ import { AstmMessage, PRecord, RRecord } from '@astm-e1394/core';
29
+
30
+ const msg = AstmMessage.parse(text);
31
+
32
+ msg.get('P-6-1'); // the first patient's last name
33
+ msg.get('/P(1)/O/R(2)-4'); // the second patient's first order's third result
34
+
35
+ for (const r of msg.getRecords('R')) {
36
+ console.log(r.field(RRecord.UniversalTestID).getValue(4), r.field(RRecord.DataOrMeasurementValue).getValue());
37
+ }
38
+
39
+ const errors = msg.validate();
40
+ ```
41
+
42
+ Building a message numbers its records as the hierarchy has them:
43
+
44
+ ```typescript
45
+ const msg = new AstmMessage();
46
+ msg.addRecord('P').field(PRecord.PatientName).setValue('DOE', 1);
47
+ msg.addRecord('O'); // O|1, under the patient
48
+ msg.addRecord('L').field(3).setValue('N');
49
+ msg.toAstmString(); // records ended by CR
50
+ ```
51
+
52
+ - Fields are numbered as the standard numbers them: the record type ID is field 1, so `P-2` is the patient's sequence number.
53
+ - A message is read in the delimiters its header declares, and written back in them.
54
+ - `buildTree()` gives the records in their hierarchy: patients under the header, orders under their patient, results under their order, comments under the record before them.
55
+ - `toObject()` and `assign()` give and take the message as a plain object shaped as that hierarchy.
56
+ - `AstmMessage.parseAll()` reads input that holds several messages.
57
+ - A Buffer is read in `options.encoding` (UTF-8 by default); the standard names no character set.
58
+
59
+ ## Talking to an instrument
60
+
61
+ `AstmLink` runs the ASTM E1381 (LIS1-A) low-level protocol over a connection: ENQ, frames with checksums, ACK and NAK, retries and timeouts. It turns the frames it receives into `AstmMessage`s and sends messages as frames. A connection only carries bytes: [`@astm-e1394/net`](https://www.npmjs.com/package/@astm-e1394/net) has TCP connections and a TCP server, [`@astm-e1394/serial`](https://www.npmjs.com/package/@astm-e1394/serial) a serial port, and any class that implements `AstmConnection` works too.
62
+
63
+ ```typescript
64
+ import { AstmLink } from '@astm-e1394/core';
65
+ import { SerialConnection } from '@astm-e1394/serial';
66
+
67
+ const link = new AstmLink(new SerialConnection({ path: 'COM3' }), {
68
+ role: 'host', // the LIS; an instrument wins when both sides start at once
69
+ encoding: 'windows-1254',
70
+ });
71
+
72
+ // Results: the frames are already acknowledged when the handler runs
73
+ link.use('result', async req => {
74
+ await store(req.message);
75
+ });
76
+
77
+ // Queries: the answer goes back as a new transfer
78
+ link.use('query', async (req, res) => {
79
+ res.message = await ordersFor(req.message.get('Q-3-2'));
80
+ });
81
+
82
+ link.on('error', err => console.error(err));
83
+ await link.open();
84
+
85
+ await link.send(orderMessage); // orders sent unasked
86
+ ```
87
+
88
+ - ASTM has no message type. A handler's filter is a kind read from the records: `'query'` (a Q record), `'result'` (R records), `'order'` (O records with no R), `'other'`, a list of these, `'any'`, or a function of the request.
89
+ - Handlers run in order of `priority` (lower first), then in the order added. A handler with a third argument runs the next one only when it calls `next()`.
90
+ - An `AstmRouter` holds a set of handlers to give to several links: `link.use(router)`.
91
+ - A query that a handler took but did not answer, failed on, or did not answer within `queryTimeout` (30 s) gets a header and an `L|1|I` record (no information available). The `defaultQueryAnswer` option replaces that answer.
92
+ - A handler that fails is reported through the `error` event. ASTM has no application acknowledgment, so nothing goes back to the instrument.
93
+
94
+ ### Instruments that differ from the standard
95
+
96
+ Every timer and limit of the standard is an option, with the standard's value as the default: `replyTimeout`, `frameTimeout`, `contentionDelay`, `busyDelay`, `maxRetries`, `maxEstablishAttempts`, `maxFrameLength`. These options are for instruments that do not follow it:
97
+
98
+ | Option | What it is for |
99
+ | --- | --- |
100
+ | `ackDelay` | A pause before each ACK or NAK, for instruments that miss a reply sent too soon |
101
+ | `frameDelay` | A pause between frames |
102
+ | `messageDelay` | A pause between one message's EOT and the next ENQ |
103
+ | `checksum: 'lenient'` | Takes frames with a wrong checksum, reporting each as a `warning` |
104
+ | `receiverInterrupt` | `'ignore'` (default) or `'stop'`: what an EOT received instead of an ACK does |
105
+ | `framing: 'none'` | Instruments that send bare records with no ENQ, frames or ACK. A message ends at its L record, or after `messageEndTimeout` (2 s) of silence |
106
+ | `idleTimeout` | Emits `idle` after a period with no traffic; close the connection there to drop a silent one |
107
+
108
+ The `send`, `receive`, `token`, `state` and `warning` events report each step with its raw bytes, for finding out what an instrument in the field does.
109
+
110
+ ### An instrument simulator
111
+
112
+ `MemoryConnection.pair()` gives two connected ends. With a link in the instrument role on one end, `query()` sends a query and resolves with the answer, which tests an LIS without an instrument:
113
+
114
+ ```typescript
115
+ import { AstmLink, MemoryConnection } from '@astm-e1394/core';
116
+
117
+ const [lisEnd, instrumentEnd] = MemoryConnection.pair();
118
+ const lis = new AstmLink(lisEnd);
119
+ lis.use('query', (req, res) => {
120
+ res.message = ordersFor(req.message);
121
+ });
122
+ const instrument = new AstmLink(instrumentEnd, { role: 'instrument' });
123
+ await lis.open();
124
+ await instrument.open();
125
+
126
+ const answer = await instrument.query('H|\\^&\rQ|1|^SPEC001||ALL\rL|1|N');
127
+ ```
128
+
129
+ The design and its reasons are in [docs/decisions/net-package.md](https://github.com/panates/astm-e1394/blob/dev/docs/decisions/net-package.md).
130
+
131
+ ## License
132
+
133
+ [MIT](https://github.com/panates/astm-e1394/blob/main/LICENSE)
@@ -0,0 +1,55 @@
1
+ import type { AstmDataTypeDefinition, AstmFieldDefinition } from '@astm-e1394/dictionary';
2
+ import type { AstmField } from './astm-field.js';
3
+ import type { AstmMessage } from './astm-message.js';
4
+ import type { AstmRecord } from './astm-record.js';
5
+ import type { AstmRepeat } from './astm-repeat.js';
6
+ /**
7
+ * A component of a field's repeat: the smallest part of an ASTM message. A
8
+ * field with one component - most of them - is its first component.
9
+ *
10
+ * Its value is undefined when empty, null for the standard's null ("") - "delete
11
+ * this value" - and otherwise what its data type reads: text, a number, or
12
+ * a date/time kept as written (see getDate()).
13
+ */
14
+ export declare class AstmComponent {
15
+ protected _value?: any;
16
+ protected _definition: AstmFieldDefinition;
17
+ protected _typeDef: AstmDataTypeDefinition;
18
+ readonly repeat: AstmRepeat;
19
+ readonly position: number;
20
+ constructor(repeat: AstmRepeat, position: number, def: AstmFieldDefinition);
21
+ get message(): AstmMessage;
22
+ get record(): AstmRecord;
23
+ get field(): AstmField;
24
+ get definition(): AstmFieldDefinition;
25
+ get typeDef(): AstmDataTypeDefinition;
26
+ get value(): any;
27
+ set value(value: any);
28
+ isEmpty(): boolean;
29
+ clear(): void;
30
+ getValue(): any;
31
+ /**
32
+ * The value as a Date, for a date or date/time value: read as local time.
33
+ * Undefined when empty.
34
+ */
35
+ getDate(): Date | undefined;
36
+ /**
37
+ * Sets the value, read by the data type as one given in code: a date/time
38
+ * field takes a Date or an ISO 8601 string. A value the type cannot read
39
+ * throws a TypeError.
40
+ */
41
+ setValue(value: any): this;
42
+ fromAstmString(value: string, options?: AstmComponentParseOptions): void;
43
+ toAstmString(options?: AstmComponentSerializeOptions): string;
44
+ [Symbol.toPrimitive](): string;
45
+ }
46
+ export interface AstmComponentParseOptions {
47
+ /**
48
+ * Throw an AstmError for a value its data type cannot read. Default false:
49
+ * the value is kept as text, and validate() reports it.
50
+ */
51
+ strict?: boolean;
52
+ }
53
+ export interface AstmComponentSerializeOptions {
54
+ serializeComponent?: (component: AstmComponent, serializedString: string, options?: AstmComponentSerializeOptions) => string;
55
+ }
@@ -0,0 +1,138 @@
1
+ import { parseAstmDateTime, toAstmDateTime } from '@astm-e1394/dictionary';
2
+ import { AstmError, AstmErrorCode } from './astm-error.js';
3
+ import { astmEscape, astmUnescape } from './utils/astm-escape.js';
4
+ /**
5
+ * A component of a field's repeat: the smallest part of an ASTM message. A
6
+ * field with one component - most of them - is its first component.
7
+ *
8
+ * Its value is undefined when empty, null for the standard's null ("") - "delete
9
+ * this value" - and otherwise what its data type reads: text, a number, or
10
+ * a date/time kept as written (see getDate()).
11
+ */
12
+ export class AstmComponent {
13
+ _value;
14
+ repeat;
15
+ position;
16
+ constructor(repeat, position, def) {
17
+ this.repeat = repeat;
18
+ this.position = position;
19
+ this._definition = def;
20
+ this._typeDef = this.message.dictionary.types[def.type] || {};
21
+ }
22
+ get message() {
23
+ return this.repeat.message;
24
+ }
25
+ get record() {
26
+ return this.repeat.record;
27
+ }
28
+ get field() {
29
+ return this.repeat.field;
30
+ }
31
+ get definition() {
32
+ return this._definition;
33
+ }
34
+ get typeDef() {
35
+ return this._typeDef;
36
+ }
37
+ get value() {
38
+ return this._value;
39
+ }
40
+ set value(value) {
41
+ this.setValue(value);
42
+ }
43
+ isEmpty() {
44
+ return this._value === undefined || this._value === '';
45
+ }
46
+ clear() {
47
+ this._value = undefined;
48
+ }
49
+ getValue() {
50
+ return this._value;
51
+ }
52
+ /**
53
+ * The value as a Date, for a date or date/time value: read as local time.
54
+ * Undefined when empty.
55
+ */
56
+ getDate() {
57
+ const v = this._value;
58
+ if (v == null || v === '')
59
+ return;
60
+ if (v instanceof Date)
61
+ return v;
62
+ return parseAstmDateTime(String(v));
63
+ }
64
+ /**
65
+ * Sets the value, read by the data type as one given in code: a date/time
66
+ * field takes a Date or an ISO 8601 string. A value the type cannot read
67
+ * throws a TypeError.
68
+ */
69
+ setValue(value) {
70
+ if (value == null || value === '') {
71
+ this._value = value === '' ? undefined : value;
72
+ return this;
73
+ }
74
+ const decode = this.definition.decode || this.typeDef.decode;
75
+ this._value = decode ? decode(value, false) : value;
76
+ return this;
77
+ }
78
+ fromAstmString(value, options) {
79
+ if (value === '') {
80
+ this._value = undefined;
81
+ return;
82
+ }
83
+ if (value === '""') {
84
+ this._value = null;
85
+ return;
86
+ }
87
+ const text = astmUnescape(value, this.message);
88
+ const decode = this.definition.decode || this.typeDef.decode;
89
+ if (!decode) {
90
+ this._value = text;
91
+ return;
92
+ }
93
+ try {
94
+ this._value = decode(text, true);
95
+ }
96
+ catch (e) {
97
+ /* Not strict: the value is kept as text, for validate() to report */
98
+ this._value = text;
99
+ if (!options?.strict)
100
+ return;
101
+ const location = `${this.record.recordType}-${this.field.position}-${this.position}`;
102
+ const err = new AstmError(`${location} holds a value of the wrong data type. ${e.message}`, {
103
+ code: AstmErrorCode.DataType,
104
+ recordType: this.record.recordType,
105
+ fieldPosition: this.field.position,
106
+ repeatIndex: this.repeat.index,
107
+ componentPosition: this.position,
108
+ });
109
+ err.stack = e.stack;
110
+ throw err;
111
+ }
112
+ }
113
+ toAstmString(options) {
114
+ let v = this._value;
115
+ if (v === null)
116
+ return '""';
117
+ if (v === undefined)
118
+ return '';
119
+ const encode = this.definition.encode || this.typeDef.encode;
120
+ if (encode) {
121
+ try {
122
+ v = encode(v);
123
+ }
124
+ catch {
125
+ v = String(v);
126
+ }
127
+ }
128
+ else if (v instanceof Date)
129
+ v = toAstmDateTime(v);
130
+ const str = astmEscape(String(v), this.message);
131
+ if (options?.serializeComponent)
132
+ return String(options.serializeComponent(this, str, options) ?? '');
133
+ return str;
134
+ }
135
+ [Symbol.toPrimitive]() {
136
+ return this.toAstmString();
137
+ }
138
+ }
@@ -0,0 +1,42 @@
1
+ /** What an AstmError is about: parsing and validate() report these */
2
+ export declare enum AstmErrorCode {
3
+ /** The message does not start with a header record, or is not one message */
4
+ InvalidMessage = "INVALID_MESSAGE",
5
+ /** A record type the dictionary does not define */
6
+ UnknownRecord = "UNKNOWN_RECORD",
7
+ /** A record where the hierarchy has no place for it: R with no O before it */
8
+ RecordOutOfPlace = "RECORD_OUT_OF_PLACE",
9
+ /** A sequence number missing or not the next one */
10
+ SequenceNumber = "SEQUENCE_NUMBER",
11
+ /** No terminator record (L) at the end */
12
+ MissingTerminator = "MISSING_TERMINATOR",
13
+ /** A value its data type cannot read */
14
+ DataType = "DATA_TYPE",
15
+ /** A field repeated that may not repeat */
16
+ Repeat = "REPEAT",
17
+ /** A code its table does not have */
18
+ TableValue = "TABLE_VALUE"
19
+ }
20
+ export declare class AstmError extends Error {
21
+ code?: AstmErrorCode;
22
+ /** The line of the message, from 1, for an error found while parsing */
23
+ line?: number;
24
+ recordType?: string;
25
+ /** The record's position among the message's records, from 0 */
26
+ recordIndex?: number;
27
+ fieldPosition?: number;
28
+ repeatIndex?: number;
29
+ componentPosition?: number;
30
+ constructor(message: string, args?: AstmError.ErrorArgs);
31
+ }
32
+ export declare namespace AstmError {
33
+ interface ErrorArgs {
34
+ code?: AstmErrorCode;
35
+ line?: number;
36
+ recordType?: string;
37
+ recordIndex?: number;
38
+ fieldPosition?: number;
39
+ repeatIndex?: number;
40
+ componentPosition?: number;
41
+ }
42
+ }
package/astm-error.js ADDED
@@ -0,0 +1,49 @@
1
+ /** What an AstmError is about: parsing and validate() report these */
2
+ export var AstmErrorCode;
3
+ (function (AstmErrorCode) {
4
+ /** The message does not start with a header record, or is not one message */
5
+ AstmErrorCode["InvalidMessage"] = "INVALID_MESSAGE";
6
+ /** A record type the dictionary does not define */
7
+ AstmErrorCode["UnknownRecord"] = "UNKNOWN_RECORD";
8
+ /** A record where the hierarchy has no place for it: R with no O before it */
9
+ AstmErrorCode["RecordOutOfPlace"] = "RECORD_OUT_OF_PLACE";
10
+ /** A sequence number missing or not the next one */
11
+ AstmErrorCode["SequenceNumber"] = "SEQUENCE_NUMBER";
12
+ /** No terminator record (L) at the end */
13
+ AstmErrorCode["MissingTerminator"] = "MISSING_TERMINATOR";
14
+ /** A value its data type cannot read */
15
+ AstmErrorCode["DataType"] = "DATA_TYPE";
16
+ /** A field repeated that may not repeat */
17
+ AstmErrorCode["Repeat"] = "REPEAT";
18
+ /** A code its table does not have */
19
+ AstmErrorCode["TableValue"] = "TABLE_VALUE";
20
+ })(AstmErrorCode || (AstmErrorCode = {}));
21
+ export class AstmError extends Error {
22
+ code;
23
+ /** The line of the message, from 1, for an error found while parsing */
24
+ line;
25
+ recordType;
26
+ /** The record's position among the message's records, from 0 */
27
+ recordIndex;
28
+ fieldPosition;
29
+ repeatIndex;
30
+ componentPosition;
31
+ constructor(message, args) {
32
+ super(message);
33
+ this.name = 'AstmError';
34
+ if (args?.code)
35
+ this.code = args.code;
36
+ if (args?.line != null)
37
+ this.line = args.line;
38
+ if (args?.recordType)
39
+ this.recordType = args.recordType;
40
+ if (args?.recordIndex != null)
41
+ this.recordIndex = args.recordIndex;
42
+ if (args?.fieldPosition != null)
43
+ this.fieldPosition = args.fieldPosition;
44
+ if (args?.repeatIndex != null)
45
+ this.repeatIndex = args.repeatIndex;
46
+ if (args?.componentPosition != null)
47
+ this.componentPosition = args.componentPosition;
48
+ }
49
+ }
@@ -0,0 +1,44 @@
1
+ import type { AstmDataTypeDefinition, AstmFieldDefinition } from '@astm-e1394/dictionary';
2
+ import type { AstmComponent } from './astm-component.js';
3
+ import type { AstmMessage } from './astm-message.js';
4
+ import type { AstmRecord } from './astm-record.js';
5
+ import { AstmRepeat, type AstmRepeatParseOptions, type AstmRepeatSerializeOptions } from './astm-repeat.js';
6
+ /** A field of a record, at its position from 1: the record type ID is field 1 */
7
+ export declare class AstmField {
8
+ protected _repeats: AstmRepeat[];
9
+ protected _definition: AstmFieldDefinition;
10
+ protected _typeDef: AstmDataTypeDefinition;
11
+ readonly record: AstmRecord;
12
+ readonly position: number;
13
+ constructor(record: AstmRecord, position: number, def: AstmFieldDefinition);
14
+ get message(): AstmMessage;
15
+ get definition(): AstmFieldDefinition;
16
+ get typeDef(): AstmDataTypeDefinition;
17
+ /** Whether the field's data type has components of its own */
18
+ get isComposite(): boolean;
19
+ get repeats(): AstmRepeat[];
20
+ add(): AstmRepeat;
21
+ clear(): void;
22
+ isEmpty(): boolean;
23
+ /** The repeat at an index, from 0, created when not there */
24
+ repeat(index?: number): AstmRepeat;
25
+ /** Alias of repeat() */
26
+ rep(index?: number): AstmRepeat;
27
+ /** A component of the first repeat */
28
+ component(position?: number): AstmComponent;
29
+ /** Alias of component() */
30
+ comp(position?: number): AstmComponent;
31
+ /** The value of a component of the first repeat; the first by default */
32
+ getValue(component?: number): any;
33
+ /** The value of a component of the first repeat as a Date */
34
+ getDate(component?: number): Date | undefined;
35
+ setValue(value: any, component?: number): this;
36
+ fromAstmString(value: string, options?: AstmFieldParseOptions): void;
37
+ toAstmString(options?: AstmFieldSerializeOptions): string;
38
+ [Symbol.toPrimitive](): string;
39
+ }
40
+ export interface AstmFieldParseOptions extends AstmRepeatParseOptions {
41
+ }
42
+ export interface AstmFieldSerializeOptions extends AstmRepeatSerializeOptions {
43
+ serializeField?: (field: AstmField, serializedString: string, options?: AstmFieldSerializeOptions) => string;
44
+ }
package/astm-field.js ADDED
@@ -0,0 +1,95 @@
1
+ import { AstmRepeat, } from './astm-repeat.js';
2
+ /** A field of a record, at its position from 1: the record type ID is field 1 */
3
+ export class AstmField {
4
+ record;
5
+ position;
6
+ constructor(record, position, def) {
7
+ this.record = record;
8
+ this.position = position;
9
+ this._definition = def;
10
+ this._typeDef = this.message.dictionary.types[def.type] || {};
11
+ this.clear();
12
+ }
13
+ get message() {
14
+ return this.record.message;
15
+ }
16
+ get definition() {
17
+ return this._definition;
18
+ }
19
+ get typeDef() {
20
+ return this._typeDef;
21
+ }
22
+ /** Whether the field's data type has components of its own */
23
+ get isComposite() {
24
+ return !!this.typeDef.fields;
25
+ }
26
+ get repeats() {
27
+ return this._repeats;
28
+ }
29
+ add() {
30
+ const rep = new AstmRepeat(this);
31
+ this._repeats.push(rep);
32
+ return rep;
33
+ }
34
+ clear() {
35
+ this._repeats = [];
36
+ }
37
+ isEmpty() {
38
+ for (const rep of this._repeats) {
39
+ if (!rep.isEmpty())
40
+ return false;
41
+ }
42
+ return true;
43
+ }
44
+ /** The repeat at an index, from 0, created when not there */
45
+ repeat(index = 0) {
46
+ if (!Number.isInteger(index) || index < 0)
47
+ throw new Error(`Invalid repeat index (${index})`);
48
+ while (index >= this._repeats.length)
49
+ this.add();
50
+ return this._repeats[index];
51
+ }
52
+ /** Alias of repeat() */
53
+ rep(index = 0) {
54
+ return this.repeat(index);
55
+ }
56
+ /** A component of the first repeat */
57
+ component(position = 1) {
58
+ return this.repeat(0).component(position);
59
+ }
60
+ /** Alias of component() */
61
+ comp(position = 1) {
62
+ return this.component(position);
63
+ }
64
+ /** The value of a component of the first repeat; the first by default */
65
+ getValue(component) {
66
+ return this._repeats[0]?.getValue(component);
67
+ }
68
+ /** The value of a component of the first repeat as a Date */
69
+ getDate(component) {
70
+ return this._repeats[0]?.getDate(component);
71
+ }
72
+ setValue(value, component) {
73
+ this.repeat(0).setValue(value, component);
74
+ return this;
75
+ }
76
+ fromAstmString(value, options) {
77
+ this._repeats = [];
78
+ for (const s of value.split(this.message.repeatDelimiter)) {
79
+ this.add().fromAstmString(s, options);
80
+ }
81
+ }
82
+ toAstmString(options) {
83
+ const { repeatDelimiter } = this.message;
84
+ const items = this._repeats.map(rep => rep.toAstmString(options));
85
+ while (items.length && !items[items.length - 1])
86
+ items.pop();
87
+ const str = items.join(repeatDelimiter);
88
+ if (options?.serializeField)
89
+ return String(options.serializeField(this, str, options) ?? '');
90
+ return str;
91
+ }
92
+ [Symbol.toPrimitive]() {
93
+ return this.toAstmString();
94
+ }
95
+ }
@@ -0,0 +1,22 @@
1
+ import type { AstmRecord } from './astm-record.js';
2
+ /**
3
+ * A record in the message's hierarchy, with the records that belong under
4
+ * it: a patient's orders and comments, an order's results (see
5
+ * AstmMessage.buildTree()).
6
+ */
7
+ export declare class AstmMessageNode {
8
+ readonly record: AstmRecord;
9
+ readonly children: AstmMessageNode[];
10
+ parent?: AstmMessageNode;
11
+ constructor(record: AstmRecord, parent?: AstmMessageNode);
12
+ get recordType(): string;
13
+ /** The child records of a type, in order */
14
+ getNodes(recordType: string): AstmMessageNode[];
15
+ /**
16
+ * A child record of a type: the first, the one at an index from 0, or the
17
+ * one after a given one
18
+ */
19
+ getNode(recordType: string, indexOrAfter?: number | AstmMessageNode): AstmMessageNode | undefined;
20
+ /** The record of a child node (see getNode()) */
21
+ getRecord(recordType: string, indexOrAfter?: number | AstmMessageNode): AstmRecord | undefined;
22
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * A record in the message's hierarchy, with the records that belong under
3
+ * it: a patient's orders and comments, an order's results (see
4
+ * AstmMessage.buildTree()).
5
+ */
6
+ export class AstmMessageNode {
7
+ record;
8
+ children = [];
9
+ parent;
10
+ constructor(record, parent) {
11
+ this.record = record;
12
+ this.parent = parent;
13
+ }
14
+ get recordType() {
15
+ return this.record.recordType;
16
+ }
17
+ /** The child records of a type, in order */
18
+ getNodes(recordType) {
19
+ return this.children.filter(n => n.recordType === recordType);
20
+ }
21
+ /**
22
+ * A child record of a type: the first, the one at an index from 0, or the
23
+ * one after a given one
24
+ */
25
+ getNode(recordType, indexOrAfter) {
26
+ const nodes = this.getNodes(recordType);
27
+ if (indexOrAfter == null)
28
+ return nodes[0];
29
+ if (typeof indexOrAfter === 'number')
30
+ return nodes[indexOrAfter];
31
+ const i = nodes.indexOf(indexOrAfter);
32
+ return i < 0 ? undefined : nodes[i + 1];
33
+ }
34
+ /** The record of a child node (see getNode()) */
35
+ getRecord(recordType, indexOrAfter) {
36
+ return this.getNode(recordType, indexOrAfter)?.record;
37
+ }
38
+ }
@@ -0,0 +1,9 @@
1
+ import type { AstmMessage } from './astm-message.js';
2
+ export declare function messageToObject(message: AstmMessage): Record<string, any>;
3
+ /**
4
+ * Sets a message from an object shaped as messageToObject() makes it: the
5
+ * header assigned, every other record replaced. Records are added as the
6
+ * object lists them - each record before the ones under it - and numbered
7
+ * by the hierarchy.
8
+ */
9
+ export declare function assignMessage(message: AstmMessage, object: Record<string, any>): void;