@dcmjs-org/fhir 0.0.0-stage → 1.0.0-beta.4

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/License.txt ADDED
@@ -0,0 +1,22 @@
1
+
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2017 Steve Pieper
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @dcmjs-org/fhir
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Status: preliminary.** The API of this package can change in a minor
4
+ > release while this notice is here. Such a change is not a breaking change for
5
+ > semantic versioning; the release notes name it. Pin an exact version if you
6
+ > depend on the current shape.
7
+
8
+ DICOM to FHIR R4/R4B mapping for naturalized dcmjs datasets, and the reverse
9
+ mapping of patient demographics.
10
+
11
+ - `toFhir(dataset, options)` — `{ patient, imagingStudy, documentReference }`
12
+ for one instance.
13
+ - `toBundle(datasets, options)` — a `collection` Bundle: one Patient, a
14
+ DocumentReference for each encapsulated document, and one ImagingStudy
15
+ for the images.
16
+ - `patientFromDataset`, `imagingStudyFromDatasets`,
17
+ `documentReferenceFromDataset` — the single mappers.
18
+ - `patientToDataset(patient)` — a FHIR Patient to the DICOM patient-module
19
+ attributes (`PatientName`, `PatientID`, `PatientBirthDate`, `PatientSex`).
20
+
21
+ The wrapper `@dcmjs-org/dcmjs` does not depend on this package. An
22
+ event stream gives the naturalized dataset for `toFhir`:
23
+
24
+ ```js
25
+ import { toFhir } from "@dcmjs-org/fhir";
26
+
27
+ const { patient, imagingStudy } = toFhir(await events.toNaturalized());
28
+ ```
29
+
30
+ ## Scope and change rule
31
+
32
+ This README holds the requirements of `@dcmjs-org/fhir`.
33
+
34
+ An earlier beta had `DicomEventStream.fromFhir()` and `toFhir()` in the
35
+ wrapper. The 1.0 wrapper removed them, because the FHIR mapping is
36
+ preliminary. FHIR-USR-7, FHIR-USR-8, FHIR-USR-9, FHIR-IMP-3, and FHIR-IMP-4
37
+ held the requirements of `fromFhir`. These identifiers are withdrawn, and
38
+ the git history keeps the old text and the old code.
39
+
40
+ While the status is preliminary, a user requirement (FHIR-USR-n) can change
41
+ in a minor release. After that, change a user requirement only when it
42
+ describes the behaviour wrongly, or when the intended user-facing behaviour
43
+ changes, and name the change in the pull request. The implementation
44
+ requirements (FHIR-IMP-n) describe the current approach, and can change
45
+ freely. Do not renumber an identifier.
46
+
47
+ ## § User requirements
48
+
49
+ - **FHIR-USR-1** The output is standard FHIR R4/R4B only, with no profile
50
+ extensions: no resource `id`, no `meta.tags`, and no storage references.
51
+ The consumer assigns these. An unsupported `fhirVersion` throws an
52
+ error. The relative references of FHIR-USR-10 are the one exception.
53
+ - **FHIR-USR-2** `toFhir` maps an encapsulated document to a
54
+ DocumentReference and no ImagingStudy, and an image to an ImagingStudy
55
+ and no DocumentReference.
56
+ - **FHIR-USR-3** The mapper never fabricates a value that DICOM does not
57
+ give, and never mixes two patients or two studies.
58
+ - It skips, with a `validationLog` warning: an instance with no
59
+ SOPClassUID; a dataset with no SeriesInstanceUID or no Modality; a
60
+ dataset of another study than the first. `toBundle` also skips a
61
+ dataset with another PatientID than the Patient of the Bundle.
62
+ - `Patient.gender` comes from the administrative `PatientSex`. The
63
+ Patient gets no birth-sex or clinical-sex extension.
64
+ - A number (`series.number`, `instance.number`, `numberOfFrames`) is
65
+ written only for a non-negative integer.
66
+ - `BodyPartExamined` is a display with no code system. `Laterality`
67
+ L, R, and B are SNOMED CT codes (CID 244); another value is a
68
+ display with no code system.
69
+ - **FHIR-USR-4** A FHIR `dateTime` gets a time only when the dataset has
70
+ `TimezoneOffsetFromUTC (0008,0201)`; otherwise it is the date only.
71
+ `DocumentReference.date` (an `instant`) is written only with the date,
72
+ the time, and the timezone. The date must be `YYYYMMDD` (or the legacy
73
+ `YYYY.MM.DD`), else there is no date; a time that is not `HHMMSS` (or the
74
+ legacy `HH:MM:SS`) gives the date only.
75
+ - **FHIR-USR-5** The DocumentReference attachment holds the document bytes
76
+ exactly: `EncapsulatedDocumentLength (0042,0015)` gives the length when
77
+ present, and each naturalized payload shape (including
78
+ `{ InlineBinary }`) gives the same bytes. A `{ BulkDataURI }` payload
79
+ gives `attachment.url`, and no `size` or `data`.
80
+ - **FHIR-USR-6** `patientToDataset` writes all four attributes, with an
81
+ empty string for an absent value. A text-only HumanName becomes a
82
+ single-component PN. A partial FHIR `birthDate` becomes empty, and never
83
+ a fabricated day.
84
+ - **FHIR-USR-7**, **FHIR-USR-8**, **FHIR-USR-9** Withdrawn (see the
85
+ scope section).
86
+ - **FHIR-USR-10** The output links its resources without server ids.
87
+ Without `options.subject`, `toFhir` gives the ImagingStudy or the
88
+ DocumentReference `subject: { reference: "./patient" }`, a path relative
89
+ to the returned object. `toBundle` gives each entry
90
+ `fullUrl: "./entry/<index>"`, and the ImagingStudy and the
91
+ DocumentReferences reference the Patient entry by its `fullUrl`. These
92
+ relative references are not FHIR server references; the consumer
93
+ replaces them when it stores the resources.
94
+
95
+ ## § Implementation requirements
96
+
97
+ - **FHIR-IMP-1** The package depends at run time only on `@dcmjs-org/core`
98
+ and `@dcmjs-org/encapsulated`; the tests can use `@dcmjs-org/parser` and
99
+ `@dcmjs-org/legacy`.
100
+ - **FHIR-IMP-2** The document bytes come from `extractEncapsulated` of
101
+ `@dcmjs-org/encapsulated`. The value readers (`toStringFirst`,
102
+ `toFloatFirst`), `encodeBase64`, and `MODALITY_DISPLAY` come from
103
+ `@dcmjs-org/core`.
104
+ - **FHIR-IMP-3**, **FHIR-IMP-4** Withdrawn (see the scope section).
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@dcmjs-org/fhir",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-beta.4",
4
+ "description": "DICOM ↔ FHIR R4B mapping for Patient, ImagingStudy and DocumentReference resources from naturalized dcmjs datasets",
5
+ "main": "./src/index.js",
6
+ "files": [
7
+ "src",
8
+ "README.md"
9
+ ],
10
+ "license": "MIT",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/dcmjs-org/dcmjs.git",
14
+ "directory": "packages/fhir"
15
+ },
16
+ "dependencies": {
17
+ "@dcmjs-org/core": "1.0.0-beta.4",
18
+ "@dcmjs-org/encapsulated": "1.0.0-beta.4"
19
+ },
20
+ "devDependencies": {
21
+ "@dcmjs-org/legacy": "1.0.0-beta.4",
22
+ "@dcmjs-org/parser": "1.0.0-beta.4"
23
+ }
6
24
  }
