@dcmjs-org/fhir 1.0.0-beta.3 → 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,8 +1,7 @@
1
1
  # @dcmjs-org/fhir
2
2
 
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
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
6
5
  > semantic versioning; the release notes name it. Pin an exact version if you
7
6
  > depend on the current shape.
8
7
 
@@ -19,25 +18,24 @@ mapping of patient demographics.
19
18
  - `patientToDataset(patient)` — a FHIR Patient to the DICOM patient-module
20
19
  attributes (`PatientName`, `PatientID`, `PatientBirthDate`, `PatientSex`).
21
20
 
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.
21
+ The wrapper `@dcmjs-org/dcmjs` does not depend on this package. An
22
+ event stream gives the naturalized dataset for `toFhir`:
25
23
 
26
24
  ```js
27
- const { patient, imagingStudy } = toFhir(naturalizedDataset);
25
+ import { toFhir } from "@dcmjs-org/fhir";
28
26
 
29
- const part10 = await DicomEventStream.fromFhir(documentReference, {
30
- patient,
31
- instance: priorStudyInstance,
32
- overrides: { SeriesDescription: "Scanned reports" }
33
- }).toPart10();
27
+ const { patient, imagingStudy } = toFhir(await events.toNaturalized());
34
28
  ```
35
29
 
36
30
  ## Scope and change rule
37
31
 
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`.
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.
41
39
 
42
40
  While the status is preliminary, a user requirement (FHIR-USR-n) can change
43
41
  in a minor release. After that, change a user requirement only when it
@@ -83,33 +81,8 @@ freely. Do not renumber an identifier.
83
81
  empty string for an absent value. A text-only HumanName becomes a
84
82
  single-component PN. A partial FHIR `birthDate` becomes empty, and never
85
83
  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.
84
+ - **FHIR-USR-7**, **FHIR-USR-8**, **FHIR-USR-9** Withdrawn (see the
85
+ scope section).
113
86
  - **FHIR-USR-10** The output links its resources without server ids.
114
87
  Without `options.subject`, `toFhir` gives the ImagingStudy or the
115
88
  DocumentReference `subject: { reference: "./patient" }`, a path relative
@@ -128,9 +101,4 @@ freely. Do not renumber an identifier.
128
101
  `@dcmjs-org/encapsulated`. The value readers (`toStringFirst`,
129
102
  `toFloatFirst`), `encodeBase64`, and `MODALITY_DISPLAY` come from
130
103
  `@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.
104
+ - **FHIR-IMP-3**, **FHIR-IMP-4** Withdrawn (see the scope section).
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "@dcmjs-org/fhir",
3
- "version": "1.0.0-beta.3",
3
+ "version": "1.0.0-beta.4",
4
4
  "description": "DICOM ↔ FHIR R4B mapping for Patient, ImagingStudy and DocumentReference resources from naturalized dcmjs datasets",
5
5
  "main": "./src/index.js",
6
+ "files": [
7
+ "src",
8
+ "README.md"
9
+ ],
6
10
  "license": "MIT",
7
11
  "repository": {
8
12
  "type": "git",
@@ -10,11 +14,11 @@
10
14
  "directory": "packages/fhir"
11
15
  },
12
16
  "dependencies": {
13
- "@dcmjs-org/encapsulated": "1.0.0-beta.3",
14
- "@dcmjs-org/core": "1.0.0-beta.3"
17
+ "@dcmjs-org/core": "1.0.0-beta.4",
18
+ "@dcmjs-org/encapsulated": "1.0.0-beta.4"
15
19
  },
16
20
  "devDependencies": {
17
- "@dcmjs-org/parser": "1.0.0-beta.3",
18
- "@dcmjs-org/legacy": "1.0.0-beta.3"
21
+ "@dcmjs-org/legacy": "1.0.0-beta.4",
22
+ "@dcmjs-org/parser": "1.0.0-beta.4"
19
23
  }
20
24
  }
@@ -5,8 +5,7 @@
5
5
  // patient.js's patientFromDataset, and the primitive behind demographics
6
6
  // injection ("apply this Patient to these instances").
7
7
  //
8
- // The result rules are FHIR-USR-6 in packages/fhir/README.md. fromFhir
9
- // also removes the other patient-module attributes (FHIR-USR-8).
8
+ // The result rules are FHIR-USR-6 in packages/fhir/README.md.
10
9
 
