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