@dcmjs-org/parser 0.0.0-stage → 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 ADDED
@@ -0,0 +1,3165 @@
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';
3
+ import pako from 'pako';
4
+
5
+ /**
6
+ * EventStreamListener — the push-core of the dcmjs event-stream contract.
7
+ *
8
+ * This is the canonical, low-allocation listener interface that every reader,
9
+ * writer, filter, validator, and anonymizer speaks (see CLAUDE_REFACTOR_PLAN.md,
10
+ * slice A). It formalizes the implicit `next`-middleware model that previously
11
+ * lived in DicomMetadataListener, with the richer, explicit vocabulary the
12
+ * Naturalized DICOM Metadata Behavior Specification calls for (§15.1).
13
+ *
14
+ * The vocabulary:
15
+ *
16
+ * Lifecycle: startDataSet / endDataSet
17
+ * startFileMetaInformation / endFileMetaInformation
18
+ * Structural: startElement / endElement
19
+ * startSequence / endSequence
20
+ * startItem / endItem
21
+ * value(v, { index, rawValue? })
22
+ * Binary: bulkDataReference
23
+ * startBinary / binaryFragment / endBinary
24
+ *
25
+ * The `value` event's options bag is optional and extensible; `rawValue` carries
26
+ * the source string (when available) for precision-preserving retention
27
+ * (§16/§27). Consumers that don't need it ignore it.
28
+ *
29
+ * Structural and value callbacks are synchronous (allocation-free hot path,
30
+ * §15.4 / §24.1). Backpressure is applied out of band via setDrain/awaitDrain,
31
+ * which generators await only at defined checkpoints (top-level element
32
+ * boundaries and binary-fragment emission).
33
+ *
34
+ * Filters are first-class: each filter is an object that may implement any
35
+ * vocabulary method as `method(next, ...args)`; calling `next(...)` invokes the
36
+ * rest of the chain, ending in the listener's `_base<Method>` implementation.
37
+ */
38
+
39
+ const EVENT_STREAM_VOCABULARY = [
40
+ "startDataSet",
41
+ "endDataSet",
42
+ "startFileMetaInformation",
43
+ "endFileMetaInformation",
44
+ "startElement",
45
+ "endElement",
46
+ "startSequence",
47
+ "endSequence",
48
+ "startItem",
49
+ "endItem",
50
+ "value",
51
+ "bulkDataReference",
52
+ "startBinary",
53
+ "binaryFragment",
54
+ "endBinary"
55
+ ];
56
+
57
+ /** Contract version — generators and listeners can declare conformance. */
58
+ const CONTRACT_VERSION = "1.0.0-A";
59
+
60
+ /**
61
+ * Merge raw encapsulated-pixel-data fragments into one buffer per Basic
62
+ * Offset Table window (issue #204 — eager-reader shape parity for
63
+ * BOT-aware listeners). The event stream itself stays raw (one
64
+ * binaryFragment per on-wire fragment); listeners that rebuild a dataset
65
+ * call this at endBinary time when startBinary carried a non-empty
66
+ * `basicOffsetTable`.
67
+ *
68
+ * Fragment offsets are reconstructed from the fragment lengths: fragment
69
+ * i's item header starts at Σ_{j<i} (8 + length_j), matching the BOT's
70
+ * item-header-relative offset convention. Grouping and merge semantics
71
+ * mirror BinaryRepresentation.readBytes: a single-fragment window stays
72
+ * that fragment's buffer; a multi-fragment window merges into one
73
+ * ArrayBuffer.
74
+ *
75
+ * @param {Array<ArrayBuffer|TypedArray>} fragments raw fragment buffers
76
+ * @param {number[]} basicOffsetTable BOT offsets (item-header relative)
77
+ * @returns {Array<ArrayBuffer|TypedArray>} one entry per BOT window
78
+ */
79
+ function mergeFragmentsPerBotWindow(fragments, basicOffsetTable) {
80
+ if (!basicOffsetTable || basicOffsetTable.length === 0) {
81
+ return fragments;
82
+ }
83
+ const toBytes = f =>
84
+ f instanceof ArrayBuffer
85
+ ? new Uint8Array(f)
86
+ : new Uint8Array(f.buffer, f.byteOffset, f.byteLength);
87
+ let offset = 0;
88
+ const placed = fragments.map(fragment => {
89
+ const length = fragment.byteLength;
90
+ const entry = { fragment, offset, length };
91
+ offset += 8 + length;
92
+ return entry;
93
+ });
94
+ const frames = [];
95
+ for (let i = 0; i < basicOffsetTable.length; i++) {
96
+ const start = basicOffsetTable[i];
97
+ const stop =
98
+ i + 1 < basicOffsetTable.length
99
+ ? basicOffsetTable[i + 1]
100
+ : Number.POSITIVE_INFINITY;
101
+ const windowFragments = placed.filter(
102
+ f => f.offset >= start && f.offset < stop
103
+ );
104
+ if (windowFragments.length === 1) {
105
+ frames.push(windowFragments[0].fragment);
106
+ continue;
107
+ }
108
+ const frameSize = windowFragments.reduce((n, f) => n + f.length, 0);
109
+ const merged = new Uint8Array(frameSize);
110
+ let position = 0;
111
+ for (const f of windowFragments) {
112
+ merged.set(toBytes(f.fragment), position);
113
+ position += f.length;
114
+ }
115
+ frames.push(merged.buffer);
116
+ }
117
+ return frames;
118
+ }
119
+
120
+ class EventStreamListener {
121
+ /**
122
+ * @param {...Object} filters - Filter objects. Each may implement any
123
+ * vocabulary method as `method(next, ...args)`.
124
+ */
125
+ constructor(...filters) {
126
+ this.filters = filters.filter(Boolean);
127
+ this._drain = null;
128
+ this._createMethodChains();
129
+ }
130
+
131
+ /**
132
+ * Builds, for every vocabulary method, a chain that threads each filter's
133
+ * implementation in front of the base implementation via `next`.
134
+ * @private
135
+ */
136
+ _createMethodChains() {
137
+ for (const methodName of EVENT_STREAM_VOCABULARY) {
138
+ const baseName = `_base${methodName[0].toUpperCase()}${methodName.slice(
139
+ 1
140
+ )}`;
141
+ let chain = this[baseName].bind(this);
142
+
143
+ for (let i = this.filters.length - 1; i >= 0; i--) {
144
+ const filter = this.filters[i];
145
+ const filterFn = filter && filter[methodName];
146
+ if (typeof filterFn === "function") {
147
+ const next = chain;
148
+ chain = (...args) => filterFn.call(this, next, ...args);
149
+ }
150
+ }
151
+
152
+ this[methodName] = chain;
153
+ }
154
+ }
155
+
156
+ // --- Backpressure -------------------------------------------------------
157
+
158
+ /**
159
+ * Install a backpressure gate. The function should return a Promise that
160
+ * resolves when it is safe to emit more data. Pass null to clear.
161
+ * @param {(() => Promise<void>) | null} fn
162
+ */
163
+ setDrain(fn) {
164
+ this._drain = typeof fn === "function" ? fn : null;
165
+ }
166
+
167
+ /**
168
+ * Await the backpressure gate (resolves immediately when none is set).
169
+ * Generators call this only at defined checkpoints.
170
+ * @returns {Promise<void>}
171
+ */
172
+ awaitDrain() {
173
+ return this._drain ? this._drain() : Promise.resolve();
174
+ }
175
+
176
+ // --- Base (no-op) vocabulary implementations ----------------------------
177
+ // Consumers override these (or subclass) to do real work. They are no-ops
178
+ // here so the base listener is a valid, inert sink.
179
+
180
+ _baseStartDataSet() {}
181
+ _baseEndDataSet() {}
182
+ _baseStartFileMetaInformation() {}
183
+ _baseEndFileMetaInformation() {}
184
+ _baseStartElement() {}
185
+ _baseEndElement() {}
186
+ _baseStartSequence() {}
187
+ _baseEndSequence() {}
188
+ _baseStartItem() {}
189
+ _baseEndItem() {}
190
+ _baseValue() {}
191
+ _baseBulkDataReference() {}
192
+ _baseStartBinary() {}
193
+ _baseBinaryFragment() {}
194
+ _baseEndBinary() {}
195
+ }
196
+
197
+ /**
198
+ * CollectorListener — a reference event-stream consumer that rebuilds a
199
+ * tag-keyed `{ meta, dict }` tree from the contract events.
200
+ *
201
+ * Its purpose is to validate the contract: a generator's event stream, fed
202
+ * through this listener, should reconstruct a tree equivalent to the existing
203
+ * dcmjs parse. It is intentionally NOT the naturalized listener (slice D) — it
204
+ * preserves the raw tag-keyed `{ vr, Value }` shape so it can be deep-compared
205
+ * against `DicomMessage.readFile` output.
206
+ *
207
+ * Value shapes match the existing parse:
208
+ * - scalar/multi-value element → { vr, Value: [...] }
209
+ * - sequence → { vr, Value: [ {itemDict}, ... ] }
210
+ * - binary → { vr, Value: [ArrayBuffer, ...] } (one entry
211
+ * per fragment; boundaries preserved, §33 —
212
+ * except encapsulated pixel data whose
213
+ * startBinary carries a non-empty
214
+ * basicOffsetTable: those fragments are
215
+ * merged per BOT window at endBinary, so the
216
+ * final Value shape matches the eager
217
+ * reader's one-entry-per-frame contract,
218
+ * issue #204)
219
+ * - bulk data reference → { vr, Value: [ { BulkDataURI } ] }
220
+ */
221
+ class CollectorListener extends EventStreamListener {
222
+ constructor(...filters) {
223
+ super(...filters);
224
+ this.result = { meta: {}, dict: {} };
225
+ this._stack = [];
226
+ this._current = null;
227
+ }
228
+
229
+ /** Top container: an object (dataset/item) or array (sequence Value). */
230
+ _top() {
231
+ return this._stack[this._stack.length - 1];
232
+ }
233
+
234
+ _baseStartDataSet() {
235
+ this.result = { meta: {}, dict: {} };
236
+ this._stack = [this.result.dict];
237
+ this._current = null;
238
+ }
239
+
240
+ _baseEndDataSet() {
241
+ this._current = null;
242
+ }
243
+
244
+ _baseStartFileMetaInformation() {
245
+ this._stack.push(this.result.meta);
246
+ }
247
+
248
+ _baseEndFileMetaInformation() {
249
+ this._stack.pop();
250
+ }
251
+
252
+ _baseStartElement(tag, info = {}) {
253
+ const el = { vr: info.vr, Value: [] };
254
+ this._top()[tag] = el;
255
+ this._current = el;
256
+ }
257
+
258
+ _baseEndElement() {
259
+ this._current = null;
260
+ }
261
+
262
+ _baseValue(v) {
263
+ this._current.Value.push(v);
264
+ }
265
+
266
+ _baseStartSequence(tag, info = {}) {
267
+ const seq = { vr: info.vr, Value: [] };
268
+ this._top()[tag] = seq;
269
+ this._stack.push(seq.Value);
270
+ this._current = null;
271
+ }
272
+
273
+ _baseEndSequence() {
274
+ this._stack.pop();
275
+ }
276
+
277
+ _baseStartItem() {
278
+ const item = {};
279
+ this._top().push(item);
280
+ this._stack.push(item);
281
+ this._current = null;
282
+ }
283
+
284
+ _baseEndItem() {
285
+ this._stack.pop();
286
+ }
287
+
288
+ _baseBulkDataReference(ref = {}) {
289
+ this._current.Value.push({ BulkDataURI: ref.uri });
290
+ }
291
+
292
+ _baseStartBinary(info = {}) {
293
+ // The current element accumulates fragments as Value entries. A
294
+ // non-empty basicOffsetTable is kept so endBinary can merge the
295
+ // fragments per BOT window (eager-reader shape parity, issue #204).
296
+ this._binaryInfo = info;
297
+ }
298
+
299
+ _baseBinaryFragment(chunk) {
300
+ this._current.Value.push(chunk);
301
+ }
302
+
303
+ _baseEndBinary() {
304
+ const bot = this._binaryInfo && this._binaryInfo.basicOffsetTable;
305
+ this._binaryInfo = null;
306
+ if (bot && bot.length && this._current) {
307
+ this._current.Value = mergeFragmentsPerBotWindow(
308
+ this._current.Value,
309
+ bot
310
+ );
311
+ }
312
+ }
313
+ }
314
+
315
+ /**
316
+ * NaturalizedListener — slice D1: the core naturalized value model.
317
+ *
318
+ * An event-stream consumer that builds the application-facing naturalized
319
+ * object per the Naturalized DICOM Metadata Behavior Specification: canonical
320
+ * keyword keys (§5) and VM-driven cardinality (§7-§14). Because it consumes the
321
+ * source-agnostic contract, the SAME naturalized object is produced from Part 10
322
+ * bytes, a dcmjs dict, or DICOMweb JSON.
323
+ *
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
+ *
330
+ * Sequence note: a DICOM sequence's declared VM ("1") constrains how many times
331
+ * the attribute appears, NOT its item count — multi-item sequences (e.g.
332
+ * PerFrameFunctionalGroupsSequence) are normal, not violations. Violations apply
333
+ * to non-sequence scalar VRs whose value count exceeds the declared VM.
334
+ */
335
+ class NaturalizedListener extends EventStreamListener {
336
+ /**
337
+ * @param {Object} [options]
338
+ * @param {string} [options.cardinalityViolationPolicy="warnAndPreserve"]
339
+ * One of preserve | discardExtra | warnAndPreserve | warnAndDiscardExtra |
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.
344
+ */
345
+ constructor(options = {}, ...filters) {
346
+ super(...filters);
347
+ this.policy = options.cardinalityViolationPolicy || "warnAndPreserve";
348
+ this.binaryAs = checkBinaryAs(options.binaryAs);
349
+ this.result = {};
350
+ this.meta = {};
351
+ this.violations = [];
352
+ // Frame stack. Each frame is one of:
353
+ // { kind: "object", obj } dataset or sequence item
354
+ // { kind: "element", tag, vr, values, binary }
355
+ // { kind: "sequence", tag, vr, items }
356
+ this._stack = [];
357
+ }
358
+
359
+ _objectFrame() {
360
+ for (let i = this._stack.length - 1; i >= 0; i--) {
361
+ if (this._stack[i].kind === "object") {
362
+ return this._stack[i];
363
+ }
364
+ }
365
+ return null;
366
+ }
367
+
368
+ _baseStartDataSet() {
369
+ this.result = { _vrMap: {} };
370
+ this.meta = { _vrMap: {} };
371
+ this.violations = [];
372
+ this._stack = [objectFrame(this.result)];
373
+ }
374
+
375
+ _baseEndDataSet() {
376
+ endObject(this._stack[0]);
377
+ }
378
+
379
+ _baseStartFileMetaInformation() {
380
+ this._stack.push(objectFrame(this.meta));
381
+ }
382
+
383
+ _baseEndFileMetaInformation() {
384
+ endObject(this._stack.pop());
385
+ }
386
+
387
+ _baseStartElement(tag, info = {}) {
388
+ this._stack.push({
389
+ kind: "element",
390
+ tag,
391
+ vr: info.vr,
392
+ values: [],
393
+ rawValues: [],
394
+ binary: undefined
395
+ });
396
+ }
397
+
398
+ _baseValue(v, opts = {}) {
399
+ const frame = this._stack[this._stack.length - 1];
400
+ frame.values.push(v);
401
+ frame.rawValues.push(opts.rawValue);
402
+ }
403
+
404
+ _baseBulkDataReference(ref = {}) {
405
+ this._stack[this._stack.length - 1].binary = { BulkDataURI: ref.uri };
406
+ }
407
+
408
+ _baseStartBinary(info = {}) {
409
+ const frame = this._stack[this._stack.length - 1];
410
+ frame._fragments = [];
411
+ // A non-empty basicOffsetTable is kept so endBinary can merge the
412
+ // raw fragments per BOT window (eager-reader frame shape parity,
413
+ // issue #204).
414
+ frame._binaryInfo = info;
415
+ }
416
+
417
+ _baseBinaryFragment(chunk) {
418
+ this._stack[this._stack.length - 1]._fragments.push(chunk);
419
+ }
420
+
421
+ _baseEndBinary() {
422
+ const frame = this._stack[this._stack.length - 1];
423
+ let fragments = frame._fragments || [];
424
+ const bot = frame._binaryInfo && frame._binaryInfo.basicOffsetTable;
425
+ if (bot && bot.length) {
426
+ fragments = mergeFragmentsPerBotWindow(fragments, bot);
427
+ }
428
+ frame.binary = binaryValue(fragments, this.binaryAs);
429
+ frame._fragments = undefined;
430
+ frame._binaryInfo = undefined;
431
+ }
432
+
433
+ _baseEndElement() {
434
+ const frame = this._stack.pop();
435
+ const targetFrame = this._objectFrame();
436
+
437
+ // §16 precision: where a canonical JS number would lose precision and a
438
+ // raw source string is available, retain the raw string.
439
+ if (frame.binary === undefined && frame.rawValues) {
440
+ for (let i = 0; i < frame.values.length; i++) {
441
+ frame.values[i] = retainPrecision(
442
+ frame.vr,
443
+ frame.values[i],
444
+ frame.rawValues[i]
445
+ );
446
+ }
447
+ }
448
+
449
+ if (isPrivateTag(frame.tag)) {
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
+ });
467
+ return;
468
+ }
469
+
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);
475
+ if (frame.binary !== undefined) {
476
+ targetFrame.obj[key] = frame.binary;
477
+ return;
478
+ }
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;
488
+ }
489
+ targetFrame.obj[key] = shaped;
490
+ }
491
+
492
+ _baseStartSequence(tag, info = {}) {
493
+ this._stack.push({ kind: "sequence", tag, vr: info.vr, items: [] });
494
+ }
495
+
496
+ _baseStartItem() {
497
+ this._stack.push(objectFrame({ _vrMap: {} }));
498
+ }
499
+
500
+ _baseEndItem() {
501
+ const itemFrame = this._stack.pop();
502
+ endObject(itemFrame);
503
+ // The enclosing frame is the sequence.
504
+ this._stack[this._stack.length - 1].items.push(itemFrame.obj);
505
+ }
506
+
507
+ _baseEndSequence() {
508
+ const frame = this._stack.pop();
509
+ const targetFrame = this._objectFrame();
510
+ if (isPrivateTag(frame.tag)) {
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
+ });
519
+ return;
520
+ }
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);
527
+ targetFrame.obj[key] = shaped;
528
+ }
529
+
530
+ // --- cardinality shaping ------------------------------------------------
531
+
532
+ _shapeValues(frame, entry, key) {
533
+ const values = frame.values;
534
+ // no dictionary VM (a private or unknown element): as for VM > 1
535
+ if (valueLength(entry) !== 1) {
536
+ // §10/§11: always list-like; present-empty -> [].
537
+ return values;
538
+ }
539
+ // Scalar VM (1 or 0-1).
540
+ if (values.length === 0) {
541
+ return null; // §7/§9 present-empty
542
+ }
543
+ if (values.length === 1) {
544
+ return values[0];
545
+ }
546
+ // §8: scalar VM with 2+ actual values -> cardinality violation.
547
+ return this._applyViolation(key, values, 1);
548
+ }
549
+
550
+ _shapeSequence(frame, entry) {
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);
554
+ }
555
+
556
+ _applyViolation(keyword, values, declaredMax) {
557
+ const violation = {
558
+ keyword,
559
+ declaredMax,
560
+ actual: values.length
561
+ };
562
+ const discard = /DiscardExtra$/.test(this.policy);
563
+ const kept = discard ? values.slice(0, declaredMax) : values.slice();
564
+
565
+ if (this.policy === "throw") {
566
+ throw new Error(
567
+ `Cardinality violation: ${keyword} has ${values.length} values, declared VM ${declaredMax}`
568
+ );
569
+ }
570
+ if (/^warn/.test(this.policy)) {
571
+ log.warn(
572
+ `Cardinality violation: ${keyword} has ${values.length} values (declared VM ${declaredMax})`
573
+ );
574
+ }
575
+ this.violations.push(violation);
576
+
577
+ // discardExtra of a now-scalar VM collapses to the single kept value.
578
+ if (discard && declaredMax === 1) {
579
+ return kept[0];
580
+ }
581
+ return kept;
582
+ }
583
+ }
584
+
585
+ /**
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).
588
+ */
589
+ function objectFrame(obj) {
590
+ return { kind: "object", obj, privates: [] };
591
+ }
592
+
593
+ function endObject(frame) {
594
+ placePrivateElements(frame.obj, frame.obj._vrMap, frame.privates);
595
+ frame.privates = [];
596
+ }
597
+
598
+ /**
599
+ * §16 precision retention (raw-retention default "inexact only", §27). A numeric
600
+ * VR value (IS/DS) decoded to a JS number has lost precision when the number's
601
+ * shortest decimal cannot reproduce the source string (an over-length decimal,
602
+ * or an integer beyond the safe range). In that case retain the original string.
603
+ * This is VR-agnostic: it fires only when a number and its source string
604
+ * disagree, so normal values keep their number.
605
+ */
606
+ function retainPrecision(vr, value, raw) {
607
+ if (typeof value !== "number" || typeof raw !== "string") {
608
+ return value;
609
+ }
610
+ const source = raw.trim();
611
+ if (source === "" || !Number.isFinite(value)) {
612
+ return value;
613
+ }
614
+ if (canonicalDecimal(source) === canonicalDecimal(value.toString())) {
615
+ return value; // recoverable from the number -> no loss
616
+ }
617
+ return source;
618
+ }
619
+
620
+ /**
621
+ * Canonical decimal form for comparing whether two decimal strings denote the
622
+ * same number, ignoring formatting (sign, leading/trailing zeros). Exponent
623
+ * notation is left intact, so a number serialized in exponent form that differs
624
+ * from a fixed-notation source compares unequal (conservatively retained).
625
+ */
626
+ function canonicalDecimal(s) {
627
+ let str = s.trim().replace(/^\+/, "");
628
+ if (/[eE]/.test(str)) {
629
+ return str;
630
+ }
631
+ let neg = false;
632
+ if (str.startsWith("-")) {
633
+ neg = true;
634
+ str = str.slice(1);
635
+ }
636
+ let [int = "", frac = ""] = str.split(".");
637
+ int = int.replace(/^0+(?=\d)/, "");
638
+ frac = frac.replace(/0+$/, "");
639
+ if (int === "") {
640
+ int = "0";
641
+ }
642
+ const body = frac ? `${int}.${frac}` : int;
643
+ return neg && body !== "0" ? `-${body}` : body;
644
+ }
645
+
646
+ /**
647
+ * Add Person Name accessors (§17): a non-enumerable toString() returning the raw
648
+ * PN string and toJSON() keeping the DICOM JSON model. Component access
649
+ * (`.Alphabetic`) works directly because the value IS the {Alphabetic,...}
650
+ * object (VM 1) or an array of them (VM n). Reuses dcmjs's shared helper.
651
+ */
652
+ function addPersonNameAccessors(shaped) {
653
+ if (typeof shaped === "string") {
654
+ shaped = new String(shaped);
655
+ }
656
+ if (shaped && typeof shaped === "object") {
657
+ return dicomJson.pnAddValueAccessors(shaped);
658
+ }
659
+ return shaped;
660
+ }
661
+
662
+ /**
663
+ * fromDicomWebJson — slice C: a DICOMweb JSON (DICOM JSON model) ->
664
+ * event-stream generator.
665
+ *
666
+ * Walks a parsed DICOMweb JSON object and emits the event-stream contract,
667
+ * proving the source-agnostic claim (§4.4): the same contract a Part 10 reader
668
+ * produces is produced here from a third source. Implemented as a low-allocation
669
+ * visitor that calls listener callbacks directly, without building intermediate
670
+ * event objects (§24.1).
671
+ *
672
+ * Values are emitted AS-IS — Person Names stay as DICOMweb `{ Alphabetic }`
673
+ * objects, numbers stay numbers. Cross-source value canonicalization (PN proxy,
674
+ * IS/DS normalization, §17/§28) belongs to the naturalized listener (slice D).
675
+ * The two binary forms are handled per spec:
676
+ * - `BulkDataURI` -> bulkDataReference (nothing fetched, §21)
677
+ * - `InlineBinary` -> base64 decoded to a buffer fragment (§22)
678
+ *
679
+ * @param {Object} json - DICOM JSON model: { "ggggeeee": { vr, Value | BulkDataURI | InlineBinary }, ... }
680
+ * @param {import("./EventStreamListener").EventStreamListener} listener
681
+ */
682
+ async function fromDicomWebJson(json, listener) {
683
+ const tags = Object.keys(json);
684
+ const metaTags = tags.filter(isMetaTag);
685
+ const bodyTags = tags.filter(t => !isMetaTag(t));
686
+
687
+ listener.startDataSet({ transferSyntaxUID: transferSyntaxOf$1(json) });
688
+
689
+ if (metaTags.length) {
690
+ listener.startFileMetaInformation();
691
+ for (const tag of metaTags) {
692
+ emitAttribute(listener, tag, json[tag]);
693
+ }
694
+ listener.endFileMetaInformation();
695
+ }
696
+
697
+ for (const tag of bodyTags) {
698
+ emitAttribute(listener, tag, json[tag]);
699
+ // Top-level element boundary: a defined backpressure checkpoint.
700
+ await listener.awaitDrain();
701
+ }
702
+
703
+ listener.endDataSet();
704
+ }
705
+
706
+ function emitAttribute(listener, tag, attr) {
707
+ if (!attr) {
708
+ return;
709
+ }
710
+ const vr = attr.vr;
711
+
712
+ if (vr === "SQ") {
713
+ listener.startSequence(tag, { vr });
714
+ for (const item of attr.Value || []) {
715
+ listener.startItem({});
716
+ for (const childTag of Object.keys(item)) {
717
+ emitAttribute(listener, childTag, item[childTag]);
718
+ }
719
+ listener.endItem();
720
+ }
721
+ listener.endSequence();
722
+ return;
723
+ }
724
+
725
+ if (attr.BulkDataURI !== undefined) {
726
+ listener.startElement(tag, { vr });
727
+ listener.bulkDataReference({ uri: attr.BulkDataURI });
728
+ listener.endElement();
729
+ return;
730
+ }
731
+
732
+ if (attr.InlineBinary !== undefined) {
733
+ listener.startElement(tag, { vr });
734
+ listener.startBinary({ encapsulated: false });
735
+ listener.binaryFragment(base64ToArrayBuffer(attr.InlineBinary));
736
+ listener.endBinary();
737
+ listener.endElement();
738
+ return;
739
+ }
740
+
741
+ listener.startElement(tag, { vr });
742
+ let index = 0;
743
+ for (const v of attr.Value || []) {
744
+ listener.value(v, { index: index++ });
745
+ }
746
+ listener.endElement();
747
+ }
748
+
749
+ function transferSyntaxOf$1(json) {
750
+ const ts = json["00020010"];
751
+ return ts && ts.Value ? ts.Value[0] : undefined;
752
+ }
753
+
754
+ function isMetaTag(tag) {
755
+ return tag.slice(0, 4) === "0002";
756
+ }
757
+
758
+ /**
759
+ * fromDataSet — the reference event-stream generator for slice A.
760
+ *
761
+ * Walks a parsed dcmjs dataset (a `{ meta, dict }` shape — e.g. the DicomDict
762
+ * returned by `DicomMessage.readFile`, produced by the lazy core over
763
+ * `@dcmjs-org/parser`) and pushes the event-stream contract to a listener. It
764
+ * reuses the lazy core's already-decoded values rather than re-decoding raw
765
+ * offsets, which keeps slice A decoupled from the Part 10 byte parser (that
766
+ * production "bytes -> events" generator is slice B). This generator exercises
767
+ * the spec §32 "tag / naturalized source -> event stream" path and proves the
768
+ * vocabulary can carry a real dataset losslessly.
769
+ *
770
+ * Async by design: structural/value callbacks are synchronous, but the
771
+ * generator awaits `listener.awaitDrain()` at the defined backpressure
772
+ * checkpoints — top-level element boundaries and between binary fragments.
773
+ *
774
+ * @param {{ meta?: Object, dict?: Object }} dataset
775
+ * @param {import("./EventStreamListener").EventStreamListener} listener
776
+ */
777
+
778
+ async function fromDataSet(dataset, listener) {
779
+ const meta = dataset.meta || null;
780
+ const dict = dataset.dict || dataset;
781
+
782
+ listener.startDataSet({
783
+ transferSyntaxUID: transferSyntaxOf(meta)
784
+ });
785
+
786
+ if (meta && Object.keys(meta).length) {
787
+ listener.startFileMetaInformation();
788
+ for (const tag of Object.keys(meta)) {
789
+ emitEntry(listener, tag, meta[tag]);
790
+ }
791
+ listener.endFileMetaInformation();
792
+ }
793
+
794
+ for (const tag of Object.keys(dict)) {
795
+ emitEntry(listener, tag, dict[tag]);
796
+ // Top-level element boundary: a defined backpressure checkpoint.
797
+ await listener.awaitDrain();
798
+ }
799
+
800
+ listener.endDataSet();
801
+ }
802
+
803
+ function transferSyntaxOf(meta) {
804
+ const ts = meta && meta["00020010"];
805
+ return ts && ts.Value ? ts.Value[0] : undefined;
806
+ }
807
+
808
+ /** Emit one tag entry (element, sequence, or binary) and its children.
809
+ * Exported for fromPart10's §6.2.2 UN-sequence emission (issue #363). */
810
+ function emitEntry(listener, tag, entry) {
811
+ if (!entry) {
812
+ return;
813
+ }
814
+ const values = entry.Value || [];
815
+
816
+ if (entry.vr === "SQ") {
817
+ listener.startSequence(tag, { vr: entry.vr, length: entry.length });
818
+ for (const item of values) {
819
+ listener.startItem({ length: item && item._length });
820
+ for (const childTag of Object.keys(item)) {
821
+ emitEntry(listener, childTag, item[childTag]);
822
+ }
823
+ listener.endItem();
824
+ }
825
+ listener.endSequence();
826
+ return;
827
+ }
828
+
829
+ if (entry.InlineBinary !== undefined || values.some(isInlineBinary)) {
830
+ emitInlineBinary(listener, tag, entry, values);
831
+ return;
832
+ }
833
+
834
+ if (isBinary(values)) {
835
+ listener.startElement(tag, { vr: entry.vr, length: entry.length });
836
+ listener.startBinary({ encapsulated: !!entry.encapsulatedPixelData });
837
+ for (const fragment of values) {
838
+ listener.binaryFragment(fragment);
839
+ }
840
+ listener.endBinary();
841
+ listener.endElement();
842
+ return;
843
+ }
844
+
845
+ listener.startElement(tag, { vr: entry.vr, length: entry.length });
846
+ // _rawValue (when present on lazy/eager dict entries) carries the source
847
+ // string for precision-preserving retention (§16/§27).
848
+ const rawValues = entry._rawValue;
849
+ let index = 0;
850
+ for (const v of values) {
851
+ if (isBulkDataReference(v)) {
852
+ listener.bulkDataReference({ uri: v.BulkDataURI });
853
+ } else {
854
+ listener.value(v, {
855
+ index,
856
+ rawValue: Array.isArray(rawValues)
857
+ ? rawValues[index]
858
+ : undefined
859
+ });
860
+ }
861
+ index++;
862
+ }
863
+ listener.endElement();
864
+ }
865
+
866
+ /**
867
+ * Emit an entry that holds {InlineBinary} wrappers as binary events.
868
+ *
869
+ * {InlineBinary} wrappers are the naturalized binary form produced by both
870
+ * NaturalizedListener and DicomMetaDictionary.naturalizeDataset (§22). They
871
+ * are unwrapped to binary events exactly as fromDicomWebJson does; without
872
+ * this the wrapper object reaches BinaryRepresentation.writeBytes and throws
873
+ * (the UN naturalize→write round-trip crash). The wrapper may sit on the
874
+ * entry itself (no Value array) or inside Value; its content may be an
875
+ * ArrayBuffer, a typed-array view, a base64 string, or an array of fragments
876
+ * in any of those forms.
877
+ */
878
+ function emitInlineBinary(listener, tag, entry, values) {
879
+ const wrappers = entry.InlineBinary !== undefined ? [entry] : values;
880
+ listener.startElement(tag, { vr: entry.vr, length: entry.length });
881
+ listener.startBinary({ encapsulated: !!entry.encapsulatedPixelData });
882
+ for (const w of wrappers) {
883
+ const inline = isInlineBinary(w) ? w.InlineBinary : w;
884
+ for (const fragment of Array.isArray(inline) ? inline : [inline]) {
885
+ listener.binaryFragment(toBinaryFragment(fragment));
886
+ }
887
+ }
888
+ listener.endBinary();
889
+ listener.endElement();
890
+ }
891
+
892
+ function isBinary(values) {
893
+ return values.some(isBinaryData);
894
+ }
895
+
896
+ /** True for a naturalized binary wrapper: { InlineBinary: <content> }. */
897
+ function isInlineBinary(v) {
898
+ return (
899
+ v &&
900
+ typeof v === "object" &&
901
+ v.InlineBinary !== undefined &&
902
+ !(v instanceof ArrayBuffer) &&
903
+ !ArrayBuffer.isView(v)
904
+ );
905
+ }
906
+
907
+ /** Coerce one InlineBinary fragment (buffer, view, or base64) to bytes. */
908
+ function toBinaryFragment(fragment) {
909
+ if (typeof fragment === "string") {
910
+ return base64ToArrayBuffer(fragment);
911
+ }
912
+ return fragment;
913
+ }
914
+
915
+ function isBulkDataReference(v) {
916
+ return (
917
+ v &&
918
+ typeof v === "object" &&
919
+ typeof v.BulkDataURI === "string" &&
920
+ !(v instanceof ArrayBuffer) &&
921
+ !ArrayBuffer.isView(v)
922
+ );
923
+ }
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
+
948
+ /**
949
+ * createEventAsyncIterable — the pull adapter of the hybrid contract.
950
+ *
951
+ * The push/callback listener is canonical; this wraps a generator run as an
952
+ * async-iterable so ergonomic consumers can `for await (const ev of ...)`.
953
+ * Each yielded event is `{ type, args }` where `type` is a vocabulary method
954
+ * name and `args` is the argument array.
955
+ *
956
+ * Backpressure is real: the bridge installs a drain gate on the listener, so a
957
+ * slow consumer suspends the generator at its checkpoints once the internal
958
+ * queue exceeds `highWaterMark`. Events are freshly allocated (not pooled) so
959
+ * consumers may retain them safely.
960
+ *
961
+ * @param {(listener: EventStreamListener) => Promise<void>} run - drives the listener
962
+ * @param {{ highWaterMark?: number }} [options]
963
+ * @returns {AsyncIterable<{type: string, args: any[]}>}
964
+ */
965
+ function createEventAsyncIterable(run, { highWaterMark = 64 } = {}) {
966
+ return {
967
+ [Symbol.asyncIterator]() {
968
+ const queue = [];
969
+ let finished = false;
970
+ let cancelled = false;
971
+ let failure = null;
972
+ let onItem = null; // resolve a waiting consumer
973
+ let onSpace = null; // {resolve, reject} of a suspended producer
974
+
975
+ const cancellation = () => {
976
+ const err = new Error("event iteration cancelled");
977
+ err.name = "EventIterationCancelled";
978
+ return err;
979
+ };
980
+ const wakeConsumer = () => {
981
+ if (onItem) {
982
+ const r = onItem;
983
+ onItem = null;
984
+ r();
985
+ }
986
+ };
987
+ const wakeProducer = () => {
988
+ if (onSpace && queue.length < highWaterMark) {
989
+ const r = onSpace;
990
+ onSpace = null;
991
+ r.resolve();
992
+ }
993
+ };
994
+
995
+ // A capture filter enqueues one event per vocabulary call.
996
+ const captureFilter = {};
997
+ for (const name of EVENT_STREAM_VOCABULARY) {
998
+ captureFilter[name] = function (next, ...args) {
999
+ queue.push({ type: name, args });
1000
+ wakeConsumer();
1001
+ return next(...args);
1002
+ };
1003
+ }
1004
+
1005
+ const listener = new EventStreamListener(captureFilter);
1006
+ listener.setDrain(() => {
1007
+ if (cancelled) {
1008
+ return Promise.reject(cancellation());
1009
+ }
1010
+ return queue.length < highWaterMark
1011
+ ? Promise.resolve()
1012
+ : new Promise((resolve, reject) => {
1013
+ onSpace = { resolve, reject };
1014
+ });
1015
+ });
1016
+
1017
+ Promise.resolve()
1018
+ .then(() => run(listener))
1019
+ .then(
1020
+ () => {
1021
+ finished = true;
1022
+ wakeConsumer();
1023
+ },
1024
+ err => {
1025
+ // A rejection we caused by cancelling is a clean end,
1026
+ // not a stream failure.
1027
+ if (
1028
+ !cancelled ||
1029
+ err?.name !== "EventIterationCancelled"
1030
+ ) {
1031
+ failure = err || new Error("event stream failed");
1032
+ }
1033
+ finished = true;
1034
+ wakeConsumer();
1035
+ }
1036
+ );
1037
+
1038
+ return {
1039
+ async next() {
1040
+ while (queue.length === 0 && !finished) {
1041
+ await new Promise(resolve => {
1042
+ onItem = resolve;
1043
+ });
1044
+ }
1045
+ if (queue.length > 0) {
1046
+ const value = queue.shift();
1047
+ wakeProducer();
1048
+ return { value, done: false };
1049
+ }
1050
+ if (failure) {
1051
+ throw failure;
1052
+ }
1053
+ return { value: undefined, done: true };
1054
+ },
1055
+ // Called by `break`/`return` out of a for-await loop. Without
1056
+ // it a producer suspended in awaitDrain waits forever on a
1057
+ // consumer that is gone.
1058
+ async return(value) {
1059
+ cancelled = true;
1060
+ queue.length = 0;
1061
+ if (onSpace) {
1062
+ const r = onSpace;
1063
+ onSpace = null;
1064
+ r.reject(cancellation());
1065
+ }
1066
+ return { value, done: true };
1067
+ }
1068
+ };
1069
+ }
1070
+ };
1071
+ }
1072
+
1073
+ /**
1074
+ * Shared emit helpers for byte-level event sources.
1075
+ *
1076
+ * These route a decoded element ({ values, rawValues }) to the correct
1077
+ * listener events. They lived in the tokenizer-backed fromPart10 module;
1078
+ * with the vendored tokenizer removed they are a standalone module the
1079
+ * streaming reader (and the thin fromPart10 wrapper) share.
1080
+ */
1081
+
1082
+ /**
1083
+ * Emits a decoded leaf element. Sequence-shaped decodes yield item dicts —
1084
+ * those are emitted as sequence events (matching the eager dict shape);
1085
+ * everything else routes through emitValues.
1086
+ *
1087
+ * Two decodes are sequence-shaped: (a) UN with undefined length parsed as an
1088
+ * implicit-VR sequence (PS3.5 §6.2.2, issue #363), and (b) defined-length UN
1089
+ * whose dictionary VR is SQ (ParsedUnknownValue re-parses the value as a
1090
+ * sequence — corpus shape "EVRLE SQ as UN"). Both decode to item dicts in
1091
+ * `values` and must be emitted as sequence events; emitting them through the
1092
+ * scalar value() path crashed on rawValues[index] (the corpus bare-TypeError
1093
+ * cluster).
1094
+ */
1095
+ function emitDecodedLeaf(
1096
+ listener,
1097
+ tag,
1098
+ vrInstance,
1099
+ el,
1100
+ values,
1101
+ rawValues
1102
+ ) {
1103
+ // Sequence-shaped decodes (see JSDoc).
1104
+ if (
1105
+ (vrInstance.type === "SQ" ||
1106
+ (vrInstance.type === "UN" && el.hadUndefinedLength)) &&
1107
+ Array.isArray(values) &&
1108
+ values.every(isItemDictLike)
1109
+ ) {
1110
+ listener.startSequence(tag, { vr: "SQ", length: el.length });
1111
+ for (const itemDict of values) {
1112
+ listener.startItem({});
1113
+ for (const childTag of Object.keys(itemDict)) {
1114
+ emitEntry(listener, childTag, itemDict[childTag]);
1115
+ }
1116
+ listener.endItem();
1117
+ }
1118
+ listener.endSequence();
1119
+ return;
1120
+ }
1121
+ emitValues(listener, tag, vrInstance, el, values, rawValues);
1122
+ }
1123
+
1124
+ /**
1125
+ * Route decoded {values, rawValues} to binary or scalar listener events.
1126
+ *
1127
+ * The decoded shapes are normalized first: some VR reads legitimately yield
1128
+ * a bare value or no rawValues array (classic stores these shapes untouched
1129
+ * in the dict; the event stream must not crash on them — corpus
1130
+ * bare-TypeError cluster).
1131
+ */
1132
+ function emitValues(listener, tag, vrInstance, el, values, rawValues) {
1133
+ // Normalize bare / missing values to a list (see JSDoc).
1134
+ const list = Array.isArray(values)
1135
+ ? values
1136
+ : values === undefined || values === null
1137
+ ? []
1138
+ : [values];
1139
+ if (list.some(isBinaryData)) {
1140
+ listener.startElement(tag, { vr: vrInstance.type, length: el.length });
1141
+ listener.startBinary({ encapsulated: false });
1142
+ for (const buf of list) {
1143
+ listener.binaryFragment(buf);
1144
+ }
1145
+ listener.endBinary();
1146
+ listener.endElement();
1147
+ return;
1148
+ }
1149
+
1150
+ listener.startElement(tag, { vr: vrInstance.type, length: el.length });
1151
+ let index = 0;
1152
+ for (const v of list) {
1153
+ listener.value(v, {
1154
+ index,
1155
+ rawValue: Array.isArray(rawValues) ? rawValues[index] : undefined
1156
+ });
1157
+ index++;
1158
+ }
1159
+ listener.endElement();
1160
+ }
1161
+
1162
+ function isItemDictLike(v) {
1163
+ return (
1164
+ v &&
1165
+ typeof v === "object" &&
1166
+ !(v instanceof ArrayBuffer) &&
1167
+ !ArrayBuffer.isView(v) &&
1168
+ Object.keys(v).every(k => /^[0-9A-Fx]{8,9}$/i.test(k))
1169
+ );
1170
+ }
1171
+
1172
+ /**
1173
+ * Shared element-decode core extracted from src/lazy/LazyDicomReader.js.
1174
+ *
1175
+ * All functions operate on two read-only input shapes instead of the mutable
1176
+ * `ctx` used by the lazy reader:
1177
+ *
1178
+ * window = { arrayBuffer, baseOffset, syntax, littleEndian, implicit, decoder }
1179
+ * A fully-resolved byte region. Callers construct a *meta window*
1180
+ * (original buffer, EXPLICIT_LITTLE_ENDIAN, littleEndian=true,
1181
+ * implicit=false, decoder=null) or a *body window* (post-inflate
1182
+ * buffer, negotiated syntax/endianness/implicitness, active decoder).
1183
+ * There is no `isMeta` parameter anywhere in this module: callers
1184
+ * select the correct window.
1185
+ *
1186
+ * policy = { forceStoreRaw, noCopy, ignoreErrors }
1187
+ *
1188
+ * Every function body that reaches DicomMessage / Tag accesses them at call
1189
+ * time, never at module-evaluation time, to honour the circular-import
1190
+ * discipline of the wider codebase.
1191
+ */
1192
+
1193
+ // ──────────────────────────────────────────────────────────────────────────────
1194
+ // Internal helpers (not exported)
1195
+ // ──────────────────────────────────────────────────────────────────────────────
1196
+
1197
+ // ──────────────────────────────────────────────────────────────────────────────
1198
+ // Exported functions
1199
+ // ──────────────────────────────────────────────────────────────────────────────
1200
+
1201
+ /**
1202
+ * Resolves the ValueRepresentation instance for a parser element,
1203
+ * replicating DicomMessage._readTag's VR resolution rules
1204
+ * (src/DicomMessage.js, explicit + implicit branches).
1205
+ *
1206
+ * THIS IS THE SINGLE CANONICAL IMPLICIT-VR CONTRACT (AD-1). Every read
1207
+ * path — eager, lazy, fromPart10, fromPart10Stream — resolves implicit
1208
+ * VRs here, with eager parity: a DEFINED-length dictionary-miss element
1209
+ * resolves to UN (or OW/LO by tag rules) and is NEVER data-peek-promoted
1210
+ * to SQ, regardless of its value bytes; an UNDEFINED-length dictionary
1211
+ * miss resolves to SQ by the length rule. The parser's el.items (its
1212
+ * framing peek) is metadata only and must not influence VR resolution.
1213
+ *
1214
+ * `window.implicit` is already resolved by the caller: a meta window
1215
+ * always carries implicit=false; a body window carries the negotiated value.
1216
+ * The lazy source computed `ctx.implicit && !isMeta`; here the caller
1217
+ * selects the window instead.
1218
+ *
1219
+ * Uses DicomMetaDictionary.lookupTag, ValueRepresentation.parseUnknownVr /
1220
+ * createByTypeString, Tag — all accessed inside the function body.
1221
+ */
1222
+ function resolveVrInstance(el, window) {
1223
+ const implicit = window.implicit;
1224
+
1225
+ if (!implicit) {
1226
+ const vrType = el.vr;
1227
+ if (vrType === "UN") {
1228
+ const tag = new Tag(el.tagValue);
1229
+ const elementData = DicomMetaDictionary.lookupTag(tag);
1230
+ if (elementData && elementData.vr) {
1231
+ // UN with a known dictionary VR: eager re-parses the value
1232
+ // as the dictionary VR via ParsedUnknownValue.
1233
+ let dictVr = elementData.vr;
1234
+ if (dictVr === "xs") {
1235
+ dictVr = resolveXsVr(window);
1236
+ }
1237
+ return ValueRepresentation.parseUnknownVr(dictVr);
1238
+ }
1239
+ }
1240
+ return ValueRepresentation.createByTypeString(vrType);
1241
+ }
1242
+
1243
+ // Implicit VR: dictionary lookup with _readTag's fallback rules.
1244
+ const tag = new Tag(el.tagValue);
1245
+ const elementData = DicomMetaDictionary.lookupTag(tag);
1246
+ let vrType;
1247
+ if (elementData) {
1248
+ vrType = elementData.vr;
1249
+ if (vrType === "xs") {
1250
+ vrType = resolveXsVr(window);
1251
+ }
1252
+ } else if (el.hadUndefinedLength) {
1253
+ // eager: length == UNDEFINED_LENGTH (the parser corrects element
1254
+ // .length for undefined-length elements, so use the flag)
1255
+ vrType = "SQ";
1256
+ } else if (tag.isPixelDataTag()) {
1257
+ vrType = "OW";
1258
+ } else if (tag.isPrivateCreator()) {
1259
+ vrType = "LO";
1260
+ } else {
1261
+ vrType = "UN";
1262
+ }
1263
+ return ValueRepresentation.createByTypeString(vrType);
1264
+ }
1265
+
1266
+ /**
1267
+ * Resolves the dictionary meta-VR "xs" ("US or SS") by PixelRepresentation
1268
+ * (PS3.5): SS when (0028,0103) is 1, US otherwise — including when the
1269
+ * window carries no pixelRepresentation (parity with DicomMessage._readTag,
1270
+ * fixed in this arc for issue #368). Sources thread the parsed
1271
+ * (0028,0103) value onto their read window as `pixelRepresentation`;
1272
+ * (0028,0103) precedes every xs tag in tag order.
1273
+ */
1274
+ function resolveXsVr(window) {
1275
+ return window.pixelRepresentation === 1 ? "SS" : "US";
1276
+ }
1277
+
1278
+ /**
1279
+ * True when resolveVrInstance produced a ParsedUnknownValue (UN element with
1280
+ * a known dictionary VR): those are per-call instances, while every plain VR
1281
+ * resolves to the shared VRinstances singleton.
1282
+ */
1283
+ function isParsedUnknownVr(vrInstance) {
1284
+ return (
1285
+ vrInstance !== ValueRepresentation.createByTypeString(vrInstance.type)
1286
+ );
1287
+ }
1288
+
1289
+ /**
1290
+ * Verbatim replication of DicomMessage._readTag's value-shaping block
1291
+ * (src/DicomMessage.js:380-402): string VM splitting, the SQ and OW/OB
1292
+ * passthroughs and the array-or-push fallback (which yields
1293
+ * `_rawValue: [undefined]` for non-raw-storing VRs like UN/OF/OD - a quirk
1294
+ * the lazy core must reproduce).
1295
+ *
1296
+ * Uses the canonical singleVRs exported from @dcmjs-org/core (includes LT).
1297
+ * Arg order is (vr, rawValue, value) — same as the source.
1298
+ */
1299
+ function shapeReadValues(vr, rawValue, value) {
1300
+ let values = [];
1301
+ let rawValues = [];
1302
+ if (!vr.isBinary() && singleVRs.indexOf(vr.type) == -1) {
1303
+ rawValues = rawValue;
1304
+ values = value;
1305
+ if (typeof value === "string") {
1306
+ const delimiterChar = String.fromCharCode(VM_DELIMITER);
1307
+ rawValues = vr.dropPadByte(rawValue.split(delimiterChar));
1308
+ values = vr.dropPadByte(value.split(delimiterChar));
1309
+ }
1310
+ } else if (vr.type == "SQ") {
1311
+ rawValues = rawValue;
1312
+ values = value;
1313
+ } else if (vr.type == "OW" || vr.type == "OB") {
1314
+ rawValues = rawValue;
1315
+ values = value;
1316
+ } else {
1317
+ Array.isArray(value) ? (values = value) : values.push(value);
1318
+ Array.isArray(rawValue)
1319
+ ? (rawValues = rawValue)
1320
+ : rawValues.push(rawValue);
1321
+ }
1322
+ return { values, rawValues };
1323
+ }
1324
+
1325
+ /**
1326
+ * Constructs a ReadBufferStream over the element's data bytes within the
1327
+ * given window, mirroring the stream construction in materializeElement
1328
+ * (src/lazy/LazyDicomReader.js:565-575).
1329
+ *
1330
+ * start = window.baseOffset + el.dataOffset
1331
+ * stop = start + el.length
1332
+ *
1333
+ * policy.noCopy controls whether getBuffer() returns a Uint8Array (true) or
1334
+ * an ArrayBuffer (false), exactly as the source does. When window.decoder is
1335
+ * non-null the stream's decoder is set before returning.
1336
+ * NOTE: callers using a meta window must pass policy.noCopy = false (the lazy
1337
+ * source always forced noCopy off for meta reads).
1338
+ */
1339
+ function buildElementStream(window, el, policy) {
1340
+ const start = window.baseOffset + el.dataOffset;
1341
+ const stream = new ReadBufferStream(
1342
+ window.arrayBuffer,
1343
+ window.littleEndian,
1344
+ {
1345
+ start,
1346
+ stop: start + effectiveElementLength(window, el, true),
1347
+ // eager's body stream carries noCopy (getBuffer then returns
1348
+ // Uint8Array instead of ArrayBuffer); its meta stream comes from
1349
+ // stream.more(), which drops it
1350
+ noCopy: policy.noCopy
1351
+ }
1352
+ );
1353
+ if (window.decoder) {
1354
+ stream.setDecoder(window.decoder);
1355
+ }
1356
+ return stream;
1357
+ }
1358
+
1359
+ /**
1360
+ * Corrective guard: a defined length that overruns the underlying buffer is
1361
+ * a corrupt length (or a derailed walk). Historic (and test-pinned) leniency
1362
+ * reads truncated trailing elements, so the length is CLAMPED to the bytes
1363
+ * actually available — but no longer silently (the corruption is logged, and
1364
+ * phantom multi-GB allocations from garbage lengths are avoided). Parity
1365
+ * with the classic reader's overrun clamp in DicomMessage._readTag.
1366
+ */
1367
+ function effectiveElementLength(window, el, warn) {
1368
+ const available =
1369
+ window.arrayBuffer.byteLength - (window.baseOffset + el.dataOffset);
1370
+ if (
1371
+ el.length === undefined ||
1372
+ el.length === UNDEFINED_LENGTH ||
1373
+ el.length <= available
1374
+ ) {
1375
+ return el.length;
1376
+ }
1377
+ if (warn) {
1378
+ log.warn(
1379
+ `decodeCore: element ${el.tag || ""} declares ${el.length} ` +
1380
+ `bytes but only ${Math.max(available, 0)} remain in the ` +
1381
+ `buffer; clamping to the remaining bytes`
1382
+ );
1383
+ }
1384
+ return Math.max(available, 0);
1385
+ }
1386
+
1387
+ /**
1388
+ * Decodes the value phase of a defined-length element, mirroring the tail of
1389
+ * materializeElement (src/lazy/LazyDicomReader.js:557-598): the binary
1390
+ * multi-read loop (oversized binary values), or a single vr.read() followed
1391
+ * by shapeReadValues for everything else.
1392
+ *
1393
+ * Callers must already have built the stream via buildElementStream or have
1394
+ * established that the element is defined-length (not undefined-length, not
1395
+ * a sequence, not encapsulated pixel data). Use classifyElement to determine
1396
+ * the routing before calling.
1397
+ */
1398
+ function decodeElementValues(window, el, vrInstance, policy) {
1399
+ const vr = vrInstance;
1400
+ // Clamped for buffer-overrunning corrupt lengths (see
1401
+ // effectiveElementLength); buildElementStream applies (and logs) the
1402
+ // same clamp for the stream's stop offset.
1403
+ const length = effectiveElementLength(window, el, false);
1404
+ const stream = buildElementStream(window, el, policy);
1405
+ return readValues(window, vr, stream, length, policy);
1406
+ }
1407
+
1408
+ /**
1409
+ * Decodes the value of an undefined-length element that is not a streamed
1410
+ * sequence and not encapsulated pixel data (classifyElement "eagerWindow").
1411
+ * The value bytes are [dataOffset, endOffset) of the window; endOffset is the
1412
+ * end of the closing delimiter. The VR reads with UNDEFINED_LENGTH, so the
1413
+ * result is the same as DicomMessage._readTag gives for the element.
1414
+ *
1415
+ * Returns { values, rawValues } in the same shape as decodeElementValues.
1416
+ */
1417
+ function decodeUndefinedLengthValues(window, el, vrInstance, policy) {
1418
+ const stream = new ReadBufferStream(
1419
+ window.arrayBuffer,
1420
+ window.littleEndian,
1421
+ {
1422
+ start: window.baseOffset + el.dataOffset,
1423
+ stop: window.baseOffset + el.endOffset,
1424
+ noCopy: policy.noCopy
1425
+ }
1426
+ );
1427
+ if (window.decoder) {
1428
+ stream.setDecoder(window.decoder);
1429
+ }
1430
+ return readValues(window, vrInstance, stream, UNDEFINED_LENGTH, policy);
1431
+ }
1432
+
1433
+ /**
1434
+ * The value read of DicomMessage._readTag: the binary multi-read loop for
1435
+ * oversized binary values, or one vr.read() followed by shapeReadValues.
1436
+ */
1437
+ function readValues(window, vr, stream, length, policy) {
1438
+ const readOptions = { forceStoreRaw: policy.forceStoreRaw };
1439
+
1440
+ if (vr.isBinary() && length > vr.maxLength && !vr.noMultiple) {
1441
+ const values = [];
1442
+ const rawValues = [];
1443
+ const times = length / vr.maxLength;
1444
+ let i = 0;
1445
+ while (i++ < times) {
1446
+ const { rawValue, value } = vr.read(
1447
+ stream,
1448
+ vr.maxLength,
1449
+ window.syntax,
1450
+ readOptions
1451
+ );
1452
+ rawValues.push(rawValue);
1453
+ values.push(value);
1454
+ }
1455
+ return { values, rawValues };
1456
+ }
1457
+ const { rawValue, value } =
1458
+ vr.read(stream, length, window.syntax, readOptions) || {};
1459
+ return shapeReadValues(vr, rawValue, value);
1460
+ }
1461
+
1462
+ /**
1463
+ * Resolves the dataset decoder from SpecificCharacterSet (00080005) with
1464
+ * the exact eager semantics of DicomMessage._read (src/DicomMessage.js:77-105):
1465
+ * encodingMapping lookup, warn-or-throw per policy.ignoreErrors for unsupported
1466
+ * or multiple charsets, and the entry Value rewritten to ["ISO_IR 192"] while
1467
+ * _rawValue keeps the original.
1468
+ *
1469
+ * Side-effect-free version of resolveCharacterSet in LazyDicomReader: instead
1470
+ * of assigning ctx.decoder the resolved TextDecoder is RETURNED in the result
1471
+ * object. The caller is responsible for setting it on the body window.
1472
+ *
1473
+ * Returns { decoder, vrInstance, originalValues, seedState } or null if csEl
1474
+ * is absent.
1475
+ *
1476
+ * decoder — the resolved TextDecoder, or null when the charset is
1477
+ * unsupported under ignoreErrors=true.
1478
+ * vrInstance — the resolved VR for the charset element.
1479
+ * originalValues — the values as stored in the file, BEFORE the ISO_IR 192
1480
+ * rewrite (consumed by the charsetPassthroughSafe check).
1481
+ * seedState — { values: ["ISO_IR 192"], rawValues } — the seed for the
1482
+ * 00080005 lazy entry (eager quirk: rewrites Value to UTF-8).
1483
+ */
1484
+ function resolveCharacterSet(window, csEl, policy) {
1485
+ if (!csEl) {
1486
+ return null;
1487
+ }
1488
+ const vrInstance = resolveVrInstance(csEl, window);
1489
+ // Read with the default (latin1) decoder, exactly like the eager loop
1490
+ // does before it reaches the setDecoder call.
1491
+ const { values, rawValues } = decodeElementValues(
1492
+ window,
1493
+ csEl,
1494
+ vrInstance,
1495
+ policy
1496
+ );
1497
+
1498
+ // Shared charset resolution (single charsets, ISO 2022 code extensions,
1499
+ // error policy) — src/charset/iso2022.js. Same eager error semantics:
1500
+ // throws when ignoreErrors=false, warns and degrades to a null decoder
1501
+ // when ignoreErrors=true.
1502
+ const decoder = resolveCharsetDecoder(values, {
1503
+ ignoreErrors: policy.ignoreErrors
1504
+ });
1505
+
1506
+ return {
1507
+ decoder,
1508
+ vrInstance,
1509
+ // the values as stored in the file, BEFORE the ISO_IR 192 rewrite
1510
+ // (consumed by the charsetPassthroughSafe computation)
1511
+ originalValues: values,
1512
+ seedState: {
1513
+ // change SpecificCharacterSet to UTF-8 (eager quirk, kept)
1514
+ values: ["ISO_IR 192"],
1515
+ rawValues
1516
+ }
1517
+ };
1518
+ }
1519
+
1520
+ /**
1521
+ * src/eventStream/fromPart10Stream.js
1522
+ *
1523
+ * fromPart10Stream — chunked bytes → events source (slice K, stage 2).
1524
+ *
1525
+ * This is the public entry point for the bounded-memory streaming path.
1526
+ * Input is normalized into an AsyncIterable and fed into a ReadBufferStream
1527
+ * concurrently with parsing.
1528
+ *
1529
+ * The **preamble + File Meta Information phase** is genuinely incremental (K2+):
1530
+ * FMI elements are decoded on-the-fly as bytes arrive, so `startFileMetaInformation` /
1531
+ * per-element events / `endFileMetaInformation` are emitted before body bytes finish.
1532
+ *
1533
+ * The **body phase** streams natively for all transfer syntaxes (K3+ native paths):
1534
+ * defined-length, undefined-length, and encapsulated fragments stream directly
1535
+ * from the source. Deflate-compressed bodies (K5) inflate incrementally via
1536
+ * chunked pako.Inflate into a zero-based bodyStream, avoiding full-buffer copies.
1537
+ *
1538
+ * Both streams use clearBuffers=true with per-top-level-element consume() so that
1539
+ * chunk memory is released as the parse advances (bounded-memory streaming). A
1540
+ * bare (meta-less) dataset streams through the same body loop, behind the
1541
+ * allowMissingHeader opt-in.
1542
+ *
1543
+ * Decision D-E: noCopy is intentionally unsupported (see JSDoc above).
1544
+ */
1545
+
1546
+
1547
+ // ---------------------------------------------------------------------------
1548
+ // Public API
1549
+ // ---------------------------------------------------------------------------
1550
+
1551
+ /**
1552
+ * K5b: how far (in retained, unconsumed bytes) the raw feed loop may run
1553
+ * ahead of the parse before throttling itself. Pending demand always wins —
1554
+ * a consumer blocked in ensureAvailable wakes the feed regardless of the
1555
+ * watermark — so an element or fragment larger than this still accumulates
1556
+ * fully and the gate cannot deadlock. Overridable per call via
1557
+ * `options.feedHighWater`.
1558
+ *
1559
+ * Without this throttle, a listener stalled on its drain gate (e.g. a write
1560
+ * sink flushing a fragment to disk) lets the feed buffer the entire remaining
1561
+ * input. Parse settlement (parseState) wakes the gate on early exit or error.
1562
+ */
1563
+ const FEED_HIGH_WATER = 4 * 1024 * 1024;
1564
+
1565
+ /**
1566
+ * pako.Inflate chunkSize for the K5 deflate relay: controls when pako calls
1567
+ * onData. The default is 64 KiB (pako 2.x source: 1024*64) — large enough
1568
+ * that typical DICOM deflate bodies never fill a single chunk before the
1569
+ * stream is finalised, so onData would never fire mid-stream. 16 KiB keeps
1570
+ * the buffer small enough to ensure onData fires for every 16 KiB of
1571
+ * inflated output, giving the body loop bytes to parse before the raw stream
1572
+ * ends.
1573
+ */
1574
+ const INFLATE_CHUNK_SIZE = 16384;
1575
+
1576
+ /**
1577
+ * K5 relay throttle (ED-1): pause the relay while the body loop holds more
1578
+ * than RELAY_HIGH_WATER inflated bytes and has no pending demand — otherwise
1579
+ * a fast feed + slow listener grows bodyStream without bound (the
1580
+ * relay-balloon risk).
1581
+ */
1582
+ const RELAY_HIGH_WATER = 16384;
1583
+
1584
+ /**
1585
+ * K5 relay sub-slice size (ED-1). Because DEFLATE can expand >100× (a whole
1586
+ * file's output can hide in a few hundred compressed bytes), pausing between
1587
+ * network chunks is not enough: raw bytes are fed to the inflater in
1588
+ * RELAY_RAW_SLICE sub-slices with a retention check between each, bounding
1589
+ * the overshoot to one sub-slice's expansion.
1590
+ */
1591
+ const RELAY_RAW_SLICE = 128;
1592
+
1593
+ /**
1594
+ * fromPart10Stream — parse a chunked DICOM Part 10 byte source into events.
1595
+ *
1596
+ * Accepted `input` forms (all normalized to AsyncIterable internally):
1597
+ *
1598
+ * 1. `ArrayBuffer | Uint8Array`
1599
+ * Degenerate single-chunk input. Re-runnable: each call starts fresh.
1600
+ *
1601
+ * 2. `AsyncIterable<Uint8Array | ArrayBuffer | Buffer>`
1602
+ * Streamed chunks (async generators, Node.js Readable streams in
1603
+ * object mode, etc.). Single-use: the iterator is exhausted on the
1604
+ * first call and cannot be rewound.
1605
+ *
1606
+ * 3. WHATWG `ReadableStream`
1607
+ * Adapted to AsyncIterable via `Symbol.asyncIterator` (Node ≥ 16.14).
1608
+ * A reader-loop fallback is provided for environments where ReadableStream
1609
+ * does not implement AsyncIterable (older browsers / Node builds). No
1610
+ * additional dependencies are required.
1611
+ *
1612
+ * NOTE — `noCopy` is intentionally NOT accepted. The streaming source forces
1613
+ * noCopy semantics OFF because zero-copy views alias chunk memory that
1614
+ * `consume()` releases when the incremental loop (K3-K5) is in place
1615
+ * (decision D-E).
1616
+ *
1617
+ * @param {ArrayBuffer|Uint8Array|AsyncIterable|ReadableStream} input
1618
+ * @param {import("./EventStreamListener").EventStreamListener} listener
1619
+ * @param {Object} [options]
1620
+ * @param {boolean} [options.forceStoreRaw] Thread to the decode core.
1621
+ * @param {boolean} [options.ignoreErrors] Thread to the decode core.
1622
+ * @param {number} [options.feedHighWater] K5b feed throttle watermark in
1623
+ * bytes (default {@link FEED_HIGH_WATER}); see the constant's JSDoc.
1624
+ * @returns {Promise<void>}
1625
+ */
1626
+ function fromPart10Stream(input, listener, options = {}) {
1627
+ // Settlement handshake for the K5b feed gate: when the parse settles
1628
+ // (success OR error, from any of the many exit points), a throttled feed
1629
+ // must wake and wind down instead of waiting forever for consumer
1630
+ // activity that will never come.
1631
+ const parseState = { done: false, resolveDone: null };
1632
+ parseState.donePromise = new Promise(
1633
+ resolve => (parseState.resolveDone = resolve)
1634
+ );
1635
+ return fromPart10StreamImpl(input, listener, options, parseState).finally(
1636
+ () => {
1637
+ parseState.done = true;
1638
+ parseState.resolveDone();
1639
+ }
1640
+ );
1641
+ }
1642
+
1643
+ /**
1644
+ * The parse behind {@link fromPart10Stream}. It runs in four phases:
1645
+ *
1646
+ * 1. Preamble detection ({@link detectPreamble}); a bare dataset gets its
1647
+ * body syntax from {@link detectBareSyntax} and skips phase 2.
1648
+ * 2. Incremental FMI parse ({@link readFileMetaInformation}).
1649
+ * 3. Emission of the collected FMI events, after startDataSet.
1650
+ * 4. The body phase (K4 — fully incremental element loop).
1651
+ *
1652
+ * K4: the raw `stream` uses clearBuffers:true — the incremental body loop
1653
+ * consume()s each completed top-level element, so chunk memory is released
1654
+ * as the parse advances (bounded-memory streaming). The deflate relay
1655
+ * consumes the raw stream itself as it advances.
1656
+ *
1657
+ * Body phase: every structure now streams natively, in source order, bounded
1658
+ * only by the element currently being decoded:
1659
+ *
1660
+ * - Defined-length leaves and SQ: emitted directly (K3 behavior).
1661
+ * - Undefined-length SQ / items: parsed delimiter-driven; the subtree is
1662
+ * buffered ONLY long enough to backfill the buffered-parity content-span
1663
+ * length payload on startSequence/startItem (unknown until the closing
1664
+ * FFFE,E0DD / FFFE,E00D is reached), then flushed.
1665
+ * - Encapsulated pixel data: fragments streamed one at a time (the Basic
1666
+ * Offset Table item is skipped, matching buffered fromPart10).
1667
+ * - Undefined-length non-SQ leaves ("eagerWindow"): the value is bounded
1668
+ * by a delimiter scan ({@link skipUndefinedSequence}) and decoded via
1669
+ * decodeUndefinedLengthValues.
1670
+ *
1671
+ * The K3 tail-fallback (walkBodyTail / TailFallbackSignal / EventBuffer-for-
1672
+ * atomicity) is deleted: nothing can fall back mid-subtree anymore because
1673
+ * deflate is decided BEFORE the body loop. The only remaining buffered path
1674
+ * is deflate (K5). Chunk release is LIVE (clearBuffers:true + consume()).
1675
+ *
1676
+ * K5 deflate: a relay coroutine (runInflateRelay) reads compressed bytes from
1677
+ * `stream` (raw space, fixed at metaEndOffset after FMI parsing) and pushes
1678
+ * them through pako.Inflate into `bodyStream` (inflated/zero-based space).
1679
+ * The body element loop reads from `bsrc`, which is `bodyStream` for deflate
1680
+ * and `stream` for everything else. This is the ONLY branch that decides
1681
+ * which offset space the body loop operates in.
1682
+ *
1683
+ * Offset-space invariant: `stream` coordinates are always raw/compressed;
1684
+ * `bodyStream` coordinates are always inflated/zero-based. The two spaces are
1685
+ * NEVER mixed: body element offsets, `ensureAbs` calls, `slice` calls, and
1686
+ * `consume` calls all operate exclusively on whichever `bsrc` resolves to.
1687
+ * The relay is the sole owner of `stream` during the body phase.
1688
+ *
1689
+ * K5 top-level body element loop: every element (defined or undefined
1690
+ * length, leaf or SQ or encapsulated) is read and emitted incrementally by
1691
+ * parseOneElement. After each top-level element completes, consume()
1692
+ * releases the chunks it no longer needs. For deflate, `bsrc` is bodyStream
1693
+ * (inflated space, zero-based); the relay concurrently pushes inflated
1694
+ * chunks. For all other paths, `bsrc` is stream (raw space).
1695
+ */
1696
+ async function fromPart10StreamImpl(input, listener, options, parseState) {
1697
+ const iterable = normalizeInput(input);
1698
+
1699
+ // K4: clearBuffers releases chunks as the parse advances (see JSDoc).
1700
+ const stream = new ReadBufferStream(null, true, { clearBuffers: true });
1701
+
1702
+ // Feed runs unawaited so the FMI parse can proceed concurrently.
1703
+ const feedHighWater = options.feedHighWater ?? FEED_HIGH_WATER;
1704
+ let feedError = null;
1705
+ const feedPromise = runFeed();
1706
+
1707
+ /**
1708
+ * Feed loop: copies each source chunk into `stream`, then completes it.
1709
+ * K5b: the loop throttles against the parse loop at `feedHighWater`
1710
+ * retained bytes (see {@link FEED_HIGH_WATER}). Pending demand always
1711
+ * wins so a starved consumer can never deadlock; parse settlement
1712
+ * (parseState) wakes the gate on early exit or error. A source error is
1713
+ * stored in `feedError` for the parse to rethrow.
1714
+ */
1715
+ async function runFeed() {
1716
+ try {
1717
+ for await (const chunk of iterable) {
1718
+ stream.addBuffer(toArrayBuffer(chunk));
1719
+ // K5b: throttle against the parse loop (see JSDoc).
1720
+ while (
1721
+ !parseState.done &&
1722
+ stream.getBufferMemoryInfo().totalSize > feedHighWater &&
1723
+ !stream.hasPendingDemand()
1724
+ ) {
1725
+ await Promise.race([
1726
+ stream.awaitConsumerActivity(),
1727
+ parseState.donePromise
1728
+ ]);
1729
+ }
1730
+ }
1731
+ stream.setComplete();
1732
+ } catch (e) {
1733
+ feedError = e;
1734
+ // Unblock any stream.ensureAvailable() waiters so the parse
1735
+ // can observe the error and propagate it.
1736
+ stream.setComplete();
1737
+ }
1738
+ }
1739
+
1740
+ const policy = {
1741
+ forceStoreRaw: !!options.forceStoreRaw,
1742
+ noCopy: false,
1743
+ ignoreErrors: !!options.ignoreErrors
1744
+ };
1745
+
1746
+ // ---- Phase 1: Preamble detection (incremental) ----
1747
+ let fmiElements = [];
1748
+ let transferSyntaxUID;
1749
+ let rawTransferSyntaxUID;
1750
+ if (await detectPreamble(stream)) {
1751
+ // A bare dataset has no FMI; its body starts at byte 0.
1752
+ transferSyntaxUID = await detectBareSyntax(stream, options);
1753
+ rawTransferSyntaxUID = transferSyntaxUID;
1754
+ } else {
1755
+ // ---- Phase 2: Incremental FMI parse ----
1756
+ ({ fmiElements, transferSyntaxUID, rawTransferSyntaxUID } =
1757
+ await readFileMetaInformation(stream, policy));
1758
+ }
1759
+
1760
+ // ---- Phase 3: Emit collected FMI events ----
1761
+ //
1762
+ // Now that we know the TransferSyntaxUID we can emit startDataSet with
1763
+ // the correct TS before the FMI bracket and element events.
1764
+
1765
+ listener.startDataSet({ transferSyntaxUID });
1766
+
1767
+ if (fmiElements.length > 0) {
1768
+ listener.startFileMetaInformation();
1769
+ for (const el of fmiElements) {
1770
+ emitFmiElement(listener, el);
1771
+ }
1772
+ listener.endFileMetaInformation();
1773
+ }
1774
+
1775
+ // ---- Phase 4: Body phase (K4 — fully incremental; see JSDoc) ----
1776
+
1777
+ let bodyStream = null;
1778
+ let inflateError = null;
1779
+ let relayPromise = Promise.resolve();
1780
+
1781
+ // F6: the body-loop catch below awaits relayPromise, so the relay must
1782
+ // never park on consumer activity that a failed body loop will never
1783
+ // produce. The catch resolves this deferred BEFORE awaiting the relay,
1784
+ // and the relay races it inside its throttle gate and winds down.
1785
+ let bodyFailed = false;
1786
+ let signalBodyFailed = null;
1787
+ const bodyFailedPromise = new Promise(
1788
+ resolve => (signalBodyFailed = resolve)
1789
+ );
1790
+
1791
+ if (rawTransferSyntaxUID === DEFLATED_EXPLICIT_LITTLE_ENDIAN) {
1792
+ bodyStream = new ReadBufferStream(null, true, { clearBuffers: true });
1793
+
1794
+ // `stream.offset` is fixed at metaEndOffset throughout the body phase
1795
+ // for the deflate path — the body parser reads from bodyStream, never
1796
+ // from stream. This keeps raw-space and inflated-space counters separate.
1797
+ const relayStartPos = stream.offset; // == metaEndOffset
1798
+
1799
+ relayPromise = runInflateRelay(relayStartPos);
1800
+ }
1801
+
1802
+ /**
1803
+ * K5 deflate relay: reads compressed bytes from `stream` starting at
1804
+ * `relayStartPos`, inflates them (raw DEFLATE, chunk size
1805
+ * {@link INFLATE_CHUNK_SIZE}) and appends the output to `bodyStream`.
1806
+ * Sets `inflateError` on a decompress failure, or copies `feedError`
1807
+ * there when the raw stream failed, then completes `bodyStream`.
1808
+ *
1809
+ * Throttle (ED-1, see {@link RELAY_HIGH_WATER} and
1810
+ * {@link RELAY_RAW_SLICE}): after each raw sub-slice, the relay waits for
1811
+ * the body loop to consume below the watermark before it inflates more.
1812
+ * A consumer blocked on ensureAvailable (pending demand) always wins — the
1813
+ * relay resumes immediately. A body loop that FAILED (listener threw)
1814
+ * produces no consumer activity ever again, so the gate also races the
1815
+ * bodyFailed deferred and winds down (F6).
1816
+ */
1817
+ async function runInflateRelay(relayStartPos) {
1818
+ const inflater = new pako.Inflate({
1819
+ raw: true,
1820
+ chunkSize: INFLATE_CHUNK_SIZE
1821
+ });
1822
+ inflater.onData = chunk => {
1823
+ // chunk is a Uint8Array (pako 2.x). Slice to an owned
1824
+ // ArrayBuffer so bodyStream's view doesn't alias pako's buffer.
1825
+ bodyStream.addBuffer(
1826
+ chunk.buffer.slice(
1827
+ chunk.byteOffset,
1828
+ chunk.byteOffset + chunk.byteLength
1829
+ )
1830
+ );
1831
+ };
1832
+
1833
+ let relayPos = relayStartPos;
1834
+ for (;;) {
1835
+ // Wait for at least one new byte at relayPos, or raw stream done.
1836
+ // stream.offset stays fixed (== metaEndOffset), so:
1837
+ // need = relayPos + 1 - stream.offset = bytes to advance past offset.
1838
+ const need = relayPos + 1 - stream.offset;
1839
+ await stream.ensureAvailable(need);
1840
+
1841
+ // Synchronous snapshot after the await (JS single-threaded:
1842
+ // no feed-loop interleaving between these two reads).
1843
+ const nowEnd = stream.endOffset;
1844
+ const done = stream.isComplete;
1845
+
1846
+ if (nowEnd > relayPos) {
1847
+ const rawSlice = new Uint8Array(stream.slice(relayPos, nowEnd));
1848
+ relayPos = nowEnd;
1849
+ // Release raw chunks that the relay has fully passed.
1850
+ stream.consume(relayPos);
1851
+ // isLast: feed loop called setComplete() — no more chunks.
1852
+ const isLast = done;
1853
+ for (let s = 0; s < rawSlice.length; s += RELAY_RAW_SLICE) {
1854
+ const subEnd = Math.min(
1855
+ s + RELAY_RAW_SLICE,
1856
+ rawSlice.length
1857
+ );
1858
+ const subLast = isLast && subEnd === rawSlice.length;
1859
+ inflater.push(rawSlice.subarray(s, subEnd), subLast);
1860
+ if (inflater.err) {
1861
+ // pako 2.x stores the error message in inflater.msg.
1862
+ inflateError = new Error(
1863
+ `fromPart10Stream: deflate decompress failed: ${inflater.msg}`
1864
+ );
1865
+ bodyStream.setComplete(); // unblock waiting body parser
1866
+ return;
1867
+ }
1868
+ if (subLast) break;
1869
+ // Throttle below the watermark; races bodyFailed (F6).
1870
+ while (
1871
+ !bodyFailed &&
1872
+ bodyStream.getBufferMemoryInfo().totalSize >
1873
+ RELAY_HIGH_WATER &&
1874
+ !bodyStream.hasPendingDemand()
1875
+ ) {
1876
+ await Promise.race([
1877
+ bodyStream.awaitConsumerActivity(),
1878
+ bodyFailedPromise
1879
+ ]);
1880
+ }
1881
+ if (bodyFailed) {
1882
+ bodyStream.setComplete();
1883
+ return;
1884
+ }
1885
+ }
1886
+ if (isLast) break;
1887
+ } else {
1888
+ // No new bytes — stream must be isComplete (OR-complete).
1889
+ // Finalize: push empty batch with isLast=true.
1890
+ inflater.push(new Uint8Array(0), true);
1891
+ if (inflater.err) {
1892
+ inflateError = new Error(
1893
+ `fromPart10Stream: deflate decompress failed: ${inflater.msg}`
1894
+ );
1895
+ }
1896
+ break;
1897
+ }
1898
+ }
1899
+
1900
+ // Propagate a feed error if the raw stream failed (e.g. network
1901
+ // error mid-stream). Prefer inflate error if both occurred.
1902
+ if (!inflateError && feedError) {
1903
+ inflateError = feedError;
1904
+ }
1905
+
1906
+ bodyStream.setComplete();
1907
+ }
1908
+
1909
+ // Body source: inflated bodyStream for deflate, raw stream for everything else.
1910
+ // ALL body helper functions and the body loop use `bsrc` exclusively.
1911
+ const bsrc = bodyStream ?? stream;
1912
+
1913
+ // Body transfer syntax characteristics — drive all element reads.
1914
+ const bodyLittleEndian = transferSyntaxUID !== EXPLICIT_BIG_ENDIAN;
1915
+ const bodyImplicit = transferSyntaxUID === IMPLICIT_LITTLE_ENDIAN;
1916
+
1917
+ // Chunk release is LIVE for all paths: clearBuffers=true on both `stream`
1918
+ // (non-deflate) and `bodyStream` (deflate). The relay releases raw chunks
1919
+ // as it advances; the body loop releases inflated (or native) chunks below.
1920
+ const releaseEnabled = true;
1921
+
1922
+ const UNDEFINED_LEN = 0xffffffff;
1923
+ const EMPTY_WIN = {
1924
+ implicit: bodyImplicit};
1925
+
1926
+ /**
1927
+ * Byte-order helpers for body elements (tag, VR, length). They use `bsrc`
1928
+ * (bodyStream for deflate, stream for everything else) so that they
1929
+ * operate in the correct offset space.
1930
+ *
1931
+ * FFFE-family item/delimiter tags (FFFE,E000 / FFFE,E00D / FFFE,E0DD) and
1932
+ * their length fields are read in the body transfer-syntax byte order,
1933
+ * exactly as the buffered fromPart10 reads them via Tag.readTag →
1934
+ * readUint16, which honors stream.isLittleEndian. They are NOT
1935
+ * unconditionally little-endian: in an Explicit Big Endian dataset the
1936
+ * item bytes on wire are big-endian (FF FE for the group, E0 00 for the
1937
+ * element, etc.) and must be read as BE.
1938
+ */
1939
+ const getU16 = abs => bsrc.view.getUint16(abs, bodyLittleEndian);
1940
+ /** 32-bit form of {@link getU16}, in the body byte order. */
1941
+ const getU32 = abs => bsrc.view.getUint32(abs, bodyLittleEndian);
1942
+
1943
+ /** Convert (group, element) numbers to clean DICOM tag string "GGGGEEEE". */
1944
+ function bodyTagStr(g, e) {
1945
+ return (
1946
+ g.toString(16).padStart(4, "0").toUpperCase() +
1947
+ e.toString(16).padStart(4, "0").toUpperCase()
1948
+ );
1949
+ }
1950
+
1951
+ /**
1952
+ * EventBuffer — records listener events as lambdas so an undefined-length
1953
+ * SQ / item subtree can be replayed AFTER its closing delimiter is reached,
1954
+ * once the content-span length payload is known (buffered fromPart10 emits
1955
+ * that computed span, not the on-wire 0xFFFFFFFF). Values are baked into the
1956
+ * lambdas at decode time, so charset scoping and fresh-copy semantics are
1957
+ * unaffected by the deferred flush. awaitDrain is a local no-op during
1958
+ * buffering (backpressure is applied by the real listener after the flush).
1959
+ */
1960
+ class EventBuffer {
1961
+ constructor() {
1962
+ this._q = [];
1963
+ }
1964
+ startElement(tag, info) {
1965
+ this._q.push(l => l.startElement(tag, info));
1966
+ }
1967
+ endElement() {
1968
+ this._q.push(l => l.endElement());
1969
+ }
1970
+ value(v, opts) {
1971
+ this._q.push(l => l.value(v, opts));
1972
+ }
1973
+ startBinary(opts) {
1974
+ this._q.push(l => l.startBinary(opts));
1975
+ }
1976
+ binaryFragment(buf) {
1977
+ this._q.push(l => l.binaryFragment(buf));
1978
+ }
1979
+ endBinary() {
1980
+ this._q.push(l => l.endBinary());
1981
+ }
1982
+ startSequence(tag, info) {
1983
+ this._q.push(l => l.startSequence(tag, info));
1984
+ }
1985
+ endSequence() {
1986
+ this._q.push(l => l.endSequence());
1987
+ }
1988
+ startItem(info) {
1989
+ this._q.push(l => l.startItem(info));
1990
+ }
1991
+ endItem() {
1992
+ this._q.push(l => l.endItem());
1993
+ }
1994
+ awaitDrain() {} // no-op during buffering
1995
+ /** Replay all buffered events to `realListener`. */
1996
+ flushTo(realListener) {
1997
+ for (const fn of this._q) fn(realListener);
1998
+ }
1999
+ }
2000
+
2001
+ /**
2002
+ * Ensure the bytes up to absolute offset `absEnd` are present, then re-check
2003
+ * strict availability (ensureAvailable resolves at EOF too — OR-complete
2004
+ * semantics). Returns true only when the bytes are genuinely available.
2005
+ */
2006
+ async function ensureAbs(absEnd) {
2007
+ // Operate on `bsrc`: bodyStream (inflated, zero-based) for deflate,
2008
+ // stream (raw) for everything else. Never mix offset spaces.
2009
+ const need = absEnd - bsrc.offset;
2010
+ if (need > 0) {
2011
+ await bsrc.ensureAvailable(need);
2012
+ }
2013
+ return absEnd <= bsrc.endOffset;
2014
+ }
2015
+
2016
+ // ---- Undefined-length structural end-finders (element-aware skip, no emission) ----
2017
+
2018
+ /**
2019
+ * Skip an undefined-length sequence's items, returning
2020
+ * `{ contentEnd, end }`: `contentEnd` is the offset of the closing
2021
+ * FFFE,E0DD (the parser's content-span end == element.length base), `end`
2022
+ * is the offset just past it. Mirrors readSQElementUndefinedLength*.
2023
+ *
2024
+ * DICOM PS3.5 permits undefined length (0xFFFFFFFF) ONLY for SQ elements,
2025
+ * items, and encapsulated pixel data. The only non-SQ undefined-length
2026
+ * element dcmjs decodes cleanly (classifyElement "eagerWindow", via
2027
+ * decodeUndefinedLengthValues) is explicit-VR UN of undefined length (and private
2028
+ * implicit undefined-length elements), which the offsets parser routes
2029
+ * through readSequenceItemsImplicit. These end at the SEQUENCE delimiter
2030
+ * FFFE,E0DD, NOT at an item delimiter.
2031
+ *
2032
+ * For non-conformant text VRs (UT/UC/UR) with undefined length, the two
2033
+ * paths DELIBERATELY diverge (empirically verified; pinned in the K4 test
2034
+ * suite):
2035
+ * - buffered fromPart10 — readEncodedString clamps the 0xFFFFFFFF read
2036
+ * to the actual buffer size, bleeds past any FFFE,E00D delimiter and
2037
+ * returns a garbage string containing all remaining bytes (no throw);
2038
+ * any element following the delimiter is silently consumed into the
2039
+ * string value.
2040
+ * - fromPart10Stream — emitUndefinedLeaf's skipUndefinedSequence sees
2041
+ * the non-FFFE value bytes as malformed (not FFFE,E0DD / FFFE,E000),
2042
+ * stops the window at the value start; the body loop then re-parses
2043
+ * the value bytes as a DICOM element, producing a truncation throw.
2044
+ *
2045
+ * This loud-failure divergence is DELIBERATE: stream fails loudly on
2046
+ * non-conformant data that buffered silently mishandles.
2047
+ *
2048
+ * For binary VRs (OB/OW/etc.) with undefined length, both paths throw
2049
+ * (buffered: "Item tag not found after undefined binary length"; stream:
2050
+ * similar truncation), so no path-divergence arises there.
2051
+ *
2052
+ * These scanners mirror the parser's sequence walk (FFFE,E0DD) with
2053
+ * nested item-delimiter (FFFE,E00D) handling. skipUndefinedItem is
2054
+ * ELEMENT-AWARE — it steps whole element headers/values via
2055
+ * skipOneElementEnd — not a 2-byte byte-scan like findItemDelimitationItem.
2056
+ */
2057
+ async function skipUndefinedSequence(fromAbs) {
2058
+ let pos = fromAbs;
2059
+ for (;;) {
2060
+ if (!(await ensureAbs(pos + 8))) {
2061
+ return { contentEnd: bsrc.endOffset, end: bsrc.endOffset };
2062
+ }
2063
+ const g = getU16(pos);
2064
+ const e = getU16(pos + 2);
2065
+ if (g === 0xfffe && e === 0xe0dd) {
2066
+ return { contentEnd: pos, end: pos + 8 };
2067
+ }
2068
+ if (g !== 0xfffe || e !== 0xe000) {
2069
+ return { contentEnd: pos, end: pos }; // malformed — stop
2070
+ }
2071
+ const itemLength = getU32(pos + 4);
2072
+ pos += 8;
2073
+ pos =
2074
+ itemLength === UNDEFINED_LEN
2075
+ ? await skipUndefinedItem(pos)
2076
+ : pos + itemLength;
2077
+ }
2078
+ }
2079
+
2080
+ /**
2081
+ * Skip an undefined-length item's elements, returning the offset just past
2082
+ * its FFFE,E00D delimiter (findItemDelimitationItem semantics, but element-
2083
+ * aware so nested defined-length values are stepped over correctly).
2084
+ */
2085
+ async function skipUndefinedItem(fromAbs) {
2086
+ let pos = fromAbs;
2087
+ for (;;) {
2088
+ if (!(await ensureAbs(pos + 8))) return bsrc.endOffset;
2089
+ const g = getU16(pos);
2090
+ const e = getU16(pos + 2);
2091
+ if (g === 0xfffe && e === 0xe00d) return pos + 8;
2092
+ pos = await skipOneElementEnd(pos);
2093
+ }
2094
+ }
2095
+
2096
+ /** Skip a single element header + value, recursing into nested structures. */
2097
+ async function skipOneElementEnd(fromAbs) {
2098
+ let pos = fromAbs;
2099
+ if (!(await ensureAbs(pos + 8))) return bsrc.endOffset;
2100
+ pos += 4; // tag
2101
+ let valueLength;
2102
+ if (bodyImplicit) {
2103
+ valueLength = bsrc.view.getUint32(pos, true);
2104
+ pos += 4;
2105
+ } else {
2106
+ const vr =
2107
+ String.fromCharCode(bsrc.view.getUint8(pos)) +
2108
+ String.fromCharCode(bsrc.view.getUint8(pos + 1));
2109
+ pos += 2;
2110
+ if (ValueRepresentation.createByTypeString(vr).isLength32()) {
2111
+ if (!(await ensureAbs(pos + 6))) return bsrc.endOffset;
2112
+ pos += 2; // reserved
2113
+ valueLength = getU32(pos);
2114
+ pos += 4;
2115
+ } else {
2116
+ valueLength = getU16(pos);
2117
+ pos += 2;
2118
+ }
2119
+ }
2120
+ if (valueLength === UNDEFINED_LEN) {
2121
+ return (await skipUndefinedSequence(pos)).end;
2122
+ }
2123
+ if (!(await ensureAbs(pos + valueLength))) return bsrc.endOffset;
2124
+ return pos + valueLength;
2125
+ }
2126
+
2127
+ /**
2128
+ * Read ONE element header at `elemStartAbs` (the caller has verified it is
2129
+ * not a delimiter tag) and route it by classification, emitting into
2130
+ * `target`. Returns the (possibly charset-updated) decoder for the caller
2131
+ * to thread into the next element. Mirrors decodeCore.classifyElement.
2132
+ *
2133
+ * Defined length: resolveVrInstance is the single canonical implicit-VR
2134
+ * contract (AD-1) — dictionary-miss elements resolve to UN and are never
2135
+ * data-peek-promoted to SQ (eager parity). Only dictionary-known SQs take
2136
+ * the sequence path.
2137
+ *
2138
+ * Undefined length: the element is classified as SQ
2139
+ * ({@link isUndefinedLengthSequence}), encapsulated pixel data, or an
2140
+ * eagerWindow leaf, matching decodeCore.classifyElement + the parser's SQ
2141
+ * resolution.
2142
+ */
2143
+ async function parseOneElement(target, elemStartAbs, currentDecoder) {
2144
+ bsrc.offset = elemStartAbs;
2145
+ const elGroup = getU16(elemStartAbs);
2146
+ const elElement = getU16(elemStartAbs + 2);
2147
+ bsrc.offset = elemStartAbs + 4;
2148
+ const tagStr = bodyTagStr(elGroup, elElement);
2149
+
2150
+ let vrStr = null;
2151
+ let valueLength;
2152
+ if (bodyImplicit) {
2153
+ if (!(await ensureAbs(bsrc.offset + 4))) {
2154
+ throw new Error(
2155
+ `fromPart10Stream: truncated at ${elemStartAbs}: missing implicit length`
2156
+ );
2157
+ }
2158
+ // Implicit is always LITTLE_ENDIAN regardless of body TS.
2159
+ valueLength = bsrc.view.getUint32(bsrc.offset, true);
2160
+ bsrc.offset += 4;
2161
+ } else {
2162
+ if (!(await ensureAbs(bsrc.offset + 2))) {
2163
+ throw new Error(
2164
+ `fromPart10Stream: truncated at ${elemStartAbs}: missing VR bytes`
2165
+ );
2166
+ }
2167
+ vrStr =
2168
+ String.fromCharCode(bsrc.view.getUint8(bsrc.offset)) +
2169
+ String.fromCharCode(bsrc.view.getUint8(bsrc.offset + 1));
2170
+ bsrc.offset += 2;
2171
+ const vrForLen = ValueRepresentation.createByTypeString(vrStr);
2172
+ if (vrForLen.isLength32()) {
2173
+ if (!(await ensureAbs(bsrc.offset + 6))) {
2174
+ throw new Error(
2175
+ `fromPart10Stream: truncated at ${elemStartAbs}: missing extended length`
2176
+ );
2177
+ }
2178
+ bsrc.offset += 2; // reserved
2179
+ valueLength = getU32(bsrc.offset);
2180
+ bsrc.offset += 4;
2181
+ } else {
2182
+ if (!(await ensureAbs(bsrc.offset + 2))) {
2183
+ throw new Error(
2184
+ `fromPart10Stream: truncated at ${elemStartAbs}: missing 2-byte length`
2185
+ );
2186
+ }
2187
+ valueLength = getU16(bsrc.offset);
2188
+ bsrc.offset += 2;
2189
+ }
2190
+ }
2191
+
2192
+ const valueStartAbs = bsrc.offset;
2193
+ const undef = valueLength === UNDEFINED_LEN;
2194
+ const elLike = {
2195
+ vr: vrStr,
2196
+ tagValue: ((elGroup << 16) | elElement) >>> 0,
2197
+ dataOffset: 0,
2198
+ length: valueLength,
2199
+ hadUndefinedLength: undef
2200
+ };
2201
+ let vrInstance = resolveVrInstance(elLike, EMPTY_WIN);
2202
+
2203
+ if (!undef) {
2204
+ // Only dictionary-known SQs take the sequence path (AD-1).
2205
+ if (vrInstance.type === "SQ") {
2206
+ await emitSequence(
2207
+ target,
2208
+ tagStr,
2209
+ valueStartAbs,
2210
+ valueLength,
2211
+ currentDecoder
2212
+ );
2213
+ return currentDecoder;
2214
+ }
2215
+ return await emitDefinedLeaf(
2216
+ target,
2217
+ tagStr,
2218
+ elLike,
2219
+ vrInstance,
2220
+ valueLength,
2221
+ valueStartAbs,
2222
+ currentDecoder
2223
+ );
2224
+ }
2225
+
2226
+ // Undefined length: classify SQ / encapsulated / eagerWindow leaf.
2227
+ const treatAsSq = await isUndefinedLengthSequence(
2228
+ elLike,
2229
+ vrInstance,
2230
+ valueStartAbs
2231
+ );
2232
+ if (treatAsSq) {
2233
+ await emitSequence(
2234
+ target,
2235
+ tagStr,
2236
+ valueStartAbs,
2237
+ UNDEFINED_LEN,
2238
+ currentDecoder
2239
+ );
2240
+ return currentDecoder;
2241
+ }
2242
+ if (tagStr === "7FE00010" && !isParsedUnknownVr(vrInstance)) {
2243
+ await emitEncapsulated(target, tagStr, vrInstance, valueStartAbs);
2244
+ return currentDecoder;
2245
+ }
2246
+ await emitUndefinedLeaf(
2247
+ target,
2248
+ tagStr,
2249
+ valueStartAbs,
2250
+ elLike,
2251
+ vrInstance,
2252
+ currentDecoder
2253
+ );
2254
+ return currentDecoder;
2255
+ }
2256
+
2257
+ /**
2258
+ * Decide whether an undefined-length element streams as a sequence.
2259
+ * Explicit VR: true when the resolved VR is SQ. Implicit VR: true for a
2260
+ * dictionary-known SQ (no peek); a dictionary-unknown element that
2261
+ * resolved to SQ (hadUndefinedLength fallback) is peeked for an
2262
+ * FFFE,E000 / FFFE,E0DD first tag.
2263
+ *
2264
+ * The peek is ROUTING-ONLY (AD-1): it chooses between streamed
2265
+ * emitSequence and the delimiter-scanned eager-window leaf, both of which
2266
+ * yield eager-SQ semantics for undefined-length dictionary-miss elements
2267
+ * (resolveVrInstance's length rule). The semantic contract itself never
2268
+ * data-peek-promotes defined-length elements.
2269
+ */
2270
+ async function isUndefinedLengthSequence(
2271
+ elLike,
2272
+ vrInstance,
2273
+ valueStartAbs
2274
+ ) {
2275
+ let treatAsSq = false;
2276
+ if (vrInstance.type === "SQ") {
2277
+ if (!bodyImplicit) {
2278
+ treatAsSq = true; // explicit VR SQ
2279
+ } else {
2280
+ const dictVr = resolveVrInstance(
2281
+ { ...elLike, hadUndefinedLength: false },
2282
+ EMPTY_WIN
2283
+ );
2284
+ if (dictVr.type === "SQ") {
2285
+ treatAsSq = true;
2286
+ } else if (await ensureAbs(valueStartAbs + 4)) {
2287
+ const pg = bsrc.view.getUint16(valueStartAbs, true);
2288
+ const pe = bsrc.view.getUint16(valueStartAbs + 2, true);
2289
+ treatAsSq =
2290
+ pg === 0xfffe && (pe === 0xe000 || pe === 0xe0dd);
2291
+ }
2292
+ }
2293
+ }
2294
+ return treatAsSq;
2295
+ }
2296
+
2297
+ /**
2298
+ * Defined-length leaf element: decode the value and emit directly. Returns
2299
+ * the decoder to thread onward (updated when this is (0008,0005)).
2300
+ *
2301
+ * (0028,0103) PixelRepresentation drives the "xs" (US-or-SS) meta-VR
2302
+ * resolution of subsequent elements (issue #368). EMPTY_WIN is the window
2303
+ * handed to resolveVrInstance and is created per parse, so the in-place
2304
+ * update is private to this stream.
2305
+ */
2306
+ async function emitDefinedLeaf(
2307
+ target,
2308
+ tagStr,
2309
+ elLike,
2310
+ vrInstance,
2311
+ valueLength,
2312
+ valueStartAbs,
2313
+ decoder
2314
+ ) {
2315
+ const valueEndAbs = valueStartAbs + valueLength;
2316
+ if (valueLength > 0 && !(await ensureAbs(valueEndAbs))) {
2317
+ throw new Error(
2318
+ `fromPart10Stream: truncated: element at ${valueStartAbs} ` +
2319
+ `declares ${valueLength} bytes but stream ended`
2320
+ );
2321
+ }
2322
+ const valueAB = bsrc.slice(valueStartAbs, valueEndAbs);
2323
+ const win = {
2324
+ arrayBuffer: valueAB,
2325
+ baseOffset: 0,
2326
+ syntax: transferSyntaxUID,
2327
+ littleEndian: bodyLittleEndian,
2328
+ implicit: bodyImplicit,
2329
+ decoder
2330
+ };
2331
+ const { values, rawValues } = decodeElementValues(
2332
+ win,
2333
+ elLike,
2334
+ vrInstance,
2335
+ policy
2336
+ );
2337
+ let newDecoder = decoder;
2338
+ // (0008,0005) SpecificCharacterSet sets the decoder for subsequent
2339
+ // elements in this scope (top-level body or the current SQ item).
2340
+ if (tagStr === "00080005") {
2341
+ const csResult = resolveCharacterSet(win, elLike, policy);
2342
+ newDecoder = csResult?.decoder ?? null;
2343
+ }
2344
+ // (0028,0103) drives "xs" VR resolution (issue #368; see JSDoc).
2345
+ if (tagStr === "00280103" && values && values.length) {
2346
+ EMPTY_WIN.pixelRepresentation = values[0];
2347
+ }
2348
+ emitValues(target, tagStr, vrInstance, elLike, values, rawValues);
2349
+ bsrc.offset = valueEndAbs;
2350
+ return newDecoder;
2351
+ }
2352
+
2353
+ /**
2354
+ * Emit a sequence (defined or undefined length) into `target`.
2355
+ * `dataOffsetAbs` is the absolute offset of the sequence's first content
2356
+ * byte. Defined-length sequences emit directly with the declared length;
2357
+ * undefined-length sequences buffer their items so the content-span length
2358
+ * payload (parity with buffered fromPart10) can be backfilled at the
2359
+ * closing FFFE,E0DD.
2360
+ */
2361
+ async function emitSequence(
2362
+ target,
2363
+ tagStr,
2364
+ dataOffsetAbs,
2365
+ declaredLength,
2366
+ outerDecoder
2367
+ ) {
2368
+ if (declaredLength !== UNDEFINED_LEN) {
2369
+ const sqEndAbs = dataOffsetAbs + declaredLength;
2370
+ target.startSequence(tagStr, { vr: "SQ", length: declaredLength });
2371
+ await parseSqItems(target, sqEndAbs, false, outerDecoder);
2372
+ target.endSequence();
2373
+ bsrc.offset = sqEndAbs;
2374
+ } else {
2375
+ const buf = new EventBuffer();
2376
+ const delimStart = await parseSqItems(buf, -1, true, outerDecoder);
2377
+ const contentSpan = delimStart - dataOffsetAbs;
2378
+ target.startSequence(tagStr, { vr: "SQ", length: contentSpan });
2379
+ buf.flushTo(target);
2380
+ target.endSequence();
2381
+ // bsrc.offset already advanced past FFFE,E0DD by parseSqItems.
2382
+ }
2383
+ }
2384
+
2385
+ /**
2386
+ * Encapsulated pixel data: stream fragments one at a time. The first item is
2387
+ * the Basic Offset Table — its header is read and its bytes skipped (buffered
2388
+ * fromPart10 keeps it in element.basicOffsetTable and does NOT emit it as a
2389
+ * fragment). The startElement length payload is the on-wire 0xFFFFFFFF
2390
+ * (the computed span is unknown until the closing delimiter, which would
2391
+ * defeat fragment streaming) — a documented delta from buffered fromPart10.
2392
+ *
2393
+ * The Basic Offset Table item (FFFE,E000) offsets are surfaced on
2394
+ * startBinary so BOT-aware listeners can merge fragments per frame window
2395
+ * (issue #204).
2396
+ *
2397
+ * K6: per-fragment release (see {@link releaseConsumedChunks}) bounds
2398
+ * peak memory to (largest fragment + chunk size + fixed slack) rather than
2399
+ * the full pixel-data element. The fragment bytes were already copied
2400
+ * into an owned ArrayBuffer by bsrc.slice(), so aliasing is safe to
2401
+ * discard. Without this, the whole encapsulated element accumulates in
2402
+ * the stream buffer until the post-element consume() in the body loop
2403
+ * fires.
2404
+ */
2405
+ async function emitEncapsulated(target, tagStr, vrInstance, dataOffsetAbs) {
2406
+ target.startElement(tagStr, {
2407
+ vr: vrInstance.type,
2408
+ length: UNDEFINED_LEN
2409
+ });
2410
+ bsrc.offset = dataOffsetAbs;
2411
+
2412
+ // Basic Offset Table: surface offsets (issue #204), then skip bytes.
2413
+ if (!(await ensureAbs(bsrc.offset + 8))) {
2414
+ throw new Error(
2415
+ `fromPart10Stream: truncated: encapsulated BOT header at ${bsrc.offset}`
2416
+ );
2417
+ }
2418
+ const botLen = getU32(bsrc.offset + 4);
2419
+ bsrc.offset += 8;
2420
+ const startBinaryInfo = { encapsulated: true };
2421
+ if (botLen > 0) {
2422
+ if (!(await ensureAbs(bsrc.offset + botLen))) {
2423
+ throw new Error(
2424
+ `fromPart10Stream: truncated: encapsulated BOT (${botLen} bytes)`
2425
+ );
2426
+ }
2427
+ const botCount = Math.floor(botLen / 4);
2428
+ if (botCount > 0) {
2429
+ const basicOffsetTable = new Array(botCount);
2430
+ for (let i = 0; i < botCount; i++) {
2431
+ basicOffsetTable[i] = getU32(bsrc.offset + i * 4);
2432
+ }
2433
+ startBinaryInfo.basicOffsetTable = basicOffsetTable;
2434
+ }
2435
+ bsrc.offset += botLen;
2436
+ }
2437
+ target.startBinary(startBinaryInfo);
2438
+
2439
+ for (;;) {
2440
+ if (!(await ensureAbs(bsrc.offset + 8))) {
2441
+ throw new Error(
2442
+ `fromPart10Stream: truncated: encapsulated item header at ${bsrc.offset}`
2443
+ );
2444
+ }
2445
+ const g = getU16(bsrc.offset);
2446
+ const e = getU16(bsrc.offset + 2);
2447
+ if (g === 0xfffe && e === 0xe0dd) {
2448
+ bsrc.offset += 8; // sequence-delimiter tag + 4-byte length
2449
+ break;
2450
+ }
2451
+ if (g !== 0xfffe || e !== 0xe000) {
2452
+ break; // unexpected tag — stop gracefully
2453
+ }
2454
+ const fragLen = getU32(bsrc.offset + 4);
2455
+ bsrc.offset += 8;
2456
+ const fragStart = bsrc.offset;
2457
+ const fragEnd = fragStart + fragLen;
2458
+ if (!(await ensureAbs(fragEnd))) {
2459
+ throw new Error(
2460
+ `fromPart10Stream: truncated: pixel-data fragment (${fragLen} bytes) at ${fragStart}`
2461
+ );
2462
+ }
2463
+ // Fresh copy — the emitted buffer must not alias released chunks.
2464
+ target.binaryFragment(bsrc.slice(fragStart, fragEnd));
2465
+ bsrc.offset = fragEnd;
2466
+ await target.awaitDrain(); // backpressure between fragments
2467
+ // K6: per-fragment release (see JSDoc).
2468
+ {
2469
+ releaseConsumedChunks();
2470
+ }
2471
+ }
2472
+ target.endBinary();
2473
+ target.endElement();
2474
+ }
2475
+
2476
+ /**
2477
+ * Release every `bsrc` chunk fully behind the current position, then
2478
+ * report the buffer memory state to `options.onConsume`. For the deflate
2479
+ * path (bodyStream active), the report also includes the raw stream
2480
+ * memory state, so tests can verify both streams release chunks
2481
+ * concurrently.
2482
+ */
2483
+ function releaseConsumedChunks() {
2484
+ bsrc.consume(bsrc.offset);
2485
+ const info = bsrc.getBufferMemoryInfo();
2486
+ if (bodyStream) {
2487
+ info.rawStreamInfo = stream.getBufferMemoryInfo();
2488
+ }
2489
+ options.onConsume?.(info);
2490
+ }
2491
+
2492
+ /**
2493
+ * Undefined-length non-SQ leaf ("eagerWindow"): bound the value by
2494
+ * walking the structure to its closing sequence delimiter, copy the value
2495
+ * bytes, and decode via decodeUndefinedLengthValues. The emitted length
2496
+ * payload is the content span (delimiter offset minus the data offset),
2497
+ * for parity with buffered. See {@link skipUndefinedSequence} for the
2498
+ * deliberate divergence on non-conformant undefined-length UT/UC/UR.
2499
+ */
2500
+ async function emitUndefinedLeaf(
2501
+ target,
2502
+ tagStr,
2503
+ valueStartAbs,
2504
+ elLike,
2505
+ vrInstance,
2506
+ decoder
2507
+ ) {
2508
+ const { contentEnd, end } = await skipUndefinedSequence(valueStartAbs);
2509
+ const win = {
2510
+ arrayBuffer: bsrc.slice(valueStartAbs, end),
2511
+ baseOffset: 0,
2512
+ syntax: transferSyntaxUID,
2513
+ littleEndian: bodyLittleEndian,
2514
+ decoder
2515
+ };
2516
+ const valueEl = {
2517
+ ...elLike,
2518
+ dataOffset: 0,
2519
+ endOffset: end - valueStartAbs,
2520
+ length: contentEnd - valueStartAbs
2521
+ };
2522
+ const { values, rawValues } = decodeUndefinedLengthValues(
2523
+ win,
2524
+ valueEl,
2525
+ vrInstance,
2526
+ policy
2527
+ );
2528
+ emitDecodedLeaf(target, tagStr, vrInstance, valueEl, values, rawValues);
2529
+ bsrc.offset = end;
2530
+ }
2531
+
2532
+ /**
2533
+ * Parse the items of a sequence into `target`.
2534
+ * - Defined-length SQ (`undefinedSeq=false`): items until `sqEndAbs`.
2535
+ * - Undefined-length SQ (`undefinedSeq=true`, `sqEndAbs` ignored): items
2536
+ * until the sequence delimiter (FFFE,E0DD); returns the absolute offset
2537
+ * of that delimiter (the parser's content-span end).
2538
+ * `outerDecoder` is the parent-scope charset decoder inherited by items.
2539
+ */
2540
+ async function parseSqItems(target, sqEndAbs, undefinedSeq, outerDecoder) {
2541
+ while (undefinedSeq || bsrc.offset < sqEndAbs) {
2542
+ if (!(await ensureAbs(bsrc.offset + 8))) {
2543
+ if (undefinedSeq) return bsrc.offset; // EOF before delimiter
2544
+ throw new Error(
2545
+ `fromPart10Stream: truncated: SQ item header at ${bsrc.offset}`
2546
+ );
2547
+ }
2548
+ const itemStart = bsrc.offset;
2549
+ const itemGroup = getU16(itemStart);
2550
+ const itemElement = getU16(itemStart + 2);
2551
+
2552
+ if (itemGroup === 0xfffe && itemElement === 0xe0dd) {
2553
+ bsrc.offset = itemStart + 8; // consume seq-delimiter + length
2554
+ return itemStart;
2555
+ }
2556
+ if (itemGroup !== 0xfffe || itemElement !== 0xe000) {
2557
+ return itemStart; // unexpected tag — stop gracefully
2558
+ }
2559
+ const itemLength = getU32(itemStart + 4);
2560
+ bsrc.offset = itemStart + 8; // past item header
2561
+ const itemDataOffset = bsrc.offset;
2562
+
2563
+ if (itemLength !== UNDEFINED_LEN) {
2564
+ const itemEndAbs = itemDataOffset + itemLength;
2565
+ target.startItem({ length: itemLength });
2566
+ await parseItemElements(
2567
+ target,
2568
+ itemEndAbs,
2569
+ false,
2570
+ outerDecoder
2571
+ );
2572
+ target.endItem();
2573
+ bsrc.offset = itemEndAbs;
2574
+ } else {
2575
+ // Undefined-length item: buffer to backfill the parser's item
2576
+ // span (data offset → past the closing item delimiter).
2577
+ const ibuf = new EventBuffer();
2578
+ const delimStart = await parseItemElements(
2579
+ ibuf,
2580
+ -1,
2581
+ true,
2582
+ outerDecoder
2583
+ );
2584
+ const itemSpan = delimStart + 8 - itemDataOffset;
2585
+ target.startItem({ length: itemSpan });
2586
+ ibuf.flushTo(target);
2587
+ target.endItem();
2588
+ }
2589
+ }
2590
+ return bsrc.offset;
2591
+ }
2592
+
2593
+ /**
2594
+ * Parse the elements of a single sequence item into `target`.
2595
+ * - Defined-length item (`undefinedItem=false`): elements until
2596
+ * `itemEndAbs`.
2597
+ * - Undefined-length item (`undefinedItem=true`, `itemEndAbs` ignored):
2598
+ * elements until the item delimiter (FFFE,E00D); returns the absolute
2599
+ * offset of that delimiter.
2600
+ * Per-item charset scoping: this item's own (0008,0005) overrides
2601
+ * `parentDecoder` for subsequent elements in its subtree.
2602
+ */
2603
+ async function parseItemElements(
2604
+ target,
2605
+ itemEndAbs,
2606
+ undefinedItem,
2607
+ parentDecoder
2608
+ ) {
2609
+ let itemDecoder = parentDecoder;
2610
+ while (undefinedItem || bsrc.offset < itemEndAbs) {
2611
+ if (!(await ensureAbs(bsrc.offset + 4))) {
2612
+ if (undefinedItem) return bsrc.offset;
2613
+ throw new Error(
2614
+ `fromPart10Stream: truncated: item element header at ${bsrc.offset}`
2615
+ );
2616
+ }
2617
+ const elemStart = bsrc.offset;
2618
+ const g = getU16(elemStart);
2619
+ const e = getU16(elemStart + 2);
2620
+ if (g === 0xfffe && e === 0xe00d) {
2621
+ // Item delimiter: consume tag + 4-byte length.
2622
+ if (!(await ensureAbs(elemStart + 8)) && undefinedItem) {
2623
+ return elemStart;
2624
+ }
2625
+ bsrc.offset = elemStart + 8;
2626
+ return elemStart;
2627
+ }
2628
+ itemDecoder = await parseOneElement(target, elemStart, itemDecoder);
2629
+ }
2630
+ return bsrc.offset;
2631
+ }
2632
+
2633
+ // ---- K5 top-level body element loop (see fromPart10StreamImpl JSDoc) ----
2634
+ let bodyDecoder = null; // resolved when (0008,0005) is first seen in body
2635
+
2636
+ try {
2637
+ bodyLoop: for (;;) {
2638
+ // --- Read next element tag (4 bytes) ---
2639
+ if (!(await ensureAbs(bsrc.offset + 4))) break bodyLoop; // clean EOF
2640
+
2641
+ const elemStartAbs = bsrc.offset;
2642
+ const elGroup = getU16(elemStartAbs);
2643
+
2644
+ // Defensive: stray top-level FFFE delimiter tags are malformed for a
2645
+ // well-formed Part 10 body; skip them so the next real element frames
2646
+ // correctly (native SQ/encapsulated handlers already consume their own
2647
+ // delimiters, so this is only reached on malformed input).
2648
+ if (elGroup === 0xfffe) {
2649
+ if (!(await ensureAbs(elemStartAbs + 8))) break bodyLoop;
2650
+ bsrc.offset = elemStartAbs + 8;
2651
+ continue bodyLoop;
2652
+ }
2653
+
2654
+ bodyDecoder = await parseOneElement(
2655
+ listener,
2656
+ elemStartAbs,
2657
+ bodyDecoder
2658
+ );
2659
+ await listener.awaitDrain();
2660
+ if (releaseEnabled) {
2661
+ releaseConsumedChunks();
2662
+ }
2663
+ }
2664
+ } catch (bodyErr) {
2665
+ // F6: wake a relay parked on consumer activity BEFORE awaiting it,
2666
+ // or the two awaits deadlock each other and the promise never settles.
2667
+ bodyFailed = true;
2668
+ signalBodyFailed();
2669
+ // Wait for the relay to settle so inflateError is populated (if any).
2670
+ await relayPromise;
2671
+ // Prioritize the root cause over the symptom: an inflate or source
2672
+ // (feed) error explains the truncated read the body loop tripped on.
2673
+ throw inflateError ?? feedError ?? bodyErr;
2674
+ }
2675
+
2676
+ // Relay must finish before we inspect inflateError.
2677
+ await relayPromise;
2678
+ if (inflateError) throw inflateError;
2679
+
2680
+ // F7: the body loop treats stream-complete as a clean EOF, but the feed
2681
+ // catch also calls setComplete() when the SOURCE throws mid-transfer. A
2682
+ // clean end is only clean if the feed finished without error — otherwise
2683
+ // a truncated transfer would resolve as a well-formed shorter dataset.
2684
+ await feedPromise;
2685
+ if (feedError) throw feedError;
2686
+
2687
+ // Observable hook: fires for ALL paths (deflate and non-deflate) now that
2688
+ // the early deflate return is gone.
2689
+ options.onPhase?.("native");
2690
+
2691
+ listener.endDataSet();
2692
+ }
2693
+
2694
+ // ---------------------------------------------------------------------------
2695
+ // Preamble, bare dataset and FMI parse
2696
+ // ---------------------------------------------------------------------------
2697
+
2698
+ /**
2699
+ * Phase 1: preamble detection (incremental). Sets `stream.offset` to the
2700
+ * start of the FMI and returns false, or returns true when the input is a
2701
+ * bare dataset.
2702
+ *
2703
+ * - "DICM" at bytes 128-131 → normal Part 10, advance to offset 132
2704
+ * - First 2 bytes are group 0x0002 → PART10_NO_PREAMBLE, stay at 0
2705
+ * - Neither → bare dataset or non-DICOM input
2706
+ * (see {@link detectBareSyntax}).
2707
+ *
2708
+ * @param {ReadBufferStream} stream the raw input stream
2709
+ * @returns {Promise<boolean>} true for a bare dataset
2710
+ */
2711
+ async function detectPreamble(stream) {
2712
+ let rawDatasetFallback = false;
2713
+
2714
+ // Wait for enough bytes to check the DICM marker (requires 132 bytes:
2715
+ // 128-byte preamble + 4-byte "DICM"). ensureAvailable resolves even
2716
+ // at EOF if bytes are insufficient (OR-complete semantics), so we
2717
+ // always re-check with isAvailable(N, false) after the await.
2718
+ await stream.ensureAvailable(132);
2719
+
2720
+ if (stream.isAvailable(132, false)) {
2721
+ // We have at least 132 bytes — check for "DICM" at bytes 128-131.
2722
+ const hasDicm =
2723
+ stream.view.getUint8(128) === 0x44 && // D
2724
+ stream.view.getUint8(129) === 0x49 && // I
2725
+ stream.view.getUint8(130) === 0x43 && // C
2726
+ stream.view.getUint8(131) === 0x4d; // M
2727
+ if (hasDicm) {
2728
+ // Normal Part 10: skip preamble + DICM marker.
2729
+ stream.offset = 132;
2730
+ } else {
2731
+ // No DICM — check whether the file starts with group 0x0002.
2732
+ const firstGroup = stream.view.getUint16(0, true); // LE
2733
+ if (firstGroup === 0x0002) {
2734
+ // PART10_NO_PREAMBLE: FMI starts at byte 0.
2735
+ stream.offset = 0;
2736
+ } else {
2737
+ rawDatasetFallback = true;
2738
+ }
2739
+ }
2740
+ } else {
2741
+ // Fewer than 132 bytes available (short stream or early EOF).
2742
+ // Try to at least check the 0x0002 group in the first 2 bytes.
2743
+ await stream.ensureAvailable(4);
2744
+ if (stream.isAvailable(2, false)) {
2745
+ const firstGroup = stream.view.getUint16(0, true); // LE
2746
+ if (firstGroup === 0x0002) {
2747
+ stream.offset = 0; // PART10_NO_PREAMBLE
2748
+ } else {
2749
+ rawDatasetFallback = true;
2750
+ }
2751
+ } else {
2752
+ rawDatasetFallback = true;
2753
+ }
2754
+ }
2755
+ return rawDatasetFallback;
2756
+ }
2757
+
2758
+ /**
2759
+ * Bare (meta-less, DIMSE-style) dataset: returns the transfer syntax of the
2760
+ * body, or refuses the input (issue #93).
2761
+ *
2762
+ * The input needs an explicit opt-in: allowMissingHeader, or the tolerant
2763
+ * ignoreErrors mode. The body is Explicit Little Endian when bytes 4-5 of the
2764
+ * first element header are a valid VR code, and Implicit Little Endian
2765
+ * otherwise (the same rule as DicomMessage._detectBareSyntax). The body then
2766
+ * streams through the standard body loop from byte 0.
2767
+ *
2768
+ * Without the opt-in, the reader refuses input that is neither Part 10 nor
2769
+ * an FMI group, with the streaming reader's own error text.
2770
+ *
2771
+ * @param {ReadBufferStream} stream the raw input stream, at offset 0
2772
+ * @param {Object} options the fromPart10Stream options
2773
+ * @returns {Promise<string>} the body transfer syntax UID
2774
+ */
2775
+ async function detectBareSyntax(stream, options) {
2776
+ if (!options.allowMissingHeader && !options.ignoreErrors) {
2777
+ throw new Error(
2778
+ "fromPart10Stream: input has no DICM marker and does not start " +
2779
+ "with a File Meta Information group; pass " +
2780
+ "allowMissingHeader: true (or ignoreErrors: true) to " +
2781
+ "force-read a bare dataset"
2782
+ );
2783
+ }
2784
+ stream.offset = 0;
2785
+ await stream.ensureAvailable(8);
2786
+ if (!stream.isAvailable(8, false)) {
2787
+ return EXPLICIT_LITTLE_ENDIAN;
2788
+ }
2789
+ const vrStr =
2790
+ String.fromCharCode(stream.view.getUint8(4)) +
2791
+ String.fromCharCode(stream.view.getUint8(5));
2792
+ return VALID_VRS.has(vrStr)
2793
+ ? EXPLICIT_LITTLE_ENDIAN
2794
+ : IMPLICIT_LITTLE_ENDIAN;
2795
+ }
2796
+
2797
+ /**
2798
+ * Phase 2: incremental FMI parse, from `stream.offset` to the end of the
2799
+ * File Meta Information. Leaves `stream.offset` at the first body byte.
2800
+ *
2801
+ * FMI is always EXPLICIT_LITTLE_ENDIAN regardless of the body TS. The decoded
2802
+ * FMI elements (tag, VR, values, rawValues) are accumulated into an array so
2803
+ * that the caller can emit startDataSet *after* it knows the
2804
+ * TransferSyntaxUID from (0002,0010) — the listener must receive
2805
+ * startDataSet with the correct TS before any FMI events.
2806
+ *
2807
+ * Two forms of the TS are returned. `rawTransferSyntaxUID` is the raw
2808
+ * (un-normalised) TS read from (0002,0010): it is used for the K5 deflate
2809
+ * detection because _normalizeSyntax maps deflate → ELE, which would prevent
2810
+ * bodyStream from being created (K5 root bug). `transferSyntaxUID`
2811
+ * (normalised) is kept for listener.startDataSet and body-parsing parity with
2812
+ * the eager reader, which normalises the same way. Both default to
2813
+ * EXPLICIT_LITTLE_ENDIAN when (0002,0010) is absent.
2814
+ *
2815
+ * @param {ReadBufferStream} stream the raw input stream
2816
+ * @param {Object} policy the decode policy
2817
+ * @returns {Promise<{fmiElements: Array<{tag:string, vrStr:string, length:number, values:any[], rawValues:any[]}>, transferSyntaxUID: string, rawTransferSyntaxUID: string}>}
2818
+ */
2819
+ async function readFileMetaInformation(stream, policy) {
2820
+ const fmiElements = [];
2821
+ let transferSyntaxUID = EXPLICIT_LITTLE_ENDIAN; // default if 0002,0010 absent
2822
+ let rawTransferSyntaxUID = EXPLICIT_LITTLE_ENDIAN;
2823
+
2824
+ // We need at least 8 bytes for the smallest possible FMI header.
2825
+ await stream.ensureAvailable(8);
2826
+
2827
+ // Determine whether (0002,0000) FileMetaInformationGroupLength is present.
2828
+ // If present, we know the exact end-of-FMI offset; otherwise we stop
2829
+ // when the first non-0002 group tag appears (AsyncDicomReader.readMeta
2830
+ // §233–240 fallback).
2831
+ let metaEndOffset = null; // null → no fixed bound
2832
+
2833
+ if (
2834
+ stream.isAvailable(8, false) &&
2835
+ stream.view.getUint16(stream.offset, true) === 0x0002 &&
2836
+ stream.view.getUint16(stream.offset + 2, true) === 0x0000
2837
+ ) ;
2838
+
2839
+ // ---- FMI element loop ----
2840
+ while (true) {
2841
+ // Fixed-bound termination: used when (0002,0000) was found.
2842
+ if (metaEndOffset !== null && stream.offset >= metaEndOffset) break;
2843
+
2844
+ // Wait for enough bytes to read a minimal element header (8 bytes:
2845
+ // 4-byte tag + 2-byte VR + 2-byte length). If the stream ends
2846
+ // before we get 8 bytes (unlikely for valid FMI), we stop.
2847
+ await stream.ensureAvailable(8);
2848
+
2849
+ // EOF or insufficient data: stop FMI loop gracefully.
2850
+ if (!stream.isAvailable(4, false)) break;
2851
+
2852
+ // Peek at the next element's group tag (LE uint16).
2853
+ // For the no-group-length fallback: stop as soon as group != 0x0002.
2854
+ const peekGroup = stream.view.getUint16(stream.offset, true);
2855
+ if (peekGroup !== 0x0002) break; // body starts here
2856
+
2857
+ // Confirm we have at least a full 8-byte header before committing.
2858
+ if (!stream.isAvailable(8, false)) break;
2859
+
2860
+ // ---- Read element header (Explicit Little Endian) ----
2861
+ const elGroup = stream.readUint16(); // always 0x0002
2862
+ const elElement = stream.readUint16();
2863
+ // Build DICOM clean tag string: "GGGGEEEE" (uppercase hex, 8 chars)
2864
+ const tagStr =
2865
+ elGroup.toString(16).padStart(4, "0").toUpperCase() +
2866
+ elElement.toString(16).padStart(4, "0").toUpperCase();
2867
+
2868
+ // VR: 2 ASCII bytes
2869
+ const vrStr =
2870
+ String.fromCharCode(stream.view.getUint8(stream.offset)) +
2871
+ String.fromCharCode(stream.view.getUint8(stream.offset + 1));
2872
+ stream.offset += 2;
2873
+
2874
+ // Length: 2 bytes (standard VR) or 2 reserved + 4 bytes (extended VR)
2875
+ let valueLength;
2876
+ // Resolve VR instance to determine header framing via isLength32()
2877
+ // createByTypeString handles invalid VR strings by falling back to UN.
2878
+ const vrForHeader = ValueRepresentation.createByTypeString(vrStr);
2879
+ if (vrForHeader.isLength32()) {
2880
+ // Extended form: need 2 more bytes (reserved) + 4 bytes (length32)
2881
+ await stream.ensureAvailable(6);
2882
+ if (!stream.isAvailable(6, false)) break; // truncated
2883
+ stream.offset += 2; // skip reserved (0x0000)
2884
+ valueLength = stream.readUint32();
2885
+ } else {
2886
+ // Standard form: length is already in the next 2 bytes
2887
+ await stream.ensureAvailable(2);
2888
+ if (!stream.isAvailable(2, false)) break; // truncated
2889
+ valueLength = stream.readUint16();
2890
+ }
2891
+
2892
+ // Set metaEndOffset after reading the FileMetaInformationGroupLength
2893
+ // value (0002,0000) UL. The bound is relative to the END of this
2894
+ // element (i.e., the first byte AFTER the UL value bytes).
2895
+ const isGroupLengthTag = elGroup === 0x0002 && elElement === 0x0000;
2896
+
2897
+ // Wait for value bytes
2898
+ await stream.ensureAvailable(valueLength);
2899
+
2900
+ if (!stream.isAvailable(valueLength, false)) {
2901
+ // Stream ended mid-value: best-effort stop (truncated FMI)
2902
+ break;
2903
+ }
2904
+
2905
+ // Extract value bytes into a fresh ArrayBuffer (copy is acceptable
2906
+ // for FMI — FMI is at most a few hundred bytes).
2907
+ const valueStart = stream.offset;
2908
+ const valueAB = stream.slice(valueStart, valueStart + valueLength);
2909
+
2910
+ const { values, rawValues } = decodeFmiValue(
2911
+ valueAB,
2912
+ elGroup,
2913
+ elElement,
2914
+ vrStr,
2915
+ valueLength,
2916
+ policy
2917
+ );
2918
+
2919
+ // Capture TransferSyntaxUID for startDataSet and body-phase delegation.
2920
+ // Matches seedReadContext's normalization (core normalizeSyntax).
2921
+ if (tagStr === "00020010" && values[0]) {
2922
+ rawTransferSyntaxUID = values[0];
2923
+ transferSyntaxUID = normalizeSyntax(values[0]);
2924
+ }
2925
+
2926
+ // Set meta end offset from (0002,0000) FileMetaInformationGroupLength
2927
+ if (isGroupLengthTag && values[0] !== undefined) {
2928
+ // values[0] is the UL integer: bytes after THIS element
2929
+ metaEndOffset = valueStart + valueLength + values[0];
2930
+ }
2931
+
2932
+ fmiElements.push({
2933
+ tag: tagStr,
2934
+ vrStr,
2935
+ length: valueLength,
2936
+ values,
2937
+ rawValues
2938
+ });
2939
+
2940
+ // Advance stream past the value bytes
2941
+ stream.offset = valueStart + valueLength;
2942
+ }
2943
+
2944
+ return { fmiElements, transferSyntaxUID, rawTransferSyntaxUID };
2945
+ }
2946
+
2947
+ /**
2948
+ * Decode one FMI element value through decodeCore, over a minimal
2949
+ * Explicit Little Endian read window that holds only the value bytes.
2950
+ *
2951
+ * The `elLike` object is the minimal shape decodeCore.resolveVrInstance and
2952
+ * decodeCore.decodeElementValues require:
2953
+ * - vr — VR string (e.g. "UI", "UL", "OB")
2954
+ * - tagValue — numeric tag (group << 16) | element, for UN dictionary lookup
2955
+ * - dataOffset — byte offset of value within the window.arrayBuffer
2956
+ * - length — value byte count
2957
+ * - hadUndefinedLength — always false for FMI elements (PS3.5 §7.1)
2958
+ *
2959
+ * @param {ArrayBuffer} valueAB a fresh copy of the value bytes
2960
+ * @param {number} elGroup the tag group
2961
+ * @param {number} elElement the tag element
2962
+ * @param {string} vrStr the on-wire VR string
2963
+ * @param {number} valueLength the value byte count
2964
+ * @param {Object} policy the decode policy
2965
+ * @returns {{values: any[], rawValues: any[]}}
2966
+ */
2967
+ function decodeFmiValue(
2968
+ valueAB,
2969
+ elGroup,
2970
+ elElement,
2971
+ vrStr,
2972
+ valueLength,
2973
+ policy
2974
+ ) {
2975
+ const fakeWindow = {
2976
+ arrayBuffer: valueAB,
2977
+ baseOffset: 0,
2978
+ syntax: EXPLICIT_LITTLE_ENDIAN,
2979
+ littleEndian: true,
2980
+ implicit: false,
2981
+ decoder: null
2982
+ };
2983
+ const elLike = {
2984
+ vr: vrStr,
2985
+ tagValue: (elGroup << 16) | elElement,
2986
+ dataOffset: 0,
2987
+ length: valueLength,
2988
+ hadUndefinedLength: false
2989
+ };
2990
+
2991
+ const vrInstance = resolveVrInstance(elLike, fakeWindow);
2992
+ return decodeElementValues(fakeWindow, elLike, vrInstance, policy);
2993
+ }
2994
+
2995
+ // ---------------------------------------------------------------------------
2996
+ // FMI element emission
2997
+ // ---------------------------------------------------------------------------
2998
+
2999
+ /**
3000
+ * Emit a single FMI element's events into `listener`.
3001
+ *
3002
+ * Mirrors fromPart10's `emitValues` logic:
3003
+ * - Buffer-valued VRs (OB, OW, OD, …) → startBinary / binaryFragment / endBinary
3004
+ * - Everything else → one or more value() calls
3005
+ *
3006
+ * FMI elements are never sequences (SQ) or undefined-length elements, so
3007
+ * those branches from the full emitElement are not needed here.
3008
+ */
3009
+ function emitFmiElement(listener, el) {
3010
+ const { tag, vrStr, length, values, rawValues } = el;
3011
+
3012
+ const hasBuffer = values.some(
3013
+ v => v instanceof ArrayBuffer || ArrayBuffer.isView(v)
3014
+ );
3015
+
3016
+ listener.startElement(tag, { vr: vrStr, length });
3017
+
3018
+ if (hasBuffer) {
3019
+ listener.startBinary({ encapsulated: false });
3020
+ for (const buf of values) {
3021
+ listener.binaryFragment(buf);
3022
+ }
3023
+ listener.endBinary();
3024
+ } else {
3025
+ let index = 0;
3026
+ for (const v of values) {
3027
+ listener.value(v, { index, rawValue: rawValues[index] });
3028
+ index++;
3029
+ }
3030
+ }
3031
+
3032
+ listener.endElement();
3033
+ }
3034
+
3035
+ // ---------------------------------------------------------------------------
3036
+ // Input normalization
3037
+ // ---------------------------------------------------------------------------
3038
+
3039
+ /**
3040
+ * Normalize `input` to an `AsyncIterable<Uint8Array | ArrayBuffer>`.
3041
+ *
3042
+ * Dispatch order:
3043
+ * 1. ArrayBuffer / TypedArray → single-item async iterable
3044
+ * 2. WHATWG ReadableStream → AsyncIterable (native) or reader-loop adapter
3045
+ * 3. AsyncIterable (generator, etc.) → returned as-is
3046
+ *
3047
+ * @param {*} input
3048
+ * @returns {AsyncIterable<Uint8Array|ArrayBuffer>}
3049
+ */
3050
+ function normalizeInput(input) {
3051
+ // Case 1: flat buffer — degenerate single-chunk
3052
+ if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {
3053
+ return singleChunkIterable(input);
3054
+ }
3055
+
3056
+ // Case 2: WHATWG ReadableStream
3057
+ if (isWhatwgReadableStream(input)) {
3058
+ // Modern Node (≥ 16.14) and modern browsers expose Symbol.asyncIterator
3059
+ // on ReadableStream natively — use it directly.
3060
+ if (Symbol.asyncIterator in input) {
3061
+ return input;
3062
+ }
3063
+ // Fallback for environments where ReadableStream is defined but not
3064
+ // yet AsyncIterable (older browsers, certain polyfills).
3065
+ return readableStreamToAsyncIterable(input);
3066
+ }
3067
+
3068
+ // Case 3: AsyncIterable (async generators, Node.js streams, etc.)
3069
+ if (input != null && typeof input[Symbol.asyncIterator] === "function") {
3070
+ return input;
3071
+ }
3072
+
3073
+ throw new TypeError(
3074
+ "fromPart10Stream: `input` must be an ArrayBuffer, Uint8Array, " +
3075
+ "AsyncIterable<Uint8Array|ArrayBuffer>, or a WHATWG ReadableStream. " +
3076
+ `Got: ${Object.prototype.toString.call(input)}`
3077
+ );
3078
+ }
3079
+
3080
+ /** True if `input` is a WHATWG ReadableStream (works in browser and Node). */
3081
+ function isWhatwgReadableStream(input) {
3082
+ return (
3083
+ typeof ReadableStream !== "undefined" && input instanceof ReadableStream
3084
+ );
3085
+ }
3086
+
3087
+ /** Single-item async iterable that yields `buffer` as a Uint8Array chunk. */
3088
+ async function* singleChunkIterable(buffer) {
3089
+ yield buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
3090
+ }
3091
+
3092
+ /**
3093
+ * Adapter: wrap a WHATWG ReadableStream in an async generator for
3094
+ * environments where the stream does not implement Symbol.asyncIterator.
3095
+ * This is dependency-free and works in both browser and Node.
3096
+ */
3097
+ async function* readableStreamToAsyncIterable(stream) {
3098
+ const reader = stream.getReader();
3099
+ try {
3100
+ for (;;) {
3101
+ const { done, value } = await reader.read();
3102
+ if (done) break;
3103
+ yield value;
3104
+ }
3105
+ } finally {
3106
+ reader.releaseLock();
3107
+ }
3108
+ }
3109
+
3110
+ // ---------------------------------------------------------------------------
3111
+ // Chunk helpers
3112
+ // ---------------------------------------------------------------------------
3113
+
3114
+ /**
3115
+ * Coerce a chunk from the async iterable to an ArrayBuffer for
3116
+ * `stream.addBuffer()`. Handles Uint8Array, Buffer (Node), other typed
3117
+ * arrays, and plain ArrayBuffers.
3118
+ *
3119
+ * @param {Uint8Array|ArrayBuffer} chunk
3120
+ * @returns {ArrayBuffer}
3121
+ */
3122
+ function toArrayBuffer(chunk) {
3123
+ if (chunk instanceof ArrayBuffer) return chunk;
3124
+ if (ArrayBuffer.isView(chunk)) {
3125
+ // Typed array (Uint8Array, Buffer, etc.): slice to own ArrayBuffer.
3126
+ return chunk.buffer.slice(
3127
+ chunk.byteOffset,
3128
+ chunk.byteOffset + chunk.byteLength
3129
+ );
3130
+ }
3131
+ throw new TypeError(
3132
+ `fromPart10Stream: expected Uint8Array|ArrayBuffer chunk from iterable, ` +
3133
+ `got ${Object.prototype.toString.call(chunk)}`
3134
+ );
3135
+ }
3136
+
3137
+ /**
3138
+ * fromPart10 — whole-buffer Part 10 bytes → event stream.
3139
+ *
3140
+ * A thin wrapper: the buffer is fed to the streaming reader as a single
3141
+ * chunk. Earlier drafts of the rewrite implemented this on a vendored
3142
+ * copy of the dicom-parser tokenizer; that package is removed from 1.0,
3143
+ * so the streaming reader's tokenizer is the only one in the library and
3144
+ * this wrapper keeps the buffered entry point working unchanged.
3145
+ *
3146
+ * @param {ArrayBuffer|ArrayBufferView} buffer - complete Part 10 bytes
3147
+ * @param {EventStreamListener} listener - the event consumer
3148
+ * @param {object} [options] - forwarded to fromPart10Stream
3149
+ */
3150
+ async function fromPart10(buffer, listener, options = {}) {
3151
+ const bytes =
3152
+ buffer instanceof Uint8Array
3153
+ ? buffer
3154
+ : ArrayBuffer.isView(buffer)
3155
+ ? new Uint8Array(
3156
+ buffer.buffer,
3157
+ buffer.byteOffset,
3158
+ buffer.byteLength
3159
+ )
3160
+ : new Uint8Array(buffer);
3161
+ await fromPart10Stream(bytes, listener, options);
3162
+ }
3163
+
3164
+ export { CONTRACT_VERSION, CollectorListener, EVENT_STREAM_VOCABULARY, EventStreamListener, NaturalizedListener, createEventAsyncIterable, emitDecodedLeaf, emitEntry, emitValues, fromDataSet, fromDicomWebJson, fromNaturalized, fromPart10, fromPart10Stream, mergeFragmentsPerBotWindow };
3165
+ //# sourceMappingURL=index.mjs.map