UNPKG

dcmjs-dimse

Version:

DICOM DIMSE implementation for Node.js using dcmjs

2 lines 86.6 kB
/*! dcmjs-dimse - 0.2.7 - 2025-05-23 | (c) 2021-2025 Pantelis Georgiadis | https://github.com/PantelisGeorgiadis/dcmjs-dimse */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("dcmjs"),require("memorystream"),require("loglevel"),require("ts-mixer"),require("dcmjs-codecs"),require("loglevel-plugin-prefix"),require("async-eventemitter"),require("smart-buffer")):"function"==typeof define&&define.amd?define("dcmjs-dimse",["dcmjs","memorystream","loglevel","ts-mixer","dcmjs-codecs","loglevel-plugin-prefix","async-eventemitter","smart-buffer"],t):"object"==typeof exports?exports["dcmjs-dimse"]=t(require("dcmjs"),require("memorystream"),require("loglevel"),require("ts-mixer"),require("dcmjs-codecs"),require("loglevel-plugin-prefix"),require("async-eventemitter"),require("smart-buffer")):e["dcmjs-dimse"]=t(e.dcmjs,e.memorystream,e.loglevel,e["ts-mixer"],e["dcmjs-codecs"],e["loglevel-plugin-prefix"],e["async-eventemitter"],e["smart-buffer"])}(global,((e,t,s,n,i,r,a,o)=>{return c={73:(e,t,s)=>{const{NativeCodecs:n,Transcoder:i}=s(593),{TranscodableTransferSyntaxes:r,TransferSyntax:a}=s(492),o=s(825),c=s(547);e.exports=class{static async initializeAsync(e={}){await n.initializeAsync(e)}static release(){n.release()}static transcodeDataset(e,t,s={}){if(e.getTransferSyntaxUid()===t)return e;if(t!==a.ImplicitVRLittleEndian&&t!==a.ExplicitVRLittleEndian&&t!==a.ExplicitVRBigEndian&&!0!==n.isInitialized())throw new Error("Transcoding is not initialized. Please call Transcoding.initializeAsync() first.");if(!r.includes(e.getTransferSyntaxUid())||!r.includes(t))throw new Error(`Transcoding dataset from ${this._transferSyntaxDescriptionFromValue(e.getTransferSyntaxUid())} to ${this._transferSyntaxDescriptionFromValue(t)} is not supported.`);c.info(`Transcoding dataset from ${this._transferSyntaxDescriptionFromValue(e.getTransferSyntaxUid())} to ${this._transferSyntaxDescriptionFromValue(t)}...`);const d=new i(e.getElements(),e.getTransferSyntaxUid());return d.transcode(t,s),new o(d.getElements(),d.getTransferSyntaxUid())}static _transferSyntaxDescriptionFromValue(e){const t=Object.keys(a).find((t=>a[t]===e));return t?`${t} (${e})`:e}}},111:t=>{"use strict";t.exports=e},139:(e,t,s)=>{const{DefaultImplementation:n}=s(492);e.exports=class{static getImplementationClassUid(){return this.implementationClassUid||n.ImplementationClassUid}static setImplementationClassUid(e){this.implementationClassUid=e}static getImplementationVersion(){return this.implementationVersion||n.ImplementationVersion}static setImplementationVersion(e){if("string"!=typeof e||e.length>16)throw new Error("Implementation version should be a string with less than 16 characters");this.implementationVersion=e}static getMaxPduLength(){return this.maxPduLength||n.MaxPduLength}static setMaxPduLength(e){this.maxPduLength=e}}},235:e=>{"use strict";e.exports=t},237:(e,t,s)=>{const{Association:n,PresentationContext:i}=s(570),{Scp:r,Server:a}=s(538),{CCancelRequest:o,CEchoRequest:c,CEchoResponse:d,CFindRequest:u,CFindResponse:h,CGetRequest:m,CGetResponse:g,CMoveRequest:l,CMoveResponse:p,CStoreRequest:R,CStoreResponse:S,NActionRequest:y,NActionResponse:f,NCreateRequest:I,NCreateResponse:C,NDeleteRequest:P,NDeleteResponse:A,NEventReportRequest:v,NEventReportResponse:x,NGetRequest:w,NGetResponse:U,NSetRequest:q,NSetResponse:D}=s(940),{AbortReason:E,AbortSource:T,CommandFieldType:b,PresentationContextResult:O,Priority:N,RawPduType:M,RejectReason:B,RejectResult:L,RejectSource:F,SopClass:k,Status:$,StorageClass:j,TransferSyntax:V,Uid:_,UserIdentityType:G}=s(492),z=s(422),Q=s(825),W=s(139),J=s(906),X=s(73),H={association:{Association:n,PresentationContext:i},Client:z,constants:{AbortReason:E,AbortSource:T,CommandFieldType:b,PresentationContextResult:O,Priority:N,RawPduType:M,RejectReason:B,RejectResult:L,RejectSource:F,SopClass:k,Status:$,StorageClass:j,TransferSyntax:V,Uid:_,UserIdentityType:G},Dataset:Q,Implementation:W,log:s(547),requests:{CCancelRequest:o,CEchoRequest:c,CFindRequest:u,CGetRequest:m,CMoveRequest:l,CStoreRequest:R,NActionRequest:y,NCreateRequest:I,NDeleteRequest:P,NEventReportRequest:v,NGetRequest:w,NSetRequest:q},responses:{CEchoResponse:d,CFindResponse:h,CGetResponse:g,CMoveResponse:p,CStoreResponse:S,NActionResponse:f,NCreateResponse:C,NDeleteResponse:A,NEventReportResponse:x,NGetResponse:U,NSetResponse:D},Scp:r,Server:a,Statistics:J,Transcoding:X,version:s(837)};e.exports=H},278:e=>{"use strict";e.exports=require("net")},360:e=>{"use strict";e.exports=s},371:(e,t,s)=>{const{Association:n}=s(570),{AAbort:i,AAssociateAC:r,AAssociateRJ:a,AAssociateRQ:o,AReleaseRP:c,AReleaseRQ:d,PDataTF:u,Pdv:h,RawPdu:m}=s(942),{CommandFieldType:g,RawPduType:l,Status:p}=s(492),{CCancelRequest:R,CEchoRequest:S,CEchoResponse:y,CFindRequest:f,CFindResponse:I,CGetRequest:C,CGetResponse:P,CMoveRequest:A,CMoveResponse:v,Command:x,CStoreRequest:w,CStoreResponse:U,NActionRequest:q,NActionResponse:D,NCreateRequest:E,NCreateResponse:T,NDeleteRequest:b,NDeleteResponse:O,NEventReportRequest:N,NEventReportResponse:M,NGetRequest:B,NGetResponse:L,NSetRequest:F,NSetResponse:k,Response:$}=s(940),j=s(825),V=s(139),_=s(906),G=s(73),z=s(547),{SmartBuffer:Q}=s(766),{EOL:W}=s(857),J=s(733),X=s(235);class H extends J{constructor(){super()}accumulate(e){do{e=this._process(e)}while(void 0!==e)}_process(e){if(void 0===this.receiving){if(this.minimumReceived&&(e=Buffer.concat([this.minimumReceived,e],this.minimumReceived.length+e.length),this.minimumReceived=void 0),e.length<6)return void(this.minimumReceived=e);const t=Q.fromBuffer(e,"ascii"),s=t.readUInt8();if(s!==l.AAssociateRQ&&s!==l.AAssociateAC&&s!==l.AAssociateRJ&&s!==l.PDataTF&&s!==l.AReleaseRQ&&s!==l.AReleaseRP&&s!==l.AAbort)return void this.emit("error",new Error(`Unknown PDU type: ${s}`));t.readUInt8();const n=t.readUInt32BE();let i=e.length-6;if(n>i)this.receiving=e,this.receivedLength=n;else{let t,s=e;if(n<i&&(s=e.slice(0,n+6),t=e.slice(n+6,i+6)),this.receiving=void 0,this.receivedLength=void 0,this.emit("pdu",s),t)return t}}else{let t=Buffer.concat([this.receiving,e],this.receiving.length+e.length);const s=t.length-6;if(s<this.receivedLength)this.receiving=t;else{let e;if(s>this.receivedLength&&(e=t.slice(this.receivedLength+6,s+6),t=t.slice(0,this.receivedLength+6)),this.receiving=void 0,this.receivedLength=void 0,this.emit("pdu",t),e)return e}}}}e.exports=class extends J{constructor(e,t){super(),this.messageId=0,this.socket=e,this.requests=[],this.pending=[],this.dimseStream=void 0,this.dimseStoreStream=void 0,this.dimse=void 0,t=t||{},this.connectTimeout=t.connectTimeout||18e4,this.associationTimeout=t.associationTimeout||6e4,this.pduTimeout=t.pduTimeout||6e4,this.logCommandDatasets=t.logCommandDatasets||!1,this.logDatasets=t.logDatasets||!1,this.datasetReadOptions=t.datasetReadOptions||{},this.datasetWriteOptions=t.datasetWriteOptions||{},this.datasetNameMap=t.datasetNameMap||{},this.datasetTranscodeOptions=t.datasetTranscodeOptions||{},this.logId="",this.connected=!1,this.connectedTime=void 0,this.lastPduTime=void 0,this.timeoutIntervalId=void 0,this.statistics=new _,this._wrapSocket()}sendAssociationRequest(e){this.association=e;const t=new o(this.association).write();this.logId=this.association.getCalledAeTitle(),z.info(`${this.logId} -> Association request:${W}${this.association.toString()}`),this._sendPdu(t)}sendAssociationAccept(){this.association.setImplementationClassUid(V.getImplementationClassUid()),this.association.setImplementationVersion(V.getImplementationVersion()),this.association.setMaxPduLength(Math.min(this.association.getMaxPduLength(),V.getMaxPduLength()));const e=new r(this.association).write();z.info(`${this.logId} -> Association accept:${W}${this.association.toString()}`),this._sendPdu(e)}sendAssociationReject(e,t,s){const n=new a(e,t,s),i=n.write();z.info(`${this.logId} -> Association reject ${n.toString()}`),this._sendPdu(i)}sendAssociationReleaseRequest(){const e=(new d).write();z.info(`${this.logId} -> Association release request`),this._sendPdu(e)}sendAssociationReleaseResponse(){const e=(new c).write();z.info(`${this.logId} -> Association release response`),this._sendPdu(e)}sendRequests(e){const t=Array.isArray(e)?e:[e];this.requests.push(...t),this._sendNextRequests()}sendResponse(e,t){const s=this.association.getAcceptedPresentationContextFromRequest(e);if(!s)return void z.error(`Could not find an accepted presentation context for request ${e.toString()}. Skipping...`);const n={context:s,command:t};this._sendDimse(n)}sendCancel(e){if(!this.association)return void z.error(`There is no association in which to cancel request ${e.toString()}. Skipping...`);const t=R.fromRequest(e),s=this.association.getAcceptedPresentationContextFromRequest(t);if(!s)return void z.error(`Could not find an accepted presentation context to cancel request ${e.toString()}. Skipping...`);const n={context:s,command:t};this._sendDimse(n)}sendAbort(e,t){if(!this.association)return void z.error("There is no association to perform abort. Skipping...");const s=new i(e,t),n=s.write();z.info(`${this.logId} -> Abort ${s.toString()}`),this._sendPdu(n)}getStatistics(){return this.statistics}createStoreWritableStream(e,t){return X.createWriteStream()}createDatasetFromStoreWritableStream(e,t,s){s(new j(e.toBuffer(),t.getAcceptedTransferSyntaxUid()))}_getNextMessageId(){return++this.messageId%65536}_sendPdu(e){try{const t=e.writePdu();this.socket.write(t),this.statistics.addBytesSent(t.length)}catch(t){z.error(`${this.logId} -> Error sending PDU [type: ${e.getType()}]: ${t.message}`),this.emit("networkError",t)}}_sendNextRequests(){const e=()=>{const t=this.requests.shift();if(!t)return void this.emit("done");const s=this.association.getAcceptedPresentationContextFromRequest(t);if(s){t instanceof w&&t.loadFullDatasetIfNeeded(),t.setMessageId(this._getNextMessageId()),this.pending.push(t);const n={context:s,command:t};n.command.on("done",(()=>{e()})),this._sendDimse(n)}else z.error(`Could not find an accepted presentation context for request ${t.toString()}. Skipping...`),e()};e()}_sendDimse(e){try{const t=e.command.getDataset(),s=this.association.getPresentationContext(e.context.getPresentationContextId()).getAcceptedTransferSyntaxUid();if(t&&s!==t.getTransferSyntaxUid())try{const n=G.transcodeDataset(t,s,this.datasetTranscodeOptions);e.command.setDataset(n)}catch(t){return z.error(t.message),void e.command.raiseDoneEvent()}this._sendPDataTF(e.command,e.context.getPresentationContextId(),this.association.getMaxPduLength())}catch(e){z.error(`${this.logId} -> Error sending DIMSE: ${e.message}`),this.emit("networkError",e)}}_sendPDataTF(e,t,s){const n=4194304;s=0===s?n:Math.min(s,n);const i=e.getCommandDataset().getDenaturalizedCommandDataset();z.info(`${this.logId} -> ${e.toString({includeCommandDataset:this.logCommandDatasets,includeDataset:this.logDatasets})} [pc: ${t}]`);const r=new u,a=new h(t,i,!0,!0);r.addPdv(a);const o=r.write().writePdu();this.socket.write(o),this.statistics.addBytesSent(o.length);const c=e.getDataset();if(c){const e=c.getDenaturalizedDataset(this.datasetWriteOptions,this.datasetNameMap),n=[],i=e.length,r=s-6;let a=0;for(;a<i;)n.push(e.slice(a,a+=r));for(let e=0;e<n.length;e++){const s=n.length===e+1,i=new h(t,n[e],!1,s),r=new u;r.addPdv(i);const a=r.write().writePdu();this.socket.write(a),this.statistics.addBytesSent(a.length)}}}async _processPdu(e){const t=new m(e);try{switch(t.readPdu(),t.getType()){case l.AAssociateRQ:this.association=new n,new o(this.association).read(t),this.logId=this.association.getCallingAeTitle(),z.info(`${this.logId} <- Association request:${W}${this.association.toString()}`),this.emit("associationRequested",this.association);break;case l.AAssociateAC:new r(this.association).read(t),this.logId=this.association.getCalledAeTitle(),z.info(`${this.logId} <- Association accept:${W}${this.association.toString()}`),this.emit("associationAccepted",this.association);break;case l.AAssociateRJ:{const e=new a;e.read(t),z.info(`${this.logId} <- Association reject ${e.toString()}`),this.emit("associationRejected",{result:e.getResult(),source:e.getSource(),reason:e.getReason()});break}case l.PDataTF:{const e=new u;e.read(t),await this._processPDataTf(e);break}case l.AReleaseRQ:(new d).read(t),z.info(`${this.logId} <- Association release request`),this.emit("associationReleaseRequested");break;case l.AReleaseRP:(new c).read(t),z.info(`${this.logId} <- Association release response`),this.emit("associationReleaseResponse");break;case l.AAbort:{const e=new i;e.read(t),z.info(`${this.logId} <- Association abort ${e.toString()}`),this.emit("abort",{source:e.getSource(),reason:e.getReason()});break}case 255:break;default:throw new Error(`Unknown PDU type: ${t.getType()}`)}}catch(e){z.error(`${this.logId} -> Error reading PDU [type: ${t.getType()}]: ${e.message}`),this.emit("networkError",e)}}async _processPDataTf(e){try{let t;const s=e.getPdvs();for(let e=0;e<s.length;e++){const n=s[e],i=this.association.getPresentationContext(n.getPresentationContextId());if(this.dimse&&this.dimse.getCommandFieldType()===g.CStoreRequest?this.dimseStoreStream||(this.dimseStream=void 0,this.dimseStoreStream=this.createStoreWritableStream(i,this.dimse),t=new Promise((e=>this.dimseStoreStream.once("drain",e)))):this.dimseStream||(this.dimseStream=X.createWriteStream(),this.dimseStoreStream=void 0),!(this.dimseStream||this.dimseStoreStream).write(n.getValue())&&t&&await t,n.isLastFragment())if(n.isCommand()){const e=new x(new j(this.dimseStream.toBuffer()));switch(e.getCommandFieldType()){case g.CEchoRequest:this.dimse=Object.assign(new S,e);break;case g.CEchoResponse:this.dimse=Object.assign(new y,e);break;case g.CFindRequest:this.dimse=Object.assign(new f,e);break;case g.CFindResponse:this.dimse=Object.assign(new I,e);break;case g.CStoreRequest:this.dimse=Object.assign(new w,e);break;case g.CStoreResponse:this.dimse=Object.assign(new U,e);break;case g.CMoveRequest:this.dimse=Object.assign(new A,e);break;case g.CMoveResponse:this.dimse=Object.assign(new v,e);break;case g.CGetRequest:this.dimse=Object.assign(new C,e);break;case g.CGetResponse:this.dimse=Object.assign(new P,e);break;case g.NCreateRequest:this.dimse=Object.assign(new E,e);break;case g.NCreateResponse:this.dimse=Object.assign(new T,e);break;case g.NActionRequest:this.dimse=Object.assign(new q,e);break;case g.NActionResponse:this.dimse=Object.assign(new D,e);break;case g.NDeleteRequest:this.dimse=Object.assign(new b,e);break;case g.NDeleteResponse:this.dimse=Object.assign(new O,e);break;case g.NEventReportRequest:this.dimse=Object.assign(new N,e);break;case g.NEventReportResponse:this.dimse=Object.assign(new M,e);break;case g.NGetRequest:this.dimse=Object.assign(new B,e);break;case g.NGetResponse:this.dimse=Object.assign(new L,e);break;case g.NSetRequest:this.dimse=Object.assign(new F,e);break;case g.NSetResponse:this.dimse=Object.assign(new k,e);break;case g.CCancelRequest:this.dimse=Object.assign(new R,e);break;default:this.dimse=e}if(z.info(`${this.logId} <- ${this.dimse.toString({includeCommandDataset:this.logCommandDatasets,includeDataset:this.logDatasets})} [pc: ${n.getPresentationContextId()}]`),!this.dimse.hasDataset())return this._performDimse(i,this.dimse),void(this.dimse=void 0);this.dimseStream=void 0,this.dimseStoreStream=void 0}else if(this.dimse.getCommandFieldType()===g.CStoreRequest)this.dimseStoreStream.end(),this.createDatasetFromStoreWritableStream(this.dimseStoreStream,i,(e=>{this.dimse.setDataset(e),this._performDimse(i,this.dimse),this.dimseStream=void 0,this.dimseStoreStream=void 0,this.dimse=void 0}));else{this.dimseStream.end();const e=new j(this.dimseStream.toBuffer(),i.getAcceptedTransferSyntaxUid(),this.datasetReadOptions);this.dimse.setDataset(e),this._performDimse(i,this.dimse),this.dimseStream=void 0,this.dimseStoreStream=void 0,this.dimse=void 0}}}catch(e){z.error(`${this.logId} -> Error reading DIMSE: ${e.message}`),this.emit("networkError",e)}}_performDimse(e,t){if(t instanceof $){const e=Object.assign(Object.create(Object.getPrototypeOf(t)),t),s=this.pending.find((e=>e.getMessageId()===t.getMessageIdBeingRespondedTo()));s&&(s.raiseResponseEvent(e),e.getStatus()!==p.Pending&&s.raiseDoneEvent())}else t.getCommandFieldType()===g.CEchoRequest?this.emit("cEchoRequest",t,(t=>{this._sendDimse({context:e,command:t})})):t.getCommandFieldType()===g.CFindRequest?this.emit("cFindRequest",t,(t=>{(Array.isArray(t)?t:[t]).forEach((t=>{this._sendDimse({context:e,command:t})}))})):t.getCommandFieldType()===g.CStoreRequest?this.emit("cStoreRequest",t,(t=>{this._sendDimse({context:e,command:t})})):t.getCommandFieldType()===g.CMoveRequest?this.emit("cMoveRequest",t,(t=>{(Array.isArray(t)?t:[t]).forEach((t=>{this._sendDimse({context:e,command:t})}))})):t.getCommandFieldType()===g.CGetRequest?this.emit("cGetRequest",t,(t=>{(Array.isArray(t)?t:[t]).forEach((t=>{this._sendDimse({context:e,command:t})}))})):t.getCommandFieldType()===g.NCreateRequest?this.emit("nCreateRequest",t,(t=>{this._sendDimse({context:e,command:t})})):t.getCommandFieldType()===g.NActionRequest?this.emit("nActionRequest",t,(t=>{this._sendDimse({context:e,command:t})})):t.getCommandFieldType()===g.NDeleteRequest?this.emit("nDeleteRequest",t,(t=>{this._sendDimse({context:e,command:t})})):t.getCommandFieldType()===g.NEventReportRequest?this.emit("nEventReportRequest",t,(t=>{this._sendDimse({context:e,command:t})})):t.getCommandFieldType()===g.NGetRequest?this.emit("nGetRequest",t,(t=>{this._sendDimse({context:e,command:t})})):t.getCommandFieldType()===g.NSetRequest?this.emit("nSetRequest",t,(t=>{this._sendDimse({context:e,command:t})})):t.getCommandFieldType()===g.CCancelRequest&&this.emit("cCancelRequest",t)}_wrapSocket(){this.socket.setTimeout(this.connectTimeout),this.socket.on("connect",(()=>{this.connected=!0,this.connectedTime=Date.now(),this.emit("connect")}));const e=new H;e.on("pdu",(async e=>{this.lastPduTime=Date.now(),await this._processPdu(e)})),e.on("error",(e=>{this._reset();const t=`${this.logId} -> Connection error: ${e.message}`;z.error(t),this.emit("networkError",new Error(t))})),this.socket.on("data",(t=>{e.accumulate(t),this.statistics.addBytesReceived(t.length)})),this.socket.on("error",(e=>{this._reset();const t=`${this.logId} -> Connection error: ${e.message}`;z.error(t),this.emit("networkError",new Error(t))})),this.socket.on("timeout",(()=>{this._reset();const e=`${this.logId} -> Connection timeout`;z.error(e),this.emit("networkError",new Error(e))})),this.socket.on("close",(()=>{this._reset(),z.info(`${this.logId} -> Connection closed`),this.emit("close")})),this.timeoutIntervalId=setInterval((()=>{const e=Date.now();let t,s=!1;this.connected&&!this.lastPduTime&&e-this.connectedTime>=this.associationTimeout?(t=`${this.logId} -> Exceeded association timeout (${this.associationTimeout}), closing connection...`,s=!0):this.connected&&this.lastPduTime&&e-this.lastPduTime>=this.pduTimeout&&(t=`${this.logId} -> Exceeded PDU timeout (${this.pduTimeout}), closing connection...`,s=!0),s&&(this.sendAbort(),this._reset(),z.error(t),this.emit("networkError",new Error(`Connection timeout: ${t}`)))}),1e3)}_reset(){this.connected=!1,this.lastPduTime=void 0,this.connectedTime=void 0,this.timeoutIntervalId&&(clearInterval(this.timeoutIntervalId),this.timeoutIntervalId=void 0)}}},422:(e,t,s)=>{const{Association:n,PresentationContext:i}=s(570),{TransferSyntax:r,UserIdentityType:a}=s(492),{Request:o}=s(940),c=s(371),d=s(906),u=s(547),h=s(733),m=s(278),g=s(756);e.exports=class extends h{constructor(){super(),this.requests=[],this.additionalPresentationContexts=[],this.network=void 0,this.statistics=new d}addRequest(e){if(!(e instanceof o))throw new Error(`${e.toString()} is not a request`);this.requests.includes(e)?u.warn(`${e.toString()} request has already been added. Ignoring...`):this.requests.push(e)}clearRequests(){this.requests.length=0}addAdditionalPresentationContext(e,t){if(t=t||!1,!(e instanceof i))throw new Error(`${e.toString()} is not a presentation context`);this.additionalPresentationContexts.some((t=>t.context===e))?u.warn(`${e.toString()} context has already been added. Ignoring...`):this.additionalPresentationContexts.push({context:e,addAsNew:t})}send(e,t,s,i,o){if(o=o||{},this.associationLingerTimeout=o.associationLingerTimeout||0,0===this.requests.length)throw new Error("There are no requests to perform");const d=new n(s,i);o.asyncOps&&(d.setMaxAsyncOpsInvoked(o.asyncOps.maxAsyncOpsInvoked||1),d.setMaxAsyncOpsPerformed(o.asyncOps.maxAsyncOpsPerformed||1),d.setNegotiateAsyncOps(1!==d.getMaxAsyncOpsInvoked()||1!==d.getMaxAsyncOpsPerformed())),o.userIdentity&&(d.setUserIdentityType(o.userIdentity.type||a.Username),d.setUserIdentityPositiveResponseRequested(o.userIdentity.positiveResponseRequested||!1),d.setUserIdentityPrimaryField(o.userIdentity.primaryField||""),d.setUserIdentitySecondaryField(o.userIdentity.secondaryField||""),d.setNegotiateUserIdentity(!0)),this.requests.forEach((e=>{d.addPresentationContextFromRequest(e,[r.ImplicitVRLittleEndian,r.ExplicitVRLittleEndian])})),this.additionalPresentationContexts.forEach((e=>{const t=e.addAsNew?d.addPresentationContext(e.context.getAbstractSyntaxUid()):d.addOrGetPresentationContext(e.context.getAbstractSyntaxUid());e.context.getTransferSyntaxUids().forEach((e=>{d.addTransferSyntaxToPresentationContext(t,e)}))}));let h={};o.securityOptions&&(h={key:o.securityOptions.key,cert:o.securityOptions.cert,ca:o.securityOptions.ca,requestCert:o.securityOptions.requestCert,rejectUnauthorized:o.securityOptions.rejectUnauthorized,minVersion:o.securityOptions.minVersion,maxVersion:o.securityOptions.maxVersion,ciphers:o.securityOptions.ciphers}),u.info(`Connecting to ${e}:${t} ${o.securityOptions?"(TLS)":""}`);const l=(o.securityOptions?g:m).connect({host:e,port:t,...h}),p=new c(l,o);p.on("connect",(()=>{this.emit("connected"),p.sendAssociationRequest(d)})),p.on("associationAccepted",(e=>{this.emit("associationAccepted",e),p.sendRequests(this.requests)})),p.on("associationReleaseResponse",(()=>{this.emit("associationReleased"),l.end()})),p.on("associationRejected",(e=>{this.emit("associationRejected",e),l.end()})),p.on("done",(()=>{setTimeout((()=>p.sendAssociationReleaseRequest()),this.associationLingerTimeout)})),p.on("cStoreRequest",((e,t)=>{this.emit("cStoreRequest",e,t)})),p.on("nEventReportRequest",((e,t)=>{this.emit("nEventReportRequest",e,t)})),p.on("networkError",(e=>{l.end(),this.emit("networkError",e)})),p.on("close",(()=>{this.statistics.addFromOtherStatistics(p.getStatistics()),this.network=void 0,this.emit("closed")})),this.network=p}getStatistics(){return this.statistics}abort(e,t){if(!this.network)throw new Error("Network has not been initialized");this.network.sendAbort(e,t)}cancel(e){if(!this.network)throw new Error("Network has not been initialized");this.network.sendCancel(e)}}},429:e=>{"use strict";e.exports=n},492:e=>{const t={AAbort:7,AAssociateAC:2,AAssociateRJ:3,AAssociateRQ:1,AReleaseRP:6,AReleaseRQ:5,PDataTF:4};Object.freeze(t);const s={CStoreRequest:1,CStoreResponse:32769,CGetRequest:16,CGetResponse:32784,CFindRequest:32,CFindResponse:32800,CMoveRequest:33,CMoveResponse:32801,CEchoRequest:48,CEchoResponse:32816,NEventReportRequest:256,NEventReportResponse:33024,NGetRequest:272,NGetResponse:33040,NSetRequest:288,NSetResponse:33056,NActionRequest:304,NActionResponse:33072,NCreateRequest:320,NCreateResponse:33088,NDeleteRequest:336,NDeleteResponse:33104,CCancelRequest:4095};Object.freeze(s);const n={Proposed:255,Accept:0,RejectUser:1,RejectNoReason:2,RejectAbstractSyntaxNotSupported:3,RejectTransferSyntaxesNotSupported:4};Object.freeze(n);const i={Username:1,UsernameAndPasscode:2,Kerberos:3,Saml:4,Jwt:5};Object.freeze(i);const r={ServiceUser:0,Unknown:1,ServiceProvider:2};Object.freeze(r);const a={NotSpecified:0,UnrecognizedPdu:1,UnexpectedPdu:2,UnrecognizedPduParameter:4,UnexpectedPduParameter:5,InvalidPduParameter:6};Object.freeze(a);const o={Permanent:1,Transient:2};Object.freeze(o);const c={ServiceUser:1,ServiceProviderAcse:2,ServiceProviderPresentation:3};Object.freeze(c);const d={NoReasonGiven:1,ApplicationContextNotSupported:2,CallingAeNotRecognized:3,CalledAeNotRecognized:7,ProtocolVersionNotSupported:2,TemporaryCongestion:1,LocalLimitExceeded:2};Object.freeze(d);const u={Low:2,Medium:0,High:1};Object.freeze(u);const h={Success:0,Cancel:65024,Pending:65280,ClassInstanceConflict:281,DataSetSopClassMismatch:43264,DuplicateSOPInstance:273,DuplicateInvocation:528,InvalidArgumentValue:277,InvalidAttributeValue:262,InvalidObjectInstance:279,MissingAttribute:288,MissingAttributeValue:289,MistypedArgument:530,MoveDestinationUnknown:43009,NoSuchActionType:291,NoSuchArgument:276,NoSuchEventType:275,NoSuchObjectInstance:274,NoSuchSopClass:280,NotAuthorized:292,OutOfResourcesNumberOfMatches:42753,OutOfResourcesSubOperations:42754,ProcessingFailure:272,ResourceLimitation:531,SopClassNotSupported:290,UnrecognizedOperation:529};Object.freeze(h);const m={ApplicationContextName:"1.2.840.10008.3.1.1.1"};Object.freeze(m);const g={BasicTextSrStorage:"1.2.840.10008.5.1.4.1.1.88.11",BreastProjectionXRayImageStorageForPresentation:"1.2.840.10008.5.1.4.1.1.13.1.4",BreastProjectionXRayImageStorageForProcessing:"1.2.840.10008.5.1.4.1.1.13.1.5",BreastTomosynthesisImageStorage:"1.2.840.10008.5.1.4.1.1.13.1.3",ChestCadSrStorage:"1.2.840.10008.5.1.4.1.1.88.65",ComprehensiveSrStorage:"1.2.840.10008.5.1.4.1.1.88.33",ComputedRadiographyImageStorage:"1.2.840.10008.5.1.4.1.1.1",CtImageStorage:"1.2.840.10008.5.1.4.1.1.2",DigitalIntraOralXRayImageStorageForPresentation:"1.2.840.10008.5.1.4.1.1.1.3",DigitalIntraOralXRayImageStorageForProcessing:"1.2.840.10008.5.1.4.1.1.1.3.1",DigitalMammographyXRayImageStorageForPresentation:"1.2.840.10008.5.1.4.1.1.1.2",DigitalMammographyXRayImageStorageForProcessing:"1.2.840.10008.5.1.4.1.1.1.2.1",DigitalXRayImageStorageForPresentation:"1.2.840.10008.5.1.4.1.1.1.1",DigitalXRayImageStorageForProcessing:"1.2.840.10008.5.1.4.1.1.1.1.1",EncapsulatedCdaStorage:"1.2.840.10008.5.1.4.1.1.104.2",EncapsulatedPdfStorage:"1.2.840.10008.5.1.4.1.1.104.1",EnhancedCtImageStorage:"1.2.840.10008.5.1.4.1.1.2.1",EnhancedMrColorImageStorage:"1.2.840.10008.5.1.4.1.1.4.3",EnhancedMrImageStorage:"1.2.840.10008.5.1.4.1.1.4.1",EnhancedPetImageStorage:"1.2.840.10008.5.1.4.1.1.130",EnhancedSrStorage:"1.2.840.10008.5.1.4.1.1.88.22",EnhancedXaImageStorage:"1.2.840.10008.5.1.4.1.1.12.1.1",EnhancedXrfImageStorage:"1.2.840.10008.5.1.4.1.1.12.2.1",IntravascularOpticalCoherenceTomographyImageStorageForPresentation:"1.2.840.10008.5.1.4.1.1.14.1",IntravascularOpticalCoherenceTomographyImageStorageForProcessing:"1.2.840.10008.5.1.4.1.1.14.2",LegacyConvertedEnhancedCTImageStorage:"1.2.840.10008.5.1.4.1.1.2.2",LegacyConvertedEnhancedMRImageStorage:"1.2.840.10008.5.1.4.1.1.4.4",LegacyConvertedEnhancedPETImageStorage:"1.2.840.10008.5.1.4.1.1.128.1",MammographyCadSrStorage:"1.2.840.10008.5.1.4.1.1.88.50",MrImageStorage:"1.2.840.10008.5.1.4.1.1.4",MultiframeGrayscaleByteSecondaryCaptureImageStorage:"1.2.840.10008.5.1.4.1.1.7.2",MultiframeGrayscaleWordSecondaryCaptureImageStorage:"1.2.840.10008.5.1.4.1.1.7.3",MultiframeSingleBitSecondaryCaptureImageStorage:"1.2.840.10008.5.1.4.1.1.7.1",MultiframeTrueColorSecondaryCaptureImageStorage:"1.2.840.10008.5.1.4.1.1.7.4",NuclearMedicineImageStorage:"1.2.840.10008.5.1.4.1.1.20",OphthalmicOpticalCoherenceTomographyEnFaceImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.5.7",OphthalmicPhotography16BitImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.5.2",OphthalmicPhotography8BitImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.5.1",OphthalmicTomographyImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.5.4",PositronEmissionTomographyImageStorage:"1.2.840.10008.5.1.4.1.1.128",RtImageStorage:"1.2.840.10008.5.1.4.1.1.481.1",SecondaryCaptureImageStorage:"1.2.840.10008.5.1.4.1.1.7",UltrasoundImageStorage:"1.2.840.10008.5.1.4.1.1.6.1",UltrasoundMultiframeImageStorage:"1.2.840.10008.5.1.4.1.1.3.1",VideoEndoscopicImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.1.1",VideoMicroscopicImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.2.1",VideoPhotographicImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.4.1",VlEndoscopicImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.1",VlMicroscopicImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.2",VlPhotographicImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.4",VlSlideCoordinatesMicroscopicImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.3",VlWholeSlideMicroscopyImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.6",WideFieldOphthalmicPhotography3dCoordinatesImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.5.6",WideFieldOphthalmicPhotographyStereographicProjectionImageStorage:"1.2.840.10008.5.1.4.1.1.77.1.5.5",XRay3dAngiographicImageStorage:"1.2.840.10008.5.1.4.1.1.13.1.1",XRay3dCraniofacialImageStorage:"1.2.840.10008.5.1.4.1.1.13.1.2",XRayAngiographicImageStorage:"1.2.840.10008.5.1.4.1.1.12.1",XRayRadiationDoseSRStorage:"1.2.840.10008.5.1.4.1.1.88.67",XRayRadiofluoroscopicImageStorage:"1.2.840.10008.5.1.4.1.1.12.2"};Object.freeze(g);const l={Verification:"1.2.840.10008.1.1",StudyRootQueryRetrieveInformationModelFind:"1.2.840.10008.5.1.4.1.2.2.1",ModalityWorklistInformationModelFind:"1.2.840.10008.5.1.4.31",ModalityPerformedProcedureStep:"1.2.840.10008.3.1.2.3.3",StudyRootQueryRetrieveInformationModelMove:"1.2.840.10008.5.1.4.1.2.2.2",StudyRootQueryRetrieveInformationModelGet:"1.2.840.10008.5.1.4.1.2.2.3",StorageCommitmentPushModel:"1.2.840.10008.1.20.1",BasicFilmSession:"1.2.840.10008.5.1.1.1",PrintJob:"1.2.840.10008.5.1.1.14",BasicAnnotationBox:"1.2.840.10008.5.1.1.15",Printer:"1.2.840.10008.5.1.1.16",PrinterConfigurationRetrieval:"1.2.840.10008.5.1.1.16.376",BasicGrayscalePrintManagementMeta:"1.2.840.10008.5.1.1.9",BasicColorPrintManagementMeta:"1.2.840.10008.5.1.1.18",BasicFilmBox:"1.2.840.10008.5.1.1.2",PresentationLut:"1.2.840.10008.5.1.1.23",BasicGrayscaleImageBox:"1.2.840.10008.5.1.1.4",BasicColorImageBox:"1.2.840.10008.5.1.1.4.1",InstanceAvailabilityNotification:"1.2.840.10008.5.1.4.33"};Object.freeze(l);const p={ImplicitVRLittleEndian:"1.2.840.10008.1.2",ExplicitVRLittleEndian:"1.2.840.10008.1.2.1",DeflatedExplicitVRLittleEndian:"1.2.840.10008.1.2.1.99",ExplicitVRBigEndian:"1.2.840.10008.1.2.2",RleLossless:"1.2.840.10008.1.2.5",JpegBaseline:"1.2.840.10008.1.2.4.50",JpegLossless:"1.2.840.10008.1.2.4.70",JpegLsLossless:"1.2.840.10008.1.2.4.80",JpegLsLossy:"1.2.840.10008.1.2.4.81",Jpeg2000Lossless:"1.2.840.10008.1.2.4.90",Jpeg2000Lossy:"1.2.840.10008.1.2.4.91",JpegXlLossless:"1.2.840.10008.1.2.4.110",JpegXlRecompression:"1.2.840.10008.1.2.4.111",JpegXl:"1.2.840.10008.1.2.4.112",HtJpeg2000Lossless:"1.2.840.10008.1.2.4.201",HtJpeg2000LosslessRpcl:"1.2.840.10008.1.2.4.202",HtJpeg2000Lossy:"1.2.840.10008.1.2.4.203"};Object.freeze(p);const R=[p.ImplicitVRLittleEndian,p.ExplicitVRLittleEndian,p.ExplicitVRBigEndian,p.RleLossless,p.JpegBaseline,p.JpegLossless,p.JpegLsLossless,p.JpegLsLossy,p.Jpeg2000Lossless,p.Jpeg2000Lossy,p.HtJpeg2000Lossless,p.HtJpeg2000LosslessRpcl,p.HtJpeg2000Lossy];Object.freeze(R);const S={ImplementationClassUid:"1.2.826.0.1.3680043.10.854",ImplementationVersion:"DCMJS-DIMSE-V0.2",MaxPduLength:262144};Object.freeze(S),e.exports={AbortReason:a,AbortSource:r,CommandFieldType:s,DefaultImplementation:S,PresentationContextResult:n,Priority:u,RawPduType:t,RejectReason:d,RejectResult:o,RejectSource:c,SopClass:l,Status:h,StorageClass:g,TranscodableTransferSyntaxes:R,TransferSyntax:p,Uid:m,UserIdentityType:i}},538:(e,t,s)=>{const{CEchoResponse:n,CFindResponse:i,CGetResponse:r,CMoveResponse:a,CStoreResponse:o,NActionResponse:c,NCreateResponse:d,NDeleteResponse:u,NEventReportResponse:h,NGetResponse:m,NSetResponse:g}=s(940),l=s(371),p=s(906),R=s(547),S=s(733),y=s(278),f=s(756);e.exports={Scp:class extends l{constructor(e,t){super(e,t),this.on("associationRequested",(e=>{this.associationRequested(e)})),this.on("associationReleaseRequested",(()=>{this.associationReleaseRequested()})),this.on("cEchoRequest",((e,t)=>{this.cEchoRequest(e,t)})),this.on("cFindRequest",((e,t)=>{this.cFindRequest(e,t)})),this.on("cStoreRequest",((e,t)=>{this.cStoreRequest(e,t)})),this.on("cMoveRequest",((e,t)=>{this.cMoveRequest(e,t)})),this.on("cGetRequest",((e,t)=>{this.cGetRequest(e,t)})),this.on("nCreateRequest",((e,t)=>{this.nCreateRequest(e,t)})),this.on("nActionRequest",((e,t)=>{this.nActionRequest(e,t)})),this.on("nDeleteRequest",((e,t)=>{this.nDeleteRequest(e,t)})),this.on("nEventReportRequest",((e,t)=>{this.nEventReportRequest(e,t)})),this.on("nGetRequest",((e,t)=>{this.nGetRequest(e,t)})),this.on("nSetRequest",((e,t)=>{this.nSetRequest(e,t)})),this.on("cCancelRequest",(e=>{this.cCancelRequest(e)})),this.on("abort",(({source:e,reason:t})=>{this.abort(e,t)}))}createStoreWritableStream(e,t){return super.createStoreWritableStream(e,t)}createDatasetFromStoreWritableStream(e,t,s){return super.createDatasetFromStoreWritableStream(e,t,s)}associationRequested(e){R.error("associationRequested method must be implemented"),this.sendAssociationReject()}associationReleaseRequested(){R.error("associationReleaseRequested method must be implemented"),this.sendAssociationReleaseResponse()}cEchoRequest(e,t){R.error("cEchoRequest method must be implemented"),t(n.fromRequest(e))}cFindRequest(e,t){R.error("cFindRequest method must be implemented"),t(i.fromRequest(e))}cStoreRequest(e,t){R.error("cStoreRequest method must be implemented"),t(o.fromRequest(e))}cMoveRequest(e,t){R.error("cMoveRequest method must be implemented"),t(a.fromRequest(e))}cGetRequest(e,t){R.error("cGetRequest method must be implemented"),t(r.fromRequest(e))}nCreateRequest(e,t){R.error("nCreateRequest method must be implemented"),t(d.fromRequest(e))}nActionRequest(e,t){R.error("nActionRequest method must be implemented"),t(c.fromRequest(e))}nDeleteRequest(e,t){R.error("nDeleteRequest method must be implemented"),t(u.fromRequest(e))}nEventReportRequest(e,t){R.error("nEventReportRequest method must be implemented"),t(h.fromRequest(e))}nGetRequest(e,t){R.error("nGetRequest method must be implemented"),t(m.fromRequest(e))}nSetRequest(e,t){R.error("nSetRequest method must be implemented"),t(g.fromRequest(e))}cCancelRequest(e){R.error("cCancelRequest method must be implemented")}abort(e,t){R.error("abort method must be implemented")}},Server:class extends S{constructor(e){super(),this.scp={class:e},this.server=void 0,this.clients=[],this.statistics=new p}listen(e,t){let s={};(t=t||{}).securityOptions&&(s={key:t.securityOptions.key,cert:t.securityOptions.cert,ca:t.securityOptions.ca,requestCert:t.securityOptions.requestCert,rejectUnauthorized:t.securityOptions.rejectUnauthorized,minVersion:t.securityOptions.minVersion,maxVersion:t.securityOptions.maxVersion,ciphers:t.securityOptions.ciphers,SNICallback:t.securityOptions.SNICallback});const n=t.securityOptions?f:y;this.server=n.createServer(s,(e=>{R.info(`Client connecting from ${e.remoteAddress}:${e.remotePort} ${t.securityOptions?e.authorized?"(Authorized)":"(Unauthorized)":""}`);const s=new this.scp.class(e,t);s.connected=!0,s.on("close",(()=>{this.statistics.addFromOtherStatistics(s.getStatistics())})),s.on("networkError",(t=>{e.end(),this.emit("networkError",t)})),this.clients.push(s),this.clients=this.clients.filter((e=>e.connected))})),this.server.on("listening",(()=>{R.info(`DICOM server listening on port ${e} ${t.securityOptions?"(TLS)":""}`),this.emit("listening")})),this.server.on("error",(e=>{const t=`Server error: ${e.message}`;R.error(t),this.emit("networkError",e)})),this.server.listen(e)}getStatistics(){return this.statistics}close(){this.server&&this.server.listening&&this.server.close(),this.clients.forEach((e=>e.socket.destroy())),this.clients=[]}}}},547:(e,t,s)=>{const n=s(360),i=s(707);i.reg(n),n.enableAll(!1),i.apply(n,{format:(e,t,s)=>`${s} -- ${e.toUpperCase()} --`,timestampFormatter:e=>e.toISOString()}),e.exports=n},570:(e,t,s)=>{const{CGetRequest:n,CStoreRequest:i}=s(940),{CommandFieldType:r,PresentationContextResult:a,SopClass:o,StorageClass:c,TransferSyntax:d,Uid:u,UserIdentityType:h}=s(492),m=s(139),{EOL:g}=s(857);class l{constructor(e,t,s,n){this.pcId=e,this.abstractSyntaxUid=t,this.transferSyntaxes=[],s&&this.transferSyntaxes.push(s),this.result=n||a.Proposed}getPresentationContextId(){return this.pcId}getAbstractSyntaxUid(){return this.abstractSyntaxUid}getTransferSyntaxUids(){return this.transferSyntaxes}addTransferSyntaxUid(e){this.transferSyntaxes.includes(e)||this.transferSyntaxes.push(e)}removeTransferSyntaxUid(e){if(!this.transferSyntaxes.includes(e))return;const t=this.transferSyntaxes.indexOf(e);-1!==t&&this.transferSyntaxes.splice(t,1)}hasTransferSyntaxUid(e){return this.transferSyntaxes.includes(e)}getAcceptedTransferSyntaxUid(){return this.transferSyntaxes.length>0?this.transferSyntaxes[0]:void 0}getResult(){return this.result}setResult(e,t){this.result=e;const s=[...this.transferSyntaxes];this.transferSyntaxes.length=0,t?this.transferSyntaxes.push(t):s.length>0&&this.transferSyntaxes.push(s[0])}getResultDescription(){switch(this.result){case a.Accept:return"Accept";case a.Proposed:return"Proposed";case a.RejectAbstractSyntaxNotSupported:return"Reject - Abstract Syntax Not Supported";case a.RejectNoReason:return"Reject - No Reason";case a.RejectTransferSyntaxesNotSupported:return"Reject - Transfer Syntaxes Not Supported";case a.RejectUser:return"Reject - User";default:return"Unknown"}}toString(){const e=[];return e.push(`Presentation Context: ${this.getPresentationContextId()} [${this.getResultDescription()}]`),e.push(` Abstract: ${this.getAbstractSyntaxUid()}`),this.getTransferSyntaxUids().forEach((t=>{e.push(` Transfer: ${t}`)})),e.join(g)}}e.exports={Association:class{constructor(e,t){this.callingAeTitle=e,this.calledAeTitle=t,this.maxPduLength=m.getMaxPduLength(),this.applicationContextName=u.ApplicationContextName,this.implementationClassUid=m.getImplementationClassUid(),this.implementationVersion=m.getImplementationVersion(),this.presentationContexts=[],this.negotiateAsyncOps=!1,this.maxAsyncOpsInvoked=1,this.maxAsyncOpsPerformed=1,this.negotiateUserIdentity=!1,this.userIdentityType=h.Username,this.userIdentityPositiveResponseRequested=!1,this.userIdentityPrimaryField="",this.userIdentitySecondaryField="",this.negotiateUserIdentityServerResponse=!1,this.userIdentityServerResponse=""}getCallingAeTitle(){return this.callingAeTitle}setCallingAeTitle(e){this.callingAeTitle=e}getCalledAeTitle(){return this.calledAeTitle}setCalledAeTitle(e){this.calledAeTitle=e}getMaxPduLength(){return this.maxPduLength}setMaxPduLength(e){this.maxPduLength=e}getApplicationContextName(){return this.applicationContextName}getImplementationClassUid(){return this.implementationClassUid}setImplementationClassUid(e){this.implementationClassUid=e}getImplementationVersion(){return this.implementationVersion}setImplementationVersion(e){this.implementationVersion=e}getNegotiateAsyncOps(){return this.negotiateAsyncOps}setNegotiateAsyncOps(e){this.negotiateAsyncOps=e}getMaxAsyncOpsInvoked(){return this.maxAsyncOpsInvoked}setMaxAsyncOpsInvoked(e){this.maxAsyncOpsInvoked=e}getMaxAsyncOpsPerformed(){return this.maxAsyncOpsPerformed}setMaxAsyncOpsPerformed(e){this.maxAsyncOpsPerformed=e}getNegotiateUserIdentity(){return this.negotiateUserIdentity}setNegotiateUserIdentity(e){this.negotiateUserIdentity=e}getUserIdentityType(){return this.userIdentityType}setUserIdentityType(e){this.userIdentityType=e}getUserIdentityPositiveResponseRequested(){return this.userIdentityPositiveResponseRequested}setUserIdentityPositiveResponseRequested(e){this.userIdentityPositiveResponseRequested=e}getUserIdentityPrimaryField(){return this.userIdentityPrimaryField}setUserIdentityPrimaryField(e){this.userIdentityPrimaryField=e}getUserIdentitySecondaryField(){return this.userIdentitySecondaryField}setUserIdentitySecondaryField(e){this.userIdentitySecondaryField=e}getNegotiateUserIdentityServerResponse(){return this.negotiateUserIdentityServerResponse}setNegotiateUserIdentityServerResponse(e){this.negotiateUserIdentityServerResponse=e}getUserIdentityServerResponse(){return this.userIdentityServerResponse}setUserIdentityServerResponse(e){this.userIdentityServerResponse=e}addPresentationContext(e,t){let s=t||1;return this.presentationContexts.forEach((e=>{const t=e.id;t>=s&&(s=t+2)})),this.presentationContexts.push({id:s,context:new l(s,e)}),s}addOrGetPresentationContext(e){const t=this.getPresentationContexts();for(let s=0;s<t.length;s++){const n=t[s];if(n.context.getAbstractSyntaxUid()===e)return n.context.getPresentationContextId()}return this.addPresentationContext(e)}addTransferSyntaxToPresentationContext(e,t){this.getPresentationContext(e).addTransferSyntaxUid(t)}findPresentationContextByAbstractSyntaxAndTransferSyntax(e,t){const s=this.getPresentationContexts();for(let n=0;n<s.length;n++){const i=s[n];if(i.context.getAbstractSyntaxUid()===e&&i.context.hasTransferSyntaxUid(t))return i.context.getPresentationContextId()}}getPresentationContext(e){const t=this.presentationContexts.find((t=>t.id===e));if(!t)throw new Error(`Invalid presentation context ID: ${e}`);return t.context}getPresentationContexts(){return this.presentationContexts}clearPresentationContexts(){this.presentationContexts.length=0}addPresentationContextFromRequest(e,t){let s=t||d.ImplicitVRLittleEndian;s=Array.isArray(s)?s:[s];const r=this._sopClassFromRequest(e);let a;if(e instanceof i){a=this.addOrGetPresentationContext(r),s.forEach((e=>{this.addTransferSyntaxToPresentationContext(a,e)})),e.getAdditionalTransferSyntaxes().forEach((e=>{this.addTransferSyntaxToPresentationContext(a,e)}));const t=e.getDataset().getTransferSyntaxUid();t!==d.ImplicitVRLittleEndian&&t!==d.ExplicitVRLittleEndian&&(a=this.findPresentationContextByAbstractSyntaxAndTransferSyntax(r,t),void 0===a&&(a=this.addPresentationContext(r),this.addTransferSyntaxToPresentationContext(a,t)))}else e instanceof n?(a=this.addOrGetPresentationContext(r),s.forEach((e=>{this.addTransferSyntaxToPresentationContext(a,e)})),!0===e.getAddStorageSopClassesToAssociation()&&Object.keys(c).forEach((e=>{const t=c[e],n=this.addOrGetPresentationContext(t);s.forEach((e=>{this.addTransferSyntaxToPresentationContext(n,e)}))}))):(a=this.addOrGetPresentationContext(r),s.forEach((e=>{this.addTransferSyntaxToPresentationContext(a,e)})));return a}getAcceptedPresentationContextFromRequest(e){let t;const s=this.getPresentationContexts();return e.getDataset()&&s.forEach((s=>{const n=this.getPresentationContext(s.id);n.getAbstractSyntaxUid()===this._sopClassFromRequest(e)&&n.getAcceptedTransferSyntaxUid()===e.getDataset().getTransferSyntaxUid()&&n.getResult()===a.Accept&&(t=n)})),void 0===t&&s.forEach((s=>{const n=this.getPresentationContext(s.id);n.getAbstractSyntaxUid()===this._sopClassFromRequest(e)&&n.getResult()===a.Accept&&(t=n)})),t}toString(){const e=[];return e.push(`Application Context: ${this.getApplicationContextName()}`),e.push(`Implementation Class: ${this.getImplementationClassUid()}`),e.push(`Implementation Version: ${this.getImplementationVersion()}`),e.push(`Maximum PDU Length: ${this.getMaxPduLength()}`),e.push(`Called AE Title: ${this.getCalledAeTitle()}`),e.push(`Calling AE Title: ${this.getCallingAeTitle()}`),this.getNegotiateAsyncOps()&&e.push(`Asynchronous Operations: Invoked: ${this.getMaxAsyncOpsInvoked()} Performed:${this.getMaxAsyncOpsPerformed()}`),this.getNegotiateUserIdentity()&&e.push(`User Identity: ${this._userIdentityTypeToString(this.getUserIdentityType())||""}`),e.push(`Presentation Contexts: ${this.presentationContexts.length}`),this.presentationContexts.forEach((t=>{const s=this.getPresentationContext(t.id);e.push(` Presentation Context: ${t.id} [${s.getResultDescription()}]`),e.push(` Abstract: ${this._uidNameFromValue([o,c],s.getAbstractSyntaxUid())||s.getAbstractSyntaxUid()}`),s.getTransferSyntaxUids().forEach((t=>{e.push(` Transfer: ${this._uidNameFromValue(d,t)||t}`)}))})),e.push(""),e.join(g)}_uidNameFromValue(e,t){const s=Array.isArray(e)?Object.assign({},...e):e;return Object.keys(s).find((e=>s[e]===t))}_sopClassFromRequest(e){switch(e.getCommandFieldType()){case r.NGetRequest:case r.NSetRequest:case r.NActionRequest:case r.NDeleteRequest:return void 0!==e.getMetaSopClassUid()?e.getMetaSopClassUid():e.getRequestedSopClassUid();case r.CStoreRequest:case r.CFindRequest:case r.CGetRequest:case r.CMoveRequest:case r.CEchoRequest:return e.getAffectedSopClassUid();case r.NEventReportRequest:case r.NCreateRequest:return void 0!==e.getMetaSopClassUid()?e.getMetaSopClassUid():e.getAffectedSopClassUid();default:return e.getAffectedSopClassUid()}}_userIdentityTypeToString(e){switch(e){case h.Username:return"Username";case h.UsernameAndPasscode:return"Username and Passcode";case h.Kerberos:return"Kerberos Service Ticket";case h.Saml:return"SAML Assertion";case h.Jwt:return"JSON Web Token";default:return`${e}`}}},PresentationContext:l}},593:e=>{"use strict";e.exports=i},707:e=>{"use strict";e.exports=r},733:e=>{"use strict";e.exports=a},756:e=>{"use strict";e.exports=require("tls")},766:e=>{"use strict";e.exports=o},825:(e,t,s)=>{const{StorageClass:n,TransferSyntax:i}=s(492),r=s(139),{readFile:a,readFileSync:o,writeFile:c,writeFileSync:d}=s(896),{EOL:u}=s(857),h=s(111),{DicomDict:m,DicomMessage:g,DicomMetaDictionary:l,ReadBufferStream:p,WriteBufferStream:R}=h.data,S=h.log;class y{constructor(e,t,s){s=s||{},s={ignoreErrors:!0,...s},S.level="error",this.transferSyntaxUid=t||i.ImplicitVRLittleEndian,Buffer.isBuffer(e)?this.elements=this._fromElementsBuffer(e,this.transferSyntaxUid,s):this.elements=e||{}}getElement(e){return this.elements[e]}setElement(e,t){this.elements[e]=t}getElements(){return this.elements}getTransferSyntaxUid(){return this.transferSyntaxUid}setTransferSyntaxUid(e){this.transferSyntaxUid=e}getDenaturalizedDataset(e,t){const s=t?l.denaturalizeDataset(this.getElements(),{...l.nameMap,...t}):l.denaturalizeDataset(this.getElements()),n=new R;return g.write(s,n,this.transferSyntaxUid,e),Buffer.from(n.getBuffer())}getDenaturalizedCommandDataset(e){const t=l.denaturalizeDataset(this.getElements()),s=new R,n=new R;return g.write(t,n,i.ImplicitVRLittleEndian,e),g.writeTagObject(s,"00000000","UL",n.size,i.ImplicitVRLittleEndian,e),s.concat(n),Buffer.from(s.getBuffer())}static fromFile(e,t,s){if(!(void 0!==t&&t instanceof Function))return this._fromP10Buffer(o(e),s);a(e,((e,n)=>{if(e)t(e,void 0);else try{t(void 0,this._fromP10Buffer(n,s))}catch(e){t(e,void 0)}}))}toFile(e,t,s,i){const a={_meta:{FileMetaInformationVersion:new Uint8Array([0,1]).buffer,MediaStorageSOPClassUID:this.getElement("SOPClassUID")||n.SecondaryCaptureImageStorage,MediaStorageSOPInstanceUID:this.getElement("SOPInstanceUID")||y.generateDerivedUid(),TransferSyntaxUID:this.getTransferSyntaxUid(),ImplementationClassUID:r.getImplementationClassUid(),ImplementationVersionName:r.getImplementationVersion()},...this.getElements()},o=l.denaturalizeDataset(a._meta),u=new m(o);u.dict=s?l.denaturalizeDataset(a,{...l.nameMap,...s}):l.denaturalizeDataset(a),t instanceof Function?c(e,Buffer.from(u.write(i)),(e=>{t(e||void 0)})):d(e,Buffer.from(u.write(i)))}static generateDerivedUid(){return l.uid()}toString(){const e=[];return e.push("Dataset:"),e.push("=".repeat(50)),e.push(JSON.stringify(this.getElements())),e.join(u)}static _fromP10Buffer(e,t){t=t||{},t={ignoreErrors:!0,...t};const s=g.readFile(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),t),n=l.naturalizeDataset(s.meta).TransferSyntaxUID,i=l.naturalizeDataset(s.dict);return new y(i,n)}_fromElementsBuffer(e,t,s){const n=new p(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)),r=t===i.ImplicitVRLittleEndian?i.ImplicitVRLittleEndian:t===i.ExplicitVRBigEndian?i.ExplicitVRBigEndian:i.ExplicitVRLittleEndian,a=g._read(n,r,s);return l.naturalizeDataset(a)}}e.exports=y},837:e=>{e.exports="0.2.7"},857:e=>{"use strict";e.exports=require("os")},896:e=>{"use strict";e.exports=require("fs")},906:e=>{e.exports=class{constructor(){this.bytesReceived=0,this.bytesSent=0}getBytesReceived(){return this.bytesReceived}getBytesSent(){return this.bytesSent}addBytesReceived(e){this.bytesReceived+=e}addBytesSent(e){this.bytesSent+=e}addFromOtherStatistics(e){this.addBytesReceived(e.getBytesReceived()),this.addBytesSent(e.getBytesSent())}reset(){this.bytesReceived=0,this.bytesSent=0}toString(){return`Sent: ${this._formatBytes(this.getBytesSent())}, Received: ${this._formatBytes(this.getBytesReceived())}`}_formatBytes(e){if(void 0===e||0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,t)).toFixed(3))} ${["Bytes","KB","MB","GB","TB","PB"][t]}`}}},940:(e,t,s)=>{const{CommandFieldType:n,Priority:i,SopClass:r,Status:a}=s(492),o=s(825),{Mixin:c}=s(429),{EOL:d}=s(857),u=s(733),h=s(111),{DicomMetaDictionary:m}=h.data;class g{constructor(e,t){this.commandDataset=e||new o,this.dataset=t}getCommandDataset(){return this.commandDataset}setCommandDataset(e){this.commandDataset=e}getDataset(){return this.dataset}setDataset(e){this.dataset=e,this.commandDataset.setElement("CommandDataSetType",this.dataset?514:257)}getCommandFieldType(){return this.commandDataset.getElement("CommandField")}hasDataset(){return 257!==this.commandDataset.getElement("CommandDataSetType")}toString(e){const t=e||{},s=t.includeCommandDataset||!1,n=t.includeDataset||!1,i=[];return i.push(`${this._typeToString(this.getCommandFieldType())} [HasDataset: ${this.hasDataset()}]`),s&&(i.push("DIMSE Command Dataset:"),i.push("=".repeat(50)),i.push(JSON.stringify(this.commandDataset.getElements()))),n&&this.dataset&&(i.push("DIMSE Dataset:"),i.push("=".repeat(50)),i.push(JSON.stringify(this.dataset.getElements()))),i.join(d)}_typeToString(e){switch(e){case n.CCancelRequest:return"C-CANCEL RQ";case n.CEchoRequest:return"C-ECHO RQ";case n.CEchoResponse:return"C-ECHO RSP";case n.CFindRequest:return"C-FIND RQ";case n.CFindResponse:return"C-FIND RSP";case n.CGetRequest:return"C-GET RQ";case n.CGetResponse:return"C-GET RSP";case n.CMoveRequest:return"C-MOVE RQ";case n.CMove