@ubercode/dcmtk 1.0.0-rc.1 → 1.0.0-rc.3

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/dicom.js CHANGED
@@ -3,10 +3,12 @@ import { stderr, tryCatch } from 'stderr-lib';
3
3
  import { spawn, execSync } from 'child_process';
4
4
  import kill from 'tree-kill';
5
5
  import { existsSync } from 'fs';
6
- import { copyFile, unlink, stat, rm, mkdtemp } from 'fs/promises';
6
+ import { copyFile, unlink, stat, rm, mkdtemp, readFile, open } from 'fs/promises';
7
7
  import { tmpdir } from 'os';
8
8
  import { z } from 'zod';
9
9
  import { XMLParser } from 'fast-xml-parser';
10
+ import { inflateRawSync } from 'zlib';
11
+ import dicomParser2 from 'dicom-parser';
10
12
 
11
13
  var __defProp = Object.defineProperty;
12
14
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -29667,6 +29669,8 @@ var REQUIRED_BINARIES = ["dcm2json", "dcm2xml", "dcmodify", "dcmdump", "dcmrecv"
29667
29669
  var MAX_TRAVERSAL_DEPTH = 50;
29668
29670
  var MAX_CHANGESET_OPERATIONS = 1e4;
29669
29671
  var MAX_OUTPUT_BYTES = 100 * 1024 * 1024;
29672
+ var BOUNDED_READ_THRESHOLD_BYTES = 8 * 1024 * 1024;
29673
+ var BOUNDED_READ_CHUNK_BYTES = 1024 * 1024;
29670
29674
 
29671
29675
  // src/dicom/tagPath.ts
29672
29676
  var SEGMENT_PATTERN = /^\(([0-9A-Fa-f]{4}),([0-9A-Fa-f]{4})\)(?:\[(\d+|\*)\])?/;
@@ -30386,9 +30390,9 @@ var ToolExecutionError = class extends Error {
30386
30390
  this.exitCode = details.exitCode;
30387
30391
  }
30388
30392
  };
