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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,136 @@
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, and the FHIR methods of
4
+ > `DicomEventStream` (`fromFhir`, `toFhir`), can change in a minor release
5
+ > while this notice is here. Such a change is not a breaking change for
6
+ > semantic versioning; the release notes name it. Pin an exact version if you
7
+ > depend on the current shape.
8
+
9
+ DICOM to FHIR R4/R4B mapping for naturalized dcmjs datasets, and the reverse
10
+ mapping of patient demographics.
11
+
12
+ - `toFhir(dataset, options)` — `{ patient, imagingStudy, documentReference }`
13
+ for one instance.
14
+ - `toBundle(datasets, options)` — a `collection` Bundle: one Patient, a
15
+ DocumentReference for each encapsulated document, and one ImagingStudy
16
+ for the images.
17
+ - `patientFromDataset`, `imagingStudyFromDatasets`,
18
+ `documentReferenceFromDataset` — the single mappers.
19
+ - `patientToDataset(patient)` — a FHIR Patient to the DICOM patient-module
20
+ attributes (`PatientName`, `PatientID`, `PatientBirthDate`, `PatientSex`).
21
+
22
+ The event-stream source `DicomEventStream.fromFhir(resource, options)` (in
23
+ `src/eventStream/fromFhir.js`) turns a DocumentReference or Media with inline
24
+ data, or a Bundle that holds one, into a DICOM instance.
25
+
26
+ ```js
27
+ const { patient, imagingStudy } = toFhir(naturalizedDataset);
28
+
29
+ const part10 = await DicomEventStream.fromFhir(documentReference, {
30
+ patient,
31
+ instance: priorStudyInstance,
32
+ overrides: { SeriesDescription: "Scanned reports" }
33
+ }).toPart10();
34
+ ```
35
+
36
+ ## Scope and change rule
37
+
38
+ This README holds the requirements of `@dcmjs-org/fhir` and of
39
+ `DicomEventStream.fromFhir` and `toFhir`. The options of `fromFhir` follow
40
+ the `createInstance` requirements (CORE-USR-n) in `packages/core/README.md`.
41
+
42
+ While the status is preliminary, a user requirement (FHIR-USR-n) can change
43
+ in a minor release. After that, change a user requirement only when it
44
+ describes the behaviour wrongly, or when the intended user-facing behaviour
45
+ changes, and name the change in the pull request. The implementation
46
+ requirements (FHIR-IMP-n) describe the current approach, and can change
47
+ freely. Do not renumber an identifier.
48
+
49
+ ## § User requirements
50
+
51
+ - **FHIR-USR-1** The output is standard FHIR R4/R4B only, with no profile
52
+ extensions: no resource `id`, no `meta.tags`, and no storage references.
53
+ The consumer assigns these. An unsupported `fhirVersion` throws an
54
+ error. The relative references of FHIR-USR-10 are the one exception.
55
+ - **FHIR-USR-2** `toFhir` maps an encapsulated document to a
56
+ DocumentReference and no ImagingStudy, and an image to an ImagingStudy
57
+ and no DocumentReference.
58
+ - **FHIR-USR-3** The mapper never fabricates a value that DICOM does not
59
+ give, and never mixes two patients or two studies.
60
+ - It skips, with a `validationLog` warning: an instance with no
61
+ SOPClassUID; a dataset with no SeriesInstanceUID or no Modality; a
62
+ dataset of another study than the first. `toBundle` also skips a
63
+ dataset with another PatientID than the Patient of the Bundle.
64
+ - `Patient.gender` comes from the administrative `PatientSex`. The
65
+ Patient gets no birth-sex or clinical-sex extension.
66
+ - A number (`series.number`, `instance.number`, `numberOfFrames`) is
67
+ written only for a non-negative integer.
68
+ - `BodyPartExamined` is a display with no code system. `Laterality`
69
+ L, R, and B are SNOMED CT codes (CID 244); another value is a
70
+ display with no code system.
71
+ - **FHIR-USR-4** A FHIR `dateTime` gets a time only when the dataset has
72
+ `TimezoneOffsetFromUTC (0008,0201)`; otherwise it is the date only.
73
+ `DocumentReference.date` (an `instant`) is written only with the date,
74
+ the time, and the timezone. The date must be `YYYYMMDD` (or the legacy
75
+ `YYYY.MM.DD`), else there is no date; a time that is not `HHMMSS` (or the
76
+ legacy `HH:MM:SS`) gives the date only.
77
+ - **FHIR-USR-5** The DocumentReference attachment holds the document bytes
78
+ exactly: `EncapsulatedDocumentLength (0042,0015)` gives the length when
79
+ present, and each naturalized payload shape (including
80
+ `{ InlineBinary }`) gives the same bytes. A `{ BulkDataURI }` payload
81
+ gives `attachment.url`, and no `size` or `data`.
82
+ - **FHIR-USR-6** `patientToDataset` writes all four attributes, with an
83
+ empty string for an absent value. A text-only HumanName becomes a
84
+ single-component PN. A partial FHIR `birthDate` becomes empty, and never
85
+ a fabricated day.
86
+ - **FHIR-USR-7** `fromFhir` makes an Encapsulated PDF instance from an
87
+ inline PDF, and an image instance that carries an inline JPEG verbatim,
88
+ with DICOM-valid geometry and photometric interpretation (IMG-USR-11).
89
+ A lossy JPEG (baseline or extended) gets `LossyImageCompression` "01"
90
+ and `LossyImageCompressionMethod` "ISO_10918_1". A Patient
91
+ alone, an attachment with only a `url`, and an unsupported content type
92
+ give a corrective error. The error comes from the sink call, not from
93
+ the `fromFhir` factory.
94
+ - **FHIR-USR-8** The `fromFhir` options are `patient` plus the
95
+ `createInstance` options. The caller `overrides` win over the values from
96
+ FHIR (demographics, DocumentTitle), and those win over the inherited and
97
+ base values. With no FHIR title, the base or inherited `DocumentTitle`
98
+ stays.
99
+ - A FHIR Patient replaces the whole patient module: the four attributes
100
+ of FHIR-USR-6, and no other patient-level attribute of `instance`
101
+ (for example `IssuerOfPatientID` or `OtherPatientIDs`) stays.
102
+ - An `instance` with a non-empty PatientID that is not the PatientID of
103
+ the FHIR Patient throws an error, because the new instance would
104
+ join the study of another patient.
105
+ - **FHIR-USR-9** A Bundle for `fromFhir` must hold exactly one
106
+ DocumentReference or Media. Its Patient is `options.patient`, else the
107
+ Patient that the `subject` reference names, else the only Patient. A
108
+ reference matches the `fullUrl` of an entry exactly; only a relative
109
+ reference (`Patient/<id>`, with an optional `/_history/<n>`) also matches
110
+ by `id`. A `subject` that matches no Patient or more than one, or more
111
+ than one Patient with no `subject`, throws an error, so the demographics
112
+ never go to the wrong patient.
113
+ - **FHIR-USR-10** The output links its resources without server ids.
114
+ Without `options.subject`, `toFhir` gives the ImagingStudy or the
115
+ DocumentReference `subject: { reference: "./patient" }`, a path relative
116
+ to the returned object. `toBundle` gives each entry
117
+ `fullUrl: "./entry/<index>"`, and the ImagingStudy and the
118
+ DocumentReferences reference the Patient entry by its `fullUrl`. These
119
+ relative references are not FHIR server references; the consumer
120
+ replaces them when it stores the resources.
121
+
122
+ ## § Implementation requirements
123
+
124
+ - **FHIR-IMP-1** The package depends at run time only on `@dcmjs-org/core`
125
+ and `@dcmjs-org/encapsulated`; the tests can use `@dcmjs-org/parser` and
126
+ `@dcmjs-org/legacy`.
127
+ - **FHIR-IMP-2** The document bytes come from `extractEncapsulated` of
128
+ `@dcmjs-org/encapsulated`. The value readers (`toStringFirst`,
129
+ `toFloatFirst`), `encodeBase64`, and `MODALITY_DISPLAY` come from
130
+ `@dcmjs-org/core`.
131
+ - **FHIR-IMP-3** `fromFhir` builds the instance with `encapsulatePdf` or
132
+ `buildImageDataset` (both on `createInstance`), and reads the JPEG frame
133
+ header with `parseJpegInfo` of `@dcmjs-org/imaging`.
134
+ - **FHIR-IMP-4** `fromFhir.js` lives at `src/eventStream/`, beside `api.js`,
135
+ because it composes several packages. It moves into the wrapper package
136
+ with the facade.
package/package.json CHANGED
@@ -1,6 +1,20 @@
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.3",
4
+ "description": "DICOM ↔ FHIR R4B mapping for Patient, ImagingStudy and DocumentReference resources from naturalized dcmjs datasets",
5
+ "main": "./src/index.js",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/dcmjs-org/dcmjs.git",
10
+ "directory": "packages/fhir"
11
+ },
12
+ "dependencies": {
13
+ "@dcmjs-org/encapsulated": "1.0.0-beta.3",
14
+ "@dcmjs-org/core": "1.0.0-beta.3"
15
+ },
16
+ "devDependencies": {
17
+ "@dcmjs-org/parser": "1.0.0-beta.3",
18
+ "@dcmjs-org/legacy": "1.0.0-beta.3"
19
+ }
6
20
  }
@@ -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
+ }