@@ -0,0 +1,169 @@
1
+ // packages/fhir/src/documentReference.js
2
+ //
3
+ // FHIR R4B DocumentReference from a DICOM Encapsulated Document instance
4
+ // (Encapsulated PDF, SOP Class 1.2.840.10008.5.1.4.1.1.104.1) — the "PDF
5
+ // arrived via DICOM" mapping. Emits standard FHIR only — no ids, no
6
+ // meta.tags; id assignment is the consumer's job (same contract as
7
+ // patient.js / imagingStudy.js).
8
+ //
9
+ // DocumentReference.date is a FHIR instant, so it is written only when the
10
+ // dataset has ContentDate, ContentTime, and TimezoneOffsetFromUTC.
11
+
12
+ import { encodeBase64, toStringFirst } from "@dcmjs-org/core";
13
+ import {
14
+ extractEncapsulated,
15
+ ENCAPSULATED_PDF_SOP_CLASS_UID,
16
+ PDF_MIME_TYPE
17
+ } from "@dcmjs-org/encapsulated";
18
+ import {
19
+ dicomDateTimeToInstant,
20
+ uidToUrn,
21
+ DICOM_UID_SYSTEM
22
+ } from "./helpers.js";
23
+
24
+ const CODING_SCHEME_SYSTEMS = {
25
+ LN: "http://loinc.org",
26
+ DCM: "http://dicom.nema.org/resources/ontology/DCM",
27
+ SCT: "http://snomed.info/sct",
28
+ SRT: "http://snomed.info/sct"
29
+ };
30
+
31
+ /**
32
+ * Naturalized ConceptNameCodeSequence (item object, array of items, or
33
+ * addAccessors proxy) → FHIR CodeableConcept, or null.
34
+ */
35
+ function conceptNameToCodeableConcept(conceptName) {
36
+ let item = conceptName;
37
+ if (Array.isArray(item)) {
38
+ item = item.length > 0 ? item[0] : null;
39
+ }
40
+ if (!item || typeof item !== "object") {
41
+ return null;
42
+ }
43
+
44
+ const code = toStringFirst(item.CodeValue);
45
+ const meaning = toStringFirst(item.CodeMeaning);
46
+ if (!code && !meaning) {
47
+ return null;
48
+ }
49
+
50
+ const codeableConcept = {};
51
+ if (code) {
52
+ const designator = toStringFirst(item.CodingSchemeDesignator);
53
+ const coding = { code };
54
+ if (designator) {
55
+ coding.system = CODING_SCHEME_SYSTEMS[designator] || designator;
56
+ }
57
+ if (meaning) {
58
+ coding.display = meaning;
59
+ }
60
+ codeableConcept.coding = [coding];
61
+ }
62
+ if (meaning) {
63
+ codeableConcept.text = meaning;
64
+ }
65
+ return codeableConcept;
66
+ }
67
+
68
+ /** The BulkDataURI of a naturalized `{ BulkDataURI }` payload, or null. */
69
+ function bulkDataUriOf(payload) {
70
+ const value = Array.isArray(payload) ? payload[0] : payload;
71
+ return toStringFirst(value?.BulkDataURI);
72
+ }
73
+
74
+ /**
75
+ * Build a FHIR DocumentReference from a naturalized Encapsulated Document
76
+ * dataset.
77
+ * @param {Object} dataset - DicomMetaDictionary.naturalizeDataset output
78
+ * @param {Object} [options]
79
+ * @param {Object} [options.subject] - FHIR Reference for .subject
80
+ * @param {boolean} [options.includeData=true] - inline the document as
81
+ * base64 in content[0].attachment.data (size is always emitted)
82
+ * @returns {Object|null} FHIR DocumentReference, or null when the dataset
83
+ * is not an encapsulated document instance
84
+ */
85
+ export function documentReferenceFromDataset(dataset, options = {}) {
86
+ if (!dataset) {
87
+ return null;
88
+ }
89
+
90
+ const mimeType = toStringFirst(dataset.MIMETypeOfEncapsulatedDocument);
91
+ const sopClassUid = toStringFirst(dataset.SOPClassUID);
92
+ const isEncapsulated =
93
+ mimeType !== null || sopClassUid === ENCAPSULATED_PDF_SOP_CLASS_UID;
94
+ if (!isEncapsulated || dataset.EncapsulatedDocument === undefined) {
95
+ return null;
96
+ }
97
+
98
+ const includeData = options.includeData !== false;
99
+ const documentReference = {
100
+ resourceType: "DocumentReference",
101
+ status: "current"
102
+ };
103
+
104
+ const sopInstanceUrn = uidToUrn(dataset.SOPInstanceUID);
105
+ if (sopInstanceUrn) {
106
+ documentReference.masterIdentifier = {
107
+ system: DICOM_UID_SYSTEM,
108
+ value: sopInstanceUrn
109
+ };
110
+ }
111
+
112
+ const type = conceptNameToCodeableConcept(dataset.ConceptNameCodeSequence);
113
+ if (type) {
114
+ documentReference.type = type;
115
+ }
116
+
117
+ if (options.subject) {
118
+ documentReference.subject = options.subject;
119
+ }
120
+
121
+ const date = dicomDateTimeToInstant(
122
+ dataset.ContentDate,
123
+ dataset.ContentTime,
124
+ dataset.TimezoneOffsetFromUTC
125
+ );
126
+ if (date) {
127
+ documentReference.date = date;
128
+ }
129
+
130
+ const title = toStringFirst(dataset.DocumentTitle);
131
+ if (title) {
132
+ documentReference.description = title;
133
+ }
134
+
135
+ const attachment = {
136
+ contentType: mimeType || PDF_MIME_TYPE
137
+ };
138
+ if (title) {
139
+ attachment.title = title;
140
+ }
141
+ const bytes = extractEncapsulated(dataset);
142
+ const bulkDataUri = bulkDataUriOf(dataset.EncapsulatedDocument);
143
+ if (bytes) {
144
+ attachment.size = bytes.byteLength;
145
+ // FHIR does not permit an empty string value.
146
+ if (includeData && bytes.byteLength > 0) {
147
+ attachment.data = encodeBase64(bytes);
148
+ }
149
+ } else if (bulkDataUri) {
150
+ attachment.url = bulkDataUri;
151
+ }
152
+ documentReference.content = [{ attachment }];
153
+
154
+ const studyUrn = uidToUrn(dataset.StudyInstanceUID);
155
+ if (studyUrn) {
156
+ documentReference.context = {
157
+ related: [
158
+ {
159
+ identifier: {
160
+ system: DICOM_UID_SYSTEM,
161
+ value: studyUrn
162
+ }
163
+ }
164
+ ]
165
+ };
166
+ }
167
+
168
+ return documentReference;
169
+ }
package/src/helpers.js ADDED
@@ -0,0 +1,270 @@
1
+ // packages/fhir/src/helpers.js
2
+ //
3
+ // Shared DICOM → FHIR value mappers. Inputs are values from a NATURALIZED
4
+ // dcmjs dataset (DicomMetaDictionary.naturalizeDataset): keyword keys,
5
+ // single-value arrays collapsed to scalars, PN values as [{ Alphabetic }],
6
+ // IS values as numbers. Helpers are permissive about input shape
7
+ // (string / number / array / PN object) and strict about output — absent
8
+ // or unparseable inputs return null, never partial garbage.
9
+
10
+ import { MODALITY_DISPLAY, toStringFirst } from "@dcmjs-org/core";
11
+
12
+ export const DICOM_UID_SYSTEM = "urn:dicom:uid";
13
+ export const DICOM_MODALITY_SYSTEM =
14
+ "http://dicom.nema.org/resources/ontology/DCM";
15
+
16
+ /**
17
+ * Prefix a DICOM UID with urn:oid: for FHIR identifier/uid slots.
18
+ */
19
+ export function uidToUrn(uid) {
20
+ const clean = toStringFirst(uid);
21
+ if (!clean) {
22
+ return null;
23
+ }
24
+ return clean.startsWith("urn:oid:") ? clean : `urn:oid:${clean}`;
25
+ }
26
+
27
+ /**
28
+ * DICOM DA (YYYYMMDD) + optional TM (HHMMSS.ffffff) → a FHIR dateTime.
29
+ *
30
+ * FHIR requires a timezone when a dateTime has a time. The time is written
31
+ * only with a valid `timezoneOffset` (TimezoneOffsetFromUTC (0008,0201),
32
+ * "+HHMM" or "-HHMM"); without it the result is the date only, which is
33
+ * a valid dateTime that asserts no zone.
34
+ *
35
+ * The date must be YYYYMMDD (the ACR-NEMA form YYYY.MM.DD is accepted), else
36
+ * the result is null. The time must start with HHMMSS (the form HH:MM:SS is
37
+ * accepted), else the result is the date only.
38
+ */
39
+ export function dicomDateTimeToIso(dicomDate, dicomTime, timezoneOffset) {
40
+ const rawDate = toStringFirst(dicomDate);
41
+ const date = /^\d{4}\.\d{2}\.\d{2}$/.test(rawDate || "")
42
+ ? rawDate.replace(/\./g, "")
43
+ : rawDate;
44
+ if (!date || !/^\d{8}$/.test(date)) {
45
+ return null;
46
+ }
47
+
48
+ let iso = `${date.substring(0, 4)}-${date.substring(4, 6)}-${date.substring(
49
+ 6,
50
+ 8
51
+ )}`;
52
+
53
+ const rawTime = toStringFirst(dicomTime);
54
+ const time = /^\d{2}:\d{2}:\d{2}/.test(rawTime || "")
55
+ ? rawTime.replace(/:/g, "")
56
+ : rawTime;
57
+ const offset = toStringFirst(timezoneOffset);
58
+ if (time && /^\d{6}/.test(time) && offset && /^[+-]\d{4}$/.test(offset)) {
59
+ iso +=
60
+ `T${time.substring(0, 2)}:${time.substring(2, 4)}:` +
61
+ `${time.substring(4, 6)}${offset.substring(0, 3)}:` +
62
+ offset.substring(3);
63
+ }
64
+
65
+ return iso;
66
+ }
67
+
68
+ /**
69
+ * DICOM DA + TM + TimezoneOffsetFromUTC → a FHIR instant, or null when a
70
+ * part is missing (an instant needs the full time and the zone).
71
+ */
72
+ export function dicomDateTimeToInstant(dicomDate, dicomTime, timezoneOffset) {
73
+ const iso = dicomDateTimeToIso(dicomDate, dicomTime, timezoneOffset);
74
+ return iso && iso.includes("T") ? iso : null;
75
+ }
76
+
77
+ /**
78
+ * Parse a DICOM person name into FHIR HumanName parts.
79
+ * Accepts the naturalized PN shape ([{ Alphabetic: "Family^Given" }] or
80
+ * { Alphabetic }) as well as a raw "Family^Given^Middle^Prefix^Suffix"
81
+ * string.
82
+ * @returns {Object|null} { family, given, middle, prefix, suffix, text }
83
+ */
84
+ export function parsePersonName(pnValue) {
85
+ let raw = pnValue;
86
+ if (Array.isArray(raw)) {
87
+ raw = raw.length > 0 ? raw[0] : null;
88
+ }
89
+ if (raw && typeof raw === "object" && "Alphabetic" in raw) {
90
+ raw = raw.Alphabetic;
91
+ }
92
+ if (typeof raw !== "string" || raw.trim().length === 0) {
93
+ return null;
94
+ }
95
+
96
+ const parts = raw.split("^");
97
+ return {
98
+ family: parts[0] || "",
99
+ given: parts[1] || "",
100
+ middle: parts[2] || "",
101
+ prefix: parts[3] || "",
102
+ suffix: parts[4] || "",
103
+ text: parts.filter(part => part).join(" ")
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Parsed person name → FHIR HumanName element (or null when empty).
109
+ */
110
+ export function personNameToHumanName(parsed) {
111
+ if (!parsed) {
112
+ return null;
113
+ }
114
+ const humanName = {};
115
+ if (parsed.family) {
116
+ humanName.family = parsed.family;
117
+ }
118
+ const given = [parsed.given, parsed.middle].filter(Boolean);
119
+ if (given.length > 0) {
120
+ humanName.given = given;
121
+ }
122
+ if (parsed.prefix) {
123
+ humanName.prefix = [parsed.prefix];
124
+ }
125
+ if (parsed.suffix) {
126
+ humanName.suffix = [parsed.suffix];
127
+ }
128
+ if (parsed.text) {
129
+ humanName.text = parsed.text;
130
+ }
131
+ return Object.keys(humanName).length > 0 ? humanName : null;
132
+ }
133
+
134
+ /**
135
+ * DICOM PatientSex (M/F/O) → FHIR administrative gender. PatientSex is an
136
+ * administrative value, so the Patient gets no birth-sex or clinical-sex
137
+ * extension from it (FHIR-USR-3).
138
+ */
139
+ export function sexToGender(dicomSex) {
140
+ const mapping = { M: "male", F: "female", O: "other" };
141
+ return mapping[toStringFirst(dicomSex)] || "unknown";
142
+ }
143
+
144
+ /**
145
+ * FHIR administrative gender → DICOM PatientSex (0010,0040).
146
+ *
147
+ * FHIR `Patient.gender` is *administrative
148
+ * gender*; DICOM PatientSex is a three-letter administrative repertoire
149
+ * (M / F / O, Type 2 so empty is legal). These are not the same concept as
150
+ * clinical sex or gender identity, and this mapping deliberately consults
151
+ * ONLY `Patient.gender` — never US Core birthsex / sex-for-clinical-use
152
+ * extensions, which carry different semantics and belong to profiles, not
153
+ * the base resource. The mapping is lossy by design:
154
+ *
155
+ * male → M
156
+ * female → F
157
+ * other → O (as does any unrecognized non-empty value — DICOM has
158
+ * no better bucket, and inventing codes would be worse)
159
+ * unknown → "" (DICOM PatientSex is Type 2: present-but-empty is the
160
+ * standard way to say "not known")
161
+ * absent/blank → ""
162
+ *
163
+ * Mirrors sexToGender above, so M/F/O round-trip exactly and empty ⇄
164
+ * unknown round-trips to empty.
165
+ */
166
+ export function genderToSex(gender) {
167
+ const value = toStringFirst(gender);
168
+ if (!value) {
169
+ return "";
170
+ }
171
+ const normalized = value.toLowerCase();
172
+ if (normalized === "male") {
173
+ return "M";
174
+ }
175
+ if (normalized === "female") {
176
+ return "F";
177
+ }
178
+ if (normalized === "unknown") {
179
+ return "";
180
+ }
181
+ return "O";
182
+ }
183
+
184
+ /**
185
+ * FHIR HumanName → DICOM PN string ("Family^Given^Middle^Prefix^Suffix").
186
+ * Inverse of parsePersonName/personNameToHumanName: given[0] is the given
187
+ * name, given[1] the middle; only the first prefix/suffix survive (PN has
188
+ * one slot each). Trailing empty components are trimmed per PN convention.
189
+ *
190
+ * When the name carries no structured parts at all, `HumanName.text`
191
+ * (when present) survives as a single-component PN rather than returning
192
+ * null — a text-only name must not erase an existing PatientName under
193
+ * patientToDataset's deterministic overwrite (review finding 19). The
194
+ * text is used whole; guessing a "Family, Given" split from free text
195
+ * would fabricate structure the resource never asserted.
196
+ * @returns {string|null} null when the name carries no usable parts
197
+ */
198
+ export function humanNameToPersonName(humanName) {
199
+ if (!humanName || typeof humanName !== "object") {
200
+ return null;
201
+ }
202
+ const given = Array.isArray(humanName.given) ? humanName.given : [];
203
+ const components = [
204
+ toStringFirst(humanName.family) || "",
205
+ toStringFirst(given[0]) || "",
206
+ toStringFirst(given[1]) || "",
207
+ toStringFirst(
208
+ Array.isArray(humanName.prefix) ? humanName.prefix[0] : null
209
+ ) || "",
210
+ toStringFirst(
211
+ Array.isArray(humanName.suffix) ? humanName.suffix[0] : null
212
+ ) || ""
213
+ ];
214
+ while (components.length && components[components.length - 1] === "") {
215
+ components.pop();
216
+ }
217
+ const pn = components.join("^");
218
+ if (pn.length > 0) {
219
+ return pn;
220
+ }
221
+ // No structured parts: fall back to the free-text form, if any.
222
+ return toStringFirst(humanName.text);
223
+ }
224
+
225
+ /**
226
+ * FHIR date (ISO 8601) → DICOM DA (YYYYMMDD). Inverse of
227
+ * dicomDateTimeToIso for the date part. FHIR allows partial dates (YYYY,
228
+ * YYYY-MM); DICOM DA does not — partial dates return null rather than a
229
+ * fabricated day.
230
+ */
231
+ export function isoDateToDicom(isoDate) {
232
+ const value = toStringFirst(isoDate);
233
+ if (!value) {
234
+ return null;
235
+ }
236
+ if (/^\d{8}$/.test(value)) {
237
+ return value;
238
+ }
239
+ const match = value.match(/^(\d{4})-(\d{2})-(\d{2})/);
240
+ return match ? `${match[1]}${match[2]}${match[3]}` : null;
241
+ }
242
+
243
+ /**
244
+ * FHIR Coding for a DICOM modality code.
245
+ */
246
+ export function modalityCoding(modalityCode) {
247
+ const code = toStringFirst(modalityCode);
248
+ if (!code) {
249
+ return null;
250
+ }
251
+ return {
252
+ system: DICOM_MODALITY_SYSTEM,
253
+ code,
254
+ display: MODALITY_DISPLAY[code] || code
255
+ };
256
+ }
257
+
258
+ /**
259
+ * Guard: only R4B is implemented. Throws on anything else so callers
260
+ * never silently receive the wrong flavor of JSON.
261
+ */
262
+ export function assertSupportedFhirVersion(options = {}) {
263
+ const version = options.fhirVersion || "R4B";
264
+ if (version !== "R4B" && version !== "R4") {
265
+ throw new Error(
266
+ `@dcmjs/fhir: unsupported fhirVersion "${version}" (supported: R4, R4B)`
267
+ );
268
+ }
269
+ return version;
270
+ }
@@ -0,0 +1,288 @@
1
+ // packages/fhir/src/imagingStudy.js
2
+ //
3
+ // FHIR R4B ImagingStudy from naturalized DICOM dataset(s). The DICOM
4
+ // study/series/instance hierarchy maps directly onto
5
+ // ImagingStudy.series[].instance[] — this is deliberately a thin
6
+ // restatement of the Part 10 elements as FHIR-flavored JSON.
7
+ // Based on the IHE Radiology Technical Framework (MADO) mapping.
8
+
9
+ import { validationLog, toStringFirst, toFloatFirst } from "@dcmjs-org/core";
10
+
11
+ import {
12
+ DICOM_UID_SYSTEM,
13
+ uidToUrn,
14
+ dicomDateTimeToIso,
15
+ parsePersonName,
16
+ modalityCoding
17
+ } from "./helpers.js";
18
+
19
+ function instanceFromDataset(dataset) {
20
+ const sopInstanceUid = toStringFirst(dataset.SOPInstanceUID);
21
+ if (!sopInstanceUid) {
22
+ return null;
23
+ }
24
+
25
+ const sopClassUrn = uidToUrn(dataset.SOPClassUID);
26
+ if (!sopClassUrn) {
27
+ validationLog.warn(
28
+ `@dcmjs-org/fhir: skipping instance ${sopInstanceUid} — ` +
29
+ "no SOPClassUID (instance.sopClass is required 1..1)"
30
+ );
31
+ return null;
32
+ }
33
+
34
+ const instance = {
35
+ uid: sopInstanceUid,
36
+ sopClass: {
37
+ system: "urn:ietf:rfc:3986",
38
+ code: sopClassUrn
39
+ }
40
+ };
41
+
42
+ const number = unsignedIntFirst(dataset.InstanceNumber);
43
+ if (number !== null) {
44
+ instance.number = number;
45
+ }
46
+ const numberOfFrames = unsignedIntFirst(dataset.NumberOfFrames);
47
+ if (numberOfFrames !== null) {
48
+ instance.numberOfFrames = numberOfFrames;
49
+ }
50
+ const title =
51
+ toStringFirst(dataset.SeriesDescription) ||
52
+ toStringFirst(dataset.StudyDescription);
53
+ if (title) {
54
+ instance.title = title;
55
+ }
56
+
57
+ return instance;
58
+ }
59
+
60
+ function seriesShellFromDataset(dataset) {
61
+ const series = {
62
+ uid: toStringFirst(dataset.SeriesInstanceUID),
63
+ instance: []
64
+ };
65
+
66
+ const number = unsignedIntFirst(dataset.SeriesNumber);
67
+ if (number !== null) {
68
+ series.number = number;
69
+ }
70
+ // The caller skips a dataset with no Modality (series.modality is 1..1).
71
+ series.modality = modalityCoding(dataset.Modality);
72
+ const description = toStringFirst(dataset.SeriesDescription);
73
+ if (description) {
74
+ series.description = description;
75
+ }
76
+ const started = dicomDateTimeToIso(
77
+ dataset.SeriesDate,
78
+ dataset.SeriesTime,
79
+ dataset.TimezoneOffsetFromUTC
80
+ );
81
+ if (started) {
82
+ series.started = started;
83
+ }
84
+ // A DICOM defined term is not a SNOMED display, so it has no system.
85
+ const bodyPart = toStringFirst(dataset.BodyPartExamined);
86
+ if (bodyPart) {
87
+ series.bodySite = { display: bodyPart };
88
+ }
89
+ const laterality = toStringFirst(dataset.Laterality);
90
+ if (laterality) {
91
+ series.laterality = LATERALITY_CODING[laterality] || {
92
+ display: laterality
93
+ };
94
+ }
95
+
96
+ return series;
97
+ }
98
+
99
+ /** DICOM Laterality (0020,0060) → SNOMED CT (PS3.16 CID 244). */
100
+ const LATERALITY_CODING = {
101
+ L: { system: "http://snomed.info/sct", code: "7771000", display: "Left" },
102
+ R: { system: "http://snomed.info/sct", code: "24028007", display: "Right" },
103
+ B: {
104
+ system: "http://snomed.info/sct",
105
+ code: "51440002",
106
+ display: "Right and left"
107
+ }
108
+ };
109
+
110
+ function warnSkip(dataset, reason) {
111
+ validationLog.warn(
112
+ "@dcmjs-org/fhir: skipping dataset " +
113
+ `${
114
+ toStringFirst(dataset.SOPInstanceUID) || "<no SOPInstanceUID>"
115
+ } — ${reason}`
116
+ );
117
+ }
118
+
119
+ /** The first value as a FHIR unsignedInt, or null. */
120
+ function unsignedIntFirst(value) {
121
+ const number = toFloatFirst(value);
122
+ return Number.isInteger(number) && number >= 0 ? number : null;
123
+ }
124
+
125
+ /**
126
+ * Build one FHIR ImagingStudy from one or more naturalized datasets
127
+ * belonging to the same study. Instances are grouped by
128
+ * SeriesInstanceUID. The first dataset with a StudyInstanceUID anchors the
129
+ * study-level identity.
130
+ *
131
+ * The mapper never fabricates a value that FHIR requires (FHIR-USR-3). It
132
+ * skips, with a validationLog warning: a dataset of another study, a
133
+ * dataset with no SeriesInstanceUID or no Modality (series.uid and
134
+ * series.modality are 1..1), and an instance with no SOPClassUID
135
+ * (instance.sopClass is 1..1).
136
+ *
137
+ * @param {Object[]} datasets - naturalized datasets (same StudyInstanceUID)
138
+ * @param {Object} [options]
139
+ * @param {Object} [options.subject] - FHIR Reference ({ reference, display })
140
+ * to attach as ImagingStudy.subject — generic FHIR, supplied by the caller
141
+ * @returns {Object|null} FHIR ImagingStudy, or null for empty input
142
+ */
143
+ export function imagingStudyFromDatasets(datasets, options = {}) {
144
+ const all = (datasets || []).filter(Boolean);
145
+ if (all.length === 0) {
146
+ return null;
147
+ }
148
+
149
+ const first =
150
+ all.find(dataset => toStringFirst(dataset.StudyInstanceUID)) || all[0];
151
+ const anchorStudyUid = toStringFirst(first.StudyInstanceUID);
152
+ const list = all.filter(dataset => {
153
+ const studyUid = toStringFirst(dataset.StudyInstanceUID);
154
+ if (studyUid && studyUid !== anchorStudyUid) {
155
+ warnSkip(
156
+ dataset,
157
+ `StudyInstanceUID ${studyUid} is not the study ` +
158
+ `${anchorStudyUid} of this ImagingStudy`
159
+ );
160
+ return false;
161
+ }
162
+ return true;
163
+ });
164
+
165
+ // No imaging identity at all → not a study
166
+ const hasIdentity = list.some(
167
+ dataset =>
168
+ toStringFirst(dataset.StudyInstanceUID) ||
169
+ toStringFirst(dataset.SeriesInstanceUID) ||
170
+ toStringFirst(dataset.SOPInstanceUID)
171
+ );
172
+ if (!hasIdentity) {
173
+ return null;
174
+ }
175
+
176
+ const seriesMap = new Map();
177
+ list.forEach(dataset => {
178
+ const seriesUid = toStringFirst(dataset.SeriesInstanceUID);
179
+ if (!seriesUid) {
180
+ warnSkip(dataset, "no SeriesInstanceUID (series.uid is 1..1)");
181
+ return;
182
+ }
183
+ if (!toStringFirst(dataset.Modality)) {
184
+ warnSkip(dataset, "no Modality (series.modality is 1..1)");
185
+ return;
186
+ }
187
+ if (!seriesMap.has(seriesUid)) {
188
+ seriesMap.set(seriesUid, seriesShellFromDataset(dataset));
189
+ }
190
+ const instance = instanceFromDataset(dataset);
191
+ if (instance) {
192
+ seriesMap.get(seriesUid).instance.push(instance);
193
+ }
194
+ });
195
+
196
+ const series = Array.from(seriesMap.values()).map(shell => {
197
+ const entry = { ...shell };
198
+ entry.numberOfInstances = entry.instance.length;
199
+ if (entry.instance.length === 0) {
200
+ delete entry.instance;
201
+ }
202
+ return entry;
203
+ });
204
+
205
+ const numberOfInstances = series.reduce(
206
+ (sum, entry) => sum + (entry.numberOfInstances || 0),
207
+ 0
208
+ );
209
+
210
+ const study = {
211
+ resourceType: "ImagingStudy",
212
+ status: "available",
213
+ numberOfSeries: series.length,
214
+ numberOfInstances,
215
+ series
216
+ };
217
+
218
+ const identifiers = [];
219
+ const studyUid = toStringFirst(first.StudyInstanceUID);
220
+ if (studyUid) {
221
+ identifiers.push({
222
+ use: "official",
223
+ system: DICOM_UID_SYSTEM,
224
+ value: uidToUrn(studyUid)
225
+ });
226
+ }
227
+ const accessionNumber = toStringFirst(first.AccessionNumber);
228
+ if (accessionNumber) {
229
+ identifiers.push({
230
+ use: "usual",
231
+ type: {
232
+ coding: [
233
+ {
234
+ system: "http://terminology.hl7.org/CodeSystem/v2-0203",
235
+ code: "ACSN"
236
+ }
237
+ ]
238
+ },
239
+ value: accessionNumber
240
+ });
241
+ }
242
+ if (identifiers.length > 0) {
243
+ study.identifier = identifiers;
244
+ }
245
+
246
+ const started = dicomDateTimeToIso(
247
+ first.StudyDate,
248
+ first.StudyTime,
249
+ first.TimezoneOffsetFromUTC
250
+ );
251
+ if (started) {
252
+ study.started = started;
253
+ }
254
+ const description = toStringFirst(first.StudyDescription);
255
+ if (description) {
256
+ study.description = description;
257
+ }
258
+ const referrer = parsePersonName(first.ReferringPhysicianName);
259
+ if (referrer && referrer.text) {
260
+ study.referrer = { display: referrer.text };
261
+ }
262
+ if (options.subject && options.subject.reference) {
263
+ study.subject = options.subject;
264
+ }
265
+
266
+ // Study-level modality union (distinct series modalities)
267
+ const modalities = [];
268
+ series.forEach(entry => {
269
+ if (
270
+ entry.modality &&
271
+ !modalities.some(m => m.code === entry.modality.code)
272
+ ) {
273
+ modalities.push(entry.modality);
274
+ }
275
+ });
276
+ if (modalities.length > 0) {
277
+ study.modality = modalities;
278
+ }
279
+
280
+ return study;
281
+ }
282
+
283
+ /**
284
+ * Single-dataset convenience wrapper.
285
+ */
286
+ export function imagingStudyFromDataset(dataset, options = {}) {
287
+ return imagingStudyFromDatasets(dataset ? [dataset] : [], options);
288
+ }
package/src/index.js ADDED
@@ -0,0 +1,184 @@
1
+ // packages/fhir/src/index.js
2
+ //
3
+ // @dcmjs-org/fhir — FHIR both ways.
4
+ //
5
+ // PRELIMINARY API: the exports can change in a minor release while
6
+ // packages/fhir/README.md has the preliminary notice.
7
+ //
8
+ // The sink: naturalized DICOM Part 10 datasets
9
+ // (DicomMetaDictionary.naturalizeDataset output) → FHIR R4B resources.
10
+ // The source: a FHIR Patient → DICOM patient-module attributes
11
+ // (patientToDataset), for demographics injection.
12
+ //
13
+ // Deliberately simple: standard FHIR, nothing deployment-specific.
14
+ // Consumers assign resource ids, storage references, and meta.tags.
15
+ //
16
+ // const { patient, imagingStudy, documentReference } = toFhir(dataset);
17
+ // const bundle = toBundle([dataset1, dataset2]);
18
+ // const attrs = patientToDataset(patientResource); // → { PatientName, ... }
19
+
20
+ import { toStringFirst, validationLog } from "@dcmjs-org/core";
21
+ import { patientFromDataset } from "./patient.js";
22
+ import {
23
+ imagingStudyFromDataset,
24
+ imagingStudyFromDatasets
25
+ } from "./imagingStudy.js";
26
+ import { documentReferenceFromDataset } from "./documentReference.js";
27
+ import { assertSupportedFhirVersion } from "./helpers.js";
28
+
29
+ export * from "./helpers.js";
30
+ export { patientFromDataset } from "./patient.js";
31
+ export { patientToDataset } from "./patientToDataset.js";
32
+ export {
33
+ imagingStudyFromDataset,
34
+ imagingStudyFromDatasets
35
+ } from "./imagingStudy.js";
36
+ export { documentReferenceFromDataset } from "./documentReference.js";
37
+
38
+ /**
39
+ * Map one naturalized dataset to its FHIR resources.
40
+ *
41
+ * Encapsulated document instances (e.g. Encapsulated PDF from a PACS) map
42
+ * to a DocumentReference and no ImagingStudy; image instances map to an
43
+ * ImagingStudy and no DocumentReference. The 3-key shape is stable either
44
+ * way.
45
+ *
46
+ * Without `options.subject`, the ImagingStudy or DocumentReference
47
+ * references the Patient of the result as `{ reference: "./patient" }`, a
48
+ * path relative to the returned object (FHIR-USR-10). The consumer replaces
49
+ * it when it stores the resources.
50
+ *
51
+ * @param {Object} dataset - DicomMetaDictionary.naturalizeDataset output
52
+ * @param {Object} [options]
53
+ * @param {string} [options.fhirVersion='R4B'] - R4/R4B only; throws otherwise
54
+ * @param {Object} [options.subject] - FHIR Reference for
55
+ * ImagingStudy.subject / DocumentReference.subject
56
+ * @param {boolean} [options.includeData=true] - inline document bytes as
57
+ * base64 in DocumentReference attachments
58
+ * @returns {{ patient: Object|null, imagingStudy: Object|null,
59
+ * documentReference: Object|null }}
60
+ */
61
+ export function toFhir(dataset, options = {}) {
62
+ assertSupportedFhirVersion(options);
63
+ const patient = patientFromDataset(dataset);
64
+ const resourceOptions = withSubject(options, patient && "./patient");
65
+ const documentReference = documentReferenceFromDataset(
66
+ dataset,
67
+ resourceOptions
68
+ );
69
+ return {
70
+ patient,
71
+ imagingStudy: documentReference
72
+ ? null
73
+ : imagingStudyFromDataset(dataset, resourceOptions),
74
+ documentReference
75
+ };
76
+ }
77
+
78
+ /** The options with a relative `subject`, unless the caller gave one. */
79
+ function withSubject(options, reference) {
80
+ if (options.subject || !reference) {
81
+ return options;
82
+ }
83
+ return { ...options, subject: { reference } };
84
+ }
85
+
86
+ /**
87
+ * Map one or more datasets (one study's worth of instances) to a FHIR
88
+ * collection Bundle: at most one Patient, a DocumentReference for each
89
+ * encapsulated document, and one aggregated ImagingStudy.
90
+ *
91
+ * The first dataset with a patient module gives the Patient, and the first
92
+ * dataset with a StudyInstanceUID gives the study. A dataset with a
93
+ * different PatientID or StudyInstanceUID is skipped with a validationLog
94
+ * warning (FHIR-USR-3). Each entry has `fullUrl: "./entry/<index>"`, a path
95
+ * relative to the returned Bundle, and without `options.subject` the
96
+ * ImagingStudy and the DocumentReferences reference the Patient by its
97
+ * `fullUrl` (FHIR-USR-10).
98
+ *
99
+ * @param {Object[]} datasets - naturalized datasets
100
+ * @param {Object} [options] - as toFhir
101
+ * @returns {Object} FHIR Bundle (type: collection)
102
+ */
103
+ export function toBundle(datasets, options = {}) {
104
+ assertSupportedFhirVersion(options);
105
+
106
+ const all = (datasets || []).filter(Boolean);
107
+ const resources = [];
108
+
109
+ let patient = null;
110
+ let patientId = null;
111
+ for (const dataset of all) {
112
+ patient = patientFromDataset(dataset);
113
+ if (patient) {
114
+ patientId = toStringFirst(dataset.PatientID);
115
+ break;
116
+ }
117
+ }
118
+ const studyUid = all
119
+ .map(dataset => toStringFirst(dataset.StudyInstanceUID))
120
+ .find(Boolean);
121
+ const list = all.filter(dataset =>
122
+ sameContext(dataset, patientId, studyUid)
123
+ );
124
+ if (patient) {
125
+ resources.push(patient);
126
+ }
127
+ const resourceOptions = withSubject(options, patient && "./entry/0");
128
+
129
+ // Encapsulated documents each become a DocumentReference; the
130
+ // remaining (image) datasets aggregate into one ImagingStudy.
131
+ const imageDatasets = [];
132
+ for (const dataset of list) {
133
+ const documentReference = documentReferenceFromDataset(
134
+ dataset,
135
+ resourceOptions
136
+ );
137
+ if (documentReference) {
138
+ resources.push(documentReference);
139
+ } else {
140
+ imageDatasets.push(dataset);
141
+ }
142
+ }
143
+
144
+ const imagingStudy = imagingStudyFromDatasets(
145
+ imageDatasets,
146
+ resourceOptions
147
+ );
148
+ if (imagingStudy) {
149
+ resources.push(imagingStudy);
150
+ }
151
+
152
+ return {
153
+ resourceType: "Bundle",
154
+ type: "collection",
155
+ total: resources.length,
156
+ entry: resources.map((resource, index) => ({
157
+ fullUrl: `./entry/${index}`,
158
+ resource
159
+ }))
160
+ };
161
+ }
162
+
163
+ /** True when the dataset belongs to the patient and study of the Bundle. */
164
+ function sameContext(dataset, patientId, studyUid) {
165
+ const datasetPatientId = toStringFirst(dataset.PatientID);
166
+ const datasetStudyUid = toStringFirst(dataset.StudyInstanceUID);
167
+ const reason =
168
+ patientId && datasetPatientId && datasetPatientId !== patientId
169
+ ? `PatientID ${datasetPatientId} is not ${patientId}`
170
+ : studyUid && datasetStudyUid && datasetStudyUid !== studyUid
171
+ ? `StudyInstanceUID ${datasetStudyUid} is not ${studyUid}`
172
+ : null;
173
+ if (reason) {
174
+ validationLog.warn(
175
+ "@dcmjs-org/fhir: toBundle skips dataset " +
176
+ `${
177
+ toStringFirst(dataset.SOPInstanceUID) ||
178
+ "<no SOPInstanceUID>"
179
+ } — ${reason}`
180
+ );
181
+ return false;
182
+ }
183
+ return true;
184
+ }
package/src/patient.js ADDED
@@ -0,0 +1,71 @@
1
+ // packages/fhir/src/patient.js
2
+ //
3
+ // FHIR R4B Patient from the DICOM patient module (group 0010) of a
4
+ // naturalized dataset. Emits standard FHIR only — no ids, no meta.tags,
5
+ // no storage references. Id assignment and any deployment-specific
6
+ // decoration are the consumer's job.
7
+
8
+ import { toStringFirst } from "@dcmjs-org/core";
9
+ import {
10
+ dicomDateTimeToIso,
11
+ parsePersonName,
12
+ personNameToHumanName,
13
+ sexToGender
14
+ } from "./helpers.js";
15
+
16
+ /**
17
+ * Build a FHIR Patient resource from a naturalized DICOM dataset.
18
+ * @param {Object} dataset - DicomMetaDictionary.naturalizeDataset output
19
+ * @returns {Object|null} FHIR Patient, or null when the dataset carries
20
+ * no usable patient module (no PatientName and no PatientID)
21
+ */
22
+ export function patientFromDataset(dataset) {
23
+ if (!dataset) {
24
+ return null;
25
+ }
26
+
27
+ const patientId = toStringFirst(dataset.PatientID);
28
+ const humanName = personNameToHumanName(
29
+ parsePersonName(dataset.PatientName)
30
+ );
31
+
32
+ if (!patientId && !humanName) {
33
+ return null;
34
+ }
35
+
36
+ const patient = {
37
+ resourceType: "Patient"
38
+ };
39
+
40
+ if (patientId) {
41
+ patient.identifier = [
42
+ {
43
+ use: "usual",
44
+ type: {
45
+ coding: [
46
+ {
47
+ system: "http://terminology.hl7.org/CodeSystem/v2-0203",
48
+ code: "MR",
49
+ display: "Medical Record Number"
50
+ }
51
+ ],
52
+ text: "Medical Record Number"
53
+ },
54
+ value: patientId
55
+ }
56
+ ];
57
+ }
58
+
59
+ if (humanName) {
60
+ patient.name = [humanName];
61
+ }
62
+
63
+ const birthDate = dicomDateTimeToIso(dataset.PatientBirthDate);
64
+ if (birthDate) {
65
+ patient.birthDate = birthDate;
66
+ }
67
+
68
+ patient.gender = sexToGender(dataset.PatientSex);
69
+
70
+ return patient;
71
+ }
@@ -0,0 +1,80 @@
1
+ // packages/fhir/src/patientToDataset.js
2
+ //
3
+ // The FHIR source direction: a FHIR Patient resource → DICOM patient-module
4
+ // attributes (group 0010) in naturalized keyword form. Inverse of
5
+ // patient.js's patientFromDataset, and the primitive behind demographics
6
+ // injection ("apply this Patient to these instances").
7
+ //
8
+ // The result rules are FHIR-USR-6 in packages/fhir/README.md.
9
+
10
+ import {
11
+ genderToSex,
12
+ humanNameToPersonName,
13
+ isoDateToDicom
14
+ } from "./helpers.js";
15
+
16
+ const MR_IDENTIFIER_CODE = "MR";
17
+
18
+ /**
19
+ * Pick the name to use: `official` wins, then `usual`, then the first
20
+ * entry with no `use` at all, then the first entry — so a resource
21
+ * carrying both a married (official) and maiden name maps to the married
22
+ * one, never the maiden.
23
+ */
24
+ function selectName(names) {
25
+ if (!Array.isArray(names) || names.length === 0) {
26
+ return null;
27
+ }
28
+ for (const use of ["official", "usual"]) {
29
+ const match = names.find(name => name && name.use === use);
30
+ if (match) {
31
+ return match;
32
+ }
33
+ }
34
+ return names.find(name => name && !name.use) || names[0];
35
+ }
36
+
37
+ /**
38
+ * Pick the identifier for PatientID: an MR-typed identifier wins
39
+ * (type.coding code "MR", the shape patientFromDataset emits), else the
40
+ * first identifier carrying a value.
41
+ */
42
+ function selectIdentifier(identifiers) {
43
+ if (!Array.isArray(identifiers) || identifiers.length === 0) {
44
+ return null;
45
+ }
46
+ const mrTyped = identifiers.find(identifier =>
47
+ identifier?.type?.coding?.some(
48
+ coding => coding && coding.code === MR_IDENTIFIER_CODE
49
+ )
50
+ );
51
+ return mrTyped || identifiers.find(identifier => identifier?.value) || null;
52
+ }
53
+
54
+ /**
55
+ * Map a FHIR Patient resource to DICOM patient-module attributes.
56
+ *
57
+ * @param {Object} patient - FHIR Patient (R4/R4B)
58
+ * @returns {{ PatientName: string, PatientID: string,
59
+ * PatientBirthDate: string, PatientSex: string }} naturalized keyword
60
+ * attributes; absent resource fields are "" (deterministic overwrite)
61
+ * @throws when the input is not a Patient resource
62
+ */
63
+ export function patientToDataset(patient) {
64
+ if (!patient || patient.resourceType !== "Patient") {
65
+ throw new Error(
66
+ "patientToDataset expects a FHIR Patient resource " +
67
+ `(got resourceType "${patient?.resourceType}")`
68
+ );
69
+ }
70
+
71
+ const name = selectName(patient.name);
72
+ const identifier = selectIdentifier(patient.identifier);
73
+
74
+ return {
75
+ PatientName: (name && humanNameToPersonName(name)) || "",
76
+ PatientID: identifier?.value || "",
77
+ PatientBirthDate: isoDateToDicom(patient.birthDate) || "",
78
+ PatientSex: genderToSex(patient.gender)
79
+ };
80
+ }