@cosyte/transform 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2652 @@
1
+ import { complex, primitive, list, decimal, UCUM_SYSTEM, validateUcumShape, resourceType, validateResource, UNBOUNDED } from '@cosyte/fhir';
2
+ import { parseDtm } from '@cosyte/hl7';
3
+ import { randomUUID } from 'crypto';
4
+
5
+ // src/diagnostics/codes.ts
6
+ var ISSUE_CODES = {
7
+ /** A v2 DTM/TS carried a time-of-day but no timezone offset. FHIR forbids time-without-zone, so
8
+ * the value was reduced to date precision (or an explicit sender offset applied via options) —
9
+ * **never** a guessed UTC. */
10
+ TRANSFORM_TIMESTAMP_NO_TIMEZONE: "TRANSFORM_TIMESTAMP_NO_TIMEZONE",
11
+ /** A v2 DTM/TS could not be parsed into a valid FHIR date/time; no value was emitted. */
12
+ TRANSFORM_TIMESTAMP_INVALID: "TRANSFORM_TIMESTAMP_INVALID",
13
+ /** The assigning authority (HD) could not be resolved to a FHIR `Identifier.system` URI via the
14
+ * NamingSystem registry. The identifier is emitted with its value and **no** system — a system URI
15
+ * is **never** synthesized from HD.1 alone. */
16
+ TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED: "TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED",
17
+ /** A coded value could not be mapped to a FHIR concept — either it carried no coding-system context
18
+ * (CWE.3 absent), or it is a table code the IG ConceptMap has **no target** for (e.g. an OBX-11/
19
+ * OBR-25 result status the HL70085/HL70123 map does not carry, or an OBX-8 abnormal flag absent from
20
+ * HL70078). The original code is preserved / the FHIR value left absent; **never** coerced to a
21
+ * neighbor and **never** guessed to `final`/`normal`. */
22
+ TRANSFORM_CODE_UNMAPPED: "TRANSFORM_CODE_UNMAPPED",
23
+ /** A coding-system mnemonic (CWE.3 / CWE.6) was not recognized, so no canonical system URI could
24
+ * be emitted. The code is preserved; a URI is **never** invented. */
25
+ TRANSFORM_CODE_SYSTEM_UNRESOLVED: "TRANSFORM_CODE_SYSTEM_UNRESOLVED",
26
+ /** A unit was not a valid UCUM code (or was not declared UCUM). It is preserved verbatim in
27
+ * `Quantity.unit`; `Quantity.code`/`.system` are left absent — a UCUM code is **never** fabricated
28
+ * and a magnitude is **never** converted. */
29
+ TRANSFORM_UNIT_NOT_UCUM: "TRANSFORM_UNIT_NOT_UCUM",
30
+ /** A v2 numeric value (NM) could not be represented as a FHIR `decimal` without altering it — e.g.
31
+ * a leading `+`, a leading zero, or a trailing dot, which FHIR's `decimal` lexical form forbids. No
32
+ * `Quantity` value is emitted rather than a canonicalized (and therefore altered) magnitude. */
33
+ TRANSFORM_QUANTITY_VALUE_INVALID: "TRANSFORM_QUANTITY_VALUE_INVALID",
34
+ /** A populated source element was not carried to its FHIR target and was dropped — either because
35
+ * the IG map defines no target, or because that target's conversion is **not implemented**
36
+ * (e.g. XTN→ContactPoint telecom, PV1 participants). Surfaced here rather than silently discarded,
37
+ * never a fabricated value. */
38
+ TRANSFORM_ELEMENT_DROPPED: "TRANSFORM_ELEMENT_DROPPED",
39
+ /** An XPN.7 name-type code has no equivalent in the IG's HL70200 → name-use ConceptMap;
40
+ * `HumanName.use` is left absent rather than guessed. */
41
+ TRANSFORM_NAME_USE_UNMAPPED: "TRANSFORM_NAME_USE_UNMAPPED",
42
+ /** An XAD.7 address-type code has no equivalent in the IG's HL70190 → address-use/type
43
+ * ConceptMaps; `Address.use`/`.type` are left absent rather than guessed. */
44
+ TRANSFORM_ADDRESS_USE_UNMAPPED: "TRANSFORM_ADDRESS_USE_UNMAPPED",
45
+ /** The message's trigger event has no IG *message* map, so its resource graph was assembled from
46
+ * the reusable IG *segment* maps rather than a message map. The graph is best-effort and flagged
47
+ * as such — never a fabricated message map. */
48
+ TRANSFORM_SEGMENT_ASSEMBLED: "TRANSFORM_SEGMENT_ASSEMBLED",
49
+ /** A produced FHIR resource failed `@cosyte/fhir` R4 structural validation and was **withheld**
50
+ * from the bundle rather than emitted as a silently-invalid resource — the conservative-emit gate. */
51
+ TRANSFORM_RESOURCE_INVALID: "TRANSFORM_RESOURCE_INVALID",
52
+ /** A FHIR-required element's value could not be faithfully derived from the source, so it was
53
+ * emitted with a `data-absent-reason` extension (value `unknown`) rather than fabricated — e.g.
54
+ * `MessageHeader.source.endpoint` from an MSH-3 application namespace that is not a URL. */
55
+ TRANSFORM_REQUIRED_ELEMENT_UNKNOWN: "TRANSFORM_REQUIRED_ELEMENT_UNKNOWN"
56
+ };
57
+ var FATAL_CODES = {
58
+ /** The input carried nothing to transform. */
59
+ EMPTY_INPUT: "EMPTY_INPUT",
60
+ /** The input was not a shape this transform accepts. */
61
+ TRANSFORM_UNSUPPORTED_INPUT: "TRANSFORM_UNSUPPORTED_INPUT"
62
+ };
63
+
64
+ // src/diagnostics/issue.ts
65
+ var ISSUE_REGISTRY = Object.freeze({
66
+ [ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE]: {
67
+ severity: "warning",
68
+ fhirIssueType: "value",
69
+ message: "v2 timestamp carried a time-of-day but no timezone offset; reduced to date precision (FHIR forbids time without a zone)."
70
+ },
71
+ [ISSUE_CODES.TRANSFORM_TIMESTAMP_INVALID]: {
72
+ severity: "warning",
73
+ fhirIssueType: "value",
74
+ message: "v2 timestamp could not be parsed into a valid FHIR date/time; no value emitted."
75
+ },
76
+ [ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED]: {
77
+ severity: "warning",
78
+ fhirIssueType: "not-found",
79
+ message: "assigning authority could not be resolved to an Identifier.system; identifier emitted with value and no system (never synthesized from a bare namespace)."
80
+ },
81
+ [ISSUE_CODES.TRANSFORM_CODE_UNMAPPED]: {
82
+ severity: "warning",
83
+ fhirIssueType: "code-invalid",
84
+ message: "coded value could not be mapped to a FHIR concept (no coding system, or no target in the IG ConceptMap); original code preserved / FHIR value left absent, never coerced or guessed."
85
+ },
86
+ [ISSUE_CODES.TRANSFORM_CODE_SYSTEM_UNRESOLVED]: {
87
+ severity: "warning",
88
+ fhirIssueType: "code-invalid",
89
+ message: "coding-system mnemonic not recognized; code preserved, no system URI invented."
90
+ },
91
+ [ISSUE_CODES.TRANSFORM_UNIT_NOT_UCUM]: {
92
+ severity: "warning",
93
+ fhirIssueType: "value",
94
+ message: "unit is not a valid UCUM code; preserved verbatim in Quantity.unit, code/system absent, magnitude never converted."
95
+ },
96
+ [ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID]: {
97
+ severity: "warning",
98
+ fhirIssueType: "value",
99
+ message: "numeric value is not a valid FHIR decimal literal (e.g. leading sign/zero or trailing dot); no Quantity value emitted rather than altering the magnitude."
100
+ },
101
+ [ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED]: {
102
+ severity: "information",
103
+ fhirIssueType: "informational",
104
+ message: "populated source element was not carried to its FHIR target (no target in this map, or its conversion is not implemented); dropped."
105
+ },
106
+ [ISSUE_CODES.TRANSFORM_NAME_USE_UNMAPPED]: {
107
+ severity: "information",
108
+ fhirIssueType: "value",
109
+ message: "name-type code has no equivalent in the HL70200 to name-use map; use left absent."
110
+ },
111
+ [ISSUE_CODES.TRANSFORM_ADDRESS_USE_UNMAPPED]: {
112
+ severity: "information",
113
+ fhirIssueType: "value",
114
+ message: "address-type code has no equivalent in the HL70190 to address-use/type maps; use/type left absent."
115
+ },
116
+ [ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED]: {
117
+ severity: "information",
118
+ fhirIssueType: "informational",
119
+ message: "message trigger has no IG message map; resource graph assembled from IG segment maps, best-effort."
120
+ },
121
+ [ISSUE_CODES.TRANSFORM_RESOURCE_INVALID]: {
122
+ severity: "error",
123
+ fhirIssueType: "structure",
124
+ message: "produced resource failed FHIR R4 structural validation; withheld from the bundle rather than emitted invalid."
125
+ },
126
+ [ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN]: {
127
+ severity: "information",
128
+ fhirIssueType: "informational",
129
+ message: "required FHIR element could not be derived from the source; emitted with a data-absent-reason extension, never fabricated."
130
+ }
131
+ });
132
+ function issue(code, v2Location, fhirPath) {
133
+ const meta = ISSUE_REGISTRY[code];
134
+ const base = {
135
+ code,
136
+ severity: meta.severity,
137
+ v2Location,
138
+ message: meta.message
139
+ };
140
+ return fhirPath === void 0 ? base : { ...base, fhirPath };
141
+ }
142
+ function fhirIssueTypeFor(code) {
143
+ return ISSUE_REGISTRY[code].fhirIssueType;
144
+ }
145
+ var TRANSFORM_ISSUE_SYSTEM = "https://cosyte.com/fhir/CodeSystem/transform-issue-codes";
146
+ function prop(name, value) {
147
+ return { name, value };
148
+ }
149
+ function renderIssue(i) {
150
+ const details = complex([
151
+ prop(
152
+ "coding",
153
+ list([
154
+ complex([
155
+ prop("system", primitive(TRANSFORM_ISSUE_SYSTEM)),
156
+ prop("code", primitive(i.code))
157
+ ])
158
+ ])
159
+ ),
160
+ prop("text", primitive(i.message))
161
+ ]);
162
+ const props = [
163
+ prop("severity", primitive(i.severity)),
164
+ prop("code", primitive(fhirIssueTypeFor(i.code))),
165
+ prop("details", details),
166
+ // `diagnostics` carries the v2 source location — positional metadata, never a value.
167
+ prop("diagnostics", primitive(i.v2Location))
168
+ ];
169
+ if (i.fhirPath !== void 0) {
170
+ props.push(prop("expression", list([primitive(i.fhirPath)])));
171
+ }
172
+ return complex(props);
173
+ }
174
+ function toOperationOutcome(issues) {
175
+ const rendered = issues.length > 0 ? issues.map(renderIssue) : [
176
+ complex([
177
+ prop("severity", primitive("information")),
178
+ prop("code", primitive("informational")),
179
+ prop("details", complex([prop("text", primitive("No transform issues."))]))
180
+ ])
181
+ ];
182
+ return complex([
183
+ prop("resourceType", primitive("OperationOutcome")),
184
+ prop("issue", list(rendered))
185
+ ]);
186
+ }
187
+
188
+ // src/terminology/naming-system.ts
189
+ var V2_0203_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0203";
190
+ var DEFAULT_V2_CODE_SYSTEMS = Object.freeze({
191
+ LN: "http://loinc.org",
192
+ SCT: "http://snomed.info/sct",
193
+ RXNORM: "http://www.nlm.nih.gov/research/umls/rxnorm",
194
+ CVX: "http://hl7.org/fhir/sid/cvx",
195
+ UCUM: "http://unitsofmeasure.org"
196
+ });
197
+ function isOid(value) {
198
+ return /^[0-2](\.(0|[1-9]\d*))+$/.test(value);
199
+ }
200
+ function isUuid(value) {
201
+ return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(
202
+ value
203
+ );
204
+ }
205
+ function createNamingSystem(seed = {}) {
206
+ const codeSystems = { ...DEFAULT_V2_CODE_SYSTEMS, ...seed.codeSystems };
207
+ const authorities = { ...seed.authorities };
208
+ return Object.freeze({
209
+ resolveCodeSystem(mnemonic) {
210
+ if (mnemonic === "") return void 0;
211
+ return Object.hasOwn(codeSystems, mnemonic) ? codeSystems[mnemonic] : void 0;
212
+ },
213
+ resolveAssigningAuthority(hd) {
214
+ if (hd.universalId !== void 0 && Object.hasOwn(authorities, hd.universalId)) {
215
+ return authorities[hd.universalId];
216
+ }
217
+ if (hd.namespaceId !== void 0 && Object.hasOwn(authorities, hd.namespaceId)) {
218
+ return authorities[hd.namespaceId];
219
+ }
220
+ if (hd.universalId !== void 0 && hd.universalId !== "") {
221
+ if (hd.universalIdType === "ISO" && isOid(hd.universalId)) {
222
+ return `urn:oid:${hd.universalId}`;
223
+ }
224
+ if (hd.universalIdType === "UUID" && isUuid(hd.universalId)) {
225
+ return `urn:uuid:${hd.universalId.toLowerCase()}`;
226
+ }
227
+ }
228
+ return void 0;
229
+ }
230
+ });
231
+ }
232
+
233
+ // src/datatypes/datetime.ts
234
+ function pad(value, width) {
235
+ return String(value).padStart(width, "0");
236
+ }
237
+ function formatOffset(offsetMinutes) {
238
+ const sign = offsetMinutes < 0 ? "-" : "+";
239
+ const abs = Math.abs(offsetMinutes);
240
+ return `${sign}${pad(Math.floor(abs / 60), 2)}:${pad(abs % 60, 2)}`;
241
+ }
242
+ function datePart(ts) {
243
+ let out = pad(ts.year ?? 0, 4);
244
+ if (ts.month !== void 0) out += `-${pad(ts.month, 2)}`;
245
+ if (ts.day !== void 0) out += `-${pad(ts.day, 2)}`;
246
+ return out;
247
+ }
248
+ function toFhirDateTime(ts, options = {}) {
249
+ if (!ts.valid || ts.precision === void 0 || ts.year === void 0) {
250
+ return {
251
+ value: void 0,
252
+ issues: [issue(ISSUE_CODES.TRANSFORM_TIMESTAMP_INVALID, "TS.1", "dateTime")]
253
+ };
254
+ }
255
+ const date = datePart(ts);
256
+ if (ts.hour === void 0) {
257
+ return { value: date, issues: [] };
258
+ }
259
+ const hasFullTime = ts.precision === "second" || ts.precision === "fraction";
260
+ const offset = ts.hasTimezone ? ts.offsetMinutes : options.assumeTimezoneOffsetMinutes;
261
+ if (hasFullTime && offset !== void 0) {
262
+ const frac = ts.precision === "fraction" && ts.fractionalSeconds !== void 0 ? `.${ts.fractionalSeconds}` : "";
263
+ const value = `${date}T${pad(ts.hour, 2)}:${pad(ts.minute ?? 0, 2)}:${pad(ts.second ?? 0, 2)}${frac}${formatOffset(offset)}`;
264
+ const issues = ts.hasTimezone ? [] : [issue(ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE, "TS.1", "dateTime")];
265
+ return { value, issues };
266
+ }
267
+ const code = !ts.hasTimezone && offset === void 0 ? ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE : ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED;
268
+ return { value: date, issues: [issue(code, "TS.1", "dateTime")] };
269
+ }
270
+ function text(value) {
271
+ return value === void 0 || value === "" ? void 0 : primitive(value);
272
+ }
273
+ function arr(items) {
274
+ const present = items.filter((i) => i !== void 0);
275
+ return present.length === 0 ? void 0 : list(present);
276
+ }
277
+ function object(fields) {
278
+ const props = fields.filter((f) => f[1] !== void 0).map(([name, value]) => ({ name, value }));
279
+ return props.length === 0 ? void 0 : complex(props);
280
+ }
281
+
282
+ // src/datatypes/identifier.ts
283
+ function buildType(typeCode) {
284
+ if (typeCode === void 0 || typeCode === "") return void 0;
285
+ const coding2 = object([
286
+ ["system", text(V2_0203_SYSTEM)],
287
+ ["code", text(typeCode)]
288
+ ]);
289
+ return object([["coding", arr([coding2])]]);
290
+ }
291
+ function toFhirIdentifier(cx, ctx = {}) {
292
+ const issues = [];
293
+ if (cx.idNumber === void 0 || cx.idNumber === "") {
294
+ return { value: void 0, issues };
295
+ }
296
+ let system;
297
+ const hd = cx.assigningAuthority;
298
+ const hasAuthority = hd !== void 0 && (hd.namespaceId !== void 0 || hd.universalId !== void 0 || hd.universalIdType !== void 0);
299
+ if (hd !== void 0 && hasAuthority) {
300
+ system = ctx.namingSystem?.resolveAssigningAuthority(hd);
301
+ if (system === void 0) {
302
+ issues.push(
303
+ issue(ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED, "CX.4", "Identifier.system")
304
+ );
305
+ }
306
+ }
307
+ const identifier = object([
308
+ ["type", buildType(cx.identifierTypeCode)],
309
+ ["system", text(system)],
310
+ ["value", text(cx.idNumber)]
311
+ ]);
312
+ if (cx.effectiveDate !== void 0 && cx.effectiveDate !== "") {
313
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "CX.7", "Identifier.period"));
314
+ }
315
+ if (cx.expirationDate !== void 0 && cx.expirationDate !== "") {
316
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "CX.8", "Identifier.period"));
317
+ }
318
+ if (cx.assigningJurisdiction !== void 0 && cx.assigningJurisdiction !== "") {
319
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "CX.9"));
320
+ }
321
+ if (cx.assigningAgencyOrDepartment !== void 0 && cx.assigningAgencyOrDepartment !== "") {
322
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "CX.10"));
323
+ }
324
+ return { value: identifier, issues };
325
+ }
326
+
327
+ // src/datatypes/codeable-concept.ts
328
+ function buildCoding(parts, ctx, codeLocation, systemLocation, issues) {
329
+ if ((parts.code === void 0 || parts.code === "") && (parts.display === void 0 || parts.display === "")) {
330
+ return void 0;
331
+ }
332
+ let system;
333
+ if (parts.mnemonic !== void 0 && parts.mnemonic !== "") {
334
+ system = ctx.namingSystem?.resolveCodeSystem(parts.mnemonic);
335
+ if (system === void 0) {
336
+ issues.push(
337
+ issue(ISSUE_CODES.TRANSFORM_CODE_SYSTEM_UNRESOLVED, systemLocation, "Coding.system")
338
+ );
339
+ }
340
+ } else if (parts.code !== void 0 && parts.code !== "") {
341
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, codeLocation, "Coding.code"));
342
+ }
343
+ return object([
344
+ ["system", text(system)],
345
+ ["version", text(parts.version)],
346
+ ["code", text(parts.code)],
347
+ ["display", text(parts.display)]
348
+ ]);
349
+ }
350
+ function toFhirCodeableConcept(cwe, ctx = {}) {
351
+ const issues = [];
352
+ const primary = buildCoding(
353
+ {
354
+ code: cwe.identifier,
355
+ display: cwe.text,
356
+ mnemonic: cwe.nameOfCodingSystem,
357
+ version: cwe.codingSystemVersionId
358
+ },
359
+ ctx,
360
+ "CWE.1",
361
+ "CWE.3",
362
+ issues
363
+ );
364
+ const alternate = buildCoding(
365
+ {
366
+ code: cwe.alternateIdentifier,
367
+ display: cwe.alternateText,
368
+ mnemonic: cwe.nameOfAlternateCodingSystem,
369
+ version: cwe.alternateCodingSystemVersionId
370
+ },
371
+ ctx,
372
+ "CWE.4",
373
+ "CWE.6",
374
+ issues
375
+ );
376
+ const value = object([
377
+ ["coding", arr([primary, alternate])],
378
+ ["text", text(cwe.originalText)]
379
+ ]);
380
+ return { value, issues };
381
+ }
382
+
383
+ // src/datatypes/human-name.ts
384
+ var NAME_USE_MAP = Object.freeze({
385
+ BAD: "old",
386
+ D: "usual",
387
+ L: "official",
388
+ M: "maiden",
389
+ MSK: "anonymous",
390
+ N: "nickname",
391
+ NAV: "temp",
392
+ R: "official",
393
+ TEMP: "temp"
394
+ });
395
+ function toFhirHumanName(xpn) {
396
+ const issues = [];
397
+ let use;
398
+ if (xpn.nameTypeCode !== void 0 && xpn.nameTypeCode !== "") {
399
+ use = Object.hasOwn(NAME_USE_MAP, xpn.nameTypeCode) ? NAME_USE_MAP[xpn.nameTypeCode] : void 0;
400
+ if (use === void 0) {
401
+ issues.push(issue(ISSUE_CODES.TRANSFORM_NAME_USE_UNMAPPED, "XPN.7", "HumanName.use"));
402
+ }
403
+ }
404
+ if (xpn.effectiveDate !== void 0 && xpn.effectiveDate !== "") {
405
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "XPN.12", "HumanName.period"));
406
+ }
407
+ if (xpn.expirationDate !== void 0 && xpn.expirationDate !== "") {
408
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "XPN.13", "HumanName.period"));
409
+ }
410
+ const value = object([
411
+ ["use", text(use)],
412
+ ["family", text(xpn.familyName)],
413
+ ["given", arr([text(xpn.givenName), text(xpn.secondName)])],
414
+ ["prefix", arr([text(xpn.prefix)])],
415
+ // XPN.4 (suffix), XPN.6 (degree), XPN.14 (professional suffix) all land in HumanName.suffix.
416
+ ["suffix", arr([text(xpn.suffix), text(xpn.degree), text(xpn.professionalSuffix)])]
417
+ ]);
418
+ return { value, issues };
419
+ }
420
+
421
+ // src/datatypes/address.ts
422
+ var ADDRESS_USE_MAP = Object.freeze({
423
+ BA: "old",
424
+ BI: "billing",
425
+ C: "temp",
426
+ B: "work",
427
+ H: "home",
428
+ O: "work"
429
+ });
430
+ var ADDRESS_TYPE_MAP = Object.freeze({
431
+ M: "postal",
432
+ SH: "postal"
433
+ });
434
+ function toFhirAddress(xad) {
435
+ const issues = [];
436
+ let use;
437
+ let type;
438
+ if (xad.addressType !== void 0 && xad.addressType !== "") {
439
+ use = Object.hasOwn(ADDRESS_USE_MAP, xad.addressType) ? ADDRESS_USE_MAP[xad.addressType] : void 0;
440
+ type = Object.hasOwn(ADDRESS_TYPE_MAP, xad.addressType) ? ADDRESS_TYPE_MAP[xad.addressType] : void 0;
441
+ if (use === void 0 && type === void 0) {
442
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ADDRESS_USE_UNMAPPED, "XAD.7", "Address.use"));
443
+ }
444
+ }
445
+ if (xad.otherGeographicDesignation !== void 0 && xad.otherGeographicDesignation !== "") {
446
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "XAD.8"));
447
+ }
448
+ const value = object([
449
+ ["use", text(use)],
450
+ ["type", text(type)],
451
+ ["line", arr([text(xad.street), text(xad.otherDesignation)])],
452
+ ["city", text(xad.city)],
453
+ ["district", text(xad.countyParishCode)],
454
+ ["state", text(xad.stateOrProvince)],
455
+ ["postalCode", text(xad.zipOrPostalCode)],
456
+ ["country", text(xad.country)]
457
+ ]);
458
+ return { value, issues };
459
+ }
460
+ function toFhirQuantity(value, units, ctx = {}) {
461
+ if (value.value === void 0 || value.raw === "") {
462
+ return { value: void 0, issues: [] };
463
+ }
464
+ return quantityFromRawMagnitude(value.raw, units, ctx);
465
+ }
466
+ function quantityFromRawMagnitude(raw, units, ctx = {}, comparator, valueLocation = "OBX.5", unitLocation = "OBX.6") {
467
+ const issues = [];
468
+ if (raw === "") {
469
+ return { value: void 0, issues };
470
+ }
471
+ let valueNode;
472
+ try {
473
+ valueNode = primitive(decimal(raw));
474
+ } catch {
475
+ return {
476
+ value: void 0,
477
+ issues: [
478
+ issue(ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID, valueLocation, "Quantity.value")
479
+ ]
480
+ };
481
+ }
482
+ const unitCode = units.identifier;
483
+ const unitDisplay = units.text;
484
+ const hasUnit = unitCode !== void 0 && unitCode !== "" || unitDisplay !== void 0 && unitDisplay !== "";
485
+ let ucumCode;
486
+ let system;
487
+ let unitStr = unitDisplay ?? unitCode;
488
+ if (hasUnit) {
489
+ const mnemonic = units.nameOfCodingSystem;
490
+ const declaredUcum = mnemonic === "UCUM" || mnemonic !== void 0 && ctx.namingSystem?.resolveCodeSystem(mnemonic) === UCUM_SYSTEM;
491
+ if (declaredUcum && unitCode !== void 0 && unitCode !== "" && validateUcumShape(unitCode) === "ok") {
492
+ ucumCode = unitCode;
493
+ system = UCUM_SYSTEM;
494
+ unitStr = unitDisplay ?? unitCode;
495
+ } else {
496
+ issues.push(issue(ISSUE_CODES.TRANSFORM_UNIT_NOT_UCUM, unitLocation, "Quantity.code"));
497
+ }
498
+ }
499
+ const quantity = object([
500
+ ["comparator", text(comparator)],
501
+ ["value", valueNode],
502
+ ["unit", text(unitStr)],
503
+ ["system", text(system)],
504
+ ["code", text(ucumCode)]
505
+ ]);
506
+ return { value: quantity, issues };
507
+ }
508
+ var V2_0162_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0162";
509
+ var V3_ROUTE_OF_ADMINISTRATION_SYSTEM = "http://terminology.hl7.org/CodeSystem/v3-RouteOfAdministration";
510
+ var V2_0550_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0550";
511
+ var V2_0277_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0277";
512
+ var V2_0161_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0161";
513
+ function valueMap(name, sourceSystem, sourceMnemonics, targets) {
514
+ return Object.freeze({
515
+ name,
516
+ sourceSystem,
517
+ sourceMnemonics: new Set(sourceMnemonics),
518
+ translate: (code) => Object.hasOwn(targets, code) ? targets[code] : void 0
519
+ });
520
+ }
521
+ function identityTargets(system, codes) {
522
+ const t = {};
523
+ for (const code of codes) t[code] = { system, code };
524
+ return t;
525
+ }
526
+ var ROUTE_VALUE_MAP = valueMap(
527
+ "table-hl70162-to-v2-0162",
528
+ V2_0162_SYSTEM,
529
+ ["HL70162", "0162"],
530
+ {
531
+ ...identityTargets(V2_0162_SYSTEM, [
532
+ "AP",
533
+ "B",
534
+ "DT",
535
+ "EP",
536
+ "ET",
537
+ "GTT",
538
+ "GU",
539
+ "IMR",
540
+ "IA",
541
+ "IB",
542
+ "IC",
543
+ "ICV",
544
+ "IH",
545
+ "IHA",
546
+ "IN",
547
+ "IO",
548
+ "IP",
549
+ "IS",
550
+ "IT",
551
+ "IU",
552
+ "MTH",
553
+ "MM",
554
+ "NS",
555
+ "NG",
556
+ "NP",
557
+ "NT",
558
+ "OP",
559
+ "OT",
560
+ "OTH",
561
+ "PF",
562
+ "PR",
563
+ "RM",
564
+ "SD",
565
+ "SL",
566
+ "TP",
567
+ "TRA",
568
+ "TL",
569
+ "UR",
570
+ "VG",
571
+ "VM",
572
+ "WND"
573
+ ]),
574
+ ID: {
575
+ system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,
576
+ code: "IDINJ",
577
+ display: "Injection, intradermal"
578
+ },
579
+ IM: {
580
+ system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,
581
+ code: "IM",
582
+ display: "Injection, intramuscular"
583
+ },
584
+ IV: {
585
+ system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,
586
+ code: "IVINJ",
587
+ display: "Injection, intravenous"
588
+ },
589
+ PO: { system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM, code: "PO", display: "Swallow, oral" },
590
+ SC: {
591
+ system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,
592
+ code: "SQ",
593
+ display: "Injection, subcutaneous"
594
+ },
595
+ TD: { system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM, code: "TRNSDERM", display: "Transdermal" }
596
+ }
597
+ );
598
+ var SITE_VALUE_MAP = valueMap(
599
+ "table-hl70550-to-v2-0550",
600
+ V2_0550_SYSTEM,
601
+ ["HL70550", "0550"],
602
+ identityTargets(V2_0550_SYSTEM, [
603
+ "JUGE",
604
+ "ADB",
605
+ "ACET",
606
+ "ACHIL",
607
+ "ADE",
608
+ "ADR",
609
+ "AMN",
610
+ "AMS",
611
+ "ANAL",
612
+ "ANKL",
613
+ "ANTEC",
614
+ "ANTECF",
615
+ "ANTR",
616
+ "ANUS",
617
+ "AORTA",
618
+ "AR",
619
+ "AV",
620
+ "APDX",
621
+ "AREO",
622
+ "ARM",
623
+ "ARTE",
624
+ "ASCIT",
625
+ "ASCT",
626
+ "ATR",
627
+ "AURI",
628
+ "AXI",
629
+ "BACK",
630
+ "BARTD",
631
+ "BARTG",
632
+ "BRTGF",
633
+ "BPH",
634
+ "BID",
635
+ "BIFL",
636
+ "BLAD",
637
+ "BLOOD",
638
+ "BLDA",
639
+ "BLDC",
640
+ "BLDV",
641
+ "CBLD",
642
+ "BLD",
643
+ "BDY",
644
+ "BON",
645
+ "BMAR",
646
+ "BOWEL",
647
+ "BOWLA",
648
+ "BOWSM",
649
+ "BRA",
650
+ "BRAIN",
651
+ "BCYS",
652
+ "BRST",
653
+ "BRSTFL",
654
+ "BRO",
655
+ "BROCH",
656
+ "BRONC",
657
+ "BRV",
658
+ "BUCCA",
659
+ "BURSA",
660
+ "BURSF",
661
+ "BUTT",
662
+ "CALF",
663
+ "CANAL",
664
+ "CANLI",
665
+ "CNL",
666
+ "CANTH",
667
+ "CDM",
668
+ "CARO",
669
+ "CARP",
670
+ "CAVIT",
671
+ "CHE",
672
+ "CECUM",
673
+ "CSF",
674
+ "CVX",
675
+ "CERVUT",
676
+ "CHEEK",
677
+ "CHES",
678
+ "CHEST\xC2",
679
+ "CHIN",
680
+ "CIRCU",
681
+ "CLAVI",
682
+ "CLITO",
683
+ "CLIT",
684
+ "COCCG",
685
+ "COCCY",
686
+ "COLON",
687
+ "COLOS",
688
+ "COS",
689
+ "CDUCT",
690
+ "CONJ",
691
+ "CORAL",
692
+ "COR",
693
+ "CORD",
694
+ "CORN",
695
+ "CRANE",
696
+ "CRANF",
697
+ "CRANO",
698
+ "CRANP",
699
+ "CRANS",
700
+ "CRANT",
701
+ "CUBIT",
702
+ "CUFF",
703
+ "CULD",
704
+ "CULDO",
705
+ "DELT",
706
+ "DENTA",
707
+ "DEN",
708
+ "DIAF",
709
+ "DPH",
710
+ "DIGIT",
711
+ "DISC",
712
+ "DORS",
713
+ "DUFL",
714
+ "DUODE",
715
+ "DUR",
716
+ "EAR",
717
+ "EARBI",
718
+ "EARBM",
719
+ "EARBS",
720
+ "EARLO",
721
+ "ELBOW",
722
+ "ELBOWJ",
723
+ "ENDC",
724
+ "EC",
725
+ "EOLPH",
726
+ "ENDM",
727
+ "ET",
728
+ "EUR",
729
+ "EOS",
730
+ "EPICA",
731
+ "EPICM",
732
+ "EPD",
733
+ "EPIDU",
734
+ "EPIGL",
735
+ "ESOPG",
736
+ "ESO",
737
+ "ETHMO",
738
+ "\xC2",
739
+ "EYE",
740
+ "BROW",
741
+ "EYELI",
742
+ "FACE",
743
+ "FBINC",
744
+ "FBLAC",
745
+ "FBMAX",
746
+ "FBNAS",
747
+ "FBPAL",
748
+ "FBVOM",
749
+ "FBZYG",
750
+ "FALLT",
751
+ "FEMOR",
752
+ "FMH",
753
+ "FEMUR",
754
+ "FET",
755
+ "FIBU",
756
+ "FING",
757
+ "FINGN",
758
+ "FOL",
759
+ "FOOT",
760
+ "FOREA",
761
+ "FOREH",
762
+ "FORES",
763
+ "FOURC",
764
+ "GB",
765
+ "GEN",
766
+ "GVU",
767
+ "GENC",
768
+ "GL",
769
+ "GENL",
770
+ "GLAND",
771
+ "GLANS",
772
+ "GLUTE",
773
+ "GLUT",
774
+ "GLUTM",
775
+ "GROIN",
776
+ "GUM",
777
+ "HAR",
778
+ "HAL",
779
+ "HAND",
780
+ "HEAD",
781
+ "HART",
782
+ "HV",
783
+ "HVB",
784
+ "HVT",
785
+ "HEEL",
786
+ "HEM",
787
+ "HIP",
788
+ "HIPJ",
789
+ "HUMER",
790
+ "HYMEN",
791
+ "ILC",
792
+ "ILE",
793
+ "ILEOS",
794
+ "ILEUM",
795
+ "ILIAC",
796
+ "ILCR",
797
+ "ILCON",
798
+ "INGUI",
799
+ "JUGI",
800
+ "INT",
801
+ "ICX",
802
+ "INASA",
803
+ "INTRU",
804
+ "INTRO",
805
+ "ISCHI",
806
+ "JAW",
807
+ "KIDN\xC2",
808
+ "KNEE",
809
+ "KNEEF",
810
+ "KNEEJ",
811
+ "LABIA",
812
+ "LABMA",
813
+ "LABMI",
814
+ "LACRI",
815
+ "LAM",
816
+ "INSTL",
817
+ "LARYN",
818
+ "LEG",
819
+ "LENS",
820
+ "WBC",
821
+ "LING",
822
+ "LINGU",
823
+ "LIP",
824
+ "STOOLL",
825
+ "LIVER",
826
+ "LOBE",
827
+ "LOCH",
828
+ "ISH",
829
+ "LUMBA",
830
+ "LMN",
831
+ "LUNG",
832
+ "LN",
833
+ "LNG",
834
+ "LYM",
835
+ "MAC",
836
+ "MALLE",
837
+ "MANDI",
838
+ "MAR",
839
+ "MAST",
840
+ "MAXIL",
841
+ "MAXS",
842
+ "MEATU",
843
+ "MEC",
844
+ "MEDST",
845
+ "MEDU",
846
+ "MOU",
847
+ "MPB",
848
+ "METAC",
849
+ "METAT",
850
+ "MILK",
851
+ "MITRL",
852
+ "MOLAR",
853
+ "MP",
854
+ "MONSU",
855
+ "MONSV",
856
+ "MOUTH",
857
+ "MRSA2",
858
+ "MYO",
859
+ "NAIL",
860
+ "NAILB",
861
+ "NAILF",
862
+ "NAILT",
863
+ "NARES",
864
+ "NASL",
865
+ "NSS",
866
+ "NLACR",
867
+ "NP",
868
+ "NTRAC",
869
+ "NAVEL",
870
+ "NECK",
871
+ "NERVE",
872
+ "NIPPL",
873
+ "NOS",
874
+ "NOSE",
875
+ "NOSTR",
876
+ "OCCIP",
877
+ "OLECR",
878
+ "OMEN",
879
+ "ORBIT",
880
+ "ORO",
881
+ "OSCOX",
882
+ "OVARY",
883
+ "PALAT",
884
+ "PLATH",
885
+ "PLATS",
886
+ "PALM",
887
+ "PANCR",
888
+ "PAFL",
889
+ "PAS",
890
+ "PARAT",
891
+ "PARIE",
892
+ "PARON",
893
+ "PAROT",
894
+ "PATEL",
895
+ "PELV",
896
+ "PENSH",
897
+ "PENIS",
898
+ "PANAL",
899
+ "PERI",
900
+ "PCARD",
901
+ "PCLIT",
902
+ "PERIH",
903
+ "PNEAL",
904
+ "PERIN",
905
+ "PNEPH",
906
+ "PNM",
907
+ "PORBI",
908
+ "PERRA",
909
+ "PERIS",
910
+ "PER",
911
+ "PERT",
912
+ "PERIT",
913
+ "PTONS",
914
+ "PERIU",
915
+ "PERIV",
916
+ "PHALA",
917
+ "PILO",
918
+ "PINNA",
919
+ "PLC",
920
+ "PLACF",
921
+ "PLACM",
922
+ "PLANT",
923
+ "PLEUR",
924
+ "PLEU",
925
+ "PLR",
926
+ "POPLI",
927
+ "PREAU",
928
+ "PRERE",
929
+ "PRST",
930
+ "PROS",
931
+ "PUBIC",
932
+ "PUL",
933
+ "RADI",
934
+ "RADIUS",
935
+ "RECTL",
936
+ "RECTU",
937
+ "RBC",
938
+ "RENL",
939
+ "RNP",
940
+ "RPERI",
941
+ "RIB",
942
+ "SACRA",
943
+ "SACRO",
944
+ "SACIL",
945
+ "SACRU",
946
+ "SALGL",
947
+ "SCALP",
948
+ "SCAPU",
949
+ "SCLER",
950
+ "SCROT",
951
+ "SEMN",
952
+ "SEM",
953
+ "SEPTU",
954
+ "SEROM",
955
+ "SHIN",
956
+ "SHOLJ",
957
+ "SHOL",
958
+ "SIGMO",
959
+ "SINUS",
960
+ "SKM",
961
+ "SKENE",
962
+ "SKULL",
963
+ "INSTS",
964
+ "SOLE",
965
+ "SPRM",
966
+ "SPHEN",
967
+ "SPCOR",
968
+ "SPLN",
969
+ "STER",
970
+ "STOM",
971
+ "USTOM",
972
+ "STOMA",
973
+ "STUMP",
974
+ "SCLV",
975
+ "SDP",
976
+ "SUB",
977
+ "SUBD",
978
+ "SGF",
979
+ "SUBM",
980
+ "SUBX",
981
+ "SUBME",
982
+ "SUBPH",
983
+ "SPX",
984
+ "SCLAV",
985
+ "SUPRA",
986
+ "SUPB",
987
+ "SWT",
988
+ "SWTG",
989
+ "SYNOL",
990
+ "SYN",
991
+ "SYNOV",
992
+ "TARS",
993
+ "TDUCT",
994
+ "TEAR",
995
+ "TEMPL",
996
+ "TEMPO",
997
+ "TML",
998
+ "TESTI",
999
+ "THIGH",
1000
+ "THORA",
1001
+ "THRB",
1002
+ "THUMB",
1003
+ "TNL",
1004
+ "THM",
1005
+ "THYRD",
1006
+ "TIBIA",
1007
+ "TOE",
1008
+ "TOEN",
1009
+ "TONG",
1010
+ "TONS",
1011
+ "TOOTH",
1012
+ "TSK",
1013
+ "TRCHE",
1014
+ "TBRON",
1015
+ "TCN",
1016
+ "ULNA",
1017
+ "UMB",
1018
+ "UMBL",
1019
+ "URET",
1020
+ "URTH",
1021
+ "UTERI",
1022
+ "SAC",
1023
+ "UTER",
1024
+ "VAGIN",
1025
+ "VCUFF",
1026
+ "VGV",
1027
+ "VAL",
1028
+ "VAS",
1029
+ "VASTL",
1030
+ "VAULT",
1031
+ "VEIN",
1032
+ "VENTG",
1033
+ "VCSF",
1034
+ "VERMI",
1035
+ "VERTC",
1036
+ "VERTL",
1037
+ "VERTT",
1038
+ "VESI",
1039
+ "VESCL",
1040
+ "VESFLD",
1041
+ "VESTI",
1042
+ "VITR",
1043
+ "VOC",
1044
+ "VULVA",
1045
+ "WRIST"
1046
+ ])
1047
+ );
1048
+ var APPOINTMENT_TYPE_VALUE_MAP = valueMap(
1049
+ "table-hl70277-to-v2-0277",
1050
+ V2_0277_SYSTEM,
1051
+ ["HL70277", "0277"],
1052
+ identityTargets(V2_0277_SYSTEM, ["Normal", "Tentative", "Complete"])
1053
+ );
1054
+ var SUBSTITUTION_VALUE_MAP = valueMap(
1055
+ "table-hl70161-to-v2-0161",
1056
+ V2_0161_SYSTEM,
1057
+ ["HL70161", "0161"],
1058
+ identityTargets(V2_0161_SYSTEM, ["N", "G", "T"])
1059
+ );
1060
+ function codingFrom(system, code, display, version) {
1061
+ const props = [{ name: "system", value: primitive(system) }];
1062
+ if (version !== void 0 && version !== "")
1063
+ props.push({ name: "version", value: primitive(version) });
1064
+ props.push({ name: "code", value: primitive(code) });
1065
+ if (display !== void 0 && display !== "")
1066
+ props.push({ name: "display", value: primitive(display) });
1067
+ return complex(props);
1068
+ }
1069
+ function translateBound(cwe, map) {
1070
+ const mnemonic = cwe.nameOfCodingSystem;
1071
+ const fromBoundTable = mnemonic === void 0 || mnemonic === "" || map.sourceMnemonics.has(mnemonic);
1072
+ if (!fromBoundTable) return void 0;
1073
+ const code = cwe.identifier;
1074
+ return code === void 0 || code === "" ? void 0 : map.translate(code);
1075
+ }
1076
+ function codeableConceptFromTarget(target, text2) {
1077
+ const props = [
1078
+ { name: "coding", value: list([codingFrom(target.system, target.code, target.display)]) }
1079
+ ];
1080
+ if (text2 !== void 0 && text2 !== "") props.push({ name: "text", value: primitive(text2) });
1081
+ return complex(props);
1082
+ }
1083
+ function toFhirCodeableConceptVia(cwe, map, ctx = {}) {
1084
+ const target = translateBound(cwe, map);
1085
+ if (target === void 0) {
1086
+ return toFhirCodeableConcept(cwe, ctx);
1087
+ }
1088
+ const issues = [];
1089
+ const codings = [];
1090
+ codings.push(
1091
+ codingFrom(map.sourceSystem, cwe.identifier, cwe.text, cwe.codingSystemVersionId)
1092
+ );
1093
+ const isIdentity = target.system === map.sourceSystem && target.code === cwe.identifier;
1094
+ if (!isIdentity) codings.push(codingFrom(target.system, target.code, target.display));
1095
+ const alternate = buildCoding(
1096
+ {
1097
+ code: cwe.alternateIdentifier,
1098
+ display: cwe.alternateText,
1099
+ mnemonic: cwe.nameOfAlternateCodingSystem,
1100
+ version: cwe.alternateCodingSystemVersionId
1101
+ },
1102
+ ctx,
1103
+ "CWE.4",
1104
+ "CWE.6",
1105
+ issues
1106
+ );
1107
+ if (alternate !== void 0) codings.push(alternate);
1108
+ const props = [{ name: "coding", value: list(codings) }];
1109
+ if (cwe.originalText !== void 0 && cwe.originalText !== "") {
1110
+ props.push({ name: "text", value: primitive(cwe.originalText) });
1111
+ }
1112
+ return { value: complex(props), issues };
1113
+ }
1114
+ var DATA_ABSENT_REASON_URL = "http://hl7.org/fhir/StructureDefinition/data-absent-reason";
1115
+ var IdAllocator = class {
1116
+ gen;
1117
+ /**
1118
+ * @param options - The transform options; `options.generateId` overrides the default UUID source.
1119
+ */
1120
+ constructor(options) {
1121
+ this.gen = options?.generateId ?? (() => randomUUID());
1122
+ }
1123
+ /** Mint one fresh `urn:uuid:<id>` fullUrl. */
1124
+ next() {
1125
+ return `urn:uuid:${this.gen()}`;
1126
+ }
1127
+ };
1128
+ function reference(fullUrl) {
1129
+ return complex([{ name: "reference", value: primitive(fullUrl) }]);
1130
+ }
1131
+ function coding(system, code, display) {
1132
+ if (code === void 0 || code === "") return void 0;
1133
+ const props = [
1134
+ { name: "system", value: primitive(system) },
1135
+ { name: "code", value: primitive(code) }
1136
+ ];
1137
+ if (display !== void 0 && display !== "") {
1138
+ props.push({ name: "display", value: primitive(display) });
1139
+ }
1140
+ return complex(props);
1141
+ }
1142
+ function orderIdentifier(value, typeCode) {
1143
+ if (value === "") return void 0;
1144
+ return complex([
1145
+ {
1146
+ name: "type",
1147
+ value: complex([
1148
+ {
1149
+ name: "coding",
1150
+ value: list([
1151
+ complex([
1152
+ { name: "system", value: primitive(V2_0203_SYSTEM) },
1153
+ { name: "code", value: primitive(typeCode) }
1154
+ ])
1155
+ ])
1156
+ }
1157
+ ])
1158
+ },
1159
+ { name: "value", value: primitive(value) }
1160
+ ]);
1161
+ }
1162
+ function dataAbsent(reasonCode) {
1163
+ const ext = complex([
1164
+ { name: "url", value: primitive(DATA_ABSENT_REASON_URL) },
1165
+ { name: "valueCode", value: primitive(reasonCode) }
1166
+ ]);
1167
+ return primitive(void 0, { extension: [ext] });
1168
+ }
1169
+
1170
+ // src/messages/appointment.ts
1171
+ var APPOINTMENT_STATUS_MAP = Object.freeze({
1172
+ Pending: "pending",
1173
+ Waitlist: "waitlist",
1174
+ Booked: "booked",
1175
+ Started: "checked-in",
1176
+ Complete: "fulfilled",
1177
+ Cancelled: "cancelled",
1178
+ Deleted: "entered-in-error",
1179
+ Noshow: "noshow"
1180
+ });
1181
+ var PARTICIPANT_STATUS_UNKNOWN = "unknown";
1182
+ var MINUTE_UNITS = /* @__PURE__ */ new Set(["min", "MIN", "minutes", "m"]);
1183
+ var POSITIVE_INT = /^[1-9][0-9]*$/;
1184
+ function tqInstant(raw, ctx, location, fhirPath, issues) {
1185
+ if (raw === void 0 || raw === "") return void 0;
1186
+ const ts = parseDtm(raw);
1187
+ const dt = toFhirDateTime(ts, ctx.options);
1188
+ issues.push(...dt.issues);
1189
+ if (dt.value === void 0) return void 0;
1190
+ if (dt.value.includes("T") && (dt.value.includes("+") || dt.value.endsWith("Z") || /-\d{2}:\d{2}$/.test(dt.value))) {
1191
+ return dt.value;
1192
+ }
1193
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, location, fhirPath));
1194
+ return void 0;
1195
+ }
1196
+ function rawComponent(seg, field, index) {
1197
+ const c = seg.field(field).repetitions[0]?.components[index]?.subcomponents[0];
1198
+ return c === void 0 || c === "" ? void 0 : c;
1199
+ }
1200
+ function patientParticipant(patientFullUrl, issues) {
1201
+ if (patientFullUrl === void 0) return void 0;
1202
+ issues.push(
1203
+ issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, "SIU", "Appointment.participant.status")
1204
+ );
1205
+ return complex([
1206
+ { name: "actor", value: reference(patientFullUrl) },
1207
+ { name: "status", value: dataAbsent(PARTICIPANT_STATUS_UNKNOWN) }
1208
+ ]);
1209
+ }
1210
+ function buildAppointment(sch, ais, patientFullUrl, ctx) {
1211
+ const issues = [];
1212
+ const props = [
1213
+ { name: "resourceType", value: primitive("Appointment") }
1214
+ ];
1215
+ const fillerStatus = sch.field(25).value;
1216
+ if (fillerStatus !== "") {
1217
+ const status = Object.hasOwn(APPOINTMENT_STATUS_MAP, fillerStatus) ? APPOINTMENT_STATUS_MAP[fillerStatus] : void 0;
1218
+ if (status === void 0) {
1219
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "SCH.25", "Appointment.status"));
1220
+ } else {
1221
+ props.push({ name: "status", value: primitive(status) });
1222
+ }
1223
+ }
1224
+ const identifiers = [sch.field(1).value, sch.field(2).value].filter((v) => v !== "").map((v) => complex([{ name: "value", value: primitive(v) }]));
1225
+ if (identifiers.length > 0) props.push({ name: "identifier", value: list(identifiers) });
1226
+ if (sch.field(8).value !== "") {
1227
+ const appointmentType = toFhirCodeableConceptVia(
1228
+ sch.field(8).asCwe(),
1229
+ APPOINTMENT_TYPE_VALUE_MAP,
1230
+ ctx
1231
+ );
1232
+ issues.push(...appointmentType.issues);
1233
+ if (appointmentType.value !== void 0)
1234
+ props.push({ name: "appointmentType", value: appointmentType.value });
1235
+ }
1236
+ if (ais !== void 0 && ais.field(3).value !== "") {
1237
+ const serviceType = toFhirCodeableConcept(ais.field(3).asCwe(), ctx);
1238
+ issues.push(...serviceType.issues);
1239
+ if (serviceType.value !== void 0)
1240
+ props.push({ name: "serviceType", value: list([serviceType.value]) });
1241
+ }
1242
+ if (sch.field(7).value !== "") {
1243
+ const reason = toFhirCodeableConcept(sch.field(7).asCwe(), ctx);
1244
+ issues.push(...reason.issues);
1245
+ if (reason.value !== void 0) props.push({ name: "reasonCode", value: list([reason.value]) });
1246
+ }
1247
+ const duration = sch.field(9).value;
1248
+ if (duration !== "" && POSITIVE_INT.test(duration) && MINUTE_UNITS.has(rawComponent(sch, 10, 0) ?? "")) {
1249
+ props.push({ name: "minutesDuration", value: primitive(decimal(duration)) });
1250
+ }
1251
+ const start = tqInstant(rawComponent(sch, 11, 3), ctx, "SCH.11", "Appointment.start", issues);
1252
+ if (start !== void 0) props.push({ name: "start", value: primitive(start) });
1253
+ const end = tqInstant(rawComponent(sch, 11, 4), ctx, "SCH.11", "Appointment.end", issues);
1254
+ if (end !== void 0) props.push({ name: "end", value: primitive(end) });
1255
+ const participant = patientParticipant(patientFullUrl, issues);
1256
+ if (participant !== void 0) props.push({ name: "participant", value: list([participant]) });
1257
+ return { value: complex(props), issues };
1258
+ }
1259
+ function collectAppointment(msg) {
1260
+ let sch;
1261
+ let ais;
1262
+ for (const seg of msg.allSegments()) {
1263
+ if (seg.type === "SCH" && sch === void 0) sch = seg;
1264
+ else if (seg.type === "AIS" && ais === void 0) ais = seg;
1265
+ }
1266
+ return { sch, ais };
1267
+ }
1268
+ var V2_0074_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0074";
1269
+ var DIAGNOSTIC_REPORT_STATUS_MAP = Object.freeze({
1270
+ O: "registered",
1271
+ I: "registered",
1272
+ S: "registered",
1273
+ P: "preliminary",
1274
+ R: "partial",
1275
+ C: "corrected",
1276
+ F: "final",
1277
+ X: "cancelled"
1278
+ });
1279
+ function buildDiagnosticReport(obr, resultFullUrls, subjectFullUrl, encounterFullUrl, ctx) {
1280
+ const issues = [];
1281
+ const props = [
1282
+ { name: "resourceType", value: primitive("DiagnosticReport") }
1283
+ ];
1284
+ const identifiers = [
1285
+ orderIdentifier(obr.field(2).value, "PLAC"),
1286
+ orderIdentifier(obr.field(3).value, "FILL")
1287
+ ].filter((i) => i !== void 0);
1288
+ if (identifiers.length > 0) props.push({ name: "identifier", value: list(identifiers) });
1289
+ const statusCode = obr.field(25).value;
1290
+ if (statusCode !== "") {
1291
+ const status = Object.hasOwn(DIAGNOSTIC_REPORT_STATUS_MAP, statusCode) ? DIAGNOSTIC_REPORT_STATUS_MAP[statusCode] : void 0;
1292
+ if (status === void 0) {
1293
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "OBR.25", "DiagnosticReport.status"));
1294
+ } else {
1295
+ props.push({ name: "status", value: primitive(status) });
1296
+ }
1297
+ }
1298
+ const section = obr.field(24).value;
1299
+ if (section !== "") {
1300
+ props.push({
1301
+ name: "category",
1302
+ value: list([
1303
+ complex([
1304
+ {
1305
+ name: "coding",
1306
+ value: list([
1307
+ complex([
1308
+ { name: "system", value: primitive(V2_0074_SYSTEM) },
1309
+ { name: "code", value: primitive(section) }
1310
+ ])
1311
+ ])
1312
+ }
1313
+ ])
1314
+ ])
1315
+ });
1316
+ }
1317
+ const code = toFhirCodeableConcept(obr.field(4).asCwe(), ctx);
1318
+ issues.push(...code.issues);
1319
+ if (code.value === void 0) return { value: void 0, issues };
1320
+ props.push({ name: "code", value: code.value });
1321
+ if (subjectFullUrl !== void 0)
1322
+ props.push({ name: "subject", value: reference(subjectFullUrl) });
1323
+ if (encounterFullUrl !== void 0) {
1324
+ props.push({ name: "encounter", value: reference(encounterFullUrl) });
1325
+ }
1326
+ const hasEnd = obr.field(8).value !== "";
1327
+ if (obr.field(7).value !== "") {
1328
+ const start = toFhirDateTime(obr.field(7).asTs(), ctx.options);
1329
+ issues.push(...start.issues);
1330
+ if (start.value !== void 0 && !hasEnd) {
1331
+ props.push({ name: "effectiveDateTime", value: primitive(start.value) });
1332
+ } else if (start.value !== void 0) {
1333
+ const end = toFhirDateTime(obr.field(8).asTs(), ctx.options);
1334
+ issues.push(...end.issues);
1335
+ const periodProps = [
1336
+ { name: "start", value: primitive(start.value) }
1337
+ ];
1338
+ if (end.value !== void 0) periodProps.push({ name: "end", value: primitive(end.value) });
1339
+ props.push({ name: "effectivePeriod", value: complex(periodProps) });
1340
+ }
1341
+ }
1342
+ if (obr.field(22).value !== "") {
1343
+ const issued = toFhirDateTime(obr.field(22).asTs(), ctx.options);
1344
+ issues.push(...issued.issues);
1345
+ if (issued.value !== void 0 && issued.value.includes("T")) {
1346
+ props.push({ name: "issued", value: primitive(issued.value) });
1347
+ } else if (issued.value !== void 0) {
1348
+ issues.push(
1349
+ issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "OBR.22", "DiagnosticReport.issued")
1350
+ );
1351
+ }
1352
+ }
1353
+ if (resultFullUrls.length > 0) {
1354
+ props.push({ name: "result", value: list(resultFullUrls.map((u) => reference(u))) });
1355
+ }
1356
+ return { value: complex(props), issues };
1357
+ }
1358
+ var STATUS_AVAILABLE_TARGET = "current";
1359
+ var BODY_CONTENT_TYPE = Object.freeze({
1360
+ TX: "application/text",
1361
+ FT: "text/hl7v2"
1362
+ });
1363
+ function buildContent(obx, index, issues) {
1364
+ const valueType = obx.field(2).value.toUpperCase();
1365
+ const raw = obx.field(5).value;
1366
+ if (raw === "") return void 0;
1367
+ if (Object.hasOwn(BODY_CONTENT_TYPE, valueType)) {
1368
+ const data = Buffer.from(raw, "utf8").toString("base64");
1369
+ return complex([
1370
+ {
1371
+ name: "attachment",
1372
+ value: complex([
1373
+ { name: "contentType", value: primitive(BODY_CONTENT_TYPE[valueType]) },
1374
+ { name: "data", value: primitive(data) }
1375
+ ])
1376
+ }
1377
+ ]);
1378
+ }
1379
+ if (valueType === "RP") {
1380
+ return complex([
1381
+ {
1382
+ name: "attachment",
1383
+ value: complex([{ name: "url", value: primitive(raw) }])
1384
+ }
1385
+ ]);
1386
+ }
1387
+ issues.push(
1388
+ issue(
1389
+ ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,
1390
+ `OBX[${String(index)}].5`,
1391
+ "DocumentReference.content"
1392
+ )
1393
+ );
1394
+ return void 0;
1395
+ }
1396
+ function buildDocumentReference(txa, obxs, subjectFullUrl, ctx) {
1397
+ const issues = [];
1398
+ const props = [
1399
+ { name: "resourceType", value: primitive("DocumentReference") }
1400
+ ];
1401
+ const availability = txa.field(19).value;
1402
+ if (availability === "AV") {
1403
+ props.push({ name: "status", value: primitive(STATUS_AVAILABLE_TARGET) });
1404
+ } else if (availability !== "") {
1405
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "TXA.19", "DocumentReference.status"));
1406
+ }
1407
+ if (txa.field(17).value !== "") {
1408
+ issues.push(
1409
+ issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "TXA.17", "DocumentReference.docStatus")
1410
+ );
1411
+ }
1412
+ if (txa.field(2).value !== "") {
1413
+ const type = toFhirCodeableConcept(txa.field(2).asCwe(), ctx);
1414
+ issues.push(...type.issues);
1415
+ if (type.value !== void 0) props.push({ name: "type", value: type.value });
1416
+ }
1417
+ if (txa.field(12).value !== "") {
1418
+ props.push({
1419
+ name: "masterIdentifier",
1420
+ value: complex([{ name: "value", value: primitive(txa.field(12).value) }])
1421
+ });
1422
+ }
1423
+ if (txa.field(16).value !== "") {
1424
+ props.push({
1425
+ name: "identifier",
1426
+ value: list([complex([{ name: "value", value: primitive(txa.field(16).value) }])])
1427
+ });
1428
+ }
1429
+ if (subjectFullUrl !== void 0)
1430
+ props.push({ name: "subject", value: reference(subjectFullUrl) });
1431
+ if (txa.field(6).value !== "") {
1432
+ const date = toFhirDateTime(txa.field(6).asTs(), ctx.options);
1433
+ issues.push(...date.issues);
1434
+ if (date.value !== void 0 && date.value.includes("T")) {
1435
+ props.push({ name: "date", value: primitive(date.value) });
1436
+ } else if (date.value !== void 0) {
1437
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "TXA.6", "DocumentReference.date"));
1438
+ }
1439
+ }
1440
+ if (txa.field(3).value !== "") {
1441
+ issues.push(
1442
+ issue(
1443
+ ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,
1444
+ "TXA.3",
1445
+ "DocumentReference.content.attachment.contentType"
1446
+ )
1447
+ );
1448
+ }
1449
+ if (txa.field(25).value !== "")
1450
+ props.push({ name: "description", value: primitive(txa.field(25).value) });
1451
+ const contents = [];
1452
+ for (let i = 0; i < obxs.length; i++) {
1453
+ const obx = obxs[i];
1454
+ if (obx === void 0) continue;
1455
+ const content = buildContent(obx, i, issues);
1456
+ if (content !== void 0) contents.push(content);
1457
+ }
1458
+ if (contents.length > 0) props.push({ name: "content", value: list(contents) });
1459
+ return { value: complex(props), issues };
1460
+ }
1461
+ function collectDocument(msg) {
1462
+ let txa;
1463
+ const obxs = [];
1464
+ for (const seg of msg.allSegments()) {
1465
+ if (seg.type === "TXA" && txa === void 0) txa = seg;
1466
+ else if (seg.type === "OBX") obxs.push(seg);
1467
+ }
1468
+ return { txa, obxs };
1469
+ }
1470
+ var V3_ACTCODE_SYSTEM = "http://terminology.hl7.org/CodeSystem/v3-ActCode";
1471
+ var V2_0004_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0004";
1472
+ var ENCOUNTER_CLASS_V3_MAP = Object.freeze({
1473
+ E: { code: "EMER", display: "emergency" },
1474
+ I: { code: "IMP", display: "inpatient encounter" },
1475
+ O: { code: "AMB", display: "ambulatory" },
1476
+ P: { code: "PRENC", display: "pre-admission" }
1477
+ });
1478
+ var V2_SELF_CLASSES = /* @__PURE__ */ new Set(["R", "B", "C", "N", "U"]);
1479
+ var ENCOUNTER_STATUS_MAP = Object.freeze({
1480
+ E: "in-progress",
1481
+ I: "in-progress",
1482
+ O: "in-progress",
1483
+ R: "in-progress",
1484
+ B: "in-progress",
1485
+ C: "in-progress",
1486
+ N: "in-progress",
1487
+ P: "planned",
1488
+ U: "unknown"
1489
+ });
1490
+ function buildClass(patientClass, issues) {
1491
+ if (patientClass === void 0 || patientClass === "") return void 0;
1492
+ const v3 = ENCOUNTER_CLASS_V3_MAP[patientClass];
1493
+ if (v3 !== void 0) return coding(V3_ACTCODE_SYSTEM, v3.code, v3.display);
1494
+ if (V2_SELF_CLASSES.has(patientClass)) return coding(V2_0004_SYSTEM, patientClass);
1495
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "PV1.2", "Encounter.class"));
1496
+ return void 0;
1497
+ }
1498
+ function buildEncounter(visit, subjectFullUrl, ctx) {
1499
+ const issues = [];
1500
+ const props = [
1501
+ { name: "resourceType", value: primitive("Encounter") }
1502
+ ];
1503
+ if (visit.visitNumber !== void 0 && visit.visitNumber !== "") {
1504
+ const vnCoding = complex([
1505
+ { name: "system", value: primitive(V2_0203_SYSTEM) },
1506
+ { name: "code", value: primitive("VN") }
1507
+ ]);
1508
+ const identifier = complex([
1509
+ { name: "type", value: complex([{ name: "coding", value: list([vnCoding]) }]) },
1510
+ { name: "value", value: primitive(visit.visitNumber) }
1511
+ ]);
1512
+ props.push({ name: "identifier", value: list([identifier]) });
1513
+ }
1514
+ const discharged = visit.dischargeDateTime !== void 0;
1515
+ let status;
1516
+ if (discharged) {
1517
+ status = "finished";
1518
+ } else if (visit.patientClass !== void 0 && visit.patientClass !== "") {
1519
+ status = Object.hasOwn(ENCOUNTER_STATUS_MAP, visit.patientClass) ? ENCOUNTER_STATUS_MAP[visit.patientClass] : void 0;
1520
+ if (status === void 0) {
1521
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "PV1.2", "Encounter.status"));
1522
+ }
1523
+ }
1524
+ if (status !== void 0) props.push({ name: "status", value: primitive(status) });
1525
+ const encounterClass = buildClass(visit.patientClass, issues);
1526
+ if (encounterClass !== void 0) props.push({ name: "class", value: encounterClass });
1527
+ if (subjectFullUrl !== void 0) {
1528
+ props.push({ name: "subject", value: reference(subjectFullUrl) });
1529
+ } else {
1530
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "PID", "Encounter.subject"));
1531
+ }
1532
+ const periodProps = [];
1533
+ if (visit.admitDateTime !== void 0) {
1534
+ const start = toFhirDateTime(visit.admitDateTime, ctx.options);
1535
+ issues.push(...start.issues);
1536
+ if (start.value !== void 0)
1537
+ periodProps.push({ name: "start", value: primitive(start.value) });
1538
+ }
1539
+ if (visit.dischargeDateTime !== void 0) {
1540
+ const end = toFhirDateTime(visit.dischargeDateTime, ctx.options);
1541
+ issues.push(...end.issues);
1542
+ if (end.value !== void 0) periodProps.push({ name: "end", value: primitive(end.value) });
1543
+ }
1544
+ if (periodProps.length > 0) props.push({ name: "period", value: complex(periodProps) });
1545
+ if (visit.location !== void 0) {
1546
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "PV1.3", "Encounter.location"));
1547
+ }
1548
+ if (visit.attendingDoctor !== void 0) {
1549
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "PV1.7", "Encounter.participant"));
1550
+ }
1551
+ if (visit.referringDoctor !== void 0) {
1552
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "PV1.8", "Encounter.participant"));
1553
+ }
1554
+ if (props.length === 1) return { value: void 0, issues };
1555
+ return { value: complex(props), issues };
1556
+ }
1557
+ var EMIT_SCHEMAS = Object.freeze([
1558
+ {
1559
+ type: "Encounter",
1560
+ elements: {
1561
+ status: { min: 1, max: 1, types: ["code"] },
1562
+ class: { min: 1, max: 1, types: ["Coding"] }
1563
+ }
1564
+ },
1565
+ {
1566
+ type: "MessageHeader",
1567
+ elements: {
1568
+ eventCoding: { min: 1, max: 1, types: ["Coding"] }
1569
+ }
1570
+ },
1571
+ {
1572
+ type: "RelatedPerson",
1573
+ elements: {
1574
+ patient: { min: 1, max: 1, types: ["Reference"] }
1575
+ }
1576
+ },
1577
+ {
1578
+ type: "DiagnosticReport",
1579
+ elements: {
1580
+ status: { min: 1, max: 1, types: ["code"] },
1581
+ code: { min: 1, max: 1, types: ["CodeableConcept"] }
1582
+ }
1583
+ },
1584
+ {
1585
+ type: "Observation",
1586
+ elements: {
1587
+ status: { min: 1, max: 1, types: ["code"] },
1588
+ code: { min: 1, max: 1, types: ["CodeableConcept"] }
1589
+ }
1590
+ },
1591
+ {
1592
+ type: "ServiceRequest",
1593
+ elements: {
1594
+ status: { min: 1, max: 1, types: ["code"] },
1595
+ intent: { min: 1, max: 1, types: ["code"] },
1596
+ subject: { min: 1, max: 1, types: ["Reference"] }
1597
+ }
1598
+ },
1599
+ {
1600
+ type: "MedicationRequest",
1601
+ elements: {
1602
+ status: { min: 1, max: 1, types: ["code"] },
1603
+ intent: { min: 1, max: 1, types: ["code"] },
1604
+ subject: { min: 1, max: 1, types: ["Reference"] },
1605
+ medicationCodeableConcept: { min: 1, max: 1, types: ["CodeableConcept"] }
1606
+ }
1607
+ },
1608
+ {
1609
+ // Immunization: status (1..1 code), vaccineCode (1..1 CodeableConcept), patient (1..1 Reference), and
1610
+ // occurrence[x] (1..1) are all required — the assembler only ever emits the occurrenceDateTime form, so
1611
+ // it is required here. An RXA with no groundable status/vaccine/occurrence, or no bundle Patient, is
1612
+ // withheld rather than emitted incomplete.
1613
+ type: "Immunization",
1614
+ elements: {
1615
+ status: { min: 1, max: 1, types: ["code"] },
1616
+ vaccineCode: { min: 1, max: 1, types: ["CodeableConcept"] },
1617
+ patient: { min: 1, max: 1, types: ["Reference"] },
1618
+ occurrenceDateTime: { min: 1, max: 1, types: ["dateTime"] }
1619
+ }
1620
+ },
1621
+ {
1622
+ // Appointment: status (1..1 code) and participant (1..* BackboneElement) are both required — an
1623
+ // Appointment whose SCH-25 status could not be grounded via HL70278, or that has no resolvable Patient
1624
+ // participant, is withheld rather than emitted with a guessed status or no participant.
1625
+ type: "Appointment",
1626
+ elements: {
1627
+ status: { min: 1, max: 1, types: ["code"] },
1628
+ participant: { min: 1, max: UNBOUNDED, types: ["BackboneElement"] }
1629
+ }
1630
+ },
1631
+ {
1632
+ // DocumentReference: status (1..1 code) and content (1..* BackboneElement) are both required — a
1633
+ // reference whose TXA-19 is not "AV" (no groundable status), or that carries no document body from its
1634
+ // OBX segments, is withheld rather than emitted with a guessed status or referencing nothing.
1635
+ type: "DocumentReference",
1636
+ elements: {
1637
+ status: { min: 1, max: 1, types: ["code"] },
1638
+ content: { min: 1, max: UNBOUNDED, types: ["BackboneElement"] }
1639
+ }
1640
+ }
1641
+ ]);
1642
+ var IMMUNIZATION_STATUS_MAP = Object.freeze({
1643
+ CP: "completed",
1644
+ PA: "completed",
1645
+ RE: "not-done",
1646
+ NA: "not-done"
1647
+ });
1648
+ function collectImmunizationGroups(msg) {
1649
+ const groups = [];
1650
+ let current;
1651
+ const open = () => {
1652
+ const g = { orc: void 0, rxa: void 0, rxr: void 0 };
1653
+ groups.push(g);
1654
+ current = g;
1655
+ return g;
1656
+ };
1657
+ for (const seg of msg.allSegments()) {
1658
+ switch (seg.type) {
1659
+ case "ORC":
1660
+ open().orc = seg;
1661
+ break;
1662
+ case "RXA":
1663
+ if (current === void 0 || current.rxa !== void 0) open();
1664
+ current.rxa = seg;
1665
+ break;
1666
+ case "RXR":
1667
+ if (current !== void 0 && current.rxa !== void 0 && current.rxr === void 0) {
1668
+ current.rxr = seg;
1669
+ }
1670
+ break;
1671
+ }
1672
+ }
1673
+ return groups.filter((g) => g.rxa !== void 0).map((g) => ({ orc: g.orc, rxa: g.rxa, rxr: g.rxr }));
1674
+ }
1675
+ function buildStatus(rxa, issues) {
1676
+ const actionCode = rxa.field(21).value;
1677
+ if (actionCode === "D") return "entered-in-error";
1678
+ const completion = rxa.field(20).value;
1679
+ if (completion === "") return "completed";
1680
+ const mapped = Object.hasOwn(IMMUNIZATION_STATUS_MAP, completion) ? IMMUNIZATION_STATUS_MAP[completion] : void 0;
1681
+ if (mapped === void 0) {
1682
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "RXA.20", "Immunization.status"));
1683
+ }
1684
+ return mapped;
1685
+ }
1686
+ function translatedFrom(seg, index, map, ctx, issues) {
1687
+ if (seg.field(index).value === "") return void 0;
1688
+ const cc = toFhirCodeableConceptVia(seg.field(index).asCwe(), map, ctx);
1689
+ issues.push(...cc.issues);
1690
+ return cc.value;
1691
+ }
1692
+ function buildImmunization(rxa, rxr, orc, patientFullUrl, encounterFullUrl, ctx) {
1693
+ const issues = [];
1694
+ if (rxa.field(5).value === "") return { value: void 0, issues };
1695
+ const vaccineCode = toFhirCodeableConcept(rxa.field(5).asCwe(), ctx);
1696
+ issues.push(...vaccineCode.issues);
1697
+ if (vaccineCode.value === void 0) return { value: void 0, issues };
1698
+ const props = [
1699
+ { name: "resourceType", value: primitive("Immunization") }
1700
+ ];
1701
+ if (orc !== void 0) {
1702
+ const identifiers = [
1703
+ orderIdentifier(orc.field(2).value, "PLAC"),
1704
+ orderIdentifier(orc.field(3).value, "FILL")
1705
+ ].filter((i) => i !== void 0);
1706
+ if (identifiers.length > 0) props.push({ name: "identifier", value: list(identifiers) });
1707
+ }
1708
+ const status = buildStatus(rxa, issues);
1709
+ if (status !== void 0) props.push({ name: "status", value: primitive(status) });
1710
+ props.push({ name: "vaccineCode", value: vaccineCode.value });
1711
+ if (patientFullUrl !== void 0)
1712
+ props.push({ name: "patient", value: reference(patientFullUrl) });
1713
+ if (encounterFullUrl !== void 0)
1714
+ props.push({ name: "encounter", value: reference(encounterFullUrl) });
1715
+ if (rxa.field(3).value !== "") {
1716
+ const occurrence = toFhirDateTime(rxa.field(3).asTs(), ctx.options);
1717
+ issues.push(...occurrence.issues);
1718
+ if (occurrence.value !== void 0)
1719
+ props.push({ name: "occurrenceDateTime", value: primitive(occurrence.value) });
1720
+ }
1721
+ const recordedTs = rxa.field(22).value !== "" ? rxa.field(22).asTs() : orc !== void 0 && orc.field(9).value !== "" ? orc.field(9).asTs() : void 0;
1722
+ if (recordedTs !== void 0) {
1723
+ const recorded = toFhirDateTime(recordedTs, ctx.options);
1724
+ issues.push(...recorded.issues);
1725
+ if (recorded.value !== void 0)
1726
+ props.push({ name: "recorded", value: primitive(recorded.value) });
1727
+ }
1728
+ const doseRaw = rxa.field(6).asNm().raw;
1729
+ if (doseRaw !== "") {
1730
+ const dose = quantityFromRawMagnitude(
1731
+ doseRaw,
1732
+ rxa.field(7).asCwe(),
1733
+ ctx,
1734
+ void 0,
1735
+ "RXA.6",
1736
+ "RXA.7"
1737
+ );
1738
+ issues.push(...dose.issues);
1739
+ if (dose.value !== void 0) props.push({ name: "doseQuantity", value: dose.value });
1740
+ }
1741
+ if (rxa.field(15).value !== "")
1742
+ props.push({ name: "lotNumber", value: primitive(rxa.field(15).value) });
1743
+ if (rxa.field(16).value !== "") {
1744
+ const exp = toFhirDateTime(rxa.field(16).asTs(), ctx.options);
1745
+ issues.push(...exp.issues);
1746
+ if (exp.value !== void 0 && !exp.value.includes("T")) {
1747
+ props.push({ name: "expirationDate", value: primitive(exp.value) });
1748
+ } else if (exp.value !== void 0) {
1749
+ issues.push(
1750
+ issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "RXA.16", "Immunization.expirationDate")
1751
+ );
1752
+ }
1753
+ }
1754
+ if (rxa.field(18).value !== "") {
1755
+ const reason = toFhirCodeableConcept(rxa.field(18).asCwe(), ctx);
1756
+ issues.push(...reason.issues);
1757
+ if (reason.value !== void 0) props.push({ name: "statusReason", value: reason.value });
1758
+ }
1759
+ if (rxa.field(19).value !== "") {
1760
+ const indication = toFhirCodeableConcept(rxa.field(19).asCwe(), ctx);
1761
+ issues.push(...indication.issues);
1762
+ if (indication.value !== void 0)
1763
+ props.push({ name: "reasonCode", value: list([indication.value]) });
1764
+ }
1765
+ if (rxr !== void 0) {
1766
+ const route = translatedFrom(rxr, 1, ROUTE_VALUE_MAP, ctx, issues);
1767
+ if (route !== void 0) props.push({ name: "route", value: route });
1768
+ const site = translatedFrom(rxr, 2, SITE_VALUE_MAP, ctx, issues);
1769
+ if (site !== void 0) props.push({ name: "site", value: site });
1770
+ }
1771
+ return { value: complex(props), issues };
1772
+ }
1773
+ var STATUS_UNKNOWN = "unknown";
1774
+ var ORDER_INTENT = "order";
1775
+ var UNSIGNED_INT = /^(0|[1-9][0-9]*)$/;
1776
+ function codeableFrom(seg, index, ctx, issues) {
1777
+ if (seg.field(index).value === "") return void 0;
1778
+ const cc = toFhirCodeableConcept(seg.field(index).asCwe(), ctx);
1779
+ issues.push(...cc.issues);
1780
+ return cc.value;
1781
+ }
1782
+ function translatedFrom2(seg, index, map, ctx, issues) {
1783
+ if (seg.field(index).value === "") return void 0;
1784
+ const cc = toFhirCodeableConceptVia(seg.field(index).asCwe(), map, ctx);
1785
+ issues.push(...cc.issues);
1786
+ return cc.value;
1787
+ }
1788
+ function doseEndpoint(rxo, amountIndex, units, ctx, issues) {
1789
+ const raw = rxo.field(amountIndex).asNm().raw;
1790
+ if (raw === "") return void 0;
1791
+ const q = quantityFromRawMagnitude(
1792
+ raw,
1793
+ units,
1794
+ ctx,
1795
+ void 0,
1796
+ `RXO.${String(amountIndex)}`,
1797
+ "RXO.4"
1798
+ );
1799
+ issues.push(...q.issues);
1800
+ return q.value;
1801
+ }
1802
+ function buildDosageInstruction(rxo, rxr, ctx, issues) {
1803
+ const props = [];
1804
+ if (rxr !== void 0) {
1805
+ const route = translatedFrom2(rxr, 1, ROUTE_VALUE_MAP, ctx, issues);
1806
+ if (route !== void 0) props.push({ name: "route", value: route });
1807
+ const site = translatedFrom2(rxr, 2, SITE_VALUE_MAP, ctx, issues);
1808
+ if (site !== void 0) props.push({ name: "site", value: site });
1809
+ const method = codeableFrom(rxr, 4, ctx, issues);
1810
+ if (method !== void 0) props.push({ name: "method", value: method });
1811
+ }
1812
+ if (rxo !== void 0) {
1813
+ const units = rxo.field(4).asCwe();
1814
+ const low = doseEndpoint(rxo, 2, units, ctx, issues);
1815
+ const high = doseEndpoint(rxo, 3, units, ctx, issues);
1816
+ const rangeProps = [];
1817
+ if (low !== void 0) rangeProps.push({ name: "low", value: low });
1818
+ if (high !== void 0) rangeProps.push({ name: "high", value: high });
1819
+ if (rangeProps.length > 0) {
1820
+ props.push({
1821
+ name: "doseAndRate",
1822
+ value: list([complex([{ name: "doseRange", value: complex(rangeProps) }])])
1823
+ });
1824
+ }
1825
+ }
1826
+ return props.length === 0 ? void 0 : complex(props);
1827
+ }
1828
+ function buildDispenseRequest(rxo, ctx, issues) {
1829
+ const props = [];
1830
+ const amount = rxo.field(11).asNm().raw;
1831
+ if (amount !== "") {
1832
+ const q = quantityFromRawMagnitude(
1833
+ amount,
1834
+ rxo.field(12).asCwe(),
1835
+ ctx,
1836
+ void 0,
1837
+ "RXO.11",
1838
+ "RXO.12"
1839
+ );
1840
+ issues.push(...q.issues);
1841
+ if (q.value !== void 0) props.push({ name: "quantity", value: q.value });
1842
+ }
1843
+ const refills = rxo.field(13).value;
1844
+ if (refills !== "") {
1845
+ if (UNSIGNED_INT.test(refills)) {
1846
+ props.push({ name: "numberOfRepeatsAllowed", value: primitive(decimal(refills)) });
1847
+ } else {
1848
+ issues.push(
1849
+ issue(
1850
+ ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,
1851
+ "RXO.13",
1852
+ "dispenseRequest.numberOfRepeatsAllowed"
1853
+ )
1854
+ );
1855
+ }
1856
+ }
1857
+ return props.length === 0 ? void 0 : complex(props);
1858
+ }
1859
+ function buildMedicationRequest(rxo, rxr, orc, subjectFullUrl, encounterFullUrl, ctx) {
1860
+ const issues = [];
1861
+ if (rxo === void 0 || rxo.field(1).value === "") return { value: void 0, issues };
1862
+ const medication = toFhirCodeableConcept(rxo.field(1).asCwe(), ctx);
1863
+ issues.push(...medication.issues);
1864
+ if (medication.value === void 0) return { value: void 0, issues };
1865
+ const props = [
1866
+ { name: "resourceType", value: primitive("MedicationRequest") }
1867
+ ];
1868
+ props.push({ name: "status", value: primitive(STATUS_UNKNOWN) });
1869
+ issues.push(
1870
+ issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, "RXO", "MedicationRequest.status")
1871
+ );
1872
+ props.push({ name: "intent", value: primitive(ORDER_INTENT) });
1873
+ props.push({ name: "medicationCodeableConcept", value: medication.value });
1874
+ if (subjectFullUrl !== void 0)
1875
+ props.push({ name: "subject", value: reference(subjectFullUrl) });
1876
+ if (encounterFullUrl !== void 0)
1877
+ props.push({ name: "encounter", value: reference(encounterFullUrl) });
1878
+ if (orc !== void 0 && orc.field(1).value === "NW" && orc.field(9).value !== "") {
1879
+ const authored = toFhirDateTime(orc.field(9).asTs(), ctx.options);
1880
+ issues.push(...authored.issues);
1881
+ if (authored.value !== void 0)
1882
+ props.push({ name: "authoredOn", value: primitive(authored.value) });
1883
+ }
1884
+ const dosage = buildDosageInstruction(rxo, rxr, ctx, issues);
1885
+ if (dosage !== void 0) props.push({ name: "dosageInstruction", value: list([dosage]) });
1886
+ const dispense = buildDispenseRequest(rxo, ctx, issues);
1887
+ if (dispense !== void 0) props.push({ name: "dispenseRequest", value: dispense });
1888
+ const cwe9 = rxo.field(9).asCwe();
1889
+ if (cwe9.identifier !== void 0 && cwe9.identifier !== "") {
1890
+ const target = translateBound(cwe9, SUBSTITUTION_VALUE_MAP);
1891
+ if (target === void 0) {
1892
+ issues.push(
1893
+ issue(
1894
+ ISSUE_CODES.TRANSFORM_CODE_UNMAPPED,
1895
+ "RXO.9",
1896
+ "MedicationRequest.substitution.allowedCodeableConcept"
1897
+ )
1898
+ );
1899
+ } else {
1900
+ props.push({
1901
+ name: "substitution",
1902
+ value: complex([
1903
+ {
1904
+ name: "allowedCodeableConcept",
1905
+ value: codeableConceptFromTarget(target, cwe9.originalText)
1906
+ }
1907
+ ])
1908
+ });
1909
+ }
1910
+ }
1911
+ return { value: complex(props), issues };
1912
+ }
1913
+ var V2_0003_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0003";
1914
+ function buildMessageHeader(meta, focusFullUrls) {
1915
+ const issues = [];
1916
+ const props = [
1917
+ { name: "resourceType", value: primitive("MessageHeader") }
1918
+ ];
1919
+ const eventCoding = coding(V2_0003_SYSTEM, meta.triggerEvent);
1920
+ if (eventCoding !== void 0) {
1921
+ props.push({ name: "eventCoding", value: eventCoding });
1922
+ } else {
1923
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "MSH.9", "MessageHeader.eventCoding"));
1924
+ }
1925
+ const sourceProps = [];
1926
+ if (meta.sendingApp !== void 0 && meta.sendingApp !== "") {
1927
+ sourceProps.push({ name: "name", value: primitive(meta.sendingApp) });
1928
+ }
1929
+ sourceProps.push({ name: "endpoint", value: dataAbsent("unknown") });
1930
+ issues.push(
1931
+ issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, "MSH.3", "MessageHeader.source.endpoint")
1932
+ );
1933
+ props.push({ name: "source", value: complex(sourceProps) });
1934
+ if (focusFullUrls.length > 0) {
1935
+ props.push({ name: "focus", value: list(focusFullUrls.map((url) => reference(url))) });
1936
+ }
1937
+ return { value: complex(props), issues };
1938
+ }
1939
+ var V3_OBSERVATION_INTERPRETATION_SYSTEM = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation";
1940
+ var HL70078_INTERPRETATION_CODES = /* @__PURE__ */ new Set([
1941
+ "<",
1942
+ ">",
1943
+ "A",
1944
+ "AA",
1945
+ "B",
1946
+ "CAR",
1947
+ "D",
1948
+ "DET",
1949
+ "E",
1950
+ "EX",
1951
+ "EXP",
1952
+ "H",
1953
+ "HH",
1954
+ "HU",
1955
+ "I",
1956
+ "IE",
1957
+ "IND",
1958
+ "L",
1959
+ "LL",
1960
+ "LU",
1961
+ "MS",
1962
+ "N",
1963
+ "NCL",
1964
+ "ND",
1965
+ "NEG",
1966
+ "NR",
1967
+ "NS",
1968
+ "POS",
1969
+ "R",
1970
+ "RR",
1971
+ "S",
1972
+ "SDD",
1973
+ "SYN-R",
1974
+ "SYN-S",
1975
+ "U",
1976
+ "UNE",
1977
+ "VS",
1978
+ "W",
1979
+ "WR"
1980
+ ]);
1981
+ var OBSERVATION_STATUS_MAP = Object.freeze({
1982
+ A: "amended",
1983
+ C: "corrected",
1984
+ D: "entered-in-error",
1985
+ F: "final",
1986
+ P: "preliminary",
1987
+ W: "entered-in-error",
1988
+ X: "cancelled"
1989
+ });
1990
+ var SN_COMPARATORS = /* @__PURE__ */ new Set([">", "<", ">=", "<="]);
1991
+ var CODED_VALUE_TYPES = /* @__PURE__ */ new Set(["CWE", "CE", "CF", "CNE", "IS"]);
1992
+ var DATETIME_VALUE_TYPES = /* @__PURE__ */ new Set(["DT", "DTM", "TS"]);
1993
+ var STRING_VALUE_TYPES = /* @__PURE__ */ new Set(["ST", "TX", "FT"]);
1994
+ function rawComponent2(field, index) {
1995
+ const c = field.repetitions[0]?.components[index]?.subcomponents[0];
1996
+ return c === void 0 || c === "" ? void 0 : c;
1997
+ }
1998
+ function snText(field) {
1999
+ return [0, 1, 2, 3].map((i) => rawComponent2(field, i) ?? "").join("");
2000
+ }
2001
+ function valueStringProp(raw) {
2002
+ return { name: "valueString", value: primitive(raw) };
2003
+ }
2004
+ function endpointPair(field, units, ctx, issues) {
2005
+ const n1 = rawComponent2(field, 1);
2006
+ const n2 = rawComponent2(field, 3);
2007
+ if (n1 === void 0 || n2 === void 0) return void 0;
2008
+ const first = quantityFromRawMagnitude(n1, units, ctx);
2009
+ const second = quantityFromRawMagnitude(n2, units, ctx);
2010
+ issues.push(...first.issues, ...second.issues);
2011
+ if (first.value === void 0 || second.value === void 0) return void 0;
2012
+ return { first: first.value, second: second.value };
2013
+ }
2014
+ function buildSnValue(field, units, ctx, issues) {
2015
+ const sn = field.asSn();
2016
+ const separator = sn?.separatorOrSuffix;
2017
+ if (separator === "-") {
2018
+ const pair = endpointPair(field, units, ctx, issues);
2019
+ if (pair !== void 0) {
2020
+ return {
2021
+ name: "valueRange",
2022
+ value: complex([
2023
+ { name: "low", value: pair.first },
2024
+ { name: "high", value: pair.second }
2025
+ ])
2026
+ };
2027
+ }
2028
+ return valueStringProp(snText(field));
2029
+ }
2030
+ if (separator === ":" || separator === "/") {
2031
+ const pair = endpointPair(field, units, ctx, issues);
2032
+ if (pair !== void 0) {
2033
+ return {
2034
+ name: "valueRatio",
2035
+ value: complex([
2036
+ { name: "numerator", value: pair.first },
2037
+ { name: "denominator", value: pair.second }
2038
+ ])
2039
+ };
2040
+ }
2041
+ return valueStringProp(snText(field));
2042
+ }
2043
+ const comparator = sn?.comparator;
2044
+ const num1 = rawComponent2(field, 1);
2045
+ if (comparator !== "<>" && num1 !== void 0) {
2046
+ const fhirComparator = comparator !== void 0 && SN_COMPARATORS.has(comparator) ? comparator : void 0;
2047
+ const q = quantityFromRawMagnitude(num1, units, ctx, fhirComparator);
2048
+ issues.push(...q.issues);
2049
+ if (q.value !== void 0) return { name: "valueQuantity", value: q.value };
2050
+ }
2051
+ return valueStringProp(snText(field));
2052
+ }
2053
+ function buildValue(obx, valueType, ctx, issues) {
2054
+ const field = obx.field(5);
2055
+ const rawValue = field.value;
2056
+ const vt = valueType.toUpperCase();
2057
+ if (vt === "NM") {
2058
+ const q = quantityFromRawMagnitude(field.asNm().raw, obx.field(6).asCwe(), ctx);
2059
+ issues.push(...q.issues);
2060
+ if (q.value !== void 0) return { name: "valueQuantity", value: q.value };
2061
+ return rawValue === "" ? void 0 : valueStringProp(rawValue);
2062
+ }
2063
+ if (vt === "SN") {
2064
+ if (rawValue === "" && snText(field) === "") return void 0;
2065
+ return buildSnValue(field, obx.field(6).asCwe(), ctx, issues);
2066
+ }
2067
+ if (CODED_VALUE_TYPES.has(vt)) {
2068
+ const cc = toFhirCodeableConcept(field.asCwe(), ctx);
2069
+ issues.push(...cc.issues);
2070
+ return cc.value === void 0 ? void 0 : { name: "valueCodeableConcept", value: cc.value };
2071
+ }
2072
+ if (DATETIME_VALUE_TYPES.has(vt)) {
2073
+ if (rawValue === "") return void 0;
2074
+ const dt = toFhirDateTime(field.asTs(), ctx.options);
2075
+ issues.push(...dt.issues);
2076
+ return dt.value === void 0 ? void 0 : { name: "valueDateTime", value: primitive(dt.value) };
2077
+ }
2078
+ if (rawValue === "") return void 0;
2079
+ if (STRING_VALUE_TYPES.has(vt)) return valueStringProp(rawValue);
2080
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "OBX.5", "Observation.value[x]"));
2081
+ return valueStringProp(rawValue);
2082
+ }
2083
+ function buildInterpretation(obx, issues) {
2084
+ const flags = obx.field(8).repetitions.map((r) => r.components[0]?.subcomponents[0] ?? "").filter((f) => f !== "");
2085
+ const codings = [];
2086
+ for (const flag of flags) {
2087
+ if (HL70078_INTERPRETATION_CODES.has(flag)) {
2088
+ codings.push(
2089
+ complex([
2090
+ {
2091
+ name: "coding",
2092
+ value: list([
2093
+ complex([
2094
+ { name: "system", value: primitive(V3_OBSERVATION_INTERPRETATION_SYSTEM) },
2095
+ { name: "code", value: primitive(flag) }
2096
+ ])
2097
+ ])
2098
+ }
2099
+ ])
2100
+ );
2101
+ } else {
2102
+ issues.push(
2103
+ issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "OBX.8", "Observation.interpretation")
2104
+ );
2105
+ }
2106
+ }
2107
+ return codings.length === 0 ? void 0 : list(codings);
2108
+ }
2109
+ function buildObservation(obx, subjectFullUrl, encounterFullUrl, ctx) {
2110
+ const issues = [];
2111
+ const props = [
2112
+ { name: "resourceType", value: primitive("Observation") }
2113
+ ];
2114
+ const statusCode = obx.field(11).value;
2115
+ if (statusCode !== "") {
2116
+ const status = Object.hasOwn(OBSERVATION_STATUS_MAP, statusCode) ? OBSERVATION_STATUS_MAP[statusCode] : void 0;
2117
+ if (status === void 0) {
2118
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "OBX.11", "Observation.status"));
2119
+ } else {
2120
+ props.push({ name: "status", value: primitive(status) });
2121
+ }
2122
+ }
2123
+ const code = toFhirCodeableConcept(obx.field(3).asCwe(), ctx);
2124
+ issues.push(...code.issues);
2125
+ if (code.value === void 0) return { value: void 0, issues };
2126
+ props.push({ name: "code", value: code.value });
2127
+ if (subjectFullUrl !== void 0)
2128
+ props.push({ name: "subject", value: reference(subjectFullUrl) });
2129
+ if (encounterFullUrl !== void 0) {
2130
+ props.push({ name: "encounter", value: reference(encounterFullUrl) });
2131
+ }
2132
+ if (obx.field(14).value !== "") {
2133
+ const effective = toFhirDateTime(obx.field(14).asTs(), ctx.options);
2134
+ issues.push(...effective.issues);
2135
+ if (effective.value !== void 0) {
2136
+ props.push({ name: "effectiveDateTime", value: primitive(effective.value) });
2137
+ }
2138
+ }
2139
+ const value = buildValue(obx, obx.field(2).value, ctx, issues);
2140
+ if (value !== void 0) props.push(value);
2141
+ const interpretation = buildInterpretation(obx, issues);
2142
+ if (interpretation !== void 0) props.push({ name: "interpretation", value: interpretation });
2143
+ const refRange = obx.field(7).value;
2144
+ if (refRange !== "") {
2145
+ props.push({
2146
+ name: "referenceRange",
2147
+ value: list([complex([{ name: "text", value: primitive(refRange) }])])
2148
+ });
2149
+ }
2150
+ return { value: complex(props), issues };
2151
+ }
2152
+
2153
+ // src/messages/orders.ts
2154
+ function collectOrderGroups(msg) {
2155
+ const groups = [];
2156
+ let current;
2157
+ let rxeCount = 0;
2158
+ const open = () => {
2159
+ const g = { orc: void 0, obr: void 0, rxo: void 0, rxrs: [] };
2160
+ groups.push(g);
2161
+ current = g;
2162
+ return g;
2163
+ };
2164
+ for (const seg of msg.allSegments()) {
2165
+ switch (seg.type) {
2166
+ case "ORC":
2167
+ open().orc = seg;
2168
+ break;
2169
+ case "OBR":
2170
+ if (current === void 0 || current.obr !== void 0 || current.rxo !== void 0) open();
2171
+ current.obr = seg;
2172
+ break;
2173
+ case "RXO":
2174
+ if (current === void 0 || current.obr !== void 0 || current.rxo !== void 0) open();
2175
+ current.rxo = seg;
2176
+ break;
2177
+ case "RXR":
2178
+ if (current !== void 0) current.rxrs.push(seg);
2179
+ break;
2180
+ case "RXE":
2181
+ rxeCount += 1;
2182
+ break;
2183
+ }
2184
+ }
2185
+ return {
2186
+ groups: groups.map((g) => ({ orc: g.orc, obr: g.obr, rxo: g.rxo, rxrs: g.rxrs })),
2187
+ rxeCount
2188
+ };
2189
+ }
2190
+
2191
+ // src/messages/oru.ts
2192
+ function collectReportGroups(msg) {
2193
+ const groups = [];
2194
+ let current;
2195
+ let orphanObxCount = 0;
2196
+ for (const seg of msg.allSegments()) {
2197
+ if (seg.type === "OBR") {
2198
+ current = { obr: seg, observations: [] };
2199
+ groups.push(current);
2200
+ } else if (seg.type === "OBX") {
2201
+ if (current === void 0) orphanObxCount += 1;
2202
+ else current.observations.push(seg);
2203
+ }
2204
+ }
2205
+ return { groups, orphanObxCount };
2206
+ }
2207
+ var ADMINISTRATIVE_GENDER_MAP = Object.freeze({
2208
+ F: "female",
2209
+ M: "male",
2210
+ O: "other",
2211
+ U: "unknown",
2212
+ A: "other",
2213
+ N: "other"
2214
+ });
2215
+ function listOrUndefined(items) {
2216
+ return items.length === 0 ? void 0 : list(items);
2217
+ }
2218
+ function buildPatient(patient, ctx) {
2219
+ const issues = [];
2220
+ const props = [
2221
+ { name: "resourceType", value: primitive("Patient") }
2222
+ ];
2223
+ const identifiers = [];
2224
+ for (const cx of patient.identifiers) {
2225
+ const { value, issues: idIssues } = toFhirIdentifier(cx, ctx);
2226
+ issues.push(...idIssues);
2227
+ if (value !== void 0) identifiers.push(value);
2228
+ }
2229
+ const identifierList = listOrUndefined(identifiers);
2230
+ if (identifierList !== void 0) props.push({ name: "identifier", value: identifierList });
2231
+ const name = toFhirHumanName(patient.name);
2232
+ issues.push(...name.issues);
2233
+ if (name.value !== void 0) props.push({ name: "name", value: list([name.value]) });
2234
+ if (patient.sex !== void 0 && patient.sex !== "") {
2235
+ const gender = Object.hasOwn(ADMINISTRATIVE_GENDER_MAP, patient.sex) ? ADMINISTRATIVE_GENDER_MAP[patient.sex] : void 0;
2236
+ if (gender === void 0) {
2237
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "PID.8", "Patient.gender"));
2238
+ } else {
2239
+ props.push({ name: "gender", value: primitive(gender) });
2240
+ }
2241
+ }
2242
+ if (patient.dateOfBirth !== void 0) {
2243
+ const dob = toFhirDateTime(patient.dateOfBirth, ctx.options);
2244
+ issues.push(...dob.issues);
2245
+ if (dob.value !== void 0) {
2246
+ const tIndex = dob.value.indexOf("T");
2247
+ if (tIndex === -1) {
2248
+ props.push({ name: "birthDate", value: primitive(dob.value) });
2249
+ } else {
2250
+ props.push({ name: "birthDate", value: primitive(dob.value.slice(0, tIndex)) });
2251
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "PID.7", "Patient.birthDate"));
2252
+ }
2253
+ }
2254
+ }
2255
+ if (patient.address !== void 0) {
2256
+ const address = toFhirAddress(patient.address);
2257
+ issues.push(...address.issues);
2258
+ if (address.value !== void 0) props.push({ name: "address", value: list([address.value]) });
2259
+ }
2260
+ if (patient.phoneNumbers.length > 0) {
2261
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "PID.13", "Patient.telecom"));
2262
+ }
2263
+ if (props.length === 1) return { value: void 0, issues };
2264
+ return { value: complex(props), issues };
2265
+ }
2266
+ function buildRelatedPerson(nk1, patientFullUrl, ctx, setIndex) {
2267
+ const issues = [];
2268
+ const loc = `NK1[${String(setIndex)}]`;
2269
+ const props = [
2270
+ { name: "resourceType", value: primitive("RelatedPerson") },
2271
+ { name: "patient", value: reference(patientFullUrl) }
2272
+ ];
2273
+ let hasContent = false;
2274
+ if (nk1.relationship !== void 0) {
2275
+ const rel = toFhirCodeableConcept(nk1.relationship, ctx);
2276
+ issues.push(...rel.issues);
2277
+ if (rel.value !== void 0) {
2278
+ props.push({ name: "relationship", value: list([rel.value]) });
2279
+ hasContent = true;
2280
+ }
2281
+ }
2282
+ if (nk1.name !== void 0) {
2283
+ const name = toFhirHumanName(nk1.name);
2284
+ issues.push(...name.issues);
2285
+ if (name.value !== void 0) {
2286
+ props.push({ name: "name", value: list([name.value]) });
2287
+ hasContent = true;
2288
+ }
2289
+ }
2290
+ if (nk1.address !== void 0) {
2291
+ const address = toFhirAddress(nk1.address);
2292
+ issues.push(...address.issues);
2293
+ if (address.value !== void 0) {
2294
+ props.push({ name: "address", value: list([address.value]) });
2295
+ hasContent = true;
2296
+ }
2297
+ }
2298
+ if (nk1.phone !== void 0) {
2299
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `${loc}.5`, "RelatedPerson.telecom"));
2300
+ }
2301
+ if (!hasContent) return { value: void 0, issues };
2302
+ return { value: complex(props), issues };
2303
+ }
2304
+ var REQUEST_STATUS_MAP = Object.freeze({
2305
+ AF: "active",
2306
+ CA: "active",
2307
+ CR: "revoked",
2308
+ DC: "revoked",
2309
+ DF: "revoked",
2310
+ DR: "revoked",
2311
+ FU: "completed",
2312
+ HD: "active",
2313
+ HR: "on-hold",
2314
+ NW: "active",
2315
+ OC: "revoked",
2316
+ OD: "revoked",
2317
+ OH: "on-hold",
2318
+ OK: "active",
2319
+ PR: "active",
2320
+ PY: "active",
2321
+ RL: "active",
2322
+ RO: "active",
2323
+ RQ: "active"
2324
+ });
2325
+ var SERVICE_REQUEST_PRIORITY_MAP = Object.freeze({
2326
+ S: "stat",
2327
+ A: "asap",
2328
+ R: "routine"
2329
+ });
2330
+ var ORDER_INTENT2 = "order";
2331
+ function fieldValue(seg, index) {
2332
+ return seg === void 0 ? "" : seg.field(index).value;
2333
+ }
2334
+ function buildServiceRequest(orc, obr, subjectFullUrl, encounterFullUrl, ctx) {
2335
+ const issues = [];
2336
+ if (orc === void 0 && obr === void 0) return { value: void 0, issues };
2337
+ const props = [
2338
+ { name: "resourceType", value: primitive("ServiceRequest") }
2339
+ ];
2340
+ const orc1 = fieldValue(orc, 1);
2341
+ const orc5 = fieldValue(orc, 5);
2342
+ if (orc5 !== "") {
2343
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "ORC.5", "ServiceRequest.status"));
2344
+ } else if (orc1 !== "") {
2345
+ const status = Object.hasOwn(REQUEST_STATUS_MAP, orc1) ? REQUEST_STATUS_MAP[orc1] : void 0;
2346
+ if (status === void 0) {
2347
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "ORC.1", "ServiceRequest.status"));
2348
+ } else {
2349
+ props.push({ name: "status", value: primitive(status) });
2350
+ }
2351
+ }
2352
+ props.push({ name: "intent", value: primitive(ORDER_INTENT2) });
2353
+ const placer = fieldValue(obr, 2) !== "" ? fieldValue(obr, 2) : fieldValue(orc, 2);
2354
+ const filler = fieldValue(obr, 3) !== "" ? fieldValue(obr, 3) : fieldValue(orc, 3);
2355
+ const identifiers = [orderIdentifier(placer, "PLAC"), orderIdentifier(filler, "FILL")].filter(
2356
+ (i) => i !== void 0
2357
+ );
2358
+ if (identifiers.length > 0) props.push({ name: "identifier", value: list(identifiers) });
2359
+ if (obr !== void 0 && obr.field(4).value !== "") {
2360
+ const code = toFhirCodeableConcept(obr.field(4).asCwe(), ctx);
2361
+ issues.push(...code.issues);
2362
+ if (code.value !== void 0) props.push({ name: "code", value: code.value });
2363
+ }
2364
+ const obr5cwe = obr?.field(5).asCwe();
2365
+ const obr5 = obr5cwe?.identifier ?? "";
2366
+ if (obr5 !== "") {
2367
+ const mnemonic = obr5cwe?.nameOfCodingSystem;
2368
+ const fromTable = mnemonic === void 0 || mnemonic === "" || mnemonic === "HL70485" || mnemonic === "0485";
2369
+ const priority = fromTable && Object.hasOwn(SERVICE_REQUEST_PRIORITY_MAP, obr5) ? SERVICE_REQUEST_PRIORITY_MAP[obr5] : void 0;
2370
+ if (priority === void 0) {
2371
+ issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, "OBR.5", "ServiceRequest.priority"));
2372
+ } else {
2373
+ props.push({ name: "priority", value: primitive(priority) });
2374
+ }
2375
+ }
2376
+ if (subjectFullUrl !== void 0)
2377
+ props.push({ name: "subject", value: reference(subjectFullUrl) });
2378
+ if (encounterFullUrl !== void 0)
2379
+ props.push({ name: "encounter", value: reference(encounterFullUrl) });
2380
+ if (orc1 === "NW" && fieldValue(orc, 9) !== "" && orc !== void 0) {
2381
+ const authored = toFhirDateTime(orc.field(9).asTs(), ctx.options);
2382
+ issues.push(...authored.issues);
2383
+ if (authored.value !== void 0)
2384
+ props.push({ name: "authoredOn", value: primitive(authored.value) });
2385
+ }
2386
+ if (obr !== void 0 && obr.field(6).value !== "") {
2387
+ const occurrence = toFhirDateTime(obr.field(6).asTs(), ctx.options);
2388
+ issues.push(...occurrence.issues);
2389
+ if (occurrence.value !== void 0)
2390
+ props.push({ name: "occurrenceDateTime", value: primitive(occurrence.value) });
2391
+ }
2392
+ if (obr !== void 0 && obr.field(31).value !== "") {
2393
+ const reason = toFhirCodeableConcept(obr.field(31).asCwe(), ctx);
2394
+ issues.push(...reason.issues);
2395
+ if (reason.value !== void 0) props.push({ name: "reasonCode", value: list([reason.value]) });
2396
+ }
2397
+ return { value: complex(props), issues };
2398
+ }
2399
+
2400
+ // src/messages/to-fhir.ts
2401
+ var IG_MAPPED_ADT_TRIGGERS = /* @__PURE__ */ new Set([
2402
+ "A01",
2403
+ "A02",
2404
+ "A05",
2405
+ "A06",
2406
+ "A09",
2407
+ "A11",
2408
+ "A17"
2409
+ ]);
2410
+ var IG_MAPPED_ORU_TRIGGERS = /* @__PURE__ */ new Set(["R01"]);
2411
+ var IG_MAPPED_ORDER_TRIGGERS = /* @__PURE__ */ new Set(["ORM^O01", "OML^O21"]);
2412
+ var IG_MAPPED_IMMUNIZATION_TRIGGERS = /* @__PURE__ */ new Set(["V04"]);
2413
+ var IG_MAPPED_APPOINTMENT_TRIGGERS = /* @__PURE__ */ new Set(["S12"]);
2414
+ var IG_MAPPED_DOCUMENT_TRIGGERS = /* @__PURE__ */ new Set(["T02"]);
2415
+ function passesEmitGate(resource, v2Location, fhirPath, issues) {
2416
+ const result = resourceType(resource) === "Patient" ? validateResource(resource, { mode: "strict" }) : validateResource(resource, { mode: "lenient", schemas: EMIT_SCHEMAS });
2417
+ if (result.valid) return true;
2418
+ issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_INVALID, v2Location, fhirPath));
2419
+ return false;
2420
+ }
2421
+ function buildBundle(msg, entries, ctx, issues) {
2422
+ const props = [
2423
+ { name: "resourceType", value: primitive("Bundle") }
2424
+ ];
2425
+ const controlId = msg.meta.controlId;
2426
+ if (controlId !== void 0 && controlId !== "") {
2427
+ props.push({
2428
+ name: "identifier",
2429
+ value: complex([{ name: "value", value: primitive(controlId) }])
2430
+ });
2431
+ }
2432
+ props.push({ name: "type", value: primitive("message") });
2433
+ if (msg.meta.timestamp !== void 0) {
2434
+ const ts = toFhirDateTime(msg.meta.timestamp, ctx.options);
2435
+ issues.push(...ts.issues);
2436
+ if (ts.value !== void 0 && ts.value.includes("T")) {
2437
+ props.push({ name: "timestamp", value: primitive(ts.value) });
2438
+ } else if (ts.value !== void 0) {
2439
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "MSH.7", "Bundle.timestamp"));
2440
+ }
2441
+ }
2442
+ const entryNodes = entries.map(
2443
+ (e) => complex([
2444
+ { name: "fullUrl", value: primitive(e.fullUrl) },
2445
+ { name: "resource", value: e.resource }
2446
+ ])
2447
+ );
2448
+ if (entryNodes.length > 0) props.push({ name: "entry", value: list(entryNodes) });
2449
+ return complex(props);
2450
+ }
2451
+ function toFhir(msg, opts = {}) {
2452
+ const issues = [];
2453
+ const namingSystem = opts.namingSystem ?? createNamingSystem();
2454
+ const ctx = { namingSystem, options: opts };
2455
+ const ids = new IdAllocator(opts);
2456
+ const code = msg.meta.messageCode;
2457
+ const trigger = msg.meta.triggerEvent;
2458
+ const messageMapGrounded = trigger !== void 0 && (code === "ADT" && IG_MAPPED_ADT_TRIGGERS.has(trigger) || code === "ORU" && IG_MAPPED_ORU_TRIGGERS.has(trigger) || code === "VXU" && IG_MAPPED_IMMUNIZATION_TRIGGERS.has(trigger) || code === "SIU" && IG_MAPPED_APPOINTMENT_TRIGGERS.has(trigger) || code === "MDM" && IG_MAPPED_DOCUMENT_TRIGGERS.has(trigger) || IG_MAPPED_ORDER_TRIGGERS.has(`${code ?? ""}^${trigger}`));
2459
+ if (!messageMapGrounded) {
2460
+ issues.push(issue(ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED, "MSH.9"));
2461
+ }
2462
+ const focalEntries = [];
2463
+ let patientFullUrl;
2464
+ const patientView = msg.patient;
2465
+ if (patientView !== void 0) {
2466
+ const built = buildPatient(patientView, ctx);
2467
+ issues.push(...built.issues);
2468
+ if (built.value !== void 0 && passesEmitGate(built.value, "PID", "Patient", issues)) {
2469
+ patientFullUrl = ids.next();
2470
+ focalEntries.push({ fullUrl: patientFullUrl, resource: built.value });
2471
+ }
2472
+ }
2473
+ let encounterFullUrl;
2474
+ const visitView = msg.visit;
2475
+ if (visitView !== void 0) {
2476
+ const built = buildEncounter(visitView, patientFullUrl, ctx);
2477
+ issues.push(...built.issues);
2478
+ if (built.value !== void 0 && passesEmitGate(built.value, "PV1", "Encounter", issues)) {
2479
+ encounterFullUrl = ids.next();
2480
+ focalEntries.push({ fullUrl: encounterFullUrl, resource: built.value });
2481
+ }
2482
+ }
2483
+ const nextOfKin = msg.nextOfKin();
2484
+ if (patientFullUrl !== void 0) {
2485
+ for (let i = 0; i < nextOfKin.length; i++) {
2486
+ const nk1 = nextOfKin[i];
2487
+ if (nk1 === void 0) continue;
2488
+ const built = buildRelatedPerson(nk1, patientFullUrl, ctx, i);
2489
+ issues.push(...built.issues);
2490
+ if (built.value !== void 0 && passesEmitGate(built.value, `NK1[${String(i)}]`, "RelatedPerson", issues)) {
2491
+ focalEntries.push({ fullUrl: ids.next(), resource: built.value });
2492
+ }
2493
+ }
2494
+ } else if (nextOfKin.length > 0) {
2495
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "NK1", "RelatedPerson.patient"));
2496
+ }
2497
+ const diagnosticReportFullUrls = [];
2498
+ if (code === "ORU") {
2499
+ const { groups, orphanObxCount } = collectReportGroups(msg);
2500
+ if (orphanObxCount > 0) {
2501
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "OBX", "DiagnosticReport.result"));
2502
+ }
2503
+ for (const group of groups) {
2504
+ const resultFullUrls = [];
2505
+ const observationEntries = [];
2506
+ for (let i = 0; i < group.observations.length; i++) {
2507
+ const obx = group.observations[i];
2508
+ if (obx === void 0) continue;
2509
+ const built = buildObservation(obx, patientFullUrl, encounterFullUrl, ctx);
2510
+ issues.push(...built.issues);
2511
+ if (built.value !== void 0 && passesEmitGate(built.value, `OBX[${String(i)}]`, "Observation", issues)) {
2512
+ const url = ids.next();
2513
+ resultFullUrls.push(url);
2514
+ observationEntries.push({ fullUrl: url, resource: built.value });
2515
+ }
2516
+ }
2517
+ const report = buildDiagnosticReport(
2518
+ group.obr,
2519
+ resultFullUrls,
2520
+ patientFullUrl,
2521
+ encounterFullUrl,
2522
+ ctx
2523
+ );
2524
+ issues.push(...report.issues);
2525
+ if (report.value !== void 0 && passesEmitGate(report.value, "OBR", "DiagnosticReport", issues)) {
2526
+ const reportUrl = ids.next();
2527
+ diagnosticReportFullUrls.push(reportUrl);
2528
+ focalEntries.push({ fullUrl: reportUrl, resource: report.value });
2529
+ }
2530
+ focalEntries.push(...observationEntries);
2531
+ }
2532
+ }
2533
+ const orderResourceFullUrls = [];
2534
+ if (code !== "ORU" && code !== "VXU" && code !== "SIU" && code !== "MDM") {
2535
+ const { groups, rxeCount } = collectOrderGroups(msg);
2536
+ if (rxeCount > 0) {
2537
+ issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, "RXE", "MedicationRequest"));
2538
+ }
2539
+ for (const group of groups) {
2540
+ if (group.obr !== void 0 || group.orc !== void 0 && group.rxo === void 0) {
2541
+ const built = buildServiceRequest(
2542
+ group.orc,
2543
+ group.obr,
2544
+ patientFullUrl,
2545
+ encounterFullUrl,
2546
+ ctx
2547
+ );
2548
+ issues.push(...built.issues);
2549
+ const loc = group.orc !== void 0 ? "ORC" : "OBR";
2550
+ if (built.value !== void 0 && passesEmitGate(built.value, loc, "ServiceRequest", issues)) {
2551
+ const url = ids.next();
2552
+ orderResourceFullUrls.push(url);
2553
+ focalEntries.push({ fullUrl: url, resource: built.value });
2554
+ }
2555
+ }
2556
+ if (group.rxo !== void 0) {
2557
+ const built = buildMedicationRequest(
2558
+ group.rxo,
2559
+ group.rxrs[0],
2560
+ group.orc,
2561
+ patientFullUrl,
2562
+ encounterFullUrl,
2563
+ ctx
2564
+ );
2565
+ issues.push(...built.issues);
2566
+ if (built.value !== void 0 && passesEmitGate(built.value, "RXO", "MedicationRequest", issues)) {
2567
+ const url = ids.next();
2568
+ orderResourceFullUrls.push(url);
2569
+ focalEntries.push({ fullUrl: url, resource: built.value });
2570
+ }
2571
+ }
2572
+ }
2573
+ }
2574
+ const immunizationFullUrls = [];
2575
+ if (code === "VXU") {
2576
+ for (const group of collectImmunizationGroups(msg)) {
2577
+ const built = buildImmunization(
2578
+ group.rxa,
2579
+ group.rxr,
2580
+ group.orc,
2581
+ patientFullUrl,
2582
+ encounterFullUrl,
2583
+ ctx
2584
+ );
2585
+ issues.push(...built.issues);
2586
+ if (built.value !== void 0 && passesEmitGate(built.value, "RXA", "Immunization", issues)) {
2587
+ const url = ids.next();
2588
+ immunizationFullUrls.push(url);
2589
+ focalEntries.push({ fullUrl: url, resource: built.value });
2590
+ }
2591
+ }
2592
+ for (const seg of msg.allSegments()) {
2593
+ if (seg.type !== "OBX") continue;
2594
+ const built = buildObservation(seg, patientFullUrl, encounterFullUrl, ctx);
2595
+ issues.push(...built.issues);
2596
+ if (built.value !== void 0 && passesEmitGate(built.value, "OBX", "Observation", issues)) {
2597
+ focalEntries.push({ fullUrl: ids.next(), resource: built.value });
2598
+ }
2599
+ }
2600
+ }
2601
+ const appointmentFullUrls = [];
2602
+ if (code === "SIU") {
2603
+ const { sch, ais } = collectAppointment(msg);
2604
+ if (sch !== void 0) {
2605
+ const built = buildAppointment(sch, ais, patientFullUrl, ctx);
2606
+ issues.push(...built.issues);
2607
+ if (built.value !== void 0 && passesEmitGate(built.value, "SCH", "Appointment", issues)) {
2608
+ const url = ids.next();
2609
+ appointmentFullUrls.push(url);
2610
+ focalEntries.push({ fullUrl: url, resource: built.value });
2611
+ }
2612
+ }
2613
+ }
2614
+ const documentFullUrls = [];
2615
+ if (code === "MDM") {
2616
+ const { txa, obxs } = collectDocument(msg);
2617
+ if (txa !== void 0) {
2618
+ const built = buildDocumentReference(txa, obxs, patientFullUrl, ctx);
2619
+ issues.push(...built.issues);
2620
+ if (built.value !== void 0 && passesEmitGate(built.value, "TXA", "DocumentReference", issues)) {
2621
+ const url = ids.next();
2622
+ documentFullUrls.push(url);
2623
+ focalEntries.push({ fullUrl: url, resource: built.value });
2624
+ }
2625
+ }
2626
+ }
2627
+ const focus = [
2628
+ patientFullUrl,
2629
+ encounterFullUrl,
2630
+ ...diagnosticReportFullUrls,
2631
+ ...orderResourceFullUrls,
2632
+ ...immunizationFullUrls,
2633
+ ...appointmentFullUrls,
2634
+ ...documentFullUrls
2635
+ ].filter((u) => u !== void 0);
2636
+ const header = buildMessageHeader(msg.meta, focus);
2637
+ issues.push(...header.issues);
2638
+ const entries = [];
2639
+ if (header.value !== void 0 && passesEmitGate(header.value, "MSH", "MessageHeader", issues)) {
2640
+ entries.push({ fullUrl: ids.next(), resource: header.value });
2641
+ }
2642
+ entries.push(...focalEntries);
2643
+ const bundle = buildBundle(msg, entries, ctx, issues);
2644
+ return { bundle, issues };
2645
+ }
2646
+
2647
+ // src/index.ts
2648
+ var VERSION = "0.0.0";
2649
+
2650
+ export { ADDRESS_TYPE_MAP, ADDRESS_USE_MAP, ADMINISTRATIVE_GENDER_MAP, APPOINTMENT_STATUS_MAP, APPOINTMENT_TYPE_VALUE_MAP, DEFAULT_V2_CODE_SYSTEMS, DIAGNOSTIC_REPORT_STATUS_MAP, ENCOUNTER_CLASS_V3_MAP, ENCOUNTER_STATUS_MAP, FATAL_CODES, HL70078_INTERPRETATION_CODES, IG_MAPPED_ADT_TRIGGERS, IG_MAPPED_APPOINTMENT_TRIGGERS, IG_MAPPED_DOCUMENT_TRIGGERS, IG_MAPPED_IMMUNIZATION_TRIGGERS, IG_MAPPED_ORDER_TRIGGERS, IG_MAPPED_ORU_TRIGGERS, IMMUNIZATION_STATUS_MAP, ISSUE_CODES, ISSUE_REGISTRY, NAME_USE_MAP, OBSERVATION_STATUS_MAP, REQUEST_STATUS_MAP, ROUTE_VALUE_MAP, SERVICE_REQUEST_PRIORITY_MAP, SITE_VALUE_MAP, SUBSTITUTION_VALUE_MAP, TRANSFORM_ISSUE_SYSTEM, V2_0161_SYSTEM, V2_0162_SYSTEM, V2_0203_SYSTEM, V2_0277_SYSTEM, V2_0550_SYSTEM, V3_ROUTE_OF_ADMINISTRATION_SYSTEM, VERSION, codeableConceptFromTarget, createNamingSystem, fhirIssueTypeFor, issue, toFhir, toFhirAddress, toFhirCodeableConcept, toFhirCodeableConceptVia, toFhirDateTime, toFhirHumanName, toFhirIdentifier, toFhirQuantity, toOperationOutcome, translateBound };
2651
+ //# sourceMappingURL=index.mjs.map
2652
+ //# sourceMappingURL=index.mjs.map