30389
- function createToolError(toolName, args, exitCode, stderr4, stdout = "") {
30393
+ function createToolError(toolName, args, exitCode, stderr5, stdout = "") {
30390
30394
  const argsStr = truncate(args.join(" "), MAX_ARGS_LENGTH);
30391
- const stderrStr = truncate(stderr4.trim(), MAX_STDERR_LENGTH);
30395
+ const stderrStr = truncate(stderr5.trim(), MAX_STDERR_LENGTH);
30392
30396
  const parts = [`${toolName} failed (exit code ${String(exitCode)})`];
30393
30397
  if (argsStr.length > 0) {
30394
30398
  parts.push(`args: ${argsStr}`);
@@ -30396,7 +30400,7 @@ function createToolError(toolName, args, exitCode, stderr4, stdout = "") {
30396
30400
  if (stderrStr.length > 0) {
30397
30401
  parts.push(`stderr: ${stderrStr}`);
30398
30402
  }
30399
- return new ToolExecutionError(parts.join(" | "), { stdout, stderr: stderr4, exitCode });
30403
+ return new ToolExecutionError(parts.join(" | "), { stdout, stderr: stderr5, exitCode });
30400
30404
  }
30401
30405
  function createValidationError(toolName, zodError) {
30402
30406
  const parts = [];
@@ -30428,7 +30432,7 @@ async function execCommand(binary, args, options) {
30428
30432
  }
30429
30433
  function wireSpawnListeners(binary, child, timeoutMs, resolve) {
30430
30434
  let stdout = "";
30431
- let stderr4 = "";
30435
+ let stderr5 = "";
30432
30436
  let settled = false;
30433
30437
  const name = binary.split("/").pop() ?? binary;
30434
30438
  const settle = (result) => {
@@ -30443,14 +30447,14 @@ function wireSpawnListeners(binary, child, timeoutMs, resolve) {
30443
30447
  }, timeoutMs);
30444
30448
  child.stdout?.on("data", (chunk) => {
30445
30449
  stdout += String(chunk);
30446
- if (stdout.length + stderr4.length > MAX_OUTPUT_BYTES) {
30450
+ if (stdout.length + stderr5.length > MAX_OUTPUT_BYTES) {
30447
30451
  if (child.pid !== void 0 && child.pid !== null) killTree(child.pid);
30448
30452
  settle(err(new Error(`${name} output exceeded ${MAX_OUTPUT_BYTES} bytes`)));
30449
30453
  }
30450
30454
  });
30451
30455
  child.stderr?.on("data", (chunk) => {
30452
- stderr4 += String(chunk);
30453
- if (stdout.length + stderr4.length > MAX_OUTPUT_BYTES) {
30456
+ stderr5 += String(chunk);
30457
+ if (stdout.length + stderr5.length > MAX_OUTPUT_BYTES) {
30454
30458
  if (child.pid !== void 0 && child.pid !== null) killTree(child.pid);
30455
30459
  settle(err(new Error(`${name} output exceeded ${MAX_OUTPUT_BYTES} bytes`)));
30456
30460
  }
@@ -30460,7 +30464,7 @@ function wireSpawnListeners(binary, child, timeoutMs, resolve) {
30460
30464
  settle(err(new Error(`${name} error: ${error.message}`)));
30461
30465
  });
30462
30466
  child.on("close", (code) => {
30463
- settle(ok({ stdout, stderr: stderr4, exitCode: code ?? 1 }));
30467
+ settle(ok({ stdout, stderr: stderr5, exitCode: code ?? 1 }));
30464
30468
  });
30465
30469
  }
30466
30470
  async function spawnCommand(binary, args, options) {
@@ -30682,8 +30686,8 @@ function unwrapValue(v) {
30682
30686
  const obj = v;
30683
30687
  if ("#text" in obj) return obj["#text"];
30684
30688
  const keys = Object.keys(obj);
30685
- if (keys.length === 1 && keys[0] !== void 0 && keys[0].startsWith("@_")) {
30686
- return obj[keys[0]];
30689
+ if (keys.every((k) => k.startsWith("@_"))) {
30690
+ return "";
30687
30691
  }
30688
30692
  return v;
30689
30693
  }
@@ -30889,16 +30893,948 @@ async function dcm2json(inputPath, options) {
30889
30893
  const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
30890
30894
  const signal = options?.signal;
30891
30895
  const startTime = Date.now();
30892
- const remaining = () => Math.max(1e3, timeoutMs - (Date.now() - startTime));
30896
+ const remaining = () => Math.max(0, timeoutMs - (Date.now() - startTime));
30893
30897
  const verbosity = options?.verbosity;
30894
30898
  if (options?.directOnly === true) {
30895
- return tryDirectPath(inputPath, remaining(), signal, verbosity);
30899
+ return tryDirectPath(inputPath, timeoutMs, signal, verbosity);
30896
30900
  }
30897
- const xmlResult = await tryXmlPath(inputPath, remaining(), signal, buildXmlOpts(options));
30901
+ const xmlResult = await tryXmlPath(inputPath, timeoutMs, signal, buildXmlOpts(options));
30898
30902
  if (xmlResult.ok) {
30899
30903
  return xmlResult;
30900
30904
  }
30901
- return tryDirectPath(inputPath, remaining(), signal, verbosity);
30905
+ return fallbackToDirect(inputPath, xmlResult.error, { budget: remaining(), timeoutMs, signal, verbosity });
30906
+ }
30907
+ async function fallbackToDirect(inputPath, xmlError, context) {
30908
+ if (context.budget === 0) {
30909
+ return err(
30910
+ new Error(
30911
+ `dcm2json: XML path failed and timeout budget (${String(context.timeoutMs)}ms) is exhausted (skipping direct fallback) | xml: ${xmlError.message}`
30912
+ )
30913
+ );
30914
+ }
30915
+ const directResult = await tryDirectPath(inputPath, context.budget, context.signal, context.verbosity);
30916
+ if (directResult.ok) {
30917
+ return directResult;
30918
+ }
30919
+ return err(new Error(`dcm2json: both paths failed | xml: ${xmlError.message} | direct: ${directResult.error.message}`));
30920
+ }
30921
+
30922
+ // src/tools/_charset.ts
30923
+ var LATIN1 = { kind: "latin1" };
30924
+ function label(name) {
30925
+ return { kind: "label", label: name };
30926
+ }
30927
+ var CHARSET_DECODERS = {
30928
+ "ISO_IR 6": LATIN1,
30929
+ "ISO_IR 100": LATIN1,
30930
+ "ISO_IR 101": label("iso-8859-2"),
30931
+ "ISO_IR 109": label("iso-8859-3"),
30932
+ "ISO_IR 110": label("iso-8859-4"),
30933
+ "ISO_IR 144": label("iso-8859-5"),
30934
+ "ISO_IR 127": label("iso-8859-6"),
30935
+ "ISO_IR 126": label("iso-8859-7"),
30936
+ "ISO_IR 138": label("iso-8859-8"),
30937
+ "ISO_IR 148": label("iso-8859-9"),
30938
+ "ISO_IR 203": label("iso-8859-15"),
30939
+ "ISO_IR 13": label("shift_jis"),
30940
+ "ISO_IR 166": label("windows-874"),
30941
+ "ISO_IR 192": label("utf-8"),
30942
+ GB18030: label("gb18030"),
30943
+ GBK: label("gbk")
30944
+ };
30945
+ var ISO2022_INITIAL = {
30946
+ "ISO 2022 IR 6": LATIN1,
30947
+ "ISO 2022 IR 13": label("shift_jis"),
30948
+ "ISO 2022 IR 87": LATIN1,
30949
+ "ISO 2022 IR 159": LATIN1,
30950
+ "ISO 2022 IR 149": label("euc-kr"),
30951
+ "ISO 2022 IR 58": label("gbk"),
30952
+ "ISO 2022 IR 100": LATIN1,
30953
+ "ISO 2022 IR 101": label("iso-8859-2"),
30954
+ "ISO 2022 IR 109": label("iso-8859-3"),
30955
+ "ISO 2022 IR 110": label("iso-8859-4"),
30956
+ "ISO 2022 IR 144": label("iso-8859-5"),
30957
+ "ISO 2022 IR 127": label("iso-8859-6"),
30958
+ "ISO 2022 IR 126": label("iso-8859-7"),
30959
+ "ISO 2022 IR 138": label("iso-8859-8"),
30960
+ "ISO 2022 IR 148": label("iso-8859-9"),
30961
+ "ISO 2022 IR 166": label("windows-874"),
30962
+ "ISO 2022 IR 203": label("iso-8859-15")
30963
+ };
30964
+ var ESCAPE_DECODERS = {
30965
+ "(B": LATIN1,
30966
+ // G0 = ASCII
30967
+ "(J": LATIN1,
30968
+ // G0 = JIS X 0201 romaji
30969
+ ")I": { kind: "katakana" },
30970
+ // G1 = JIS X 0201 katakana
30971
+ "$@": { kind: "iso2022jp", escape: [27, 36, 64] },
30972
+ // G0 = JIS X 0208-1978
30973
+ $B: { kind: "iso2022jp", escape: [27, 36, 66] },
30974
+ // G0 = JIS X 0208
30975
+ "$(D": { kind: "iso2022jp", escape: [27, 36, 40, 68] },
30976
+ // G0 = JIS X 0212
30977
+ "$)C": label("euc-kr"),
30978
+ // G1 = KS X 1001
30979
+ "$)A": label("gbk"),
30980
+ // G1 = GB 2312
30981
+ "-A": LATIN1,
30982
+ // G1 = ISO-8859-1
30983
+ "-B": label("iso-8859-2"),
30984
+ "-C": label("iso-8859-3"),
30985
+ "-D": label("iso-8859-4"),
30986
+ "-F": label("iso-8859-7"),
30987
+ "-G": label("iso-8859-6"),
30988
+ "-H": label("iso-8859-8"),
30989
+ "-L": label("iso-8859-5"),
30990
+ "-M": label("iso-8859-9"),
30991
+ "-T": label("windows-874"),
30992
+ "-b": label("iso-8859-15")
30993
+ };
30994
+ var CHARSET_ALIASES = {
30995
+ ascii: "ISO_IR 6",
30996
+ "latin-1": "ISO_IR 100",
30997
+ latin1: "ISO_IR 100",
30998
+ "iso-8859-1": "ISO_IR 100",
30999
+ "latin-2": "ISO_IR 101",
31000
+ "latin-3": "ISO_IR 109",
31001
+ "latin-4": "ISO_IR 110",
31002
+ "latin-5": "ISO_IR 148",
31003
+ "latin-9": "ISO_IR 203",
31004
+ cyrillic: "ISO_IR 144",
31005
+ arabic: "ISO_IR 127",
31006
+ greek: "ISO_IR 126",
31007
+ hebrew: "ISO_IR 138",
31008
+ thai: "ISO_IR 166",
31009
+ "shift-jis": "ISO_IR 13",
31010
+ shift_jis: "ISO_IR 13",
31011
+ "utf-8": "ISO_IR 192",
31012
+ utf8: "ISO_IR 192",
31013
+ gb18030: "GB18030",
31014
+ gbk: "GBK"
31015
+ };
31016
+ var SINGLE_BYTE_LABELS = /* @__PURE__ */ new Set([
31017
+ "iso-8859-2",
31018
+ "iso-8859-3",
31019
+ "iso-8859-4",
31020
+ "iso-8859-5",
31021
+ "iso-8859-6",
31022
+ "iso-8859-7",
31023
+ "iso-8859-8",
31024
+ "iso-8859-9",
31025
+ "iso-8859-15",
31026
+ "windows-874"
31027
+ ]);
31028
+ function isSingleByteDecoder(decoder) {
31029
+ return decoder.kind === "latin1" || decoder.kind === "label" && SINGLE_BYTE_LABELS.has(decoder.label);
31030
+ }
31031
+ var decoderCache = /* @__PURE__ */ new Map();
31032
+ function getTextDecoder(labelName) {
31033
+ if (decoderCache.has(labelName)) {
31034
+ return decoderCache.get(labelName);
31035
+ }
31036
+ let decoder;
31037
+ try {
31038
+ decoder = new TextDecoder(labelName);
31039
+ } catch {
31040
+ decoder = void 0;
31041
+ }
31042
+ decoderCache.set(labelName, decoder);
31043
+ return decoder;
31044
+ }
31045
+ function decodeLatin1(bytes) {
31046
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
31047
+ }
31048
+ function decodeSegment(bytes, decoder) {
31049
+ if (bytes.length === 0) return "";
31050
+ switch (decoder.kind) {
31051
+ case "latin1":
31052
+ return decodeLatin1(bytes);
31053
+ case "label": {
31054
+ const td = getTextDecoder(decoder.label);
31055
+ if (td === void 0) return decodeLatin1(bytes);
31056
+ return td.decode(bytes);
31057
+ }
31058
+ case "iso2022jp": {
31059
+ const td = getTextDecoder("iso-2022-jp");
31060
+ if (td === void 0) return decodeLatin1(bytes);
31061
+ const wrapped = new Uint8Array(decoder.escape.length + bytes.length);
31062
+ wrapped.set(decoder.escape, 0);
31063
+ wrapped.set(bytes, decoder.escape.length);
31064
+ return td.decode(wrapped);
31065
+ }
31066
+ case "katakana": {
31067
+ const td = getTextDecoder("shift_jis");
31068
+ if (td === void 0) return decodeLatin1(bytes);
31069
+ return td.decode(bytes);
31070
+ }
31071
+ }
31072
+ }
31073
+ function readEscape(bytes, start) {
31074
+ let i = start + 1;
31075
+ while (i < bytes.length && bytes[i] >= 32 && bytes[i] <= 47) {
31076
+ i++;
31077
+ }
31078
+ if (i < bytes.length && bytes[i] >= 48 && bytes[i] <= 126) {
31079
+ i++;
31080
+ }
31081
+ const seq = bytes.subarray(start + 1, i);
31082
+ return { key: decodeLatin1(seq), length: i - start };
31083
+ }
31084
+ function decodeIso2022(bytes, initial) {
31085
+ let out = "";
31086
+ let current = initial;
31087
+ let segStart = 0;
31088
+ let i = 0;
31089
+ while (i < bytes.length) {
31090
+ if (bytes[i] !== 27) {
31091
+ i++;
31092
+ continue;
31093
+ }
31094
+ out += decodeSegment(bytes.subarray(segStart, i), current);
31095
+ const esc = readEscape(bytes, i);
31096
+ current = ESCAPE_DECODERS[esc.key] ?? current;
31097
+ i += esc.length;
31098
+ segStart = i;
31099
+ }
31100
+ out += decodeSegment(bytes.subarray(segStart), current);
31101
+ return out;
31102
+ }
31103
+ var DEFAULT_CONTEXT = { terms: ["ISO_IR 6"], iso2022: false, initial: LATIN1, singleByte: true };
31104
+ function normalizeCharsetName(input) {
31105
+ const trimmed = input.trim();
31106
+ if (CHARSET_DECODERS[trimmed] !== void 0 || ISO2022_INITIAL[trimmed] !== void 0) {
31107
+ return trimmed;
31108
+ }
31109
+ return CHARSET_ALIASES[trimmed.toLowerCase()];
31110
+ }
31111
+ function buildContext(terms) {
31112
+ const iso2022 = terms.length > 1 || terms.some((t) => t.startsWith("ISO 2022"));
31113
+ const first = terms[0] ?? "ISO_IR 6";
31114
+ const initial = iso2022 ? ISO2022_INITIAL[first] : CHARSET_DECODERS[first];
31115
+ if (initial === void 0) return void 0;
31116
+ return { terms, iso2022, initial, singleByte: !iso2022 && isSingleByteDecoder(initial) };
31117
+ }
31118
+ function parseSpecificCharacterSet(raw) {
31119
+ const values = raw.split("\\").map((v) => v.trim());
31120
+ return values.map((v, idx) => v === "" && idx === 0 ? "ISO 2022 IR 6" : v).filter((v) => v !== "");
31121
+ }
31122
+ function contextFromTerms(terms, fallback, source) {
31123
+ const context = buildContext(terms);
31124
+ if (context !== void 0) {
31125
+ return ok(context);
31126
+ }
31127
+ if (fallback !== void 0) {
31128
+ const fallbackTerm = normalizeCharsetName(fallback);
31129
+ const fallbackContext = fallbackTerm !== void 0 ? buildContext([fallbackTerm]) : void 0;
31130
+ if (fallbackContext !== void 0) {
31131
+ return ok(fallbackContext);
31132
+ }
31133
+ return err(new Error(`Unsupported charset fallback '${fallback}' (while handling unsupported ${source})`));
31134
+ }
31135
+ return err(new Error(`Unsupported character set: ${source} \u2014 provide charsetFallback (e.g. 'latin-1') to decode best-effort`));
31136
+ }
31137
+ function resolveCharsetContext(specificCharacterSet, charsetAssume, charsetFallback) {
31138
+ if (specificCharacterSet === void 0 || specificCharacterSet.trim() === "") {
31139
+ if (charsetAssume === void 0) {
31140
+ return ok(DEFAULT_CONTEXT);
31141
+ }
31142
+ const term = normalizeCharsetName(charsetAssume);
31143
+ if (term === void 0) {
31144
+ return contextFromTerms([charsetAssume], charsetFallback, `charsetAssume '${charsetAssume}'`);
31145
+ }
31146
+ return contextFromTerms([term], charsetFallback, `charsetAssume '${charsetAssume}'`);
31147
+ }
31148
+ const terms = parseSpecificCharacterSet(specificCharacterSet);
31149
+ return contextFromTerms(terms, charsetFallback, `'${specificCharacterSet}' (0008,0005)`);
31150
+ }
31151
+ function decodeDicomText(bytes, context) {
31152
+ if (context.iso2022) {
31153
+ return decodeIso2022(bytes, context.initial);
31154
+ }
31155
+ return decodeSegment(bytes, context.initial);
31156
+ }
31157
+ var strictUtf8;
31158
+ function isProbableUtf8Mislabel(bytes) {
31159
+ let hasHighByte = false;
31160
+ for (const byte of bytes) {
31161
+ if (byte >= 128) {
31162
+ hasHighByte = true;
31163
+ break;
31164
+ }
31165
+ }
31166
+ if (!hasHighByte) return false;
31167
+ strictUtf8 ?? (strictUtf8 = new TextDecoder("utf-8", { fatal: true }));
31168
+ try {
31169
+ strictUtf8.decode(bytes);
31170
+ return true;
31171
+ } catch {
31172
+ return false;
31173
+ }
31174
+ }
31175
+ var UTF8_DECODER = label("utf-8");
31176
+ function decodeUtf8(bytes) {
31177
+ return decodeSegment(bytes, UTF8_DECODER);
31178
+ }
31179
+
31180
+ // src/tools/_p10ToJson.ts
31181
+ var BINARY_VRS = /* @__PURE__ */ new Set(["OB", "OW", "OD", "OF", "OL", "OV", "UN"]);
31182
+ var CHARSET_VRS = /* @__PURE__ */ new Set(["SH", "LO", "ST", "LT", "UC", "UT", "PN"]);
31183
+ var NO_SPLIT_VRS = /* @__PURE__ */ new Set(["ST", "LT", "UT", "UR"]);
31184
+ var NUMERIC_VR_SIZE = { US: 2, SS: 2, UL: 4, SL: 4, FL: 4, FD: 8, SV: 8, UV: 8 };
31185
+ var MAX_DATASETS = 1e5;
31186
+ function toJsonTag(tag) {
31187
+ return tag.slice(1).toUpperCase();
31188
+ }
31189
+ function isEncodingArtifact(tag) {
31190
+ return tag.endsWith("0000") && tag.length === 9 || tag.startsWith("xfffe");
31191
+ }
31192
+ function resolveVr(element) {
31193
+ const vr = element.vr;
31194
+ if (vr !== void 0 && KNOWN_VR_CODES.has(vr)) {
31195
+ return vr;
31196
+ }
31197
+ return "UN";
31198
+ }
31199
+ function valueBytes(element, byteArray) {
31200
+ return byteArray.subarray(element.dataOffset, element.dataOffset + element.length);
31201
+ }
31202
+ function trimPadding(value) {
31203
+ let end = value.length;
31204
+ while (end > 0) {
31205
+ const ch = value.charCodeAt(end - 1);
31206
+ if (ch !== 32 && ch !== 0) break;
31207
+ end--;
31208
+ }
31209
+ return value.slice(0, end);
31210
+ }
31211
+ function readNumericAt(view, offset, vr, littleEndian) {
31212
+ switch (vr) {
31213
+ case "US":
31214
+ return view.getUint16(offset, littleEndian);
31215
+ case "SS":
31216
+ return view.getInt16(offset, littleEndian);
31217
+ case "UL":
31218
+ return view.getUint32(offset, littleEndian);
31219
+ case "SL":
31220
+ return view.getInt32(offset, littleEndian);
31221
+ case "FL":
31222
+ return view.getFloat32(offset, littleEndian);
31223
+ case "FD":
31224
+ return view.getFloat64(offset, littleEndian);
31225
+ case "SV":
31226
+ return Number(view.getBigInt64(offset, littleEndian));
31227
+ /* v8 ignore next 2 -- 'UV' is the only remaining caller-provided VR */
31228
+ default:
31229
+ return Number(view.getBigUint64(offset, littleEndian));
31230
+ }
31231
+ }
31232
+ function convertNumeric(element, byteArray, vr, littleEndian) {
31233
+ const size = NUMERIC_VR_SIZE[vr];
31234
+ const count = Math.floor(element.length / size);
31235
+ if (count === 0) {
31236
+ return { vr };
31237
+ }
31238
+ const view = new DataView(byteArray.buffer, byteArray.byteOffset + element.dataOffset, element.length);
31239
+ const values = [];
31240
+ for (let i = 0; i < count; i++) {
31241
+ values.push(readNumericAt(view, i * size, vr, littleEndian));
31242
+ }
31243
+ return { vr, Value: values };
31244
+ }
31245
+ function convertAttributeTag(element, byteArray, littleEndian) {
31246
+ const count = Math.floor(element.length / 4);
31247
+ if (count === 0) {
31248
+ return { vr: "AT" };
31249
+ }
31250
+ const view = new DataView(byteArray.buffer, byteArray.byteOffset + element.dataOffset, element.length);
31251
+ const values = [];
31252
+ for (let i = 0; i < count; i++) {
31253
+ const group = view.getUint16(i * 4, littleEndian);
31254
+ const elem = view.getUint16(i * 4 + 2, littleEndian);
31255
+ values.push(group.toString(16).padStart(4, "0").toUpperCase() + elem.toString(16).padStart(4, "0").toUpperCase());
31256
+ }
31257
+ return { vr: "AT", Value: values };
31258
+ }
31259
+ function personNameToJson(value) {
31260
+ const groups = trimPadding(value).split("=");
31261
+ const result = {};
31262
+ const names = ["Alphabetic", "Ideographic", "Phonetic"];
31263
+ for (let i = 0; i < names.length; i++) {
31264
+ const group = (groups[i] ?? "").replace(/\^+$/u, "");
31265
+ const name = names[i];
31266
+ if (group !== "" && name !== void 0) {
31267
+ result[name] = group;
31268
+ }
31269
+ }
31270
+ return result;
31271
+ }
31272
+ function decodeTextChecked(bytes, tag, settings) {
31273
+ const { charset, mislabel } = settings;
31274
+ if (charset.singleByte && isProbableUtf8Mislabel(bytes)) {
31275
+ if (!mislabel.seen.has(tag)) {
31276
+ mislabel.seen.add(tag);
31277
+ const action = mislabel.promote ? "decoded as UTF-8" : `decoded as '${charset.terms.join("\\")}'`;
31278
+ mislabel.warnings.push(`possible UTF-8 mislabel: ${tag} (${action})`);
31279
+ }
31280
+ if (mislabel.promote) {
31281
+ return decodeUtf8(bytes);
31282
+ }
31283
+ }
31284
+ return decodeDicomText(bytes, charset);
31285
+ }
31286
+ function convertPersonName2(element, byteArray, settings) {
31287
+ const decoded = decodeTextChecked(valueBytes(element, byteArray), toJsonTag(element.tag), settings);
31288
+ const values = decoded.split("\\").map(personNameToJson);
31289
+ return { vr: "PN", Value: values };
31290
+ }
31291
+ function convertString(element, byteArray, vr, settings) {
31292
+ const bytes = valueBytes(element, byteArray);
31293
+ const decoded = CHARSET_VRS.has(vr) ? decodeTextChecked(bytes, toJsonTag(element.tag), settings) : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
31294
+ const rawValues = NO_SPLIT_VRS.has(vr) ? [decoded] : decoded.split("\\");
31295
+ const values = rawValues.map((v) => {
31296
+ const trimmed = trimPadding(v);
31297
+ return vr === "DS" || vr === "IS" ? coerceNumeric(trimmed.trim()) : trimmed;
31298
+ });
31299
+ if (values.length === 1 && values[0] === "") {
31300
+ return { vr };
31301
+ }
31302
+ return { vr, Value: values };
31303
+ }
31304
+ function convertLeaf(element, byteArray, vr, settings) {
31305
+ if (element.fragments !== void 0) {
31306
+ return { vr: "OB" };
31307
+ }
31308
+ if (BINARY_VRS.has(vr)) {
31309
+ return { vr };
31310
+ }
31311
+ if (element.length === 0) {
31312
+ return { vr };
31313
+ }
31314
+ if (NUMERIC_VR_SIZE[vr] !== void 0) {
31315
+ return convertNumeric(element, byteArray, vr, settings.littleEndian);
31316
+ }
31317
+ if (vr === "AT") {
31318
+ return convertAttributeTag(element, byteArray, settings.littleEndian);
31319
+ }
31320
+ if (vr === "PN") {
31321
+ return convertPersonName2(element, byteArray, settings);
31322
+ }
31323
+ return convertString(element, byteArray, vr, settings);
31324
+ }
31325
+ function datasetCharset(src, parent, options) {
31326
+ const raw = src.string("x00080005");
31327
+ if (raw === void 0) {
31328
+ return ok(parent);
31329
+ }
31330
+ return resolveCharsetContext(raw, void 0, options?.charsetFallback);
31331
+ }
31332
+ function convertSequence2(element, stack, charset) {
31333
+ const items = element.items ?? [];
31334
+ const values = [];
31335
+ for (const item of items) {
31336
+ const model = {};
31337
+ values.push(model);
31338
+ if (item.dataSet !== void 0) {
31339
+ stack.push({ src: item.dataSet, out: model, parentCharset: charset });
31340
+ }
31341
+ }
31342
+ if (values.length === 0) {
31343
+ return { vr: "SQ" };
31344
+ }
31345
+ return { vr: "SQ", Value: values };
31346
+ }
31347
+ function isSequence(element, vr) {
31348
+ if (element.fragments !== void 0) {
31349
+ return false;
31350
+ }
31351
+ return vr === "SQ" || element.vr === void 0 && element.items !== void 0;
31352
+ }
31353
+ function convertDataset(unit, stack, state) {
31354
+ const charsetResult = datasetCharset(unit.src, unit.parentCharset, state.options);
31355
+ if (!charsetResult.ok) {
31356
+ return err(charsetResult.error);
31357
+ }
31358
+ const charset = charsetResult.value;
31359
+ const keys = Object.keys(unit.src.elements).sort();
31360
+ for (const key of keys) {
31361
+ const element = unit.src.elements[key];
31362
+ if (element === void 0) continue;
31363
+ if (isEncodingArtifact(element.tag)) continue;
31364
+ const tag = toJsonTag(element.tag);
31365
+ const vr = resolveVr(element);
31366
+ if (isSequence(element, vr)) {
31367
+ unit.out[tag] = convertSequence2(element, stack, charset);
31368
+ } else {
31369
+ unit.out[tag] = convertLeaf(element, unit.src.byteArray, vr, { charset, littleEndian: state.littleEndian, mislabel: state.mislabel });
31370
+ }
31371
+ }
31372
+ return ok(void 0);
31373
+ }
31374
+ function inflateDeflated(byteArray, position) {
31375
+ const inflated = inflateRawSync(byteArray.subarray(position));
31376
+ const combined = new Uint8Array(position + inflated.byteLength);
31377
+ combined.set(byteArray.subarray(0, position), 0);
31378
+ combined.set(inflated, position);
31379
+ return combined;
31380
+ }
31381
+ function implicitVrLookup(tag) {
31382
+ return lookupTag(tag.slice(1))?.vr;
31383
+ }
31384
+ function parseDicomBuffer(buffer, options) {
31385
+ let dataSet;
31386
+ try {
31387
+ dataSet = dicomParser2.parseDicom(buffer, { vrCallback: implicitVrLookup, inflater: inflateDeflated });
31388
+ } catch (error) {
31389
+ return err(new Error(`Failed to parse DICOM data: ${stderr(error).message}`));
31390
+ }
31391
+ const littleEndian = dataSet.string("x00020010") !== "1.2.840.10008.1.2.2";
31392
+ const rootCharset = resolveCharsetContext(void 0, options?.charsetAssume, options?.charsetFallback);
31393
+ if (!rootCharset.ok) {
31394
+ return err(rootCharset.error);
31395
+ }
31396
+ const data = {};
31397
+ const stack = [{ src: dataSet, out: data, parentCharset: rootCharset.value }];
31398
+ const mislabel = { promote: options?.utf8MislabelPromote === true, warnings: [], seen: /* @__PURE__ */ new Set() };
31399
+ const state = { littleEndian, options, mislabel };
31400
+ let processed = 0;
31401
+ while (stack.length > 0) {
31402
+ processed++;
31403
+ if (processed > MAX_DATASETS) {
31404
+ return err(new Error(`Failed to parse DICOM data: more than ${String(MAX_DATASETS)} nested datasets`));
31405
+ }
31406
+ const unit = stack.pop();
31407
+ if (unit === void 0) break;
31408
+ const converted = convertDataset(unit, stack, state);
31409
+ if (!converted.ok) {
31410
+ return err(converted.error);
31411
+ }
31412
+ }
31413
+ return ok({ data, warnings: [...dataSet.warnings, ...mislabel.warnings] });
31414
+ }
31415
+ var TS_IMPLICIT_LE = "1.2.840.10008.1.2";
31416
+ var TS_EXPLICIT_BE = "1.2.840.10008.1.2.2";
31417
+ var TS_DEFLATED_LE = "1.2.840.10008.1.2.1.99";
31418
+ var BULK_VRS = /* @__PURE__ */ new Set(["OB", "OW", "OD", "OF", "OL", "OV", "UN"]);
31419
+ var LONG_FORM_VRS = /* @__PURE__ */ new Set(["OB", "OW", "OF", "OD", "OL", "OV", "SQ", "UC", "UR", "UT", "UN", "SV", "UV"]);
31420
+ var UNDEFINED_LENGTH = 4294967295;
31421
+ var MAX_HEADER_BYTES = 12;
31422
+ var MAX_ITERATIONS = 1e4;
31423
+ var MAX_FRAGMENT_HOPS = 1e5;
31424
+ var MAX_READ_CALLS = 1e4;
31425
+ async function readRange(handle, position, length) {
31426
+ const buffer = Buffer.alloc(length);
31427
+ let total = 0;
31428
+ for (let i = 0; i < MAX_READ_CALLS && total < length; i++) {
31429
+ const { bytesRead } = await handle.read(buffer, total, length - total, position + total);
31430
+ if (bytesRead === 0) {
31431
+ return err(new Error(`unexpected EOF at offset ${String(position + total)}`));
31432
+ }
31433
+ total += bytesRead;
31434
+ }
31435
+ if (total < length) {
31436
+ return err(new Error(`short read at offset ${String(position)}`));
31437
+ }
31438
+ return ok(buffer);
31439
+ }
31440
+ function checkAbort(state) {
31441
+ if (state.signal?.aborted === true) {
31442
+ return new Error("aborted");
31443
+ }
31444
+ if (Date.now() > state.deadline) {
31445
+ return new Error(`timed out after ${String(state.timeoutMs)}ms`);
31446
+ }
31447
+ return void 0;
31448
+ }
31449
+ var readPart10Header = dicomParser2.readPart10Header;
31450
+ function probeMeta(head) {
31451
+ let meta;
31452
+ try {
31453
+ meta = readPart10Header(head);
31454
+ } catch {
31455
+ return void 0;
31456
+ }
31457
+ const tsElement = meta.elements["x00020010"];
31458
+ if (meta.position === void 0 || tsElement === void 0) {
31459
+ return void 0;
31460
+ }
31461
+ const transferSyntax = head.subarray(tsElement.dataOffset, tsElement.dataOffset + tsElement.length).toString("latin1").replace(/[\0 ]+$/u, "");
31462
+ return { metaEnd: meta.position, transferSyntax };
31463
+ }
31464
+ function hasPartialDataSet(e) {
31465
+ return typeof e === "object" && e !== null && "dataSet" in e;
31466
+ }
31467
+ function probeParse(assembled) {
31468
+ try {
31469
+ return { dataSet: dicomParser2.parseDicom(assembled, { vrCallback: implicitVrLookup }), threw: false };
31470
+ } catch (e) {
31471
+ return { dataSet: hasPartialDataSet(e) ? e.dataSet : void 0, threw: true };
31472
+ }
31473
+ }
31474
+ function maxExtentElement(dataSet) {
31475
+ let best;
31476
+ let bestEnd = -1;
31477
+ for (const key of Object.keys(dataSet.elements)) {
31478
+ const element = dataSet.elements[key];
31479
+ if (element === void 0) continue;
31480
+ const end = element.dataOffset + element.length;
31481
+ if (end > bestEnd) {
31482
+ bestEnd = end;
31483
+ best = element;
31484
+ }
31485
+ }
31486
+ return best;
31487
+ }
31488
+ function formatTag(group, elementNum) {
31489
+ return group.toString(16).padStart(4, "0") + elementNum.toString(16).padStart(4, "0");
31490
+ }
31491
+ function parseElementHeader(assembled, position, state) {
31492
+ if (position + MAX_HEADER_BYTES > assembled.length) {
31493
+ return void 0;
31494
+ }
31495
+ if (!state.explicitVr) {
31496
+ const tag2 = formatTag(assembled.readUInt16LE(position), assembled.readUInt16LE(position + 2));
31497
+ const vr2 = implicitVrLookup(`x${tag2}`) ?? "UN";
31498
+ return { tag: tag2, vr: vr2, length: assembled.readUInt32LE(position + 4), headerLen: 8, lengthOffset: 4 };
31499
+ }
31500
+ const tag = state.bigEndian ? formatTag(assembled.readUInt16BE(position), assembled.readUInt16BE(position + 2)) : formatTag(assembled.readUInt16LE(position), assembled.readUInt16LE(position + 2));
31501
+ const vr = assembled.subarray(position + 4, position + 6).toString("latin1");
31502
+ if (!/^[A-Z]{2}$/u.test(vr)) {
31503
+ return void 0;
31504
+ }
31505
+ if (LONG_FORM_VRS.has(vr)) {
31506
+ const length2 = state.bigEndian ? assembled.readUInt32BE(position + 8) : assembled.readUInt32LE(position + 8);
31507
+ return { tag, vr, length: length2, headerLen: 12, lengthOffset: 8 };
31508
+ }
31509
+ const length = state.bigEndian ? assembled.readUInt16BE(position + 6) : assembled.readUInt16LE(position + 6);
31510
+ return { tag, vr, length, headerLen: 8, lengthOffset: 6 };
31511
+ }
31512
+ function decideAfterThrow(probe, state) {
31513
+ if (state.filePos >= state.fileSize) {
31514
+ return { kind: "fullRead" };
31515
+ }
31516
+ if (probe.dataSet === void 0) {
31517
+ return { kind: "grow" };
31518
+ }
31519
+ const last = maxExtentElement(probe.dataSet);
31520
+ const maxEnd = last === void 0 ? state.metaEnd : last.dataOffset + last.length;
31521
+ if (last !== void 0 && maxEnd > state.assembled.length) {
31522
+ return decideOversized(last, last.hadUndefinedLength === true, state);
31523
+ }
31524
+ const header = parseElementHeader(state.assembled, maxEnd, state);
31525
+ if (header === void 0) {
31526
+ return { kind: "grow" };
31527
+ }
31528
+ return decideWithHeader(state, maxEnd, header, header.length === UNDEFINED_LENGTH);
31529
+ }
31530
+ function decideWithHeader(state, position, header, undefinedLength) {
31531
+ if (undefinedLength) {
31532
+ if (header.tag === "7fe00010" && (header.vr === "OB" || header.vr === "OW") && state.explicitVr && !state.bigEndian) {
31533
+ rewriteHeader(state.assembled, position, header, true);
31534
+ return { kind: "skipEncapsulated", headerStart: position, headerEnd: position + header.headerLen };
31535
+ }
31536
+ return { kind: "grow" };
31537
+ }
31538
+ if (BULK_VRS.has(header.vr)) {
31539
+ return rewriteAndSkip(state, position, header);
31540
+ }
31541
+ return { kind: "grow" };
31542
+ }
31543
+ function rewriteHeader(assembled, position, header, forceObVr) {
31544
+ if (header.lengthOffset === 6) {
31545
+ assembled.writeUInt16LE(0, position + header.lengthOffset);
31546
+ } else {
31547
+ assembled.writeUInt32LE(0, position + header.lengthOffset);
31548
+ }
31549
+ if (forceObVr) {
31550
+ assembled.write("OB", position + 4, "latin1");
31551
+ }
31552
+ }
31553
+ function rewriteAndSkip(state, position, header) {
31554
+ rewriteHeader(state.assembled, position, header, false);
31555
+ return { kind: "skipDefined", headerEnd: position + header.headerLen, valueLength: header.length };
31556
+ }
31557
+ function decideAfterSuccess(probe, state) {
31558
+ if (probe.dataSet === void 0) return { kind: "fullRead" };
31559
+ const last = maxExtentElement(probe.dataSet);
31560
+ const maxEnd = last === void 0 ? state.metaEnd : last.dataOffset + last.length;
31561
+ const undefinedAtEnd = last?.hadUndefinedLength === true && maxEnd >= state.assembled.length;
31562
+ if (state.filePos >= state.fileSize) {
31563
+ return { kind: "done" };
31564
+ }
31565
+ if (maxEnd <= state.assembled.length && !undefinedAtEnd) {
31566
+ return { kind: "grow" };
31567
+ }
31568
+ if (last === void 0) return { kind: "grow" };
31569
+ return decideOversized(last, undefinedAtEnd, state);
31570
+ }
31571
+ function decideOversized(last, undefinedAtEnd, state) {
31572
+ const headerStart = findHeaderStart(state.assembled, last, state);
31573
+ if (headerStart === void 0) {
31574
+ return { kind: "grow" };
31575
+ }
31576
+ const header = parseElementHeader(state.assembled, headerStart, state);
31577
+ if (header === void 0) return { kind: "grow" };
31578
+ if (!undefinedAtEnd && header.length !== last.length) {
31579
+ return { kind: "grow" };
31580
+ }
31581
+ return decideWithHeader(state, headerStart, header, undefinedAtEnd);
31582
+ }
31583
+ function findHeaderStart(assembled, element, state) {
31584
+ const candidates = state.explicitVr ? [12, 8] : [8];
31585
+ for (const headerLen of candidates) {
31586
+ const start = element.dataOffset - headerLen;
31587
+ if (start < 0) continue;
31588
+ const header = parseElementHeader(assembled, start, state);
31589
+ if (header !== void 0 && header.headerLen === headerLen) {
31590
+ return start;
31591
+ }
31592
+ }
31593
+ return void 0;
31594
+ }
31595
+ function fileOffsetOf(state, assembledPos) {
31596
+ return state.filePos - (state.assembled.length - assembledPos);
31597
+ }
31598
+ function applyDefinedSkip(state, headerEnd, valueLength) {
31599
+ const valueStartInFile = fileOffsetOf(state, headerEnd);
31600
+ if (valueStartInFile + valueLength > state.fileSize) {
31601
+ return err(new Error("declared value length extends beyond EOF"));
31602
+ }
31603
+ state.filePos = valueStartInFile + valueLength;
31604
+ state.assembled = state.assembled.subarray(0, headerEnd);
31605
+ state.growSize = state.chunkBytes;
31606
+ return ok(void 0);
31607
+ }
31608
+ async function hopFragments(handle, start, fileSize) {
31609
+ let position = start;
31610
+ for (let i = 0; i < MAX_FRAGMENT_HOPS; i++) {
31611
+ if (position + 8 > fileSize) {
31612
+ return err(new Error("encapsulated data truncated"));
31613
+ }
31614
+ const headerResult = await readRange(handle, position, 8);
31615
+ if (!headerResult.ok) {
31616
+ return err(headerResult.error);
31617
+ }
31618
+ const group = headerResult.value.readUInt16LE(0);
31619
+ const elementNum = headerResult.value.readUInt16LE(2);
31620
+ const itemLength = headerResult.value.readUInt32LE(4);
31621
+ if (group !== 65534) {
31622
+ return err(new Error("unexpected tag between fragments"));
31623
+ }
31624
+ if (elementNum === 57565) {
31625
+ return ok(position + 8);
31626
+ }
31627
+ if (elementNum !== 57344 || itemLength === UNDEFINED_LENGTH) {
31628
+ return err(new Error("malformed fragment item"));
31629
+ }
31630
+ position += 8 + itemLength;
31631
+ }
31632
+ return err(new Error("fragment count exceeded bound"));
31633
+ }
31634
+ async function applyEncapsulatedSkip(state, headerEnd) {
31635
+ const valueStartInFile = fileOffsetOf(state, headerEnd);
31636
+ const afterDelimiter = await hopFragments(state.handle, valueStartInFile, state.fileSize);
31637
+ if (!afterDelimiter.ok) {
31638
+ return err(afterDelimiter.error);
31639
+ }
31640
+ state.filePos = afterDelimiter.value;
31641
+ state.assembled = state.assembled.subarray(0, headerEnd);
31642
+ state.growSize = state.chunkBytes;
31643
+ return ok(void 0);
31644
+ }
31645
+ async function appendChunk(state) {
31646
+ const length = Math.min(state.growSize, state.fileSize - state.filePos);
31647
+ if (length <= 0) return err(new Error("no bytes left to grow"));
31648
+ const chunk = await readRange(state.handle, state.filePos, length);
31649
+ if (!chunk.ok) {
31650
+ return err(chunk.error);
31651
+ }
31652
+ state.assembled = Buffer.concat([state.assembled, chunk.value]);
31653
+ state.filePos += length;
31654
+ state.growSize = Math.min(state.growSize * 2, state.fileSize);
31655
+ return ok(void 0);
31656
+ }
31657
+ async function applyAction(action, state) {
31658
+ switch (action.kind) {
31659
+ case "done":
31660
+ return "done";
31661
+ case "fullRead":
31662
+ return "fullRead";
31663
+ case "grow":
31664
+ return (await appendChunk(state)).ok ? "continue" : "fullRead";
31665
+ case "skipDefined":
31666
+ return applyDefinedSkip(state, action.headerEnd, action.valueLength).ok ? "continue" : "fullRead";
31667
+ case "skipEncapsulated":
31668
+ return (await applyEncapsulatedSkip(state, action.headerEnd)).ok ? "continue" : "fullRead";
31669
+ }
31670
+ }
31671
+ async function boundedLoop(state) {
31672
+ for (let i = 0; i < MAX_ITERATIONS; i++) {
31673
+ const abort = checkAbort(state);
31674
+ if (abort !== void 0) {
31675
+ return err(abort);
31676
+ }
31677
+ const probe = probeParse(state.assembled);
31678
+ const action = probe.threw ? decideAfterThrow(probe, state) : decideAfterSuccess(probe, state);
31679
+ const outcome = await applyAction(action, state);
31680
+ if (outcome === "done") {
31681
+ return ok(state.assembled);
31682
+ }
31683
+ if (outcome === "fullRead") {
31684
+ return "fullRead";
31685
+ }
31686
+ }
31687
+ return "fullRead";
31688
+ }
31689
+ async function readWhole(handle, fileSize, state) {
31690
+ const abort = checkAbort(state);
31691
+ if (abort !== void 0) {
31692
+ return err(abort);
31693
+ }
31694
+ return readRange(handle, 0, fileSize);
31695
+ }
31696
+ async function readWithHandle(handle, options) {
31697
+ const fileSize = (await handle.stat()).size;
31698
+ const deadline = Date.now() + options.timeoutMs;
31699
+ const guard = { deadline, signal: options.signal, timeoutMs: options.timeoutMs };
31700
+ const threshold = options.thresholdBytes ?? BOUNDED_READ_THRESHOLD_BYTES;
31701
+ const chunkBytes = options.chunkBytes ?? BOUNDED_READ_CHUNK_BYTES;
31702
+ if (fileSize <= threshold) {
31703
+ return readWhole(handle, fileSize, guard);
31704
+ }
31705
+ const headResult = await readRange(handle, 0, Math.min(chunkBytes, fileSize));
31706
+ if (!headResult.ok) {
31707
+ return err(headResult.error);
31708
+ }
31709
+ const meta = probeMeta(headResult.value);
31710
+ if (meta === void 0 || meta.transferSyntax === TS_DEFLATED_LE) {
31711
+ return readWhole(handle, fileSize, guard);
31712
+ }
31713
+ const state = {
31714
+ handle,
31715
+ fileSize,
31716
+ chunkBytes,
31717
+ explicitVr: meta.transferSyntax !== TS_IMPLICIT_LE,
31718
+ bigEndian: meta.transferSyntax === TS_EXPLICIT_BE,
31719
+ metaEnd: meta.metaEnd,
31720
+ deadline,
31721
+ timeoutMs: options.timeoutMs,
31722
+ signal: options.signal,
31723
+ assembled: headResult.value,
31724
+ filePos: headResult.value.length,
31725
+ growSize: chunkBytes
31726
+ };
31727
+ const result = await boundedLoop(state);
31728
+ if (result === "fullRead") {
31729
+ return readWhole(handle, fileSize, guard);
31730
+ }
31731
+ return result;
31732
+ }
31733
+ async function readDicomHead(inputPath, options) {
31734
+ let handle;
31735
+ try {
31736
+ handle = await open(inputPath, "r");
31737
+ } catch (error) {
31738
+ const message = error instanceof Error ? error.message : String(error);
31739
+ return err(new Error(`failed to read '${inputPath}': ${message}`));
31740
+ }
31741
+ try {
31742
+ const result = await readWithHandle(handle, options);
31743
+ if (result.ok) {
31744
+ return result;
31745
+ }
31746
+ return err(new Error(`reading '${inputPath}' failed: ${result.error.message}`));
31747
+ } catch (error) {
31748
+ const message = error instanceof Error ? error.message : String(error);
31749
+ return err(new Error(`failed to read '${inputPath}': ${message}`));
31750
+ } finally {
31751
+ await handle.close();
31752
+ }
31753
+ }
31754
+
31755
+ // src/tools/dicom2json.ts
31756
+ var Dicom2jsonOptionsSchema = z.object({
31757
+ timeoutMs: z.number().int().positive().optional(),
31758
+ signal: z.instanceof(AbortSignal).optional(),
31759
+ charsetAssume: z.string().min(1).optional(),
31760
+ charsetFallback: z.string().min(1).optional(),
31761
+ utf8MislabelPromote: z.boolean().optional(),
31762
+ dcmtkFallback: z.boolean().optional(),
31763
+ boundedRead: z.boolean().optional()
31764
+ }).strict().optional();
31765
+ z.object({
31766
+ charsetAssume: z.string().min(1).optional(),
31767
+ charsetFallback: z.string().min(1).optional(),
31768
+ utf8MislabelPromote: z.boolean().optional()
31769
+ }).strict().optional();
31770
+ async function readFileBounded(inputPath, timeoutMs, signal) {
31771
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
31772
+ const combined = signal !== void 0 ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
31773
+ try {
31774
+ return ok(await readFile(inputPath, { signal: combined }));
31775
+ } catch (error) {
31776
+ if (timeoutSignal.aborted) {
31777
+ return err(new Error(`dicom2json: reading '${inputPath}' timed out after ${String(timeoutMs)}ms`));
31778
+ }
31779
+ if (signal?.aborted === true) {
31780
+ return err(new Error(`dicom2json: aborted while reading '${inputPath}'`));
31781
+ }
31782
+ const message = error instanceof Error ? error.message : String(error);
31783
+ return err(new Error(`dicom2json: failed to read '${inputPath}': ${message}`));
31784
+ }
31785
+ }
31786
+ async function runDcmtkFallback(inputPath, jsError, remainingMs, options) {
31787
+ if (remainingMs <= 0) {
31788
+ return err(new Error(`dicom2json: JS parse failed and timeout budget exhausted (skipping DCMTK fallback) | js: ${jsError.message}`));
31789
+ }
31790
+ const fallback = await dcm2json(inputPath, {
31791
+ timeoutMs: remainingMs,
31792
+ signal: options?.signal,
31793
+ charsetAssume: options?.charsetAssume,
31794
+ charsetFallback: options?.charsetFallback
31795
+ });
31796
+ if (!fallback.ok) {
31797
+ return err(new Error(`dicom2json: both engines failed | js: ${jsError.message} | dcmtk: ${fallback.error.message}`));
31798
+ }
31799
+ return ok({ data: fallback.value.data, warnings: [], source: fallback.value.source });
31800
+ }
31801
+ async function dicom2json(inputPath, options) {
31802
+ const validation = Dicom2jsonOptionsSchema.safeParse(options);
31803
+ if (!validation.success) {
31804
+ return err(createValidationError("dicom2json", validation.error));
31805
+ }
31806
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
31807
+ const startTime = Date.now();
31808
+ const parsed = await parseFromFile(inputPath, timeoutMs, options);
31809
+ if (parsed.ok) {
31810
+ return parsed;
31811
+ }
31812
+ if (options?.dcmtkFallback === true) {
31813
+ return runDcmtkFallback(inputPath, parsed.error, timeoutMs - (Date.now() - startTime), options);
31814
+ }
31815
+ return err(parsed.error);
31816
+ }
31817
+ async function readHeadBounded(inputPath, timeoutMs, signal) {
31818
+ const result = await readDicomHead(inputPath, { timeoutMs, signal });
31819
+ if (result.ok) {
31820
+ return result;
31821
+ }
31822
+ return err(new Error(`dicom2json: ${result.error.message}`));
31823
+ }
31824
+ async function parseFromFile(inputPath, timeoutMs, options) {
31825
+ const fileResult = options?.boundedRead === false ? await readFileBounded(inputPath, timeoutMs, options?.signal) : await readHeadBounded(inputPath, timeoutMs, options?.signal);
31826
+ if (!fileResult.ok) {
31827
+ return err(fileResult.error);
31828
+ }
31829
+ const parsed = parseDicomBuffer(fileResult.value, {
31830
+ charsetAssume: options?.charsetAssume,
31831
+ charsetFallback: options?.charsetFallback,
31832
+ utf8MislabelPromote: options?.utf8MislabelPromote
31833
+ });
31834
+ if (!parsed.ok) {
31835
+ return err(parsed.error);
31836
+ }
31837
+ return ok({ data: parsed.value.data, warnings: parsed.value.warnings, source: "js" });
30902
31838
  }
30903
31839
  var TAG_OR_PATH_PATTERN = /^\([0-9A-Fa-f]{4},[0-9A-Fa-f]{4}\)(\[\d+\]\.\([0-9A-Fa-f]{4},[0-9A-Fa-f]{4}\))*(\[\d+\])?$/;
30904
31840
  var TagModificationSchema = z.object({
@@ -31005,16 +31941,56 @@ async function unlinkFile(path) {
31005
31941
  }
31006
31942
 
31007
31943
  // src/dicom/DicomInstance.ts
31944
+ async function readViaDcmtk(path, shared) {
31945
+ const result = await dcm2json(path, shared);
31946
+ if (!result.ok) return err(result.error);
31947
+ return ok({ data: result.value.data, warnings: [] });
31948
+ }
31949
+ async function readViaJs(path, shared, options) {
31950
+ const result = await dicom2json(path, {
31951
+ ...shared,
31952
+ utf8MislabelPromote: options?.utf8MislabelPromote,
31953
+ boundedRead: options?.boundedRead,
31954
+ dcmtkFallback: true
31955
+ });
31956
+ if (!result.ok) return err(result.error);
31957
+ return ok({ data: result.value.data, warnings: result.value.warnings });
31958
+ }
31959
+ async function readDicomJson(path, options) {
31960
+ const shared = {
31961
+ timeoutMs: options?.timeoutMs ?? DEFAULT_TIMEOUT_MS,
31962
+ signal: options?.signal,
31963
+ charsetAssume: options?.charsetAssume,
31964
+ charsetFallback: options?.charsetFallback
31965
+ };
31966
+ if (options?.engine === "dcmtk") {
31967
+ return readViaDcmtk(path, shared);
31968
+ }
31969
+ return readViaJs(path, shared, options);
31970
+ }
31008
31971
  var DicomInstance = class _DicomInstance {
31009
- constructor(dataset, changes, filePath, metadata) {
31972
+ constructor(state) {
31010
31973
  __publicField(this, "dicomDataset");
31011
31974
  __publicField(this, "changeSet");
31012
31975
  __publicField(this, "filepath");
31013
31976
  __publicField(this, "meta");
31014
- this.dicomDataset = dataset;
31015
- this.changeSet = changes;
31016
- this.filepath = filePath;
31017
- this.meta = metadata;
31977
+ __publicField(this, "warningList");
31978
+ this.dicomDataset = state.dataset;
31979
+ this.changeSet = state.changes;
31980
+ this.filepath = state.filePath;
31981
+ this.meta = state.metadata;
31982
+ this.warningList = state.warnings;
31983
+ }
31984
+ /** Creates a copy with the given fields replaced. */
31985
+ derive(overrides) {
31986
+ return new _DicomInstance({
31987
+ dataset: this.dicomDataset,
31988
+ changes: this.changeSet,
31989
+ filePath: this.filepath,
31990
+ metadata: this.meta,
31991
+ warnings: this.warningList,
31992
+ ...overrides
31993
+ });
31018
31994
  }
31019
31995
  // -----------------------------------------------------------------------
31020
31996
  // Factories
@@ -31029,16 +32005,19 @@ var DicomInstance = class _DicomInstance {
31029
32005
  static async open(path, options) {
31030
32006
  const filePathResult = createDicomFilePath(path);
31031
32007
  if (!filePathResult.ok) return err(filePathResult.error);
31032
- const jsonResult = await dcm2json(path, {
31033
- timeoutMs: options?.timeoutMs ?? DEFAULT_TIMEOUT_MS,
31034
- signal: options?.signal,
31035
- charsetAssume: options?.charsetAssume,
31036
- charsetFallback: options?.charsetFallback
31037
- });
32008
+ const jsonResult = await readDicomJson(path, options);
31038
32009
  if (!jsonResult.ok) return err(jsonResult.error);
31039
32010
  const datasetResult = DicomDataset.fromJson(jsonResult.value.data);
31040
32011
  if (!datasetResult.ok) return err(datasetResult.error);
31041
- return ok(new _DicomInstance(datasetResult.value, ChangeSet.empty(), filePathResult.value, /* @__PURE__ */ new Map()));
32012
+ return ok(
32013
+ new _DicomInstance({
32014
+ dataset: datasetResult.value,
32015
+ changes: ChangeSet.empty(),
32016
+ filePath: filePathResult.value,
32017
+ metadata: /* @__PURE__ */ new Map(),
32018
+ warnings: jsonResult.value.warnings
32019
+ })
32020
+ );
31042
32021
  }
31043
32022
  /**
31044
32023
  * Creates a DicomInstance from an existing DicomDataset.
@@ -31054,7 +32033,7 @@ var DicomInstance = class _DicomInstance {
31054
32033
  if (!fpResult.ok) return err(fpResult.error);
31055
32034
  fp = fpResult.value;
31056
32035
  }
31057
- return ok(new _DicomInstance(dataset, ChangeSet.empty(), fp, /* @__PURE__ */ new Map()));
32036
+ return ok(new _DicomInstance({ dataset, changes: ChangeSet.empty(), filePath: fp, metadata: /* @__PURE__ */ new Map(), warnings: [] }));
31058
32037
  }
31059
32038
  // -----------------------------------------------------------------------
31060
32039
  // Read accessors (delegate to DicomDataset)
@@ -31075,6 +32054,15 @@ var DicomInstance = class _DicomInstance {
31075
32054
  get filePath() {
31076
32055
  return this.filepath;
31077
32056
  }
32057
+ /**
32058
+ * Non-fatal parser warnings from opening the file (e.g. `possible UTF-8 mislabel: <tag>`).
32059
+ *
32060
+ * Empty for instances created via {@link DicomInstance.fromDataset} or opened with
32061
+ * `engine: 'dcmtk'`. Preserved across fluent modifications.
32062
+ */
32063
+ get warnings() {
32064
+ return this.warningList;
32065
+ }
31078
32066
  /** Patient's Name (0010,0010). */
31079
32067
  get patientName() {
31080
32068
  return this.dicomDataset.patientName;
@@ -31154,7 +32142,7 @@ var DicomInstance = class _DicomInstance {
31154
32142
  * @param value - The new value
31155
32143
  */
31156
32144
  setTag(path, value) {
31157
- return new _DicomInstance(this.dicomDataset, this.changeSet.setTag(path, value), this.filepath, this.meta);
32145
+ return this.derive({ changes: this.changeSet.setTag(path, value) });
31158
32146
  }
31159
32147
  /**
31160
32148
  * Erases a tag, returning a new DicomInstance.
@@ -31162,11 +32150,11 @@ var DicomInstance = class _DicomInstance {
31162
32150
  * @param path - The DICOM tag path to erase
31163
32151
  */
31164
32152
  eraseTag(path) {
31165
- return new _DicomInstance(this.dicomDataset, this.changeSet.eraseTag(path), this.filepath, this.meta);
32153
+ return this.derive({ changes: this.changeSet.eraseTag(path) });
31166
32154
  }
31167
32155
  /** Erases all private tags, returning a new DicomInstance. */
31168
32156
  erasePrivateTags() {
31169
- return new _DicomInstance(this.dicomDataset, this.changeSet.erasePrivateTags(), this.filepath, this.meta);
32157
+ return this.derive({ changes: this.changeSet.erasePrivateTags() });
31170
32158
  }
31171
32159
  /** Sets Patient's Name (0010,0010). */
31172
32160
  setPatientName(value) {
@@ -31220,7 +32208,7 @@ var DicomInstance = class _DicomInstance {
31220
32208
  * @param entries - A record of tag path → value pairs
31221
32209
  */
31222
32210
  setBatch(entries) {
31223
- return new _DicomInstance(this.dicomDataset, this.changeSet.setBatch(entries), this.filepath, this.meta);
32211
+ return this.derive({ changes: this.changeSet.setBatch(entries) });
31224
32212
  }
31225
32213
  /**
31226
32214
  * Returns a new DicomInstance with the given changes merged into pending changes.
@@ -31229,7 +32217,7 @@ var DicomInstance = class _DicomInstance {
31229
32217
  * @returns A new DicomInstance with accumulated changes
31230
32218
  */
31231
32219
  withChanges(changes) {
31232
- return new _DicomInstance(this.dicomDataset, this.changeSet.merge(changes), this.filepath, this.meta);
32220
+ return this.derive({ changes: this.changeSet.merge(changes) });
31233
32221
  }
31234
32222
  /**
31235
32223
  * Returns a new DicomInstance pointing to a different file path.
@@ -31243,7 +32231,7 @@ var DicomInstance = class _DicomInstance {
31243
32231
  withFilePath(newPath) {
31244
32232
  const result = createDicomFilePath(newPath);
31245
32233
  if (!result.ok) throw result.error;
31246
- return new _DicomInstance(this.dicomDataset, this.changeSet, result.value, this.meta);
32234
+ return this.derive({ filePath: result.value });
31247
32235
  }
31248
32236
  // -----------------------------------------------------------------------
31249
32237
  // File I/O
@@ -31281,7 +32269,7 @@ var DicomInstance = class _DicomInstance {
31281
32269
  return err(applyResult.error);
31282
32270
  }
31283
32271
  }
31284
- return ok(new _DicomInstance(this.dicomDataset, ChangeSet.empty(), outPathResult.value, this.meta));
32272
+ return ok(this.derive({ changes: ChangeSet.empty(), filePath: outPathResult.value }));
31285
32273
  }
31286
32274
  /**
31287
32275
  * Gets the file size in bytes.
@@ -31316,7 +32304,7 @@ var DicomInstance = class _DicomInstance {
31316
32304
  withMetadata(key, value) {
31317
32305
  const newMeta = new Map(this.meta);
31318
32306
  newMeta.set(key, value);
31319
- return new _DicomInstance(this.dicomDataset, this.changeSet, this.filepath, newMeta);
32307
+ return this.derive({ metadata: newMeta });
31320
32308
  }
31321
32309
  /**
31322
32310
  * Gets application metadata by key.