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

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.cjs CHANGED
@@ -9,10 +9,13 @@ var promises = require('fs/promises');
9
9
  var os = require('os');
10
10
  var zod = require('zod');
11
11
  var fastXmlParser = require('fast-xml-parser');
12
+ var zlib = require('zlib');
13
+ var dicomParser = require('dicom-parser');
12
14
 
13
15
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
16
 
15
17
  var kill__default = /*#__PURE__*/_interopDefault(kill);
18
+ var dicomParser__default = /*#__PURE__*/_interopDefault(dicomParser);
16
19
 
17
20
  var __defProp = Object.defineProperty;
18
21
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -30392,9 +30395,9 @@ var ToolExecutionError = class extends Error {
30392
30395
  this.exitCode = details.exitCode;
30393
30396
  }
30394
30397
  };
30395
- function createToolError(toolName, args, exitCode, stderr4, stdout = "") {
30398
+ function createToolError(toolName, args, exitCode, stderr5, stdout = "") {
30396
30399
  const argsStr = truncate(args.join(" "), MAX_ARGS_LENGTH);
30397
- const stderrStr = truncate(stderr4.trim(), MAX_STDERR_LENGTH);
30400
+ const stderrStr = truncate(stderr5.trim(), MAX_STDERR_LENGTH);
30398
30401
  const parts = [`${toolName} failed (exit code ${String(exitCode)})`];
30399
30402
  if (argsStr.length > 0) {
30400
30403
  parts.push(`args: ${argsStr}`);
@@ -30402,7 +30405,7 @@ function createToolError(toolName, args, exitCode, stderr4, stdout = "") {
30402
30405
  if (stderrStr.length > 0) {
30403
30406
  parts.push(`stderr: ${stderrStr}`);
30404
30407
  }
30405
- return new ToolExecutionError(parts.join(" | "), { stdout, stderr: stderr4, exitCode });
30408
+ return new ToolExecutionError(parts.join(" | "), { stdout, stderr: stderr5, exitCode });
30406
30409
  }
30407
30410
  function createValidationError(toolName, zodError) {
30408
30411
  const parts = [];
@@ -30434,7 +30437,7 @@ async function execCommand(binary, args, options) {
30434
30437
  }
30435
30438
  function wireSpawnListeners(binary, child, timeoutMs, resolve) {
30436
30439
  let stdout = "";
30437
- let stderr4 = "";
30440
+ let stderr5 = "";
30438
30441
  let settled = false;
30439
30442
  const name = binary.split("/").pop() ?? binary;
30440
30443
  const settle = (result) => {
@@ -30449,14 +30452,14 @@ function wireSpawnListeners(binary, child, timeoutMs, resolve) {
30449
30452
  }, timeoutMs);
30450
30453
  child.stdout?.on("data", (chunk) => {
30451
30454
  stdout += String(chunk);
30452
- if (stdout.length + stderr4.length > MAX_OUTPUT_BYTES) {
30455
+ if (stdout.length + stderr5.length > MAX_OUTPUT_BYTES) {
30453
30456
  if (child.pid !== void 0 && child.pid !== null) killTree(child.pid);
30454
30457
  settle(err(new Error(`${name} output exceeded ${MAX_OUTPUT_BYTES} bytes`)));
30455
30458
  }
30456
30459
  });
30457
30460
  child.stderr?.on("data", (chunk) => {
30458
- stderr4 += String(chunk);
30459
- if (stdout.length + stderr4.length > MAX_OUTPUT_BYTES) {
30461
+ stderr5 += String(chunk);
30462
+ if (stdout.length + stderr5.length > MAX_OUTPUT_BYTES) {
30460
30463
  if (child.pid !== void 0 && child.pid !== null) killTree(child.pid);
30461
30464
  settle(err(new Error(`${name} output exceeded ${MAX_OUTPUT_BYTES} bytes`)));
30462
30465
  }
@@ -30466,7 +30469,7 @@ function wireSpawnListeners(binary, child, timeoutMs, resolve) {
30466
30469
  settle(err(new Error(`${name} error: ${error.message}`)));
30467
30470
  });
30468
30471
  child.on("close", (code) => {
30469
- settle(ok({ stdout, stderr: stderr4, exitCode: code ?? 1 }));
30472
+ settle(ok({ stdout, stderr: stderr5, exitCode: code ?? 1 }));
30470
30473
  });
30471
30474
  }
30472
30475
  async function spawnCommand(binary, args, options) {
@@ -30688,8 +30691,8 @@ function unwrapValue(v) {
30688
30691
  const obj = v;
30689
30692
  if ("#text" in obj) return obj["#text"];
30690
30693
  const keys = Object.keys(obj);
30691
- if (keys.length === 1 && keys[0] !== void 0 && keys[0].startsWith("@_")) {
30692
- return obj[keys[0]];
30694
+ if (keys.every((k) => k.startsWith("@_"))) {
30695
+ return "";
30693
30696
  }
30694
30697
  return v;
30695
30698
  }
@@ -30895,16 +30898,542 @@ async function dcm2json(inputPath, options) {
30895
30898
  const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
30896
30899
  const signal = options?.signal;
30897
30900
  const startTime = Date.now();
30898
- const remaining = () => Math.max(1e3, timeoutMs - (Date.now() - startTime));
30901
+ const remaining = () => Math.max(0, timeoutMs - (Date.now() - startTime));
30899
30902
  const verbosity = options?.verbosity;
30900
30903
  if (options?.directOnly === true) {
30901
- return tryDirectPath(inputPath, remaining(), signal, verbosity);
30904
+ return tryDirectPath(inputPath, timeoutMs, signal, verbosity);
30902
30905
  }
30903
- const xmlResult = await tryXmlPath(inputPath, remaining(), signal, buildXmlOpts(options));
30906
+ const xmlResult = await tryXmlPath(inputPath, timeoutMs, signal, buildXmlOpts(options));
30904
30907
  if (xmlResult.ok) {
30905
30908
  return xmlResult;
30906
30909
  }
30907
- return tryDirectPath(inputPath, remaining(), signal, verbosity);
30910
+ return fallbackToDirect(inputPath, xmlResult.error, { budget: remaining(), timeoutMs, signal, verbosity });
30911
+ }
30912
+ async function fallbackToDirect(inputPath, xmlError, context) {
30913
+ if (context.budget === 0) {
30914
+ return err(
30915
+ new Error(
30916
+ `dcm2json: XML path failed and timeout budget (${String(context.timeoutMs)}ms) is exhausted (skipping direct fallback) | xml: ${xmlError.message}`
30917
+ )
30918
+ );
30919
+ }
30920
+ const directResult = await tryDirectPath(inputPath, context.budget, context.signal, context.verbosity);
30921
+ if (directResult.ok) {
30922
+ return directResult;
30923
+ }
30924
+ return err(new Error(`dcm2json: both paths failed | xml: ${xmlError.message} | direct: ${directResult.error.message}`));
30925
+ }
30926
+
30927
+ // src/tools/_charset.ts
30928
+ var LATIN1 = { kind: "latin1" };
30929
+ function label(name) {
30930
+ return { kind: "label", label: name };
30931
+ }
30932
+ var CHARSET_DECODERS = {
30933
+ "ISO_IR 6": LATIN1,
30934
+ "ISO_IR 100": LATIN1,
30935
+ "ISO_IR 101": label("iso-8859-2"),
30936
+ "ISO_IR 109": label("iso-8859-3"),
30937
+ "ISO_IR 110": label("iso-8859-4"),
30938
+ "ISO_IR 144": label("iso-8859-5"),
30939
+ "ISO_IR 127": label("iso-8859-6"),
30940
+ "ISO_IR 126": label("iso-8859-7"),
30941
+ "ISO_IR 138": label("iso-8859-8"),
30942
+ "ISO_IR 148": label("iso-8859-9"),
30943
+ "ISO_IR 203": label("iso-8859-15"),
30944
+ "ISO_IR 13": label("shift_jis"),
30945
+ "ISO_IR 166": label("windows-874"),
30946
+ "ISO_IR 192": label("utf-8"),
30947
+ GB18030: label("gb18030"),
30948
+ GBK: label("gbk")
30949
+ };
30950
+ var ISO2022_INITIAL = {
30951
+ "ISO 2022 IR 6": LATIN1,
30952
+ "ISO 2022 IR 13": label("shift_jis"),
30953
+ "ISO 2022 IR 87": LATIN1,
30954
+ "ISO 2022 IR 159": LATIN1,
30955
+ "ISO 2022 IR 149": label("euc-kr"),
30956
+ "ISO 2022 IR 58": label("gbk"),
30957
+ "ISO 2022 IR 100": LATIN1,
30958
+ "ISO 2022 IR 101": label("iso-8859-2"),
30959
+ "ISO 2022 IR 109": label("iso-8859-3"),
30960
+ "ISO 2022 IR 110": label("iso-8859-4"),
30961
+ "ISO 2022 IR 144": label("iso-8859-5"),
30962
+ "ISO 2022 IR 127": label("iso-8859-6"),
30963
+ "ISO 2022 IR 126": label("iso-8859-7"),
30964
+ "ISO 2022 IR 138": label("iso-8859-8"),
30965
+ "ISO 2022 IR 148": label("iso-8859-9"),
30966
+ "ISO 2022 IR 166": label("windows-874"),
30967
+ "ISO 2022 IR 203": label("iso-8859-15")
30968
+ };
30969
+ var ESCAPE_DECODERS = {
30970
+ "(B": LATIN1,
30971
+ // G0 = ASCII
30972
+ "(J": LATIN1,
30973
+ // G0 = JIS X 0201 romaji
30974
+ ")I": { kind: "katakana" },
30975
+ // G1 = JIS X 0201 katakana
30976
+ "$@": { kind: "iso2022jp", escape: [27, 36, 64] },
30977
+ // G0 = JIS X 0208-1978
30978
+ $B: { kind: "iso2022jp", escape: [27, 36, 66] },
30979
+ // G0 = JIS X 0208
30980
+ "$(D": { kind: "iso2022jp", escape: [27, 36, 40, 68] },
30981
+ // G0 = JIS X 0212
30982
+ "$)C": label("euc-kr"),
30983
+ // G1 = KS X 1001
30984
+ "$)A": label("gbk"),
30985
+ // G1 = GB 2312
30986
+ "-A": LATIN1,
30987
+ // G1 = ISO-8859-1
30988
+ "-B": label("iso-8859-2"),
30989
+ "-C": label("iso-8859-3"),
30990
+ "-D": label("iso-8859-4"),
30991
+ "-F": label("iso-8859-7"),
30992
+ "-G": label("iso-8859-6"),
30993
+ "-H": label("iso-8859-8"),
30994
+ "-L": label("iso-8859-5"),
30995
+ "-M": label("iso-8859-9"),
30996
+ "-T": label("windows-874"),
30997
+ "-b": label("iso-8859-15")
30998
+ };
30999
+ var CHARSET_ALIASES = {
31000
+ ascii: "ISO_IR 6",
31001
+ "latin-1": "ISO_IR 100",
31002
+ latin1: "ISO_IR 100",
31003
+ "iso-8859-1": "ISO_IR 100",
31004
+ "latin-2": "ISO_IR 101",
31005
+ "latin-3": "ISO_IR 109",
31006
+ "latin-4": "ISO_IR 110",
31007
+ "latin-5": "ISO_IR 148",
31008
+ "latin-9": "ISO_IR 203",
31009
+ cyrillic: "ISO_IR 144",
31010
+ arabic: "ISO_IR 127",
31011
+ greek: "ISO_IR 126",
31012
+ hebrew: "ISO_IR 138",
31013
+ thai: "ISO_IR 166",
31014
+ "shift-jis": "ISO_IR 13",
31015
+ shift_jis: "ISO_IR 13",
31016
+ "utf-8": "ISO_IR 192",
31017
+ utf8: "ISO_IR 192",
31018
+ gb18030: "GB18030",
31019
+ gbk: "GBK"
31020
+ };
31021
+ var decoderCache = /* @__PURE__ */ new Map();
31022
+ function getTextDecoder(labelName) {
31023
+ if (decoderCache.has(labelName)) {
31024
+ return decoderCache.get(labelName);
31025
+ }
31026
+ let decoder;
31027
+ try {
31028
+ decoder = new TextDecoder(labelName);
31029
+ } catch {
31030
+ decoder = void 0;
31031
+ }
31032
+ decoderCache.set(labelName, decoder);
31033
+ return decoder;
31034
+ }
31035
+ function decodeLatin1(bytes) {
31036
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
31037
+ }
31038
+ function decodeSegment(bytes, decoder) {
31039
+ if (bytes.length === 0) return "";
31040
+ switch (decoder.kind) {
31041
+ case "latin1":
31042
+ return decodeLatin1(bytes);
31043
+ case "label": {
31044
+ const td = getTextDecoder(decoder.label);
31045
+ if (td === void 0) return decodeLatin1(bytes);
31046
+ return td.decode(bytes);
31047
+ }
31048
+ case "iso2022jp": {
31049
+ const td = getTextDecoder("iso-2022-jp");
31050
+ if (td === void 0) return decodeLatin1(bytes);
31051
+ const wrapped = new Uint8Array(decoder.escape.length + bytes.length);
31052
+ wrapped.set(decoder.escape, 0);
31053
+ wrapped.set(bytes, decoder.escape.length);
31054
+ return td.decode(wrapped);
31055
+ }
31056
+ case "katakana": {
31057
+ const td = getTextDecoder("shift_jis");
31058
+ if (td === void 0) return decodeLatin1(bytes);
31059
+ return td.decode(bytes);
31060
+ }
31061
+ }
31062
+ }
31063
+ function readEscape(bytes, start) {
31064
+ let i = start + 1;
31065
+ while (i < bytes.length && bytes[i] >= 32 && bytes[i] <= 47) {
31066
+ i++;
31067
+ }
31068
+ if (i < bytes.length && bytes[i] >= 48 && bytes[i] <= 126) {
31069
+ i++;
31070
+ }
31071
+ const seq = bytes.subarray(start + 1, i);
31072
+ return { key: decodeLatin1(seq), length: i - start };
31073
+ }
31074
+ function decodeIso2022(bytes, initial) {
31075
+ let out = "";
31076
+ let current = initial;
31077
+ let segStart = 0;
31078
+ let i = 0;
31079
+ while (i < bytes.length) {
31080
+ if (bytes[i] !== 27) {
31081
+ i++;
31082
+ continue;
31083
+ }
31084
+ out += decodeSegment(bytes.subarray(segStart, i), current);
31085
+ const esc = readEscape(bytes, i);
31086
+ current = ESCAPE_DECODERS[esc.key] ?? current;
31087
+ i += esc.length;
31088
+ segStart = i;
31089
+ }
31090
+ out += decodeSegment(bytes.subarray(segStart), current);
31091
+ return out;
31092
+ }
31093
+ var DEFAULT_CONTEXT = { terms: ["ISO_IR 6"], iso2022: false, initial: LATIN1 };
31094
+ function normalizeCharsetName(input) {
31095
+ const trimmed = input.trim();
31096
+ if (CHARSET_DECODERS[trimmed] !== void 0 || ISO2022_INITIAL[trimmed] !== void 0) {
31097
+ return trimmed;
31098
+ }
31099
+ return CHARSET_ALIASES[trimmed.toLowerCase()];
31100
+ }
31101
+ function buildContext(terms) {
31102
+ const iso2022 = terms.length > 1 || terms.some((t) => t.startsWith("ISO 2022"));
31103
+ const first = terms[0] ?? "ISO_IR 6";
31104
+ const initial = iso2022 ? ISO2022_INITIAL[first] : CHARSET_DECODERS[first];
31105
+ if (initial === void 0) return void 0;
31106
+ return { terms, iso2022, initial };
31107
+ }
31108
+ function parseSpecificCharacterSet(raw) {
31109
+ const values = raw.split("\\").map((v) => v.trim());
31110
+ return values.map((v, idx) => v === "" && idx === 0 ? "ISO 2022 IR 6" : v).filter((v) => v !== "");
31111
+ }
31112
+ function contextFromTerms(terms, fallback, source) {
31113
+ const context = buildContext(terms);
31114
+ if (context !== void 0) {
31115
+ return ok(context);
31116
+ }
31117
+ if (fallback !== void 0) {
31118
+ const fallbackTerm = normalizeCharsetName(fallback);
31119
+ const fallbackContext = fallbackTerm !== void 0 ? buildContext([fallbackTerm]) : void 0;
31120
+ if (fallbackContext !== void 0) {
31121
+ return ok(fallbackContext);
31122
+ }
31123
+ return err(new Error(`Unsupported charset fallback '${fallback}' (while handling unsupported ${source})`));
31124
+ }
31125
+ return err(new Error(`Unsupported character set: ${source} \u2014 provide charsetFallback (e.g. 'latin-1') to decode best-effort`));
31126
+ }
31127
+ function resolveCharsetContext(specificCharacterSet, charsetAssume, charsetFallback) {
31128
+ if (specificCharacterSet === void 0 || specificCharacterSet.trim() === "") {
31129
+ if (charsetAssume === void 0) {
31130
+ return ok(DEFAULT_CONTEXT);
31131
+ }
31132
+ const term = normalizeCharsetName(charsetAssume);
31133
+ if (term === void 0) {
31134
+ return contextFromTerms([charsetAssume], charsetFallback, `charsetAssume '${charsetAssume}'`);
31135
+ }
31136
+ return contextFromTerms([term], charsetFallback, `charsetAssume '${charsetAssume}'`);
31137
+ }
31138
+ const terms = parseSpecificCharacterSet(specificCharacterSet);
31139
+ return contextFromTerms(terms, charsetFallback, `'${specificCharacterSet}' (0008,0005)`);
31140
+ }
31141
+ function decodeDicomText(bytes, context) {
31142
+ if (context.iso2022) {
31143
+ return decodeIso2022(bytes, context.initial);
31144
+ }
31145
+ return decodeSegment(bytes, context.initial);
31146
+ }
31147
+
31148
+ // src/tools/_p10ToJson.ts
31149
+ var BINARY_VRS = /* @__PURE__ */ new Set(["OB", "OW", "OD", "OF", "OL", "OV", "UN"]);
31150
+ var CHARSET_VRS = /* @__PURE__ */ new Set(["SH", "LO", "ST", "LT", "UC", "UT", "PN"]);
31151
+ var NO_SPLIT_VRS = /* @__PURE__ */ new Set(["ST", "LT", "UT", "UR"]);
31152
+ var NUMERIC_VR_SIZE = { US: 2, SS: 2, UL: 4, SL: 4, FL: 4, FD: 8, SV: 8, UV: 8 };
31153
+ var MAX_DATASETS = 1e5;
31154
+ function toJsonTag(tag) {
31155
+ return tag.slice(1).toUpperCase();
31156
+ }
31157
+ function isEncodingArtifact(tag) {
31158
+ return tag.endsWith("0000") && tag.length === 9 || tag.startsWith("xfffe");
31159
+ }
31160
+ function resolveVr(element) {
31161
+ const vr = element.vr;
31162
+ if (vr !== void 0 && KNOWN_VR_CODES.has(vr)) {
31163
+ return vr;
31164
+ }
31165
+ return "UN";
31166
+ }
31167
+ function valueBytes(element, byteArray) {
31168
+ return byteArray.subarray(element.dataOffset, element.dataOffset + element.length);
31169
+ }
31170
+ function trimPadding(value) {
31171
+ let end = value.length;
31172
+ while (end > 0) {
31173
+ const ch = value.charCodeAt(end - 1);
31174
+ if (ch !== 32 && ch !== 0) break;
31175
+ end--;
31176
+ }
31177
+ return value.slice(0, end);
31178
+ }
31179
+ function readNumericAt(view, offset, vr, littleEndian) {
31180
+ switch (vr) {
31181
+ case "US":
31182
+ return view.getUint16(offset, littleEndian);
31183
+ case "SS":
31184
+ return view.getInt16(offset, littleEndian);
31185
+ case "UL":
31186
+ return view.getUint32(offset, littleEndian);
31187
+ case "SL":
31188
+ return view.getInt32(offset, littleEndian);
31189
+ case "FL":
31190
+ return view.getFloat32(offset, littleEndian);
31191
+ case "FD":
31192
+ return view.getFloat64(offset, littleEndian);
31193
+ case "SV":
31194
+ return Number(view.getBigInt64(offset, littleEndian));
31195
+ /* v8 ignore next 2 -- 'UV' is the only remaining caller-provided VR */
31196
+ default:
31197
+ return Number(view.getBigUint64(offset, littleEndian));
31198
+ }
31199
+ }
31200
+ function convertNumeric(element, byteArray, vr, littleEndian) {
31201
+ const size = NUMERIC_VR_SIZE[vr];
31202
+ const count = Math.floor(element.length / size);
31203
+ if (count === 0) {
31204
+ return { vr };
31205
+ }
31206
+ const view = new DataView(byteArray.buffer, byteArray.byteOffset + element.dataOffset, element.length);
31207
+ const values = [];
31208
+ for (let i = 0; i < count; i++) {
31209
+ values.push(readNumericAt(view, i * size, vr, littleEndian));
31210
+ }
31211
+ return { vr, Value: values };
31212
+ }
31213
+ function convertAttributeTag(element, byteArray, littleEndian) {
31214
+ const count = Math.floor(element.length / 4);
31215
+ if (count === 0) {
31216
+ return { vr: "AT" };
31217
+ }
31218
+ const view = new DataView(byteArray.buffer, byteArray.byteOffset + element.dataOffset, element.length);
31219
+ const values = [];
31220
+ for (let i = 0; i < count; i++) {
31221
+ const group = view.getUint16(i * 4, littleEndian);
31222
+ const elem = view.getUint16(i * 4 + 2, littleEndian);
31223
+ values.push(group.toString(16).padStart(4, "0").toUpperCase() + elem.toString(16).padStart(4, "0").toUpperCase());
31224
+ }
31225
+ return { vr: "AT", Value: values };
31226
+ }
31227
+ function personNameToJson(value) {
31228
+ const groups = trimPadding(value).split("=");
31229
+ const result = {};
31230
+ const names = ["Alphabetic", "Ideographic", "Phonetic"];
31231
+ for (let i = 0; i < names.length; i++) {
31232
+ const group = (groups[i] ?? "").replace(/\^+$/u, "");
31233
+ const name = names[i];
31234
+ if (group !== "" && name !== void 0) {
31235
+ result[name] = group;
31236
+ }
31237
+ }
31238
+ return result;
31239
+ }
31240
+ function convertPersonName2(element, byteArray, charset) {
31241
+ const decoded = decodeDicomText(valueBytes(element, byteArray), charset);
31242
+ const values = decoded.split("\\").map(personNameToJson);
31243
+ return { vr: "PN", Value: values };
31244
+ }
31245
+ function convertString(element, byteArray, vr, charset) {
31246
+ const bytes = valueBytes(element, byteArray);
31247
+ const decoded = CHARSET_VRS.has(vr) ? decodeDicomText(bytes, charset) : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
31248
+ const rawValues = NO_SPLIT_VRS.has(vr) ? [decoded] : decoded.split("\\");
31249
+ const values = rawValues.map((v) => {
31250
+ const trimmed = trimPadding(v);
31251
+ return vr === "DS" || vr === "IS" ? coerceNumeric(trimmed.trim()) : trimmed;
31252
+ });
31253
+ if (values.length === 1 && values[0] === "") {
31254
+ return { vr };
31255
+ }
31256
+ return { vr, Value: values };
31257
+ }
31258
+ function convertLeaf(element, byteArray, vr, settings) {
31259
+ if (element.fragments !== void 0) {
31260
+ return { vr: "OB" };
31261
+ }
31262
+ if (BINARY_VRS.has(vr)) {
31263
+ return { vr };
31264
+ }
31265
+ if (element.length === 0) {
31266
+ return { vr };
31267
+ }
31268
+ if (NUMERIC_VR_SIZE[vr] !== void 0) {
31269
+ return convertNumeric(element, byteArray, vr, settings.littleEndian);
31270
+ }
31271
+ if (vr === "AT") {
31272
+ return convertAttributeTag(element, byteArray, settings.littleEndian);
31273
+ }
31274
+ if (vr === "PN") {
31275
+ return convertPersonName2(element, byteArray, settings.charset);
31276
+ }
31277
+ return convertString(element, byteArray, vr, settings.charset);
31278
+ }
31279
+ function datasetCharset(src, parent, options) {
31280
+ const raw = src.string("x00080005");
31281
+ if (raw === void 0) {
31282
+ return ok(parent);
31283
+ }
31284
+ return resolveCharsetContext(raw, void 0, options?.charsetFallback);
31285
+ }
31286
+ function convertSequence2(element, stack, charset) {
31287
+ const items = element.items ?? [];
31288
+ const values = [];
31289
+ for (const item of items) {
31290
+ const model = {};
31291
+ values.push(model);
31292
+ if (item.dataSet !== void 0) {
31293
+ stack.push({ src: item.dataSet, out: model, parentCharset: charset });
31294
+ }
31295
+ }
31296
+ if (values.length === 0) {
31297
+ return { vr: "SQ" };
31298
+ }
31299
+ return { vr: "SQ", Value: values };
31300
+ }
31301
+ function isSequence(element, vr) {
31302
+ if (element.fragments !== void 0) {
31303
+ return false;
31304
+ }
31305
+ return vr === "SQ" || element.vr === void 0 && element.items !== void 0;
31306
+ }
31307
+ function convertDataset(unit, stack, littleEndian, options) {
31308
+ const charsetResult = datasetCharset(unit.src, unit.parentCharset, options);
31309
+ if (!charsetResult.ok) {
31310
+ return err(charsetResult.error);
31311
+ }
31312
+ const charset = charsetResult.value;
31313
+ const keys = Object.keys(unit.src.elements).sort();
31314
+ for (const key of keys) {
31315
+ const element = unit.src.elements[key];
31316
+ if (element === void 0) continue;
31317
+ if (isEncodingArtifact(element.tag)) continue;
31318
+ const tag = toJsonTag(element.tag);
31319
+ const vr = resolveVr(element);
31320
+ if (isSequence(element, vr)) {
31321
+ unit.out[tag] = convertSequence2(element, stack, charset);
31322
+ } else {
31323
+ unit.out[tag] = convertLeaf(element, unit.src.byteArray, vr, { charset, littleEndian });
31324
+ }
31325
+ }
31326
+ return ok(void 0);
31327
+ }
31328
+ function inflateDeflated(byteArray, position) {
31329
+ const inflated = zlib.inflateRawSync(byteArray.subarray(position));
31330
+ const combined = new Uint8Array(position + inflated.byteLength);
31331
+ combined.set(byteArray.subarray(0, position), 0);
31332
+ combined.set(inflated, position);
31333
+ return combined;
31334
+ }
31335
+ function implicitVrLookup(tag) {
31336
+ return lookupTag(tag.slice(1))?.vr;
31337
+ }
31338
+ function parseDicomBuffer(buffer, options) {
31339
+ let dataSet;
31340
+ try {
31341
+ dataSet = dicomParser__default.default.parseDicom(buffer, { vrCallback: implicitVrLookup, inflater: inflateDeflated });
31342
+ } catch (error) {
31343
+ return err(new Error(`Failed to parse DICOM data: ${stderrLib.stderr(error).message}`));
31344
+ }
31345
+ const littleEndian = dataSet.string("x00020010") !== "1.2.840.10008.1.2.2";
31346
+ const rootCharset = resolveCharsetContext(void 0, options?.charsetAssume, options?.charsetFallback);
31347
+ if (!rootCharset.ok) {
31348
+ return err(rootCharset.error);
31349
+ }
31350
+ const data = {};
31351
+ const stack = [{ src: dataSet, out: data, parentCharset: rootCharset.value }];
31352
+ let processed = 0;
31353
+ while (stack.length > 0) {
31354
+ processed++;
31355
+ if (processed > MAX_DATASETS) {
31356
+ return err(new Error(`Failed to parse DICOM data: more than ${String(MAX_DATASETS)} nested datasets`));
31357
+ }
31358
+ const unit = stack.pop();
31359
+ if (unit === void 0) break;
31360
+ const converted = convertDataset(unit, stack, littleEndian, options);
31361
+ if (!converted.ok) {
31362
+ return err(converted.error);
31363
+ }
31364
+ }
31365
+ return ok({ data, warnings: dataSet.warnings });
31366
+ }
31367
+
31368
+ // src/tools/dicom2json.ts
31369
+ var Dicom2jsonOptionsSchema = zod.z.object({
31370
+ timeoutMs: zod.z.number().int().positive().optional(),
31371
+ signal: zod.z.instanceof(AbortSignal).optional(),
31372
+ charsetAssume: zod.z.string().min(1).optional(),
31373
+ charsetFallback: zod.z.string().min(1).optional(),
31374
+ dcmtkFallback: zod.z.boolean().optional()
31375
+ }).strict().optional();
31376
+ zod.z.object({
31377
+ charsetAssume: zod.z.string().min(1).optional(),
31378
+ charsetFallback: zod.z.string().min(1).optional()
31379
+ }).strict().optional();
31380
+ async function readFileBounded(inputPath, timeoutMs, signal) {
31381
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
31382
+ const combined = signal !== void 0 ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
31383
+ try {
31384
+ return ok(await promises.readFile(inputPath, { signal: combined }));
31385
+ } catch (error) {
31386
+ if (timeoutSignal.aborted) {
31387
+ return err(new Error(`dicom2json: reading '${inputPath}' timed out after ${String(timeoutMs)}ms`));
31388
+ }
31389
+ if (signal?.aborted === true) {
31390
+ return err(new Error(`dicom2json: aborted while reading '${inputPath}'`));
31391
+ }
31392
+ const message = error instanceof Error ? error.message : String(error);
31393
+ return err(new Error(`dicom2json: failed to read '${inputPath}': ${message}`));
31394
+ }
31395
+ }
31396
+ async function runDcmtkFallback(inputPath, jsError, remainingMs, options) {
31397
+ if (remainingMs <= 0) {
31398
+ return err(new Error(`dicom2json: JS parse failed and timeout budget exhausted (skipping DCMTK fallback) | js: ${jsError.message}`));
31399
+ }
31400
+ const fallback = await dcm2json(inputPath, {
31401
+ timeoutMs: remainingMs,
31402
+ signal: options?.signal,
31403
+ charsetAssume: options?.charsetAssume,
31404
+ charsetFallback: options?.charsetFallback
31405
+ });
31406
+ if (!fallback.ok) {
31407
+ return err(new Error(`dicom2json: both engines failed | js: ${jsError.message} | dcmtk: ${fallback.error.message}`));
31408
+ }
31409
+ return ok({ data: fallback.value.data, warnings: [], source: fallback.value.source });
31410
+ }
31411
+ async function dicom2json(inputPath, options) {
31412
+ const validation = Dicom2jsonOptionsSchema.safeParse(options);
31413
+ if (!validation.success) {
31414
+ return err(createValidationError("dicom2json", validation.error));
31415
+ }
31416
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
31417
+ const startTime = Date.now();
31418
+ const parsed = await parseFromFile(inputPath, timeoutMs, options);
31419
+ if (parsed.ok) {
31420
+ return parsed;
31421
+ }
31422
+ if (options?.dcmtkFallback === true) {
31423
+ return runDcmtkFallback(inputPath, parsed.error, timeoutMs - (Date.now() - startTime), options);
31424
+ }
31425
+ return err(parsed.error);
31426
+ }
31427
+ async function parseFromFile(inputPath, timeoutMs, options) {
31428
+ const fileResult = await readFileBounded(inputPath, timeoutMs, options?.signal);
31429
+ if (!fileResult.ok) {
31430
+ return err(fileResult.error);
31431
+ }
31432
+ const parsed = parseDicomBuffer(fileResult.value, { charsetAssume: options?.charsetAssume, charsetFallback: options?.charsetFallback });
31433
+ if (!parsed.ok) {
31434
+ return err(parsed.error);
31435
+ }
31436
+ return ok({ data: parsed.value.data, warnings: parsed.value.warnings, source: "js" });
30908
31437
  }
30909
31438
  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+\])?$/;
30910
31439
  var TagModificationSchema = zod.z.object({
@@ -31011,6 +31540,17 @@ async function unlinkFile(path) {
31011
31540
  }
31012
31541
 
31013
31542
  // src/dicom/DicomInstance.ts
31543
+ async function readDicomJson(path, options) {
31544
+ const shared = {
31545
+ timeoutMs: options?.timeoutMs ?? DEFAULT_TIMEOUT_MS,
31546
+ signal: options?.signal,
31547
+ charsetAssume: options?.charsetAssume,
31548
+ charsetFallback: options?.charsetFallback
31549
+ };
31550
+ const result = options?.engine === "dcmtk" ? await dcm2json(path, shared) : await dicom2json(path, { ...shared, dcmtkFallback: true });
31551
+ if (!result.ok) return err(result.error);
31552
+ return ok(result.value.data);
31553
+ }
31014
31554
  var DicomInstance = class _DicomInstance {
31015
31555
  constructor(dataset, changes, filePath, metadata) {
31016
31556
  __publicField(this, "dicomDataset");
@@ -31035,14 +31575,9 @@ var DicomInstance = class _DicomInstance {
31035
31575
  static async open(path, options) {
31036
31576
  const filePathResult = createDicomFilePath(path);
31037
31577
  if (!filePathResult.ok) return err(filePathResult.error);
31038
- const jsonResult = await dcm2json(path, {
31039
- timeoutMs: options?.timeoutMs ?? DEFAULT_TIMEOUT_MS,
31040
- signal: options?.signal,
31041
- charsetAssume: options?.charsetAssume,
31042
- charsetFallback: options?.charsetFallback
31043
- });
31578
+ const jsonResult = await readDicomJson(path, options);
31044
31579
  if (!jsonResult.ok) return err(jsonResult.error);
31045
- const datasetResult = DicomDataset.fromJson(jsonResult.value.data);
31580
+ const datasetResult = DicomDataset.fromJson(jsonResult.value);
31046
31581
  if (!datasetResult.ok) return err(datasetResult.error);
31047
31582
  return ok(new _DicomInstance(datasetResult.value, ChangeSet.empty(), filePathResult.value, /* @__PURE__ */ new Map()));
31048
31583
  }