@dcmjs-org/parser 1.0.0-beta.3 → 1.0.0-beta.5

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,4 @@
1
- import { lookupTagHex, isMultiVM, addAccessors, log, dicomJson, lookupPrivateTag, base64ToArrayBuffer, 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
2
  export { base64ToArrayBuffer } from '@dcmjs-org/core';
3
3
  import pako from 'pako';
4
4
 
@@ -321,12 +321,11 @@ class CollectorListener extends EventStreamListener {
321
321
  * source-agnostic contract, the SAME naturalized object is produced from Part 10
322
322
  * bytes, a dcmjs dict, or DICOMweb JSON.
323
323
  *
324
- * Scope (D1): keyword naming, VM cardinality, single-item sequences with hidden
325
- * length (§12, via core addAccessors, no Proxy), empty→null/[], binary
326
- * assembly (InlineBinary/BulkDataURI), and the cardinality-violation policy
327
- * (§15.2, default warnAndPreserve). Deferred to D2: the PN proxy/toString sugar
328
- * (§17), private-tag grouping (§18), and precision/raw retention (§16/§27, which
329
- * 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.
330
329
  *
331
330
  * Sequence note: a DICOM sequence's declared VM ("1") constrains how many times
332
331
  * the attribute appears, NOT its item count — multi-item sequences (e.g.
@@ -339,10 +338,14 @@ class NaturalizedListener extends EventStreamListener {
339
338
  * @param {string} [options.cardinalityViolationPolicy="warnAndPreserve"]
340
339
  * One of preserve | discardExtra | warnAndPreserve | warnAndDiscardExtra |
341
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.
342
344
  */
343
345
  constructor(options = {}, ...filters) {
344
346
  super(...filters);
345
347
  this.policy = options.cardinalityViolationPolicy || "warnAndPreserve";
348
+ this.binaryAs = checkBinaryAs(options.binaryAs);
346
349
  this.result = {};
347
350
  this.meta = {};
348
351
  this.violations = [];
@@ -363,20 +366,22 @@ class NaturalizedListener extends EventStreamListener {
363
366
  }
364
367
 
365
368
  _baseStartDataSet() {
366
- this.result = {};
367
- this.meta = {};
369
+ this.result = { _vrMap: {} };
370
+ this.meta = { _vrMap: {} };
368
371
  this.violations = [];
369
- this._stack = [{ kind: "object", obj: this.result }];
372
+ this._stack = [objectFrame(this.result)];
370
373
  }
371
374
 
372
- _baseEndDataSet() {}
375
+ _baseEndDataSet() {
376
+ endObject(this._stack[0]);
377
+ }
373
378
 
374
379
  _baseStartFileMetaInformation() {
375
- this._stack.push({ kind: "object", obj: this.meta });
380
+ this._stack.push(objectFrame(this.meta));
376
381
  }
377
382
 
378
383
  _baseEndFileMetaInformation() {
379
- this._stack.pop();
384
+ endObject(this._stack.pop());
380
385
  }
381
386
 
382
387
  _baseStartElement(tag, info = {}) {
@@ -420,9 +425,7 @@ class NaturalizedListener extends EventStreamListener {
420
425
  if (bot && bot.length) {
421
426
  fragments = mergeFragmentsPerBotWindow(fragments, bot);
422
427
  }
423
- frame.binary = {
424
- InlineBinary: fragments.length === 1 ? fragments[0] : fragments
425
- };
428
+ frame.binary = binaryValue(fragments, this.binaryAs);
426
429
  frame._fragments = undefined;
427
430
  frame._binaryInfo = undefined;
428
431
  }
@@ -444,19 +447,44 @@ class NaturalizedListener extends EventStreamListener {
444
447
  }
445
448
 
446
449
  if (isPrivateTag(frame.tag)) {
447
- 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
+ });
448
467
  return;
449
468
  }
450
469
 
451
- const entry = lookupTagHex(frame.tag);
452
- 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);
453
475
  if (frame.binary !== undefined) {
454
476
  targetFrame.obj[key] = frame.binary;
455
477
  return;
456
478
  }
457
- let shaped = this._shapeValues(frame, entry, key);
458
- if (frame.vr === "PN" && shaped !== null) {
459
- 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;
460
488
  }
461
489
  targetFrame.obj[key] = shaped;
462
490
  }
@@ -466,11 +494,12 @@ class NaturalizedListener extends EventStreamListener {
466
494
  }
467
495
 
468
496
  _baseStartItem() {
469
- this._stack.push({ kind: "object", obj: {} });
497
+ this._stack.push(objectFrame({ _vrMap: {} }));
470
498
  }
471
499
 
472
500
  _baseEndItem() {
473
501
  const itemFrame = this._stack.pop();
502
+ endObject(itemFrame);
474
503
  // The enclosing frame is the sequence.
475
504
  this._stack[this._stack.length - 1].items.push(itemFrame.obj);
476
505
  }
@@ -478,69 +507,32 @@ class NaturalizedListener extends EventStreamListener {
478
507
  _baseEndSequence() {
479
508
  const frame = this._stack.pop();
480
509
  const targetFrame = this._objectFrame();
481
- const shaped = this._shapeSequence(frame, lookupTagHex(frame.tag));
482
-
483
510
  if (isPrivateTag(frame.tag)) {
484
- 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
+ });
485
519
  return;
486
520
  }
487
- const entry = lookupTagHex(frame.tag);
488
- 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);
489
527
  targetFrame.obj[key] = shaped;
490
528
  }
491
529
 
492
- // --- private-tag grouping (§18) -----------------------------------------
493
-
494
- _placePrivate(targetFrame, frame) {
495
- const elem = parseInt(frame.tag.slice(4, 8), 16);
496
- // Private creator (gggg,00xx): record it for the block; do NOT emit it
497
- // as an ordinary attribute (§18.5).
498
- if (elem <= 0x00ff) {
499
- const v =
500
- frame.values && frame.values.length ? frame.values[0] : null;
501
- if (v != null) {
502
- targetFrame.creators = targetFrame.creators || {};
503
- targetFrame.creators[elem] = String(v);
504
- }
505
- return;
506
- }
507
- const value =
508
- frame.binary !== undefined
509
- ? frame.binary
510
- : privateShape(frame.values);
511
- this._placePrivateValue(targetFrame, frame.tag, frame.vr, value);
512
- }
513
-
514
- _placePrivateValue(targetFrame, tag, vr, value) {
515
- const elem = parseInt(tag.slice(4, 8), 16);
516
- const slot = elem >> 8; // creator slot (high byte of the element)
517
- const offset = elem & 0xff; // block-relative element (low byte)
518
- const creator = targetFrame.creators && targetFrame.creators[slot];
519
-
520
- if (creator) {
521
- const groupKey = `${hex2(slot)}:${creator}`;
522
- let group = targetFrame.obj[groupKey];
523
- if (!group) {
524
- group = { originalTagOffset: slot };
525
- targetFrame.obj[groupKey] = group;
526
- }
527
- group[privateKeyFor(tag, creator, offset, group)] = value;
528
- return;
529
- }
530
- // §18.4: no identifiable creator -> full tag key, unknown attribute shape.
531
- targetFrame.obj[tag] = {
532
- vr,
533
- Value: Array.isArray(value) ? value : value == null ? [] : [value]
534
- };
535
- }
536
-
537
530
  // --- cardinality shaping ------------------------------------------------
538
531
 
539
532
  _shapeValues(frame, entry, key) {
540
533
  const values = frame.values;
541
- const multi = isMultiVM(entry && entry.vm);
542
-
543
- if (multi) {
534
+ // no dictionary VM (a private or unknown element): as for VM > 1
535
+ if (valueLength(entry) !== 1) {
544
536
  // §10/§11: always list-like; present-empty -> [].
545
537
  return values;
546
538
  }
@@ -556,19 +548,9 @@ class NaturalizedListener extends EventStreamListener {
556
548
  }
557
549
 
558
550
  _shapeSequence(frame, entry) {
559
- const items = frame.items;
560
- const declaredMulti = isMultiVM(entry && entry.vm);
561
-
562
- if (items.length === 0) {
563
- return []; // §12 present-empty
564
- }
565
- if (items.length === 1 && !declaredMulti) {
566
- // §12: the item object itself, with a hidden [0] and length 1
567
- return addAccessors(items);
568
- }
569
- // §13: multiple items -> list-like. Not a violation (declared SQ VM
570
- // constrains attribute occurrence, not item count).
571
- 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);
572
554
  }
573
555
 
574
556
  _applyViolation(keyword, values, declaredMax) {
@@ -601,36 +583,16 @@ class NaturalizedListener extends EventStreamListener {
601
583
  }
602
584
 
603
585
  /**
604
- * A private tag has an odd group number and an element at or above 0x0010 (the
605
- * first usable private creator slot). Group-length (0x0000) and reserved low
606
- * 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).
607
588
  */
608
- function isPrivateTag(tag) {
609
- const group = parseInt(tag.slice(0, 4), 16);
610
- const elem = parseInt(tag.slice(4, 8), 16);
611
- return (group & 1) === 1 && elem >= 0x0010;
612
- }
613
-
614
- /** Two-hex-digit uppercase, e.g. 0x10 -> "10". */
615
- function hex2(n) {
616
- return n.toString(16).toUpperCase().padStart(2, "0");
589
+ function objectFrame(obj) {
590
+ return { kind: "object", obj, privates: [] };
617
591
  }
618
592
 
619
- /**
620
- * Block-relative key for a private data element (§18.2): the registered private
621
- * name when the (creator, offset) is known in the private dictionary and the
622
- * name is meaningful and non-colliding; otherwise the numeric block-relative
623
- * offset. Registered names stay scoped to the creator group.
624
- */
625
- function privateKeyFor(tag, creator, offset, group) {
626
- const numeric = hex2(offset);
627
- const reg = lookupPrivateTag(
628
- `(${tag.slice(0, 4)},"${creator}",${numeric})`
629
- );
630
- if (reg && reg.name && reg.name !== "Unknown" && !(reg.name in group)) {
631
- return reg.name;
632
- }
633
- return numeric;
593
+ function endObject(frame) {
594
+ placePrivateElements(frame.obj, frame.obj._vrMap, frame.privates);
595
+ frame.privates = [];
634
596
  }
635
597
 
636
598
  /**
@@ -681,14 +643,6 @@ function canonicalDecimal(s) {
681
643
  return neg && body !== "0" ? `-${body}` : body;
682
644
  }
683
645
 
684
- /** Shape a private data value with no VM info: scalar if one value, else array. */
685
- function privateShape(values) {
686
- if (values.length === 0) {
687
- return null;
688
- }
689
- return values.length === 1 ? values[0] : values.slice();
690
- }
691
-
692
646
  /**
693
647
  * Add Person Name accessors (§17): a non-enumerable toString() returning the raw
694
648
  * PN string and toJSON() keeping the DICOM JSON model. Component access
@@ -936,7 +890,7 @@ function emitInlineBinary(listener, tag, entry, values) {
936
890
  }
937
891
 
938
892
  function isBinary(values) {
939
- return values.some(v => v instanceof ArrayBuffer || ArrayBuffer.isView(v));
893
+ return values.some(isBinaryData);
940
894
  }
941
895
 
942
896
  /** True for a naturalized binary wrapper: { InlineBinary: <content> }. */
@@ -968,6 +922,29 @@ function isBulkDataReference(v) {
968
922
  );
969
923
  }
970
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
+
971
948
  /**
972
949
  * createEventAsyncIterable — the pull adapter of the hybrid contract.
973
950
  *
@@ -1159,7 +1136,7 @@ function emitValues(listener, tag, vrInstance, el, values, rawValues) {
1159
1136
  : values === undefined || values === null
1160
1137
  ? []
1161
1138
  : [values];
1162
- if (list.some(isBufferLike)) {
1139
+ if (list.some(isBinaryData)) {
1163
1140
  listener.startElement(tag, { vr: vrInstance.type, length: el.length });
1164
1141
  listener.startBinary({ encapsulated: false });
1165
1142
  for (const buf of list) {
@@ -1192,10 +1169,6 @@ function isItemDictLike(v) {
1192
1169
  );
1193
1170
  }
1194
1171
 
1195
- function isBufferLike(v) {
1196
- return v instanceof ArrayBuffer || ArrayBuffer.isView(v);
1197
- }
1198
-
1199
1172
  /**
1200
1173
  * Shared element-decode core extracted from src/lazy/LazyDicomReader.js.
1201
1174
  *
@@ -3188,5 +3161,5 @@ async function fromPart10(buffer, listener, options = {}) {
3188
3161
  await fromPart10Stream(bytes, listener, options);
3189
3162
  }
3190
3163
 
3191
- export { CONTRACT_VERSION, CollectorListener, EVENT_STREAM_VOCABULARY, EventStreamListener, NaturalizedListener, 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 };
3192
3165
  //# sourceMappingURL=index.mjs.map