@dcmjs-org/parser 1.0.0-beta.1 → 1.0.0-beta.10

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/dist/index.cjs CHANGED
@@ -322,12 +322,11 @@ class CollectorListener extends EventStreamListener {
322
322
  * source-agnostic contract, the SAME naturalized object is produced from Part 10
323
323
  * bytes, a dcmjs dict, or DICOMweb JSON.
324
324
  *
325
- * Scope (D1): keyword naming, VM cardinality, single-item sequences with hidden
326
- * length (§12, via core addAccessors, no Proxy), empty→null/[], binary
327
- * assembly (InlineBinary/BulkDataURI), and the cardinality-violation policy
328
- * (§15.2, default warnAndPreserve). Deferred to D2: the PN proxy/toString sugar
329
- * (§17), private-tag grouping (§18), and precision/raw retention (§16/§27, which
330
- * needs the contract to carry raw values).
325
+ * It gives the same object as DicomMetaDictionary.naturalizeDataset:
326
+ * docs/specs/naturalized-dataset.md is the specification of both (keys, VM
327
+ * cardinality, single-item sequences, `_vrMap`, private blocks, binary values
328
+ * as a list of fragments). It also applies the cardinality-violation policy
329
+ * (default warnAndPreserve) and keeps the source string of an inexact number.
331
330
  *
332
331
  * Sequence note: a DICOM sequence's declared VM ("1") constrains how many times
333
332
  * the attribute appears, NOT its item count — multi-item sequences (e.g.
@@ -340,10 +339,14 @@ class NaturalizedListener extends EventStreamListener {
340
339
  * @param {string} [options.cardinalityViolationPolicy="warnAndPreserve"]
341
340
  * One of preserve | discardExtra | warnAndPreserve | warnAndDiscardExtra |
342
341
  * recordAndPreserve | recordAndDiscardExtra | throw.
342
+ * @param {"ArrayBuffer"|"Uint8Array"} [options.binaryAs="ArrayBuffer"]
343
+ * The type of each fragment or frame of a binary value, as in
344
+ * DicomMetaDictionary.naturalizeDataset.
343
345
  */
344
346
  constructor(options = {}, ...filters) {
345
347
  super(...filters);
346
348
  this.policy = options.cardinalityViolationPolicy || "warnAndPreserve";
349
+ this.binaryAs = core.checkBinaryAs(options.binaryAs);
347
350
  this.result = {};
348
351
  this.meta = {};
349
352
  this.violations = [];
@@ -364,20 +367,22 @@ class NaturalizedListener extends EventStreamListener {
364
367
  }
365
368
 
366
369
  _baseStartDataSet() {
367
- this.result = {};
368
- this.meta = {};
370
+ this.result = { _vrMap: {} };
371
+ this.meta = { _vrMap: {} };
369
372
  this.violations = [];
370
- this._stack = [{ kind: "object", obj: this.result }];
373
+ this._stack = [objectFrame(this.result)];
371
374
  }
372
375
 
373
- _baseEndDataSet() {}
376
+ _baseEndDataSet() {
377
+ endObject(this._stack[0]);
378
+ }
374
379
 
375
380
  _baseStartFileMetaInformation() {
376
- this._stack.push({ kind: "object", obj: this.meta });
381
+ this._stack.push(objectFrame(this.meta));
377
382
  }
378
383
 
379
384
  _baseEndFileMetaInformation() {
380
- this._stack.pop();
385
+ endObject(this._stack.pop());
381
386
  }
382
387
 
383
388
  _baseStartElement(tag, info = {}) {
@@ -421,9 +426,7 @@ class NaturalizedListener extends EventStreamListener {
421
426
  if (bot && bot.length) {
422
427
  fragments = mergeFragmentsPerBotWindow(fragments, bot);
423
428
  }
424
- frame.binary = {
425
- InlineBinary: fragments.length === 1 ? fragments[0] : fragments
426
- };
429
+ frame.binary = core.binaryValue(fragments, this.binaryAs);
427
430
  frame._fragments = undefined;
428
431
  frame._binaryInfo = undefined;
429
432
  }
@@ -444,20 +447,45 @@ class NaturalizedListener extends EventStreamListener {
444
447
  }
445
448
  }
446
449
 
447
- if (isPrivateTag(frame.tag)) {
448
- this._placePrivate(targetFrame, frame);
450
+ if (core.isPrivateTag(frame.tag)) {
451
+ const entry = core.registeredTagEntry(frame.tag);
452
+ let value = frame.binary;
453
+ if (value === undefined && core.BINARY_VRS.has(frame.vr)) {
454
+ // a binary VR keeps its list, also of non-buffer values
455
+ value = core.binaryValue(frame.values);
456
+ } else if (value === undefined) {
457
+ value = this._shapeValues(frame, entry, frame.tag);
458
+ if (frame.vr === "PN" && value !== null) {
459
+ value = addPersonNameAccessors(value);
460
+ }
461
+ }
462
+ targetFrame.privates.push({
463
+ tag: frame.tag,
464
+ vr: frame.vr,
465
+ value,
466
+ entry
467
+ });
449
468
  return;
450
469
  }
451
470
 
452
- const entry = core.lookupTagHex(frame.tag);
453
- const key = (entry && entry.name) || frame.tag;
471
+ // the dictionary lookup of naturalizeDataset: repeating groups and
472
+ // registerTag() entries included
473
+ const entry = core.registeredTagEntry(frame.tag);
474
+ const key = (entry && entry.name) || frame.tag.toUpperCase();
475
+ core.recordVr(targetFrame.obj._vrMap, key, entry, frame.vr);
454
476
  if (frame.binary !== undefined) {
455
477
  targetFrame.obj[key] = frame.binary;
456
478
  return;
457
479
  }
458
- let shaped = this._shapeValues(frame, entry, key);
459
- if (frame.vr === "PN" && shaped !== null) {
460
- shaped = addPersonNameAccessors(shaped);
480
+ if (core.BINARY_VRS.has(frame.vr)) {
481
+ targetFrame.obj[key] = core.binaryValue(frame.values);
482
+ return;
483
+ }
484
+ const shaped = this._shapeValues(frame, entry, key);
485
+ if (frame.vr === "PN") {
486
+ // one conversion, and the converting setter (NAT-U-VAL-5)
487
+ core.setPersonName(targetFrame.obj, key, shaped, core.valueLength(entry));
488
+ return;
461
489
  }
462
490
  targetFrame.obj[key] = shaped;
463
491
  }
@@ -467,11 +495,12 @@ class NaturalizedListener extends EventStreamListener {
467
495
  }
468
496
 
469
497
  _baseStartItem() {
470
- this._stack.push({ kind: "object", obj: {} });
498
+ this._stack.push(objectFrame({ _vrMap: {} }));
471
499
  }
472
500
 
473
501
  _baseEndItem() {
474
502
  const itemFrame = this._stack.pop();
503
+ endObject(itemFrame);
475
504
  // The enclosing frame is the sequence.
476
505
  this._stack[this._stack.length - 1].items.push(itemFrame.obj);
477
506
  }
@@ -479,69 +508,32 @@ class NaturalizedListener extends EventStreamListener {
479
508
  _baseEndSequence() {
480
509
  const frame = this._stack.pop();
481
510
  const targetFrame = this._objectFrame();
482
- const shaped = this._shapeSequence(frame, core.lookupTagHex(frame.tag));
483
-
484
- if (isPrivateTag(frame.tag)) {
485
- this._placePrivateValue(targetFrame, frame.tag, frame.vr, shaped);
511
+ if (core.isPrivateTag(frame.tag)) {
512
+ const entry = core.registeredTagEntry(frame.tag);
513
+ const shaped = this._shapeSequence(frame, entry);
514
+ targetFrame.privates.push({
515
+ tag: frame.tag,
516
+ vr: frame.vr,
517
+ value: shaped,
518
+ entry
519
+ });
486
520
  return;
487
521
  }
488
- const entry = core.lookupTagHex(frame.tag);
489
- const key = (entry && entry.name) || frame.tag;
522
+ // the dictionary lookup of naturalizeDataset: repeating groups and
523
+ // registerTag() entries included
524
+ const entry = core.registeredTagEntry(frame.tag);
525
+ const shaped = this._shapeSequence(frame, entry);
526
+ const key = (entry && entry.name) || frame.tag.toUpperCase();
527
+ core.recordVr(targetFrame.obj._vrMap, key, entry, frame.vr);
490
528
  targetFrame.obj[key] = shaped;
491
529
  }
492
530
 
493
- // --- private-tag grouping (§18) -----------------------------------------
494
-
495
- _placePrivate(targetFrame, frame) {
496
- const elem = parseInt(frame.tag.slice(4, 8), 16);
497
- // Private creator (gggg,00xx): record it for the block; do NOT emit it
498
- // as an ordinary attribute (§18.5).
499
- if (elem <= 0x00ff) {
500
- const v =
501
- frame.values && frame.values.length ? frame.values[0] : null;
502
- if (v != null) {
503
- targetFrame.creators = targetFrame.creators || {};
504
- targetFrame.creators[elem] = String(v);
505
- }
506
- return;
507
- }
508
- const value =
509
- frame.binary !== undefined
510
- ? frame.binary
511
- : privateShape(frame.values);
512
- this._placePrivateValue(targetFrame, frame.tag, frame.vr, value);
513
- }
514
-
515
- _placePrivateValue(targetFrame, tag, vr, value) {
516
- const elem = parseInt(tag.slice(4, 8), 16);
517
- const slot = elem >> 8; // creator slot (high byte of the element)
518
- const offset = elem & 0xff; // block-relative element (low byte)
519
- const creator = targetFrame.creators && targetFrame.creators[slot];
520
-
521
- if (creator) {
522
- const groupKey = `${hex2(slot)}:${creator}`;
523
- let group = targetFrame.obj[groupKey];
524
- if (!group) {
525
- group = { originalTagOffset: slot };
526
- targetFrame.obj[groupKey] = group;
527
- }
528
- group[privateKeyFor(tag, creator, offset, group)] = value;
529
- return;
530
- }
531
- // §18.4: no identifiable creator -> full tag key, unknown attribute shape.
532
- targetFrame.obj[tag] = {
533
- vr,
534
- Value: Array.isArray(value) ? value : value == null ? [] : [value]
535
- };
536
- }
537
-
538
531
  // --- cardinality shaping ------------------------------------------------
539
532
 
540
533
  _shapeValues(frame, entry, key) {
541
534
  const values = frame.values;
542
- const multi = core.isMultiVM(entry && entry.vm);
543
-
544
- if (multi) {
535
+ // no dictionary VM (a private or unknown element): as for VM > 1
536
+ if (core.valueLength(entry) !== 1) {
545
537
  // §10/§11: always list-like; present-empty -> [].
546
538
  return values;
547
539
  }
@@ -557,19 +549,9 @@ class NaturalizedListener extends EventStreamListener {
557
549
  }
558
550
 
559
551
  _shapeSequence(frame, entry) {
560
- const items = frame.items;
561
- const declaredMulti = core.isMultiVM(entry && entry.vm);
562
-
563
- if (items.length === 0) {
564
- return []; // §12 present-empty
565
- }
566
- if (items.length === 1 && !declaredMulti) {
567
- // §12: the item object itself, with a hidden [0] and length 1
568
- return core.addAccessors(items);
569
- }
570
- // §13: multiple items -> list-like. Not a violation (declared SQ VM
571
- // constrains attribute occurrence, not item count).
572
- return items;
552
+ // a sequence's VM constrains the attribute, not its item count, so
553
+ // more items are a list, not a violation (NAT-U-SQ)
554
+ return core.sequenceValue(frame.items, entry);
573
555
  }
574
556
 
575
557
  _applyViolation(keyword, values, declaredMax) {
@@ -602,36 +584,16 @@ class NaturalizedListener extends EventStreamListener {
602
584
  }
603
585
 
604
586
  /**
605
- * A private tag has an odd group number and an element at or above 0x0010 (the
606
- * first usable private creator slot). Group-length (0x0000) and reserved low
607
- * elements fall through to standard handling.
587
+ * A dataset or item frame. Its private elements wait in `privates` until the
588
+ * level ends, so a creator that comes after its data still applies (§18).
608
589
  */
609
- function isPrivateTag(tag) {
610
- const group = parseInt(tag.slice(0, 4), 16);
611
- const elem = parseInt(tag.slice(4, 8), 16);
612
- return (group & 1) === 1 && elem >= 0x0010;
613
- }
614
-
615
- /** Two-hex-digit uppercase, e.g. 0x10 -> "10". */
616
- function hex2(n) {
617
- return n.toString(16).toUpperCase().padStart(2, "0");
590
+ function objectFrame(obj) {
591
+ return { kind: "object", obj, privates: [] };
618
592
  }
619
593
 
620
- /**
621
- * Block-relative key for a private data element (§18.2): the registered private
622
- * name when the (creator, offset) is known in the private dictionary and the
623
- * name is meaningful and non-colliding; otherwise the numeric block-relative
624
- * offset. Registered names stay scoped to the creator group.
625
- */
626
- function privateKeyFor(tag, creator, offset, group) {
627
- const numeric = hex2(offset);
628
- const reg = core.lookupPrivateTag(
629
- `(${tag.slice(0, 4)},"${creator}",${numeric})`
630
- );
631
- if (reg && reg.name && reg.name !== "Unknown" && !(reg.name in group)) {
632
- return reg.name;
633
- }
634
- return numeric;
594
+ function endObject(frame) {
595
+ core.placePrivateElements(frame.obj, frame.obj._vrMap, frame.privates);
596
+ frame.privates = [];
635
597
  }
636
598
 
637
599
  /**
@@ -682,14 +644,6 @@ function canonicalDecimal(s) {
682
644
  return neg && body !== "0" ? `-${body}` : body;
683
645
  }
684
646
 
685
- /** Shape a private data value with no VM info: scalar if one value, else array. */
686
- function privateShape(values) {
687
- if (values.length === 0) {
688
- return null;
689
- }
690
- return values.length === 1 ? values[0] : values.slice();
691
- }
692
-
693
647
  /**
694
648
  * Add Person Name accessors (§17): a non-enumerable toString() returning the raw
695
649
  * PN string and toJSON() keeping the DICOM JSON model. Component access
@@ -779,7 +733,7 @@ function emitAttribute(listener, tag, attr) {
779
733
  if (attr.InlineBinary !== undefined) {
780
734
  listener.startElement(tag, { vr });
781
735
  listener.startBinary({ encapsulated: false });
782
- listener.binaryFragment(base64ToArrayBuffer(attr.InlineBinary));
736
+ listener.binaryFragment(core.base64ToArrayBuffer(attr.InlineBinary));
783
737
  listener.endBinary();
784
738
  listener.endElement();
785
739
  return;
@@ -802,23 +756,6 @@ function isMetaTag(tag) {
802
756
  return tag.slice(0, 4) === "0002";
803
757
  }
804
758
 
805
- /** Decode a base64 string into an ArrayBuffer (Node and browser). */
806
- function base64ToArrayBuffer(b64) {
807
- if (typeof Buffer !== "undefined") {
808
- const buf = Buffer.from(b64, "base64");
809
- return buf.buffer.slice(
810
- buf.byteOffset,
811
- buf.byteOffset + buf.byteLength
812
- );
813
- }
814
- const binary = atob(b64);
815
- const bytes = new Uint8Array(binary.length);
816
- for (let i = 0; i < binary.length; i++) {
817
- bytes[i] = binary.charCodeAt(i);
818
- }
819
- return bytes.buffer;
820
- }
821
-
822
759
  /**
823
760
  * fromDataSet — the reference event-stream generator for slice A.
824
761
  *
@@ -954,7 +891,7 @@ function emitInlineBinary(listener, tag, entry, values) {
954
891
  }
955
892
 
956
893
  function isBinary(values) {
957
- return values.some(v => v instanceof ArrayBuffer || ArrayBuffer.isView(v));
894
+ return values.some(core.isBinaryData);
958
895
  }
959
896
 
960
897
  /** True for a naturalized binary wrapper: { InlineBinary: <content> }. */
@@ -971,7 +908,7 @@ function isInlineBinary(v) {
971
908
  /** Coerce one InlineBinary fragment (buffer, view, or base64) to bytes. */
972
909
  function toBinaryFragment(fragment) {
973
910
  if (typeof fragment === "string") {
974
- return base64ToArrayBuffer(fragment);
911
+ return core.base64ToArrayBuffer(fragment);
975
912
  }
976
913
  return fragment;
977
914
  }
@@ -986,6 +923,29 @@ function isBulkDataReference(v) {
986
923
  );
987
924
  }
988
925
 
926
+ /**
927
+ * fromNaturalized — the naturalized-dataset source. It denaturalizes the
928
+ * dataset (and its `_meta`, when present) with
929
+ * DicomMetaDictionary.denaturalizeDataset and streams the result through
930
+ * fromDataSet, so every sink (Part10Writer, DicomWebJsonWriter, ...) undoes
931
+ * the naturalized form the same way, private blocks included.
932
+ *
933
+ * @param {Object} dataset - a naturalized dataset
934
+ * @param {import("./EventStreamListener").EventStreamListener} listener
935
+ */
936
+ function fromNaturalized(dataset, listener) {
937
+ // no copy of the dataset: a copy loses the alias deletes (NAT-U-HIST-7);
938
+ // denaturalizeDataset skips the _meta member
939
+ const meta = dataset._meta;
940
+ return fromDataSet(
941
+ {
942
+ meta: meta ? core.DicomMetaDictionary.denaturalizeDataset(meta) : null,
943
+ dict: core.DicomMetaDictionary.denaturalizeDataset(dataset)
944
+ },
945
+ listener
946
+ );
947
+ }
948
+
989
949
  /**
990
950
  * createEventAsyncIterable — the pull adapter of the hybrid contract.
991
951
  *
@@ -1177,7 +1137,7 @@ function emitValues(listener, tag, vrInstance, el, values, rawValues) {
1177
1137
  : values === undefined || values === null
1178
1138
  ? []
1179
1139
  : [values];
1180
- if (list.some(isBufferLike)) {
1140
+ if (list.some(core.isBinaryData)) {
1181
1141
  listener.startElement(tag, { vr: vrInstance.type, length: el.length });
1182
1142
  listener.startBinary({ encapsulated: false });
1183
1143
  for (const buf of list) {
@@ -1210,10 +1170,6 @@ function isItemDictLike(v) {
1210
1170
  );
1211
1171
  }
1212
1172
 
1213
- function isBufferLike(v) {
1214
- return v instanceof ArrayBuffer || ArrayBuffer.isView(v);
1215
- }
1216
-
1217
1173
  /**
1218
1174
  * Shared element-decode core extracted from src/lazy/LazyDicomReader.js.
1219
1175
  *
@@ -3206,18 +3162,22 @@ async function fromPart10(buffer, listener, options = {}) {
3206
3162
  await fromPart10Stream(bytes, listener, options);
3207
3163
  }
3208
3164
 
3165
+ Object.defineProperty(exports, "base64ToArrayBuffer", {
3166
+ enumerable: true,
3167
+ get: function () { return core.base64ToArrayBuffer; }
3168
+ });
3209
3169
  exports.CONTRACT_VERSION = CONTRACT_VERSION;
3210
3170
  exports.CollectorListener = CollectorListener;
3211
3171
  exports.EVENT_STREAM_VOCABULARY = EVENT_STREAM_VOCABULARY;
3212
3172
  exports.EventStreamListener = EventStreamListener;
3213
3173
  exports.NaturalizedListener = NaturalizedListener;
3214
- exports.base64ToArrayBuffer = base64ToArrayBuffer;
3215
3174
  exports.createEventAsyncIterable = createEventAsyncIterable;
3216
3175
  exports.emitDecodedLeaf = emitDecodedLeaf;
3217
3176
  exports.emitEntry = emitEntry;
3218
3177
  exports.emitValues = emitValues;
3219
3178
  exports.fromDataSet = fromDataSet;
3220
3179
  exports.fromDicomWebJson = fromDicomWebJson;
3180
+ exports.fromNaturalized = fromNaturalized;
3221
3181
  exports.fromPart10 = fromPart10;
3222
3182
  exports.fromPart10Stream = fromPart10Stream;
3223
3183
  exports.mergeFragmentsPerBotWindow = mergeFragmentsPerBotWindow;