@ubercode/dcmtk 0.8.1 → 0.9.0

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.cjs CHANGED
@@ -7,10 +7,11 @@ var child_process = require('child_process');
7
7
  var kill = require('tree-kill');
8
8
  var events = require('events');
9
9
  var stderrLib = require('stderr-lib');
10
- var fastXmlParser = require('fast-xml-parser');
11
10
  var fs = require('fs/promises');
12
- var net = require('net');
13
11
  var os = require('os');
12
+ var fastXmlParser = require('fast-xml-parser');
13
+ var net = require('net');
14
+ var crypto = require('crypto');
14
15
 
15
16
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
17
 
@@ -35,8 +36,8 @@ function _interopNamespace(e) {
35
36
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
36
37
  var kill__default = /*#__PURE__*/_interopDefault(kill);
37
38
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
38
- var net__namespace = /*#__PURE__*/_interopNamespace(net);
39
39
  var os__namespace = /*#__PURE__*/_interopNamespace(os);
40
+ var net__namespace = /*#__PURE__*/_interopNamespace(net);
40
41
 
41
42
  var __defProp = Object.defineProperty;
42
43
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -31501,13 +31502,26 @@ async function tryDirectPath(inputPath, timeoutMs, signal, verbosity) {
31501
31502
  if (!jsonBinary.ok) {
31502
31503
  return err(jsonBinary.error);
31503
31504
  }
31504
- const directArgs = [...buildVerbosityArgs(verbosity), inputPath];
31505
- const result = await execCommand(jsonBinary.value, directArgs, { timeoutMs, signal });
31505
+ const bulkDir = await createBulkTempDir();
31506
+ const directArgs = [...buildVerbosityArgs(verbosity), "+b", "+bd", bulkDir, inputPath];
31507
+ try {
31508
+ const execOpts = signal !== void 0 ? { timeoutMs, signal } : { timeoutMs };
31509
+ return await execAndParse(jsonBinary.value, directArgs, inputPath, execOpts);
31510
+ } finally {
31511
+ fs.rm(bulkDir, { recursive: true, force: true }).catch(() => {
31512
+ });
31513
+ }
31514
+ }
31515
+ async function createBulkTempDir() {
31516
+ return fs.mkdtemp(path.join(os.tmpdir(), "dcm2json-bulk-"));
31517
+ }
31518
+ async function execAndParse(binary, args, inputPath, execOpts) {
31519
+ const result = await execCommand(binary, args, execOpts);
31506
31520
  if (!result.ok) {
31507
31521
  return err(result.error);
31508
31522
  }
31509
31523
  if (result.value.exitCode !== 0) {
31510
- return err(createToolError("dcm2json", directArgs, result.value.exitCode, result.value.stderr));
31524
+ return err(createToolError("dcm2json", args, result.value.exitCode, result.value.stderr));
31511
31525
  }
31512
31526
  try {
31513
31527
  const repaired = repairJson(result.value.stdout);
@@ -36881,8 +36895,8 @@ async function moveFile(src, dest) {
36881
36895
  }
36882
36896
  async function statFileSafe(filePath) {
36883
36897
  try {
36884
- const stat3 = await fs__namespace.stat(filePath);
36885
- return stat3.size;
36898
+ const stat4 = await fs__namespace.stat(filePath);
36899
+ return stat4.size;
36886
36900
  } catch {
36887
36901
  return 0;
36888
36902
  }
@@ -38293,6 +38307,341 @@ async function batch(items, operation, options) {
38293
38307
  return { results: state.results, succeeded: state.succeeded, failed: state.failed };
38294
38308
  }
38295
38309
 
38310
+ // src/testing/types.ts
38311
+ var HammerPhase = {
38312
+ /** File generation phase (copy + modify). */
38313
+ GENERATE: "generate",
38314
+ /** File sending phase (dcmsend). */
38315
+ SEND: "send"
38316
+ };
38317
+
38318
+ // src/testing/DicomHammer.ts
38319
+ var DEFAULT_FILE_COUNT = 100;
38320
+ var MAX_FILE_COUNT = 1e5;
38321
+ var DEFAULT_CONCURRENCY2 = 4;
38322
+ var MAX_CONCURRENCY2 = 64;
38323
+ var DEFAULT_CALLING_AE = "HAMMER";
38324
+ var DEFAULT_CALLED_AE = "ANY-SCP";
38325
+ var DICOM_UID_ROOT = "2.25.";
38326
+ var DicomHammerOptionsSchema = zod.z.object({
38327
+ sourceFile: zod.z.string().min(1),
38328
+ host: zod.z.string().min(1),
38329
+ port: zod.z.number().int().min(1).max(65535),
38330
+ callingAETitle: zod.z.string().min(1).max(16).refine(isValidAETitle, { message: "AE Title contains invalid characters" }).optional(),
38331
+ calledAETitle: zod.z.string().min(1).max(16).refine(isValidAETitle, { message: "AE Title contains invalid characters" }).optional(),
38332
+ fileCount: zod.z.number().int().min(1).max(MAX_FILE_COUNT).optional(),
38333
+ concurrency: zod.z.number().int().min(1).max(MAX_CONCURRENCY2).optional(),
38334
+ delayMs: zod.z.number().int().min(0).optional(),
38335
+ institution: zod.z.string().min(1).optional(),
38336
+ erasePrivateTags: zod.z.boolean().optional(),
38337
+ modifications: zod.z.array(zod.z.object({ tag: zod.z.string().min(1), value: zod.z.string() })).optional(),
38338
+ timeoutMs: zod.z.number().int().positive().optional(),
38339
+ signal: zod.z.instanceof(AbortSignal).optional(),
38340
+ outputDir: zod.z.string().min(1).optional(),
38341
+ noHalt: zod.z.boolean().optional()
38342
+ }).strict();
38343
+ function resolveNetworkOptions(options) {
38344
+ return {
38345
+ host: options.host,
38346
+ port: options.port,
38347
+ callingAETitle: options.callingAETitle ?? DEFAULT_CALLING_AE,
38348
+ calledAETitle: options.calledAETitle ?? DEFAULT_CALLED_AE,
38349
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
38350
+ noHalt: options.noHalt ?? true
38351
+ };
38352
+ }
38353
+ function resolveOptions(options) {
38354
+ return {
38355
+ sourceFile: options.sourceFile,
38356
+ ...resolveNetworkOptions(options),
38357
+ fileCount: options.fileCount ?? DEFAULT_FILE_COUNT,
38358
+ concurrency: options.concurrency ?? DEFAULT_CONCURRENCY2,
38359
+ delayMs: options.delayMs ?? 0,
38360
+ institution: options.institution,
38361
+ erasePrivateTags: options.erasePrivateTags ?? false,
38362
+ modifications: options.modifications ?? [],
38363
+ signal: options.signal,
38364
+ outputDir: options.outputDir ?? os.tmpdir()
38365
+ };
38366
+ }
38367
+ function generateUid() {
38368
+ const hex = crypto.randomUUID().replace(/-/g, "");
38369
+ const decimal = BigInt("0x" + hex).toString(10);
38370
+ return DICOM_UID_ROOT + decimal;
38371
+ }
38372
+ function formatDate() {
38373
+ const d = /* @__PURE__ */ new Date();
38374
+ const yyyy = String(d.getFullYear());
38375
+ const mm = String(d.getMonth() + 1).padStart(2, "0");
38376
+ const dd = String(d.getDate()).padStart(2, "0");
38377
+ return yyyy + mm + dd;
38378
+ }
38379
+ function buildModifications(index, opts) {
38380
+ const mods = [
38381
+ { tag: "(0020,000D)", value: generateUid() },
38382
+ { tag: "(0020,000E)", value: generateUid() },
38383
+ { tag: "(0008,0018)", value: generateUid() },
38384
+ { tag: "(0008,0020)", value: formatDate() },
38385
+ { tag: "(0008,0050)", value: `HAMMER-${String(index + 1).padStart(6, "0")}` }
38386
+ ];
38387
+ if (opts.institution !== void 0) {
38388
+ mods.push({ tag: "(0008,0080)", value: opts.institution });
38389
+ }
38390
+ for (const mod of opts.modifications) {
38391
+ mods.push({ tag: mod.tag, value: mod.value });
38392
+ }
38393
+ return mods;
38394
+ }
38395
+ function computeThroughput(succeeded, totalBytes, durationMs) {
38396
+ const durationSec = durationMs / 1e3;
38397
+ return {
38398
+ filesPerSec: durationSec > 0 ? succeeded / durationSec : 0,
38399
+ bytesPerSec: durationSec > 0 ? totalBytes / durationSec : 0
38400
+ };
38401
+ }
38402
+ function delay3(ms) {
38403
+ return new Promise((resolve) => {
38404
+ setTimeout(resolve, ms);
38405
+ });
38406
+ }
38407
+ var DicomHammer = class _DicomHammer extends events.EventEmitter {
38408
+ constructor(options) {
38409
+ super();
38410
+ __publicField(this, "opts");
38411
+ __publicField(this, "generatedDir");
38412
+ __publicField(this, "generatedFiles", []);
38413
+ this.opts = options;
38414
+ this.setMaxListeners(20);
38415
+ }
38416
+ // -----------------------------------------------------------------------
38417
+ // Factory
38418
+ // -----------------------------------------------------------------------
38419
+ /**
38420
+ * Creates a DicomHammer instance.
38421
+ *
38422
+ * @param options - Configuration for file generation and sending
38423
+ * @returns A Result containing the DicomHammer or a validation error
38424
+ */
38425
+ static create(options) {
38426
+ const validation = DicomHammerOptionsSchema.safeParse(options);
38427
+ if (!validation.success) {
38428
+ return err(createValidationError("DicomHammer", validation.error));
38429
+ }
38430
+ return ok(new _DicomHammer(resolveOptions(options)));
38431
+ }
38432
+ // -----------------------------------------------------------------------
38433
+ // Generate phase
38434
+ // -----------------------------------------------------------------------
38435
+ /**
38436
+ * Generates modified copies of the source DICOM file.
38437
+ *
38438
+ * Each copy receives unique Study/Series/SOP Instance UIDs, a unique
38439
+ * accession number, and any custom modifications.
38440
+ */
38441
+ async generate() {
38442
+ const start = Date.now();
38443
+ const dir = path.join(this.opts.outputDir, `dcmtk-hammer-${Date.now()}`);
38444
+ try {
38445
+ await fs.mkdir(dir, { recursive: true });
38446
+ } catch {
38447
+ return err(new Error(`Failed to create output directory: ${dir}`));
38448
+ }
38449
+ this.generatedDir = dir;
38450
+ const indices = Array.from({ length: this.opts.fileCount }, (_, i) => i);
38451
+ const total = this.opts.fileCount;
38452
+ let completedCount = 0;
38453
+ const result = await batch(
38454
+ indices,
38455
+ async (index) => {
38456
+ return this.generateOneFile(index, dir);
38457
+ },
38458
+ {
38459
+ concurrency: this.opts.concurrency,
38460
+ signal: this.opts.signal,
38461
+ onProgress: (_completed, _total, fileResult) => {
38462
+ completedCount++;
38463
+ if (fileResult.ok) {
38464
+ this.emit("FILE_GENERATED", { index: completedCount - 1, total, filePath: fileResult.value });
38465
+ }
38466
+ this.emitProgress(HammerPhase.GENERATE, completedCount, total);
38467
+ }
38468
+ }
38469
+ );
38470
+ const files = result.results.filter((r) => r.ok).map((r) => r.value);
38471
+ this.generatedFiles = files;
38472
+ if (files.length === 0) {
38473
+ return err(new Error(`All ${total} file generations failed`));
38474
+ }
38475
+ return ok({ files, durationMs: Date.now() - start, outputDir: dir });
38476
+ }
38477
+ /** Generates a single modified copy. Extracted for function size compliance. */
38478
+ async generateOneFile(index, dir) {
38479
+ const padded = String(index + 1).padStart(6, "0");
38480
+ const dest = path.join(dir, `hammer_${padded}.dcm`);
38481
+ const copyResult = await copyFileSafe(this.opts.sourceFile, dest);
38482
+ if (!copyResult.ok) return err(copyResult.error);
38483
+ const modResult = await dcmodify(dest, {
38484
+ modifications: buildModifications(index, this.opts),
38485
+ erasePrivateTags: this.opts.erasePrivateTags || void 0,
38486
+ insertIfMissing: true,
38487
+ noBackup: true,
38488
+ timeoutMs: this.opts.timeoutMs,
38489
+ signal: this.opts.signal
38490
+ });
38491
+ if (!modResult.ok) return err(modResult.error);
38492
+ return ok(dest);
38493
+ }
38494
+ // -----------------------------------------------------------------------
38495
+ // Send phase
38496
+ // -----------------------------------------------------------------------
38497
+ /**
38498
+ * Sends files to the target SCP.
38499
+ *
38500
+ * @param files - Files to send. Defaults to previously generated files.
38501
+ */
38502
+ async send(files) {
38503
+ const filesToSend = files ?? this.generatedFiles;
38504
+ if (filesToSend.length === 0) {
38505
+ return err(new Error("No files to send. Call generate() first or provide files."));
38506
+ }
38507
+ const fileSize = await this.getFileSize(filesToSend[0]);
38508
+ const start = Date.now();
38509
+ const total = filesToSend.length;
38510
+ const tracker = { errors: [], completedCount: 0, succeeded: 0 };
38511
+ await batch([...filesToSend], async (file) => this.sendOneFile(file), {
38512
+ concurrency: this.opts.concurrency,
38513
+ signal: this.opts.signal,
38514
+ onProgress: (_c, _t, sendResult) => this.trackSendProgress(sendResult, filesToSend, total, tracker)
38515
+ });
38516
+ return ok(this.buildSendResult(tracker, total, fileSize, Date.now() - start));
38517
+ }
38518
+ /** Tracks a single send result for progress reporting. */
38519
+ trackSendProgress(sendResult, files, total, tracker) {
38520
+ tracker.completedCount++;
38521
+ const file = files[tracker.completedCount - 1];
38522
+ if (sendResult.ok) {
38523
+ tracker.succeeded++;
38524
+ this.emit("SEND_COMPLETE", { index: tracker.completedCount - 1, total, file, durationMs: 0 });
38525
+ } else {
38526
+ tracker.errors.push({ file, error: sendResult.error });
38527
+ this.emit("SEND_FAILED", { index: tracker.completedCount - 1, total, file, error: sendResult.error });
38528
+ }
38529
+ this.emitProgress(HammerPhase.SEND, tracker.completedCount, total);
38530
+ }
38531
+ /** Assembles the final HammerSendResult. */
38532
+ buildSendResult(tracker, total, fileSize, durationMs) {
38533
+ const totalBytes = tracker.succeeded * fileSize;
38534
+ const throughput = computeThroughput(tracker.succeeded, totalBytes, durationMs);
38535
+ return {
38536
+ succeeded: tracker.succeeded,
38537
+ failed: tracker.errors.length,
38538
+ totalFiles: total,
38539
+ durationMs,
38540
+ filesPerSec: throughput.filesPerSec,
38541
+ bytesPerSec: throughput.bytesPerSec,
38542
+ totalBytes,
38543
+ errors: tracker.errors
38544
+ };
38545
+ }
38546
+ /** Sends a single file, with optional delay. */
38547
+ async sendOneFile(file) {
38548
+ if (this.opts.delayMs > 0) {
38549
+ await delay3(this.opts.delayMs);
38550
+ }
38551
+ const result = await dcmsend({
38552
+ host: this.opts.host,
38553
+ port: this.opts.port,
38554
+ files: [file],
38555
+ callingAETitle: this.opts.callingAETitle,
38556
+ calledAETitle: this.opts.calledAETitle,
38557
+ noHalt: this.opts.noHalt || void 0,
38558
+ timeoutMs: this.opts.timeoutMs,
38559
+ signal: this.opts.signal
38560
+ });
38561
+ if (!result.ok) return err(result.error);
38562
+ return ok(void 0);
38563
+ }
38564
+ /** Gets the file size in bytes, returning 0 on error. */
38565
+ async getFileSize(filePath) {
38566
+ try {
38567
+ const s = await fs.stat(filePath);
38568
+ return s.size;
38569
+ } catch {
38570
+ return 0;
38571
+ }
38572
+ }
38573
+ // -----------------------------------------------------------------------
38574
+ // Combined run
38575
+ // -----------------------------------------------------------------------
38576
+ /**
38577
+ * Generates files and sends them in one call.
38578
+ *
38579
+ * @returns Combined result with timing for both phases
38580
+ */
38581
+ async run() {
38582
+ const genResult = await this.generate();
38583
+ if (!genResult.ok) return err(genResult.error);
38584
+ const sendResult = await this.send(genResult.value.files);
38585
+ if (!sendResult.ok) return err(sendResult.error);
38586
+ const result = {
38587
+ succeeded: sendResult.value.succeeded,
38588
+ failed: sendResult.value.failed,
38589
+ totalFiles: sendResult.value.totalFiles,
38590
+ durationMs: genResult.value.durationMs + sendResult.value.durationMs,
38591
+ generateDurationMs: genResult.value.durationMs,
38592
+ sendDurationMs: sendResult.value.durationMs,
38593
+ filesPerSec: sendResult.value.filesPerSec,
38594
+ bytesPerSec: sendResult.value.bytesPerSec,
38595
+ totalBytes: sendResult.value.totalBytes,
38596
+ errors: sendResult.value.errors
38597
+ };
38598
+ this.emit("RUN_COMPLETE", result);
38599
+ return ok(result);
38600
+ }
38601
+ // -----------------------------------------------------------------------
38602
+ // Cleanup
38603
+ // -----------------------------------------------------------------------
38604
+ /** Removes all generated files and the output directory. */
38605
+ async cleanup() {
38606
+ if (this.generatedDir === void 0) return ok(void 0);
38607
+ try {
38608
+ await fs.rm(this.generatedDir, { recursive: true, force: true });
38609
+ this.generatedDir = void 0;
38610
+ this.generatedFiles = [];
38611
+ return ok(void 0);
38612
+ } catch {
38613
+ return err(new Error(`Failed to cleanup: ${this.generatedDir}`));
38614
+ }
38615
+ }
38616
+ // -----------------------------------------------------------------------
38617
+ // Event helpers
38618
+ // -----------------------------------------------------------------------
38619
+ /** Emits a PROGRESS event. */
38620
+ emitProgress(phase, completed, total) {
38621
+ this.emit("PROGRESS", { phase, completed, total, percent: Math.round(completed / total * 100) });
38622
+ }
38623
+ /** Registers a listener for FILE_GENERATED events. */
38624
+ onFileGenerated(listener) {
38625
+ return this.on("FILE_GENERATED", listener);
38626
+ }
38627
+ /** Registers a listener for SEND_COMPLETE events. */
38628
+ onSendComplete(listener) {
38629
+ return this.on("SEND_COMPLETE", listener);
38630
+ }
38631
+ /** Registers a listener for SEND_FAILED events. */
38632
+ onSendFailed(listener) {
38633
+ return this.on("SEND_FAILED", listener);
38634
+ }
38635
+ /** Registers a listener for PROGRESS events. */
38636
+ onProgress(listener) {
38637
+ return this.on("PROGRESS", listener);
38638
+ }
38639
+ /** Registers a listener for RUN_COMPLETE events. */
38640
+ onRunComplete(listener) {
38641
+ return this.on("RUN_COMPLETE", listener);
38642
+ }
38643
+ };
38644
+
38296
38645
  // src/utils/retry.ts
38297
38646
  var DEFAULT_MAX_ATTEMPTS = 3;
38298
38647
  var DEFAULT_INITIAL_DELAY_MS = 1e3;
@@ -38399,6 +38748,7 @@ exports.Dcmrecv = Dcmrecv;
38399
38748
  exports.DcmrecvEvent = DcmrecvEvent;
38400
38749
  exports.DcmtkProcess = DcmtkProcess;
38401
38750
  exports.DicomDataset = DicomDataset;
38751
+ exports.DicomHammer = DicomHammer;
38402
38752
  exports.DicomInstance = DicomInstance;
38403
38753
  exports.DicomReceiver = DicomReceiver;
38404
38754
  exports.DicomSend = DicomSend;
@@ -38407,6 +38757,7 @@ exports.DicomTagPathSchema = DicomTagPathSchema;
38407
38757
  exports.DicomTagSchema = DicomTagSchema;
38408
38758
  exports.FilenameMode = FilenameMode;
38409
38759
  exports.GetQueryModel = GetQueryModel;
38760
+ exports.HammerPhase = HammerPhase;
38410
38761
  exports.Img2dcmInputFormat = Img2dcmInputFormat;
38411
38762
  exports.JplsColorConversion = JplsColorConversion;
38412
38763
  exports.LineParser = LineParser;