11
10
  import {
12
11
  genderToSex,
@@ -1,317 +0,0 @@
1
- // packages/fhir/test/documentReference.test.js
2
- //
3
- // FHIR DocumentReference from Encapsulated PDF instances — the "PDF out of
4
- // PACS" mapping. buildPdfDataset constructs the naturalized shape of
5
- // @dcmjs-org/encapsulated's encapsulatePdf directly, with fixed UIDs and
6
- // payload shapes for each case. The round-trip case still serializes and
7
- // re-reads through @dcmjs-org/legacy (test-only; the package itself never
8
- // imports legacy), and the image fixture naturalizes through
9
- // @dcmjs-org/parser as in toFhir.test.js.
10
-
11
- import fs from "fs";
12
- import path from "path";
13
- import { validationLog } from "@dcmjs-org/core";
14
- import { fromPart10, NaturalizedListener } from "@dcmjs-org/parser";
15
- import { datasetToBuffer, DicomMessage } from "@dcmjs-org/legacy";
16
- import { DicomMetaDictionary } from "@dcmjs-org/core";
17
- import {
18
- toFhir,
19
- toBundle,
20
- documentReferenceFromDataset
21
- } from "../src/index.js";
22
-
23
- validationLog.setLevel(5);
24
-
25
- const ENCAPSULATED_PDF_SOP_CLASS_UID = "1.2.840.10008.5.1.4.1.1.104.1";
26
-
27
- const PDF_STRING =
28
- "%PDF-1.4\n" +
29
- "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n" +
30
- "trailer<</Size 2/Root 1 0 R>>\n" +
31
- "%%EOF";
32
- const PDF_BYTES = new TextEncoder().encode(PDF_STRING);
33
-
34
- const FIXTURE = path.join(
35
- __dirname,
36
- "..",
37
- "..",
38
- "fixtures",
39
- "dicom",
40
- "sample-dicom.dcm"
41
- );
42
-
43
- async function loadNaturalizedFixture() {
44
- const buffer = fs.readFileSync(FIXTURE);
45
- const arrayBuffer = buffer.buffer.slice(
46
- buffer.byteOffset,
47
- buffer.byteOffset + buffer.byteLength
48
- );
49
- const listener = new NaturalizedListener();
50
- await fromPart10(arrayBuffer, listener);
51
- return listener.result;
52
- }
53
-
54
- /** Standalone ArrayBuffer copy of a byte payload. */
55
- function toArrayBuffer(bytes) {
56
- return bytes.buffer.slice(
57
- bytes.byteOffset,
58
- bytes.byteOffset + bytes.byteLength
59
- );
60
- }
61
-
62
- // The naturalized shape dcmjs.encapsulated.encapsulatePdf emits in v2:
63
- // Encapsulated PDF SOP class, DOC modality, the document as an
64
- // ArrayBuffer, plus the identifying attributes.
65
- function buildPdfDataset(options = {}) {
66
- return {
67
- SOPClassUID: ENCAPSULATED_PDF_SOP_CLASS_UID,
68
- SOPInstanceUID: "1.2.3.4.5.6.7",
69
- StudyInstanceUID: "1.2.3.4.5",
70
- SeriesInstanceUID: "1.2.3.4.5.1",
71
- Modality: "DOC",
72
- MIMETypeOfEncapsulatedDocument: "application/pdf",
73
- EncapsulatedDocument: toArrayBuffer(PDF_BYTES),
74
- PatientName: [{ Alphabetic: "Doe^Jane" }],
75
- PatientID: "MRN-42",
76
- DocumentTitle: "Discharge Summary",
77
- ContentDate: "20260803",
78
- ContentTime: "101500",
79
- TimezoneOffsetFromUTC: "-0600",
80
- ...options
81
- };
82
- }
83
-
84
- describe("documentReferenceFromDataset", () => {
85
- test("maps an Encapsulated PDF dataset to a DocumentReference", () => {
86
- const dataset = buildPdfDataset();
87
- const documentReference = documentReferenceFromDataset(dataset);
88
-
89
- expect(documentReference.resourceType).toBe("DocumentReference");
90
- expect(documentReference.status).toBe("current");
91
- expect(documentReference.masterIdentifier).toEqual({
92
- system: "urn:dicom:uid",
93
- value: `urn:oid:${dataset.SOPInstanceUID}`
94
- });
95
- expect(documentReference.description).toBe("Discharge Summary");
96
- expect(documentReference.date).toBe("2026-08-03T10:15:00-06:00");
97
-
98
- const attachment = documentReference.content[0].attachment;
99
- expect(attachment.contentType).toBe("application/pdf");
100
- expect(attachment.title).toBe("Discharge Summary");
101
- expect(attachment.size).toBe(PDF_BYTES.byteLength);
102
- // base64 round-trip is byte-identical to the original PDF
103
- expect(Buffer.from(attachment.data, "base64").toString("latin1")).toBe(
104
- PDF_STRING
105
- );
106
-
107
- // Attached to the originating study
108
- expect(documentReference.context.related[0].identifier).toEqual({
109
- system: "urn:dicom:uid",
110
- value: "urn:oid:1.2.3.4.5"
111
- });
112
- });
113
-
114
- test("omits date when the dataset has no timezone (an instant needs one)", () => {
115
- const documentReference = documentReferenceFromDataset(
116
- buildPdfDataset({ TimezoneOffsetFromUTC: undefined })
117
- );
118
- expect(documentReference.date).toBeUndefined();
119
- });
120
-
121
- test("honors subject and includeData options", () => {
122
- const dataset = buildPdfDataset();
123
- const documentReference = documentReferenceFromDataset(dataset, {
124
- subject: { reference: "Patient/12345" },
125
- includeData: false
126
- });
127
-
128
- expect(documentReference.subject).toEqual({
129
- reference: "Patient/12345"
130
- });
131
- const attachment = documentReference.content[0].attachment;
132
- expect(attachment.data).toBeUndefined();
133
- expect(attachment.size).toBe(PDF_BYTES.byteLength);
134
- });
135
-
136
- test("uses ConceptNameCodeSequence for type when present", () => {
137
- const dataset = buildPdfDataset({
138
- ConceptNameCodeSequence: {
139
- CodeValue: "18842-5",
140
- CodingSchemeDesignator: "LN",
141
- CodeMeaning: "Discharge summary"
142
- }
143
- });
144
- const documentReference = documentReferenceFromDataset(dataset);
145
- expect(documentReference.type.coding[0].code).toBe("18842-5");
146
- expect(documentReference.type.coding[0].display).toBe(
147
- "Discharge summary"
148
- );
149
- });
150
-
151
- test("returns null for a non-encapsulated dataset", async () => {
152
- const dataset = await loadNaturalizedFixture();
153
- expect(documentReferenceFromDataset(dataset)).toBeNull();
154
- });
155
-
156
- test("survives a Part 10 round trip (odd-length OB padding)", () => {
157
- const source = buildPdfDataset({
158
- _meta: {
159
- TransferSyntaxUID: { Value: ["1.2.840.10008.1.2.1"] }
160
- }
161
- });
162
- const buffer = datasetToBuffer(source);
163
- const arrayBuffer = buffer.buffer.slice(
164
- buffer.byteOffset,
165
- buffer.byteOffset + buffer.byteLength
166
- );
167
- const readBack = DicomMetaDictionary.naturalizeDataset(
168
- DicomMessage.readFile(arrayBuffer).dict
169
- );
170
-
171
- const documentReference = documentReferenceFromDataset(readBack);
172
- const attachment = documentReference.content[0].attachment;
173
- // Trailing NUL pad trimmed: size and payload match the original PDF
174
- expect(attachment.size).toBe(PDF_BYTES.byteLength);
175
- expect(Buffer.from(attachment.data, "base64").toString("latin1")).toBe(
176
- PDF_STRING
177
- );
178
- });
179
-
180
- // Regression for review finding 8: the event-stream naturalizer wraps
181
- // binary elements with no decoded Value as { InlineBinary } (base64
182
- // string, ArrayBuffer, or view). payloadBytes never unwrapped that
183
- // shape — new Uint8Array(<plain object>) is empty — so every
184
- // naturalized encapsulated document silently mapped to
185
- // { size: 0, data: "" }.
186
- test("unwraps { InlineBinary } base64 byte-exactly (finding 8)", () => {
187
- const base64 = Buffer.from(PDF_BYTES).toString("base64");
188
- const dataset = buildPdfDataset({
189
- EncapsulatedDocument: { InlineBinary: base64 }
190
- });
191
- const documentReference = documentReferenceFromDataset(dataset);
192
- const attachment = documentReference.content[0].attachment;
193
- expect(attachment.size).toBe(PDF_BYTES.byteLength);
194
- expect(new Uint8Array(Buffer.from(attachment.data, "base64"))).toEqual(
195
- PDF_BYTES
196
- );
197
- });
198
-
199
- test("unwraps { InlineBinary } ArrayBuffer and view shapes (finding 8)", () => {
200
- for (const inline of [
201
- toArrayBuffer(PDF_BYTES),
202
- new Uint8Array(toArrayBuffer(PDF_BYTES))
203
- ]) {
204
- const dataset = buildPdfDataset({
205
- EncapsulatedDocument: { InlineBinary: inline }
206
- });
207
- const attachment =
208
- documentReferenceFromDataset(dataset).content[0].attachment;
209
- expect(attachment.size).toBe(PDF_BYTES.byteLength);
210
- expect(
211
- new Uint8Array(Buffer.from(attachment.data, "base64"))
212
- ).toEqual(PDF_BYTES);
213
- }
214
- });
215
-
216
- // Regression for review finding 16: the Part 10 writer pads only
217
- // odd-length OB values, so an even stored length has no pad byte —
218
- // but the heuristic trimmed a trailing 0x00 anyway, corrupting any
219
- // even-length payload that genuinely ends in a zero byte (ordinary
220
- // for STL/OBJ/CDA/octet-stream). EncapsulatedDocumentLength
221
- // (0042,0015) carries the exact length and must win when present.
222
- test("EncapsulatedDocumentLength preserves a real trailing zero (finding 16)", () => {
223
- const payload = new Uint8Array([
224
- 0x53, 0x54, 0x4c, 0x20, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x00
225
- ]); // 10 bytes, even, ends in a real 0x00
226
- const dataset = buildPdfDataset({
227
- MIMETypeOfEncapsulatedDocument: "model/stl",
228
- EncapsulatedDocument: toArrayBuffer(payload),
229
- EncapsulatedDocumentLength: 10
230
- });
231
- const attachment =
232
- documentReferenceFromDataset(dataset).content[0].attachment;
233
- expect(attachment.size).toBe(10);
234
- expect(new Uint8Array(Buffer.from(attachment.data, "base64"))).toEqual(
235
- payload
236
- );
237
- });
238
-
239
- test("EncapsulatedDocumentLength trims the pad the writer added (finding 16)", () => {
240
- // 9 content bytes padded to 10 on write; (0042,0015) says 9.
241
- const padded = new Uint8Array([
242
- 0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34, 0x00, 0x00
243
- ]);
244
- const dataset = buildPdfDataset({
245
- EncapsulatedDocument: toArrayBuffer(padded),
246
- EncapsulatedDocumentLength: 9
247
- });
248
- const attachment =
249
- documentReferenceFromDataset(dataset).content[0].attachment;
250
- expect(attachment.size).toBe(9);
251
- expect(new Uint8Array(Buffer.from(attachment.data, "base64"))).toEqual(
252
- padded.subarray(0, 9)
253
- );
254
- });
255
- });
256
-
257
- describe("toFhir / toBundle integration", () => {
258
- test("toFhir yields { patient, documentReference } for encapsulated PDFs", () => {
259
- const { patient, imagingStudy, documentReference } = toFhir(
260
- buildPdfDataset()
261
- );
262
- expect(patient.resourceType).toBe("Patient");
263
- expect(patient.identifier[0].value).toBe("MRN-42");
264
- expect(imagingStudy).toBeNull();
265
- expect(documentReference.resourceType).toBe("DocumentReference");
266
- });
267
-
268
- test("toFhir still yields imagingStudy (and null documentReference) for images", async () => {
269
- const dataset = await loadNaturalizedFixture();
270
- const { imagingStudy, documentReference } = toFhir(dataset);
271
- expect(imagingStudy.resourceType).toBe("ImagingStudy");
272
- expect(documentReference).toBeNull();
273
- });
274
-
275
- test("toBundle includes DocumentReference entries", () => {
276
- const bundle = toBundle([buildPdfDataset()]);
277
- const resourceTypes = bundle.entry.map(
278
- entry => entry.resource.resourceType
279
- );
280
- expect(resourceTypes).toContain("Patient");
281
- expect(resourceTypes).toContain("DocumentReference");
282
- expect(bundle.total).toBe(bundle.entry.length);
283
- });
284
-
285
- test("toBundle skips a document of another patient (FHIR-USR-3)", () => {
286
- const bundle = toBundle([
287
- buildPdfDataset(),
288
- buildPdfDataset({
289
- PatientID: "OTHER",
290
- SOPInstanceUID: "1.2.3.4.5.6.8"
291
- })
292
- ]);
293
- const documents = bundle.entry.filter(
294
- entry => entry.resource.resourceType === "DocumentReference"
295
- );
296
- expect(documents).toHaveLength(1);
297
- expect(documents[0].resource.subject).toEqual({
298
- reference: "./entry/0"
299
- });
300
- });
301
- });
302
-
303
- describe("a document that is not in the dataset", () => {
304
- test("a { BulkDataURI } payload gives attachment.url, and no size or data", () => {
305
- const documentReference = documentReferenceFromDataset(
306
- buildPdfDataset({
307
- EncapsulatedDocument: { BulkDataURI: "http://x/bulk/1" },
308
- EncapsulatedDocumentLength: undefined
309
- })
310
- );
311
- expect(documentReference.content[0].attachment).toEqual({
312
- contentType: "application/pdf",
313
- title: "Discharge Summary",
314
- url: "http://x/bulk/1"
315
- });
316
- });
317
- });
@@ -1,234 +0,0 @@
1
- // packages/fhir/test/patientToDataset.test.js
2
- //
3
- // The FHIR source direction: Patient resource → DICOM patient-module
4
- // attributes. Test identity: JANE DOE (maiden) → JANE FOX (official).
5
- // The genderToSex table is pinned exhaustively — administrative gender
6
- // only, lossy by design, empty for unknown/absent.
7
-
8
- // Imports point at the concrete modules rather than the package index:
9
- // the index (and the toFhir surface it exports) lands in a later slice.
10
- import { patientToDataset } from "../src/patientToDataset.js";
11
- import { patientFromDataset } from "../src/patient.js";
12
- import {
13
- genderToSex,
14
- humanNameToPersonName,
15
- isoDateToDicom
16
- } from "../src/helpers.js";
17
-
18
- const JANE_FOX = {
19
- resourceType: "Patient",
20
- identifier: [
21
- {
22
- use: "usual",
23
- type: {
24
- coding: [
25
- {
26
- system: "http://terminology.hl7.org/CodeSystem/v2-0203",
27
- code: "MR",
28
- display: "Medical Record Number"
29
- }
30
- ]
31
- },
32
- value: "22446688"
33
- }
34
- ],
35
- name: [
36
- { use: "official", family: "FOX", given: ["JANE"] },
37
- { use: "maiden", family: "DOE", given: ["JANE"] }
38
- ],
39
- gender: "female",
40
- birthDate: "1980-04-15"
41
- };
42
-
43
- describe("patientToDataset", () => {
44
- test("maps the full JANE FOX resource", () => {
45
- expect(patientToDataset(JANE_FOX)).toEqual({
46
- PatientName: "FOX^JANE",
47
- PatientID: "22446688",
48
- PatientBirthDate: "19800415",
49
- PatientSex: "F"
50
- });
51
- });
52
-
53
- test("official name wins over maiden regardless of order", () => {
54
- const maidenFirst = {
55
- ...JANE_FOX,
56
- name: [
57
- { use: "maiden", family: "DOE", given: ["JANE"] },
58
- { use: "official", family: "FOX", given: ["JANE"] }
59
- ]
60
- };
61
- expect(patientToDataset(maidenFirst).PatientName).toBe("FOX^JANE");
62
- });
63
-
64
- test("usual name is second preference; unadorned beats maiden", () => {
65
- const usual = {
66
- ...JANE_FOX,
67
- name: [
68
- { use: "maiden", family: "DOE", given: ["JANE"] },
69
- { use: "usual", family: "FOX", given: ["JANE"] }
70
- ]
71
- };
72
- expect(patientToDataset(usual).PatientName).toBe("FOX^JANE");
73
-
74
- const unadorned = {
75
- ...JANE_FOX,
76
- name: [
77
- { use: "maiden", family: "DOE", given: ["JANE"] },
78
- { family: "FOX", given: ["JANE"] }
79
- ]
80
- };
81
- expect(patientToDataset(unadorned).PatientName).toBe("FOX^JANE");
82
- });
83
-
84
- test("MR-typed identifier wins over other identifiers", () => {
85
- const multiId = {
86
- ...JANE_FOX,
87
- identifier: [
88
- {
89
- system: "urn:oid:2.16.840.1.113883.4.1",
90
- value: "999-99-9999"
91
- },
92
- JANE_FOX.identifier[0]
93
- ]
94
- };
95
- expect(patientToDataset(multiId).PatientID).toBe("22446688");
96
- });
97
-
98
- test("deterministic overwrite: absent fields are empty strings", () => {
99
- expect(patientToDataset({ resourceType: "Patient" })).toEqual({
100
- PatientName: "",
101
- PatientID: "",
102
- PatientBirthDate: "",
103
- PatientSex: ""
104
- });
105
- });
106
-
107
- test("partial FHIR birthDate maps to empty, never a fabricated day", () => {
108
- expect(
109
- patientToDataset({ ...JANE_FOX, birthDate: "1980" })
110
- .PatientBirthDate
111
- ).toBe("");
112
- expect(
113
- patientToDataset({ ...JANE_FOX, birthDate: "1980-04" })
114
- .PatientBirthDate
115
- ).toBe("");
116
- });
117
-
118
- test("non-Patient input throws with the resourceType named", () => {
119
- expect(() => patientToDataset({ resourceType: "Observation" })).toThrow(
120
- /expects a FHIR Patient.*Observation/
121
- );
122
- expect(() => patientToDataset(null)).toThrow(/expects a FHIR Patient/);
123
- });
124
- });
125
-
126
- describe("genderToSex — the full table", () => {
127
- test.each([
128
- ["male", "M"],
129
- ["female", "F"],
130
- ["other", "O"],
131
- ["unknown", ""],
132
- ["", ""],
133
- [null, ""],
134
- [undefined, ""],
135
- ["Male", "M"], // case-insensitive
136
- ["FEMALE", "F"],
137
- ["Unknown", ""],
138
- ["nonbinary", "O"], // unrecognized non-empty → O, never a guess
139
- ["x", "O"]
140
- ])("%p → %p", (gender, expected) => {
141
- expect(genderToSex(gender)).toBe(expected);
142
- });
143
- });
144
-
145
- describe("round trips with the sink direction", () => {
146
- test("dataset → Patient → dataset is stable for JANE FOX", () => {
147
- const dataset = {
148
- PatientName: [{ Alphabetic: "FOX^JANE" }],
149
- PatientID: "22446688",
150
- PatientBirthDate: "19800415",
151
- PatientSex: "F"
152
- };
153
- const resource = patientFromDataset(dataset);
154
- expect(patientToDataset(resource)).toEqual({
155
- PatientName: "FOX^JANE",
156
- PatientID: "22446688",
157
- PatientBirthDate: "19800415",
158
- PatientSex: "F"
159
- });
160
- });
161
-
162
- test("PatientSex M/F/O survive the round trip; empty stays empty", () => {
163
- for (const sex of ["M", "F", "O"]) {
164
- const resource = patientFromDataset({
165
- PatientID: "22446688",
166
- PatientSex: sex
167
- });
168
- expect(patientToDataset(resource).PatientSex).toBe(sex);
169
- }
170
- // empty PatientSex → gender "unknown" → empty PatientSex
171
- const resource = patientFromDataset({
172
- PatientID: "22446688",
173
- PatientSex: ""
174
- });
175
- expect(resource.gender).toBe("unknown");
176
- expect(patientToDataset(resource).PatientSex).toBe("");
177
- });
178
-
179
- test("full PN components survive", () => {
180
- const resource = patientFromDataset({
181
- PatientID: "1",
182
- PatientName: [{ Alphabetic: "FOX^JANE^MARIE^DR^III" }]
183
- });
184
- expect(patientToDataset(resource).PatientName).toBe(
185
- "FOX^JANE^MARIE^DR^III"
186
- );
187
- });
188
- });
189
-
190
- describe("inverse helpers", () => {
191
- test("humanNameToPersonName trims trailing empties", () => {
192
- expect(humanNameToPersonName({ family: "FOX", given: ["JANE"] })).toBe(
193
- "FOX^JANE"
194
- );
195
- expect(humanNameToPersonName({ given: ["JANE"] })).toBe("^JANE");
196
- expect(humanNameToPersonName({})).toBe(null);
197
- expect(humanNameToPersonName(null)).toBe(null);
198
- });
199
-
200
- // Regression for review finding 19: a HumanName carrying only `text`
201
- // used to map to null, and patientToDataset's deterministic overwrite
202
- // then erased the existing PatientName. Text-only names are common in
203
- // real FHIR feeds, so `text` must survive as a single-component PN.
204
- test("text-only HumanName falls back to text (finding 19)", () => {
205
- expect(humanNameToPersonName({ text: "Jane Doe" })).toBe("Jane Doe");
206
-
207
- const result = patientToDataset({
208
- resourceType: "Patient",
209
- name: [{ text: "Jane Doe" }],
210
- gender: "female"
211
- });
212
- expect(result.PatientName).toBe("Jane Doe");
213
- expect(result.PatientName).not.toBe("");
214
- });
215
-
216
- test("structured parts still win over text (finding 19)", () => {
217
- expect(
218
- humanNameToPersonName({
219
- family: "FOX",
220
- given: ["JANE"],
221
- text: "Jane Fox"
222
- })
223
- ).toBe("FOX^JANE");
224
- });
225
-
226
- test("isoDateToDicom accepts full dates and passthrough DA", () => {
227
- expect(isoDateToDicom("1980-04-15")).toBe("19800415");
228
- expect(isoDateToDicom("19800415")).toBe("19800415");
229
- expect(isoDateToDicom("1980-04-15T10:30:00Z")).toBe("19800415");
230
- expect(isoDateToDicom("1980")).toBe(null);
231
- expect(isoDateToDicom("1980-04")).toBe(null);
232
- expect(isoDateToDicom("")).toBe(null);
233
- });
234
- });
@@ -1,313 +0,0 @@
1
- // packages/fhir/test/toFhir.test.js
2
- //
3
- // @dcmjs-org/fhir — the FHIR sink. Parses the committed sample-dicom.dcm
4
- // fixture with @dcmjs-org/parser, naturalizes it, and asserts the FHIR
5
- // output against the fixture's known ground truth (MR study, patient
6
- // "Fall 3", PatientID 11791306742903).
7
- //
8
- // The v2 original read test/sample-dicom.dcm through the dcmjs umbrella;
9
- // here the fixture comes from packages/fixtures/dicom (same bytes, but
10
- // its upstream provenance is still being traced) and the parse goes
11
- // through the event-stream reader so the package tests stay off
12
- // @dcmjs-org/legacy. The facade half of the v2 "dcmjs.fhir umbrella
13
- // namespace" tests (an ArrayBuffer straight to FHIR) landed with the
14
- // event-stream slice as DicomEventStream.fromPart10(bytes).toFhir() —
15
- // see test/eventStream/fhirPdfEventStream.test.js at the repo root.
16
-
17
- import fs from "fs";
18
- import path from "path";
19
-
20
- import { fromPart10, NaturalizedListener } from "@dcmjs-org/parser";
21
- import {
22
- toFhir,
23
- toBundle,
24
- patientFromDataset,
25
- imagingStudyFromDatasets,
26
- parsePersonName,
27
- dicomDateTimeToIso,
28
- sexToGender
29
- } from "../src/index.js";
30
-
31
- const FIXTURE = path.join(
32
- __dirname,
33
- "..",
34
- "..",
35
- "fixtures",
36
- "dicom",
37
- "sample-dicom.dcm"
38
- );
39
- const STUDY_UID = "1.2.276.0.50.192168001092.11156604.14547392.4";
40
-
41
- async function loadNaturalizedFixture() {
42
- const buffer = fs.readFileSync(FIXTURE);
43
- const arrayBuffer = buffer.buffer.slice(
44
- buffer.byteOffset,
45
- buffer.byteOffset + buffer.byteLength
46
- );
47
- const listener = new NaturalizedListener();
48
- await fromPart10(arrayBuffer, listener);
49
- return listener.result;
50
- }
51
-
52
- describe("@dcmjs-org/fhir helpers", () => {
53
- test("parsePersonName handles naturalized PN, raw strings, and empties", () => {
54
- expect(parsePersonName([{ Alphabetic: "Doe^John^Q^Dr^Jr" }])).toEqual({
55
- family: "Doe",
56
- given: "John",
57
- middle: "Q",
58
- prefix: "Dr",
59
- suffix: "Jr",
60
- text: "Doe John Q Dr Jr"
61
- });
62
- expect(parsePersonName("Fall 3")).toMatchObject({
63
- family: "Fall 3",
64
- text: "Fall 3"
65
- });
66
- expect(parsePersonName(null)).toBeNull();
67
- expect(parsePersonName([])).toBeNull();
68
- });
69
-
70
- test("dicomDateTimeToIso writes the time only with a timezone", () => {
71
- expect(dicomDateTimeToIso("20010101")).toBe("2001-01-01");
72
- expect(dicomDateTimeToIso("20010101", "102231")).toBe("2001-01-01");
73
- expect(dicomDateTimeToIso("20010101", "102231", "+0130")).toBe(
74
- "2001-01-01T10:22:31+01:30"
75
- );
76
- expect(dicomDateTimeToIso(null)).toBeNull();
77
- // Legacy ACR-NEMA forms, and values that are not a date
78
- expect(dicomDateTimeToIso("1980.05.17", "10:22:31", "+0100")).toBe(
79
- "1980-05-17T10:22:31+01:00"
80
- );
81
- expect(dicomDateTimeToIso("1980-5-17")).toBeNull();
82
- expect(dicomDateTimeToIso("20010101", "10h22", "+0100")).toBe(
83
- "2001-01-01"
84
- );
85
- });
86
-
87
- test("sexToGender maps DICOM codes", () => {
88
- expect(sexToGender("M")).toBe("male");
89
- expect(sexToGender("F")).toBe("female");
90
- expect(sexToGender("O")).toBe("other");
91
- expect(sexToGender(undefined)).toBe("unknown");
92
- });
93
- });
94
-
95
- describe("@dcmjs-org/fhir sink", () => {
96
- let dataset;
97
- beforeAll(async () => {
98
- dataset = await loadNaturalizedFixture();
99
- });
100
-
101
- test("patientFromDataset builds a FHIR Patient from the patient module", () => {
102
- const patient = patientFromDataset(dataset);
103
-
104
- expect(patient.resourceType).toBe("Patient");
105
- expect(patient.identifier[0].value).toBe("11791306742903");
106
- expect(patient.identifier[0].type.coding[0].code).toBe("MR");
107
- expect(patient.name[0].family).toBe("Fall 3");
108
- expect(["male", "female", "other", "unknown"]).toContain(
109
- patient.gender
110
- );
111
- // No deployment-specific fields ever, and no sex extension that
112
- // DICOM does not record (FHIR-USR-3)
113
- expect(patient.id).toBeUndefined();
114
- expect(patient.meta).toBeUndefined();
115
- expect(patient.extension).toBeUndefined();
116
- });
117
-
118
- test("toFhir returns { patient, imagingStudy } with DICOM identity intact", () => {
119
- const { patient, imagingStudy } = toFhir(dataset);
120
-
121
- expect(patient.resourceType).toBe("Patient");
122
- expect(imagingStudy.resourceType).toBe("ImagingStudy");
123
- expect(imagingStudy.status).toBe("available");
124
- expect(imagingStudy.identifier[0]).toEqual({
125
- use: "official",
126
- system: "urn:dicom:uid",
127
- value: `urn:oid:${STUDY_UID}`
128
- });
129
- expect(imagingStudy.numberOfSeries).toBe(1);
130
- expect(imagingStudy.numberOfInstances).toBe(1);
131
- expect(imagingStudy.modality[0].code).toBe("MR");
132
- // The fixture has no TimezoneOffsetFromUTC, so only the date.
133
- expect(imagingStudy.started).toBe("2001-01-01");
134
-
135
- const series = imagingStudy.series[0];
136
- expect(series.modality.code).toBe("MR");
137
- expect(series.modality.display).toBe("Magnetic Resonance");
138
- expect(series.number).toBe(2101);
139
- expect(series.instance[0].number).toBe(10);
140
- expect(series.instance[0].sopClass.system).toBe("urn:ietf:rfc:3986");
141
- expect(series.instance[0].sopClass.code).toMatch(/^urn:oid:/);
142
- });
143
-
144
- test("without options.subject, the ImagingStudy references the returned patient", () => {
145
- const { imagingStudy } = toFhir(dataset);
146
- expect(imagingStudy.subject).toEqual({ reference: "./patient" });
147
- });
148
-
149
- test("options.subject passes through as ImagingStudy.subject", () => {
150
- const { imagingStudy } = toFhir(dataset, {
151
- subject: { reference: "Patient/abc", display: "Fall 3" }
152
- });
153
- expect(imagingStudy.subject).toEqual({
154
- reference: "Patient/abc",
155
- display: "Fall 3"
156
- });
157
- });
158
-
159
- test("imagingStudyFromDatasets aggregates multiple instances into one study", () => {
160
- const study = imagingStudyFromDatasets([dataset, dataset]);
161
- expect(study.numberOfSeries).toBe(1);
162
- expect(study.numberOfInstances).toBe(2);
163
- expect(study.series[0].instance).toHaveLength(2);
164
- });
165
-
166
- test("imagingStudyFromDatasets skips a dataset of another study", () => {
167
- const other = {
168
- ...dataset,
169
- StudyInstanceUID: "9.9.9",
170
- SeriesInstanceUID: "9.9.9.1",
171
- SOPInstanceUID: "9.9.9.1.1"
172
- };
173
- const study = imagingStudyFromDatasets([dataset, other]);
174
- expect(study.identifier[0].value).toBe(`urn:oid:${STUDY_UID}`);
175
- expect(study.numberOfSeries).toBe(1);
176
- expect(study.numberOfInstances).toBe(1);
177
- });
178
-
179
- test("toBundle emits one Patient and one aggregated ImagingStudy", () => {
180
- const bundle = toBundle([dataset, dataset]);
181
-
182
- expect(bundle.resourceType).toBe("Bundle");
183
- expect(bundle.type).toBe("collection");
184
- expect(bundle.total).toBe(2);
185
-
186
- const types = bundle.entry.map(entry => entry.resource.resourceType);
187
- expect(types).toEqual(["Patient", "ImagingStudy"]);
188
- expect(bundle.entry[1].resource.numberOfInstances).toBe(2);
189
- // Relative fullUrls link the ImagingStudy to the Patient entry.
190
- expect(bundle.entry.map(entry => entry.fullUrl)).toEqual([
191
- "./entry/0",
192
- "./entry/1"
193
- ]);
194
- expect(bundle.entry[1].resource.subject).toEqual({
195
- reference: "./entry/0"
196
- });
197
- });
198
-
199
- test("series and instances hold only valid FHIR values", () => {
200
- const base = {
201
- StudyInstanceUID: "1.2.3",
202
- SOPClassUID: "1.2.840.10008.5.1.4.1.1.4"
203
- };
204
- const study = imagingStudyFromDatasets([
205
- {
206
- ...base,
207
- SeriesInstanceUID: "1.2.3.1",
208
- SOPInstanceUID: "1.2.3.1.1",
209
- Modality: "MR",
210
- SeriesNumber: -1,
211
- InstanceNumber: 2.5,
212
- BodyPartExamined: "CHEST",
213
- Laterality: "L"
214
- },
215
- // No Modality: series.modality is 1..1, so the dataset is skipped.
216
- {
217
- ...base,
218
- SeriesInstanceUID: "1.2.3.2",
219
- SOPInstanceUID: "1.2.3.2.1"
220
- }
221
- ]);
222
- expect(study.numberOfSeries).toBe(1);
223
- const [series] = study.series;
224
- expect(series.number).toBeUndefined();
225
- expect(series.instance[0].number).toBeUndefined();
226
- expect(series.bodySite).toEqual({ display: "CHEST" });
227
- expect(series.laterality).toEqual({
228
- system: "http://snomed.info/sct",
229
- code: "7771000",
230
- display: "Left"
231
- });
232
- });
233
-
234
- test("unsupported fhirVersion throws (strict-out)", () => {
235
- expect(() => toFhir(dataset, { fhirVersion: "R5" })).toThrow(
236
- /unsupported fhirVersion/
237
- );
238
- expect(() => toBundle([dataset], { fhirVersion: "STU3" })).toThrow(
239
- /unsupported fhirVersion/
240
- );
241
- });
242
-
243
- test("empty input degrades gracefully", () => {
244
- expect(patientFromDataset({})).toBeNull();
245
- expect(imagingStudyFromDatasets([])).toBeNull();
246
- const { patient, imagingStudy } = toFhir({});
247
- expect(patient).toBeNull();
248
- expect(imagingStudy).toBeNull();
249
- });
250
-
251
- // Regression for review finding 17: a dataset with no SOPClassUID used
252
- // to fabricate the CT Image Storage UID (1.2.840.10008.5.1.4.1.1.2),
253
- // asserting an unknown instance is a CT image. FHIR R4B makes
254
- // instance.sopClass 1..1, so the instance is skipped with a warning
255
- // instead of emitted with invented identity.
256
- test("missing SOPClassUID skips the instance, never fabricates CT (finding 17)", () => {
257
- const study = imagingStudyFromDatasets([
258
- {
259
- StudyInstanceUID: "1.2.3",
260
- SeriesInstanceUID: "1.2.3.1",
261
- SOPInstanceUID: "1.2.3.4",
262
- Modality: "OT"
263
- }
264
- ]);
265
- const json = JSON.stringify(study);
266
- expect(json).not.toContain("1.2.840.10008.5.1.4.1.1.2");
267
- expect(study.numberOfInstances).toBe(0);
268
- expect(study.series[0].instance).toBeUndefined();
269
- });
270
-
271
- // Regression for review finding 18: a dataset with no SeriesInstanceUID
272
- // used to produce series.uid: null (invalid — ImagingStudy.series.uid is
273
- // 1..1 in R4B), and every such dataset merged under one "unknown" key.
274
- // Those datasets are now skipped with a warning, consistent with 17.
275
- test("missing SeriesInstanceUID skips the dataset, no null-uid merge (finding 18)", () => {
276
- const study = imagingStudyFromDatasets([
277
- {
278
- StudyInstanceUID: "1.2.3",
279
- SeriesInstanceUID: "1.2.3.1",
280
- SOPClassUID: "1.2.840.10008.5.1.4.1.1.4",
281
- SOPInstanceUID: "1.2.3.4",
282
- Modality: "MR"
283
- },
284
- // Two datasets from genuinely different series, both without
285
- // SeriesInstanceUID — these must not merge into one series.
286
- {
287
- StudyInstanceUID: "1.2.3",
288
- SOPClassUID: "1.2.840.10008.5.1.4.1.1.4",
289
- SOPInstanceUID: "1.2.3.5"
290
- },
291
- {
292
- StudyInstanceUID: "1.2.3",
293
- SOPClassUID: "1.2.840.10008.5.1.4.1.1.4",
294
- SOPInstanceUID: "1.2.3.6"
295
- }
296
- ]);
297
- expect(study.numberOfSeries).toBe(1);
298
- expect(study.series).toHaveLength(1);
299
- expect(study.series[0].uid).toBe("1.2.3.1");
300
- expect(study.series.every(entry => entry.uid !== null)).toBe(true);
301
- expect(study.numberOfInstances).toBe(1);
302
- });
303
- });
304
-
305
- // The v2 suite ends with a "dcmjs.fhir umbrella namespace" block
306
- // (dcmjs.fhir.fromPart10 straight to FHIR, and the namespace re-exports).
307
- // The facade integration landed with the event-stream slice: the
308
- // bytes-to-FHIR composition is DicomEventStream.fromPart10(x).toFhir(),
309
- // pinned in test/eventStream/fhirPdfEventStream.test.js at the repo root.
310
- // The dcmjs.fhir NAMESPACE itself (the spread of this package's exports
311
- // plus the fromPart10 convenience onto the dcmjs default export) is the
312
- // step-7 wrapper package's surface — the two namespace tests return when
313
- // that wrapper assembles the scoped packages.