medplum 5.1.37 → 5.1.38

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.
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ln=Object.create;var ur=Object.defineProperty;var Mn=Object.getOwnPropertyDescriptor;var Dn=Object.getOwnPropertyNames;var kn=Object.getPrototypeOf,Un=Object.prototype.hasOwnProperty;var xn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Dn(t))!Un.call(e,n)&&n!==r&&ur(e,n,{get:()=>t[n],enumerable:!(o=Mn(t,n))||o.enumerable});return e};var ce=(e,t,r)=>(r=e!=null?Ln(kn(e)):{},xn(t||!e||!e.__esModule?ur(r,"default",{value:e,enumerable:!0}):r,e));var ve=require("@medplum/core"),je=require("commander"),_r=ce(require("dotenv"),1),re=require("@medplum/core"),Fe=require("commander"),jr=require("@medplum/core"),Fr=require("@medplum/core"),ie=require("node:fs"),Wr=require("node:os"),_t=require("node:path"),J=require("@medplum/core"),Br=require("commander"),be=require("node:crypto"),ue=require("node:fs"),se=require("node:path"),Qr=require("node:util/types"),Zr=require("tar"),Z=require("@medplum/core"),ho=require("node:child_process"),fo=require("node:http"),go=require("node:os"),wo=require("node:util"),ae=require("@aws-sdk/client-cloudformation"),at=require("@aws-sdk/client-cloudfront"),Ao=require("@aws-sdk/client-ecs"),Io=require("@aws-sdk/client-s3"),Ie=require("@aws-sdk/client-ssm"),ct=require("@aws-sdk/client-sts"),lt=require("@medplum/core"),$o=require("node:fs"),Ro=ce(require("node:readline"),1),we=require("@aws-sdk/client-acm"),dt=require("@aws-sdk/client-cloudfront"),mt=require("@aws-sdk/client-sts"),ko=require("@medplum/core"),Ue=require("node:crypto"),Uo=require("node:fs"),_o=require("@aws-sdk/client-s3"),Q=require("@medplum/core"),jo=ce(require("fast-glob"),1),Y=require("node:fs"),Fo=require("node:os"),me=require("node:path"),Wo=require("node:stream"),Bo=require("node:stream/promises"),ht=require("@aws-sdk/client-s3"),Ko=require("node:child_process"),z=require("@medplum/core"),wt=require("node:fs"),ir=require("node:path"),Yo=require("node:readline"),Qo=require("node:stream"),Zo=require("node:stream/promises"),Ye=ce(require("fast-glob"),1),ar=require("node:events"),rn=require("node:fs"),yt=require("node:fs/promises"),$e=require("node:path"),on=require("node:stream"),Et=require("@medplum/core"),Le=ce(require("node:assert"),1),cn=ce(require("node:net"),1),K=require("@medplum/core"),Gt=ce(require("iconv-lite"),1),Za=require("@medplum/core"),ln=require("@medplum/core"),un=ce(require("node:net"),1),mn=require("node:fs"),hn=require("node:fs"),fn=require("node:os"),gn=require("node:path"),Sn=require("commander"),Rn=require("@medplum/core"),_n=Object.create,Jt=Object.defineProperty,jn=Object.getOwnPropertyDescriptor,Fn=Object.getOwnPropertyNames,Wn=Object.getPrototypeOf,Bn=Object.prototype.hasOwnProperty,Nr=e=>{throw TypeError(e)},Gn=(e,t,r)=>t in e?Jt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,I=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Kn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fn(t))!Bn.call(e,n)&&n!==r&&Jt(e,n,{get:()=>t[n],enumerable:!(o=jn(t,n))||o.enumerable});return e},Cr=(e,t,r)=>(r=e!=null?_n(Wn(e)):{},Kn(t||!e||!e.__esModule?Jt(r,"default",{value:e,enumerable:!0}):r,e)),X=(e,t,r)=>Gn(e,typeof t!="symbol"?t+"":t,r),Lr=(e,t,r)=>t.has(e)||Nr("Cannot "+r),pr=(e,t,r)=>(Lr(e,t,"read from private field"),r?r.call(e):t.get(e)),Hn=(e,t,r)=>t.has(e)?Nr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Jn=(e,t,r,o)=>(Lr(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r),xe=I((e,t)=>{"use strict";var r="2.0.0",o=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,i=250,s=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:o,RELEASE_TYPES:s,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}),tt=I((e,t)=>{"use strict";var r=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...o)=>console.error("SEMVER",...o):()=>{};t.exports=r}),_e=I((e,t)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:n}=xe(),i=tt();e=t.exports={};var s=e.re=[],l=e.safeRe=[],a=e.src=[],h=e.safeSrc=[],u=e.t={},w=0,c="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",n],[c,o]],f=E=>{for(let[R,N]of m)E=E.split(`${R}*`).join(`${R}{0,${N}}`).split(`${R}+`).join(`${R}{1,${N}}`);return E},d=(E,R,N)=>{let j=f(R),W=w++;i(E,W,R),u[E]=W,a[W]=R,h[W]=j,s[W]=new RegExp(R,N?"g":void 0),l[W]=new RegExp(j,N?"g":void 0)};d("NUMERICIDENTIFIER","0|[1-9]\\d*"),d("NUMERICIDENTIFIERLOOSE","\\d+"),d("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${c}*`),d("MAINVERSION",`(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})`),d("MAINVERSIONLOOSE",`(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})`),d("PRERELEASEIDENTIFIER",`(?:${a[u.NONNUMERICIDENTIFIER]}|${a[u.NUMERICIDENTIFIER]})`),d("PRERELEASEIDENTIFIERLOOSE",`(?:${a[u.NONNUMERICIDENTIFIER]}|${a[u.NUMERICIDENTIFIERLOOSE]})`),d("PRERELEASE",`(?:-(${a[u.PRERELEASEIDENTIFIER]}(?:\\.${a[u.PRERELEASEIDENTIFIER]})*))`),d("PRERELEASELOOSE",`(?:-?(${a[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[u.PRERELEASEIDENTIFIERLOOSE]})*))`),d("BUILDIDENTIFIER",`${c}+`),d("BUILD",`(?:\\+(${a[u.BUILDIDENTIFIER]}(?:\\.${a[u.BUILDIDENTIFIER]})*))`),d("FULLPLAIN",`v?${a[u.MAINVERSION]}${a[u.PRERELEASE]}?${a[u.BUILD]}?`),d("FULL",`^${a[u.FULLPLAIN]}$`),d("LOOSEPLAIN",`[v=\\s]*${a[u.MAINVERSIONLOOSE]}${a[u.PRERELEASELOOSE]}?${a[u.BUILD]}?`),d("LOOSE",`^${a[u.LOOSEPLAIN]}$`),d("GTLT","((?:<|>)?=?)"),d("XRANGEIDENTIFIERLOOSE",`${a[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),d("XRANGEIDENTIFIER",`${a[u.NUMERICIDENTIFIER]}|x|X|\\*`),d("XRANGEPLAIN",`[v=\\s]*(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:${a[u.PRERELEASE]})?${a[u.BUILD]}?)?)?`),d("XRANGEPLAINLOOSE",`[v=\\s]*(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:${a[u.PRERELEASELOOSE]})?${a[u.BUILD]}?)?)?`),d("XRANGE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAIN]}$`),d("XRANGELOOSE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAINLOOSE]}$`),d("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),d("COERCE",`${a[u.COERCEPLAIN]}(?:$|[^\\d])`),d("COERCEFULL",a[u.COERCEPLAIN]+`(?:${a[u.PRERELEASE]})?(?:${a[u.BUILD]})?(?:$|[^\\d])`),d("COERCERTL",a[u.COERCE],!0),d("COERCERTLFULL",a[u.COERCEFULL],!0),d("LONETILDE","(?:~>?)"),d("TILDETRIM",`(\\s*)${a[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",d("TILDE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAIN]}$`),d("TILDELOOSE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAINLOOSE]}$`),d("LONECARET","(?:\\^)"),d("CARETTRIM",`(\\s*)${a[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",d("CARET",`^${a[u.LONECARET]}${a[u.XRANGEPLAIN]}$`),d("CARETLOOSE",`^${a[u.LONECARET]}${a[u.XRANGEPLAINLOOSE]}$`),d("COMPARATORLOOSE",`^${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]})$|^$`),d("COMPARATOR",`^${a[u.GTLT]}\\s*(${a[u.FULLPLAIN]})$|^$`),d("COMPARATORTRIM",`(\\s*)${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]}|${a[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",d("HYPHENRANGE",`^\\s*(${a[u.XRANGEPLAIN]})\\s+-\\s+(${a[u.XRANGEPLAIN]})\\s*$`),d("HYPHENRANGELOOSE",`^\\s*(${a[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[u.XRANGEPLAINLOOSE]})\\s*$`),d("STAR","(<|>)?=?\\s*\\*"),d("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),d("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}),Vt=I((e,t)=>{"use strict";var r=Object.freeze({loose:!0}),o=Object.freeze({}),n=i=>i?typeof i!="object"?r:i:o;t.exports=n}),Mr=I((e,t)=>{"use strict";var r=/^[0-9]+$/,o=(i,s)=>{if(typeof i=="number"&&typeof s=="number")return i===s?0:i<s?-1:1;let l=r.test(i),a=r.test(s);return l&&a&&(i=+i,s=+s),i===s?0:l&&!a?-1:a&&!l?1:i<s?-1:1},n=(i,s)=>o(s,i);t.exports={compareIdentifiers:o,rcompareIdentifiers:n}}),H=I((e,t)=>{"use strict";var r=tt(),{MAX_LENGTH:o,MAX_SAFE_INTEGER:n}=xe(),{safeRe:i,t:s}=_e(),l=Vt(),{compareIdentifiers:a}=Mr(),h=(w,c)=>{let m=c.split(".");if(m.length>w.length)return!1;for(let f=0;f<m.length;f++)if(a(w[f],m[f])!==0)return!1;return!0},u=class oe{constructor(c,m){if(m=l(m),c instanceof oe){if(c.loose===!!m.loose&&c.includePrerelease===!!m.includePrerelease)return c;c=c.version}else if(typeof c!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof c}".`);if(c.length>o)throw new TypeError(`version is longer than ${o} characters`);r("SemVer",c,m),this.options=m,this.loose=!!m.loose,this.includePrerelease=!!m.includePrerelease;let f=c.trim().match(m.loose?i[s.LOOSE]:i[s.FULL]);if(!f)throw new TypeError(`Invalid Version: ${c}`);if(this.raw=c,this.major=+f[1],this.minor=+f[2],this.patch=+f[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");f[4]?this.prerelease=f[4].split(".").map(d=>{if(/^[0-9]+$/.test(d)){let E=+d;if(E>=0&&E<n)return E}return d}):this.prerelease=[],this.build=f[5]?f[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(c){if(r("SemVer.compare",this.version,this.options,c),!(c instanceof oe)){if(typeof c=="string"&&c===this.version)return 0;c=new oe(c,this.options)}return c.version===this.version?0:this.compareMain(c)||this.comparePre(c)}compareMain(c){return c instanceof oe||(c=new oe(c,this.options)),this.major<c.major?-1:this.major>c.major?1:this.minor<c.minor?-1:this.minor>c.minor?1:this.patch<c.patch?-1:this.patch>c.patch?1:0}comparePre(c){if(c instanceof oe||(c=new oe(c,this.options)),this.prerelease.length&&!c.prerelease.length)return-1;if(!this.prerelease.length&&c.prerelease.length)return 1;if(!this.prerelease.length&&!c.prerelease.length)return 0;let m=0;do{let f=this.prerelease[m],d=c.prerelease[m];if(r("prerelease compare",m,f,d),f===void 0&&d===void 0)return 0;if(d===void 0)return 1;if(f===void 0)return-1;if(f!==d)return a(f,d)}while(++m)}compareBuild(c){c instanceof oe||(c=new oe(c,this.options));let m=0;do{let f=this.build[m],d=c.build[m];if(r("build compare",m,f,d),f===void 0&&d===void 0)return 0;if(d===void 0)return 1;if(f===void 0)return-1;if(f!==d)return a(f,d)}while(++m)}inc(c,m,f){if(c.startsWith("pre")){if(!m&&f===!1)throw new Error("invalid increment argument: identifier is empty");if(m){let d=`-${m}`.match(this.options.loose?i[s.PRERELEASELOOSE]:i[s.PRERELEASE]);if(!d||d[1]!==m)throw new Error(`invalid identifier: ${m}`)}}switch(c){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",m,f);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",m,f);break;case"prepatch":this.prerelease.length=0,this.inc("patch",m,f),this.inc("pre",m,f);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",m,f),this.inc("pre",m,f);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let d=Number(f)?1:0;if(this.prerelease.length===0)this.prerelease=[d];else{let E=this.prerelease.length;for(;--E>=0;)typeof this.prerelease[E]=="number"&&(this.prerelease[E]++,E=-2);if(E===-1){if(m===this.prerelease.join(".")&&f===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(d)}}if(m){let E=[m,d];if(f===!1&&(E=[m]),h(this.prerelease,m)){let R=this.prerelease[m.split(".").length];isNaN(R)&&(this.prerelease=E)}else this.prerelease=E}break}default:throw new Error(`invalid increment argument: ${c}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t.exports=u}),he=I((e,t)=>{"use strict";var r=H(),o=(n,i,s=!1)=>{if(n instanceof r)return n;try{return new r(n,i)}catch(l){if(!s)return null;throw l}};t.exports=o}),Vn=I((e,t)=>{"use strict";var r=he(),o=(n,i)=>{let s=r(n,i);return s?s.version:null};t.exports=o}),zn=I((e,t)=>{"use strict";var r=he(),o=(n,i)=>{let s=r(n.trim().replace(/^[=v]+/,""),i);return s?s.version:null};t.exports=o}),Xn=I((e,t)=>{"use strict";var r=H(),o=(n,i,s,l,a)=>{typeof s=="string"&&(a=l,l=s,s=void 0);try{return new r(n instanceof r?n.version:n,s).inc(i,l,a).version}catch{return null}};t.exports=o}),qn=I((e,t)=>{"use strict";var r=he(),o=(n,i)=>{let s=r(n,null,!0),l=r(i,null,!0),a=s.compare(l);if(a===0)return null;let h=a>0,u=h?s:l,w=h?l:s,c=!!u.prerelease.length;if(w.prerelease.length&&!c){if(!w.patch&&!w.minor)return"major";if(w.compareMain(u)===0)return w.minor&&!w.patch?"minor":"patch"}let m=c?"pre":"";return s.major!==l.major?m+"major":s.minor!==l.minor?m+"minor":s.patch!==l.patch?m+"patch":"prerelease"};t.exports=o}),Yn=I((e,t)=>{"use strict";var r=H(),o=(n,i)=>new r(n,i).major;t.exports=o}),Qn=I((e,t)=>{"use strict";var r=H(),o=(n,i)=>new r(n,i).minor;t.exports=o}),Zn=I((e,t)=>{"use strict";var r=H(),o=(n,i)=>new r(n,i).patch;t.exports=o}),ei=I((e,t)=>{"use strict";var r=he(),o=(n,i)=>{let s=r(n,i);return s&&s.prerelease.length?s.prerelease:null};t.exports=o}),ee=I((e,t)=>{"use strict";var r=H(),o=(n,i,s)=>new r(n,s).compare(new r(i,s));t.exports=o}),ti=I((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(i,n,s);t.exports=o}),ri=I((e,t)=>{"use strict";var r=ee(),o=(n,i)=>r(n,i,!0);t.exports=o}),zt=I((e,t)=>{"use strict";var r=H(),o=(n,i,s)=>{let l=new r(n,s),a=new r(i,s);return l.compare(a)||l.compareBuild(a)};t.exports=o}),oi=I((e,t)=>{"use strict";var r=zt(),o=(n,i)=>n.sort((s,l)=>r(s,l,i));t.exports=o}),ni=I((e,t)=>{"use strict";var r=zt(),o=(n,i)=>n.sort((s,l)=>r(l,s,i));t.exports=o}),rt=I((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)>0;t.exports=o}),Xt=I((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)<0;t.exports=o}),Dr=I((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)===0;t.exports=o}),kr=I((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)!==0;t.exports=o}),qt=I((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)>=0;t.exports=o}),Yt=I((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)<=0;t.exports=o}),Ur=I((e,t)=>{"use strict";var r=Dr(),o=kr(),n=rt(),i=qt(),s=Xt(),l=Yt(),a=(h,u,w,c)=>{switch(u){case"===":return typeof h=="object"&&(h=h.version),typeof w=="object"&&(w=w.version),h===w;case"!==":return typeof h=="object"&&(h=h.version),typeof w=="object"&&(w=w.version),h!==w;case"":case"=":case"==":return r(h,w,c);case"!=":return o(h,w,c);case">":return n(h,w,c);case">=":return i(h,w,c);case"<":return s(h,w,c);case"<=":return l(h,w,c);default:throw new TypeError(`Invalid operator: ${u}`)}};t.exports=a}),ii=I((e,t)=>{"use strict";var r=H(),o=he(),{safeRe:n,t:i}=_e(),s=(l,a)=>{if(l instanceof r)return l;if(typeof l=="number"&&(l=String(l)),typeof l!="string")return null;a=a||{};let h=null;if(!a.rtl)h=l.match(a.includePrerelease?n[i.COERCEFULL]:n[i.COERCE]);else{let d=a.includePrerelease?n[i.COERCERTLFULL]:n[i.COERCERTL],E;for(;(E=d.exec(l))&&(!h||h.index+h[0].length!==l.length);)(!h||E.index+E[0].length!==h.index+h[0].length)&&(h=E),d.lastIndex=E.index+E[1].length+E[2].length;d.lastIndex=-1}if(h===null)return null;let u=h[2],w=h[3]||"0",c=h[4]||"0",m=a.includePrerelease&&h[5]?`-${h[5]}`:"",f=a.includePrerelease&&h[6]?`+${h[6]}`:"";return o(`${u}.${w}.${c}${m}${f}`,a)};t.exports=s}),si=I((e,t)=>{"use strict";var r=he(),o=xe(),n=H(),i=(h,u,w)=>{if(!o.RELEASE_TYPES.includes(u))return null;let c=s(h,w);return c&&l(c,u)},s=(h,u)=>{let w=h instanceof n?h.version:h;return r(w,u)},l=(h,u)=>{if(a(u))return h.version;switch(h.prerelease=[],u){case"major":h.minor=0,h.patch=0;break;case"minor":h.patch=0;break}return h.format()},a=h=>h.startsWith("pre");t.exports=i}),ai=I((e,t)=>{"use strict";var r=class{constructor(){this.max=1e3,this.map=new Map}get(o){let n=this.map.get(o);if(n!==void 0)return this.map.delete(o),this.map.set(o,n),n}delete(o){return this.map.delete(o)}set(o,n){if(!this.delete(o)&&n!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(o,n)}return this}};t.exports=r}),te=I((e,t)=>{"use strict";var r=/\s+/g,o=class qe{constructor(g,S){if(S=s(S),g instanceof qe)return g.loose===!!S.loose&&g.includePrerelease===!!S.includePrerelease?g:new qe(g.raw,S);if(g instanceof l)return this.raw=g.value,this.set=[[g]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=g.trim().replace(r," "),this.set=this.raw.split("||").map(b=>this.parseRange(b.trim())).filter(b=>b.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let b=this.set[0];if(this.set=this.set.filter(O=>!j(O[0])),this.set.length===0)this.set=[b];else if(this.set.length>1){for(let O of this.set)if(O.length===1&&W(O[0])){this.set=[O];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let g=0;g<this.set.length;g++){g>0&&(this.formatted+="||");let S=this.set[g];for(let b=0;b<S.length;b++)b>0&&(this.formatted+=" "),this.formatted+=S[b].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(g){g=g.replace(N,"");let S=((this.options.includePrerelease&&E)|(this.options.loose&&R))+":"+g,b=i.get(S);if(b)return b;let O=this.options.loose,v=O?u[c.HYPHENRANGELOOSE]:u[c.HYPHENRANGE];g=g.replace(v,$t(this.options.includePrerelease)),a("hyphen replace",g),g=g.replace(u[c.COMPARATORTRIM],m),a("comparator trim",g),g=g.replace(u[c.TILDETRIM],f),a("tilde trim",g),g=g.replace(u[c.CARETTRIM],d),a("caret trim",g);let A=g.split(" ").map(_=>ne(_,this.options)).join(" ").split(/\s+/).map(_=>It(_,this.options));O&&(A=A.filter(_=>(a("loose invalid filter",_,this.options),!!_.match(u[c.COMPARATORLOOSE])))),a("range list",A);let L=new Map,k=A.map(_=>new l(_,this.options));for(let _ of k){if(j(_))return[_];L.set(_.value,_)}L.size>1&&L.has("")&&L.delete("");let M=[...L.values()];return i.set(S,M),M}intersects(g,S){if(!(g instanceof qe))throw new TypeError("a Range is required");return this.set.some(b=>q(b,S)&&g.set.some(O=>q(O,S)&&b.every(v=>O.every(A=>v.intersects(A,S)))))}test(g){if(!g)return!1;if(typeof g=="string")try{g=new h(g,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(Rt(this.set[S],g,this.options))return!0;return!1}};t.exports=o;var n=ai(),i=new n,s=Vt(),l=ot(),a=tt(),h=H(),{safeRe:u,src:w,t:c,comparatorTrimReplace:m,tildeTrimReplace:f,caretTrimReplace:d}=_e(),{FLAG_INCLUDE_PRERELEASE:E,FLAG_LOOSE:R}=xe(),N=new RegExp(w[c.BUILD],"g"),j=y=>y.value==="<0.0.0-0",W=y=>y.value==="",q=(y,g)=>{let S=!0,b=y.slice(),O=b.pop();for(;S&&b.length;)S=b.every(v=>O.intersects(v,g)),O=b.pop();return S},ne=(y,g)=>(y=y.replace(u[c.BUILD],""),a("comp",y,g),y=Re(y,g),a("caret",y),y=B(y,g),a("tildes",y),y=St(y,g),a("xrange",y),y=At(y,g),a("stars",y),y),C=y=>!y||y.toLowerCase()==="x"||y==="*",x=(y,g,S)=>C(y)&&!C(g)||C(g)&&S&&!C(S),B=(y,g)=>y.trim().split(/\s+/).map(S=>P(S,g)).join(" "),P=(y,g)=>{let S=g.loose?u[c.TILDELOOSE]:u[c.TILDE],b=g.includePrerelease?"-0":"";return y.replace(S,(O,v,A,L,k)=>{a("tilde",y,O,v,A,L,k);let M;return C(v)?M="":C(A)?M=`>=${v}.0.0${b} <${+v+1}.0.0-0`:C(L)?M=`>=${v}.${A}.0${b} <${v}.${+A+1}.0-0`:k?(a("replaceTilde pr",k),M=`>=${v}.${A}.${L}-${k} <${v}.${+A+1}.0-0`):M=`>=${v}.${A}.${L} <${v}.${+A+1}.0-0`,a("tilde return",M),M})},Re=(y,g)=>y.trim().split(/\s+/).map(S=>vt(S,g)).join(" "),vt=(y,g)=>{a("caret",y,g);let S=g.loose?u[c.CARETLOOSE]:u[c.CARET],b=g.includePrerelease?"-0":"";return y.replace(S,(O,v,A,L,k)=>{a("caret",y,O,v,A,L,k);let M;return C(v)?M="":C(A)?M=`>=${v}.0.0${b} <${+v+1}.0.0-0`:C(L)?v==="0"?M=`>=${v}.${A}.0${b} <${v}.${+A+1}.0-0`:M=`>=${v}.${A}.0${b} <${+v+1}.0.0-0`:k?(a("replaceCaret pr",k),v==="0"?A==="0"?M=`>=${v}.${A}.${L}-${k} <${v}.${A}.${+L+1}-0`:M=`>=${v}.${A}.${L}-${k} <${v}.${+A+1}.0-0`:M=`>=${v}.${A}.${L}-${k} <${+v+1}.0.0-0`):(a("no pr"),v==="0"?A==="0"?M=`>=${v}.${A}.${L} <${v}.${A}.${+L+1}-0`:M=`>=${v}.${A}.${L} <${v}.${+A+1}.0-0`:M=`>=${v}.${A}.${L} <${+v+1}.0.0-0`),a("caret return",M),M})},St=(y,g)=>(a("replaceXRanges",y,g),y.split(/\s+/).map(S=>bt(S,g)).join(" ")),bt=(y,g)=>{y=y.trim();let S=g.loose?u[c.XRANGELOOSE]:u[c.XRANGE];return y.replace(S,(b,O,v,A,L,k)=>{if(a("xRange",y,b,O,v,A,L,k),x(v,A,L))return y;let M=C(v),_=M||C(A),ye=_||C(L),Te=ye;return O==="="&&Te&&(O=""),k=g.includePrerelease?"-0":"",M?O===">"||O==="<"?b="<0.0.0-0":b="*":O&&Te?(_&&(A=0),L=0,O===">"?(O=">=",_?(v=+v+1,A=0,L=0):(A=+A+1,L=0)):O==="<="&&(O="<",_?v=+v+1:A=+A+1),O==="<"&&(k="-0"),b=`${O+v}.${A}.${L}${k}`):_?b=`>=${v}.0.0${k} <${+v+1}.0.0-0`:ye&&(b=`>=${v}.${A}.0${k} <${v}.${+A+1}.0-0`),a("xRange return",b),b})},At=(y,g)=>(a("replaceStars",y,g),y.trim().replace(u[c.STAR],"")),It=(y,g)=>(a("replaceGTE0",y,g),y.trim().replace(u[g.includePrerelease?c.GTE0PRE:c.GTE0],"")),$t=y=>(g,S,b,O,v,A,L,k,M,_,ye,Te)=>(C(b)?S="":C(O)?S=`>=${b}.0.0${y?"-0":""}`:C(v)?S=`>=${b}.${O}.0${y?"-0":""}`:A?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,C(M)?k="":C(_)?k=`<${+M+1}.0.0-0`:C(ye)?k=`<${M}.${+_+1}.0-0`:Te?k=`<=${M}.${_}.${ye}-${Te}`:y?k=`<${M}.${_}.${+ye+1}-0`:k=`<=${k}`,`${S} ${k}`.trim()),Rt=(y,g,S)=>{for(let b=0;b<y.length;b++)if(!y[b].test(g))return!1;if(g.prerelease.length&&!S.includePrerelease){for(let b=0;b<y.length;b++)if(a(y[b].semver),y[b].semver!==l.ANY&&y[b].semver.prerelease.length>0){let O=y[b].semver;if(O.major===g.major&&O.minor===g.minor&&O.patch===g.patch)return!0}return!1}return!0}}),ot=I((e,t)=>{"use strict";var r=Symbol("SemVer ANY"),o=class xt{static get ANY(){return r}constructor(c,m){if(m=n(m),c instanceof xt){if(c.loose===!!m.loose)return c;c=c.value}c=c.trim().split(/\s+/).join(" "),a("comparator",c,m),this.options=m,this.loose=!!m.loose,this.parse(c),this.semver===r?this.value="":this.value=this.operator+this.semver.version,a("comp",this)}parse(c){let m=this.options.loose?i[s.COMPARATORLOOSE]:i[s.COMPARATOR],f=c.match(m);if(!f)throw new TypeError(`Invalid comparator: ${c}`);this.operator=f[1]!==void 0?f[1]:"",this.operator==="="&&(this.operator=""),f[2]?this.semver=new h(f[2],this.options.loose):this.semver=r}toString(){return this.value}test(c){if(a("Comparator.test",c,this.options.loose),this.semver===r||c===r)return!0;if(typeof c=="string")try{c=new h(c,this.options)}catch{return!1}return l(c,this.operator,this.semver,this.options)}intersects(c,m){if(!(c instanceof xt))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u(c.value,m).test(this.value):c.operator===""?c.value===""?!0:new u(this.value,m).test(c.semver):(m=n(m),m.includePrerelease&&(this.value==="<0.0.0-0"||c.value==="<0.0.0-0")||!m.includePrerelease&&(this.value.startsWith("<0.0.0")||c.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&c.operator.startsWith(">")||this.operator.startsWith("<")&&c.operator.startsWith("<")||this.semver.version===c.semver.version&&this.operator.includes("=")&&c.operator.includes("=")||l(this.semver,"<",c.semver,m)&&this.operator.startsWith(">")&&c.operator.startsWith("<")||l(this.semver,">",c.semver,m)&&this.operator.startsWith("<")&&c.operator.startsWith(">")))}};t.exports=o;var n=Vt(),{safeRe:i,t:s}=_e(),l=Ur(),a=tt(),h=H(),u=te()}),nt=I((e,t)=>{"use strict";var r=te(),o=(n,i,s)=>{try{i=new r(i,s)}catch{return!1}return i.test(n)};t.exports=o}),ci=I((e,t)=>{"use strict";var r=te(),o=(n,i)=>new r(n,i).set.map(s=>s.map(l=>l.value).join(" ").trim().split(" "));t.exports=o}),li=I((e,t)=>{"use strict";var r=H(),o=te(),n=(i,s,l)=>{let a=null,h=null,u=null;try{u=new o(s,l)}catch{return null}return i.forEach(w=>{u.test(w)&&(!a||h.compare(w)===-1)&&(a=w,h=new r(a,l))}),a};t.exports=n}),ui=I((e,t)=>{"use strict";var r=H(),o=te(),n=(i,s,l)=>{let a=null,h=null,u=null;try{u=new o(s,l)}catch{return null}return i.forEach(w=>{u.test(w)&&(!a||h.compare(w)===1)&&(a=w,h=new r(a,l))}),a};t.exports=n}),pi=I((e,t)=>{"use strict";var r=H(),o=te(),n=rt(),i=(s,l)=>{s=new o(s,l);let a=new r("0.0.0");if(s.test(a)||(a=new r("0.0.0-0"),s.test(a)))return a;a=null;for(let h=0;h<s.set.length;++h){let u=s.set[h],w=null;u.forEach(c=>{let m=new r(c.semver.version);switch(c.operator){case">":m.prerelease.length===0?m.patch++:m.prerelease.push(0),m.raw=m.format();case"":case">=":(!w||n(m,w))&&(w=m);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${c.operator}`)}}),w&&(!a||n(a,w))&&(a=w)}return a&&s.test(a)?a:null};t.exports=i}),di=I((e,t)=>{"use strict";var r=te(),o=(n,i)=>{try{return new r(n,i).range||"*"}catch{return null}};t.exports=o}),Qt=I((e,t)=>{"use strict";var r=H(),o=ot(),{ANY:n}=o,i=te(),s=nt(),l=rt(),a=Xt(),h=Yt(),u=qt(),w=(c,m,f,d)=>{c=new r(c,d),m=new i(m,d);let E,R,N,j,W;switch(f){case">":E=l,R=h,N=a,j=">",W=">=";break;case"<":E=a,R=u,N=l,j="<",W="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(c,m,d))return!1;for(let q=0;q<m.set.length;++q){let ne=m.set[q],C=null,x=null;if(ne.forEach(B=>{B.semver===n&&(B=new o(">=0.0.0")),C=C||B,x=x||B,E(B.semver,C.semver,d)?C=B:N(B.semver,x.semver,d)&&(x=B)}),C.operator===j||C.operator===W||(!x.operator||x.operator===j)&&R(c,x.semver)||x.operator===W&&N(c,x.semver))return!1}return!0};t.exports=w}),mi=I((e,t)=>{"use strict";var r=Qt(),o=(n,i,s)=>r(n,i,">",s);t.exports=o}),hi=I((e,t)=>{"use strict";var r=Qt(),o=(n,i,s)=>r(n,i,"<",s);t.exports=o}),fi=I((e,t)=>{"use strict";var r=te(),o=(n,i,s)=>(n=new r(n,s),i=new r(i,s),n.intersects(i,s));t.exports=o}),gi=I((e,t)=>{"use strict";var r=nt(),o=ee();t.exports=(n,i,s)=>{let l=[],a=null,h=null,u=n.sort((f,d)=>o(f,d,s));for(let f of u)r(f,i,s)?(h=f,a||(a=f)):(h&&l.push([a,h]),h=null,a=null);a&&l.push([a,null]);let w=[];for(let[f,d]of l)f===d?w.push(f):!d&&f===u[0]?w.push("*"):d?f===u[0]?w.push(`<=${d}`):w.push(`${f} - ${d}`):w.push(`>=${f}`);let c=w.join(" || "),m=typeof i.raw=="string"?i.raw:String(i);return c.length<m.length?c:i}}),wi=I((e,t)=>{"use strict";var r=te(),o=ot(),{ANY:n}=o,i=nt(),s=ee(),l=(m,f,d={})=>{if(m===f)return!0;m=new r(m,d),f=new r(f,d);let E=!1;e:for(let R of m.set){for(let N of f.set){let j=u(R,N,d);if(E=E||j!==null,j)continue e}if(E)return!1}return!0},a=[new o(">=0.0.0-0")],h=[new o(">=0.0.0")],u=(m,f,d)=>{if(m===f)return!0;if(m.length===1&&m[0].semver===n){if(f.length===1&&f[0].semver===n)return!0;d.includePrerelease?m=a:m=h}if(f.length===1&&f[0].semver===n){if(d.includePrerelease)return!0;f=h}let E=new Set,R,N;for(let P of m)P.operator===">"||P.operator===">="?R=w(R,P,d):P.operator==="<"||P.operator==="<="?N=c(N,P,d):E.add(P.semver);if(E.size>1)return null;let j;if(R&&N&&(j=s(R.semver,N.semver,d),j>0||j===0&&(R.operator!==">="||N.operator!=="<=")))return null;for(let P of E){if(R&&!i(P,String(R),d)||N&&!i(P,String(N),d))return null;for(let Re of f)if(!i(P,String(Re),d))return!1;return!0}let W,q,ne,C,x=N&&!d.includePrerelease&&N.semver.prerelease.length?N.semver:!1,B=R&&!d.includePrerelease&&R.semver.prerelease.length?R.semver:!1;x&&x.prerelease.length===1&&N.operator==="<"&&x.prerelease[0]===0&&(x=!1);for(let P of f){if(C=C||P.operator===">"||P.operator===">=",ne=ne||P.operator==="<"||P.operator==="<=",R){if(B&&P.semver.prerelease&&P.semver.prerelease.length&&P.semver.major===B.major&&P.semver.minor===B.minor&&P.semver.patch===B.patch&&(B=!1),P.operator===">"||P.operator===">="){if(W=w(R,P,d),W===P&&W!==R)return!1}else if(R.operator===">="&&!P.test(R.semver))return!1}if(N){if(x&&P.semver.prerelease&&P.semver.prerelease.length&&P.semver.major===x.major&&P.semver.minor===x.minor&&P.semver.patch===x.patch&&(x=!1),P.operator==="<"||P.operator==="<="){if(q=c(N,P,d),q===P&&q!==N)return!1}else if(N.operator==="<="&&!P.test(N.semver))return!1}if(!P.operator&&(N||R)&&j!==0)return!1}return!(R&&ne&&!N&&j!==0||N&&C&&!R&&j!==0||B||x)},w=(m,f,d)=>{if(!m)return f;let E=s(m.semver,f.semver,d);return E>0?m:E<0||f.operator===">"&&m.operator===">="?f:m},c=(m,f,d)=>{if(!m)return f;let E=s(m.semver,f.semver,d);return E<0?m:E>0||f.operator==="<"&&m.operator==="<="?f:m};t.exports=l}),xr=I((e,t)=>{"use strict";var r=_e(),o=xe(),n=H(),i=Mr(),s=he(),l=Vn(),a=zn(),h=Xn(),u=qn(),w=Yn(),c=Qn(),m=Zn(),f=ei(),d=ee(),E=ti(),R=ri(),N=zt(),j=oi(),W=ni(),q=rt(),ne=Xt(),C=Dr(),x=kr(),B=qt(),P=Yt(),Re=Ur(),vt=ii(),St=si(),bt=ot(),At=te(),It=nt(),$t=ci(),Rt=li(),y=ui(),g=pi(),S=di(),b=Qt(),O=mi(),v=hi(),A=fi(),L=gi(),k=wi();t.exports={parse:s,valid:l,clean:a,inc:h,diff:u,major:w,minor:c,patch:m,prerelease:f,compare:d,rcompare:E,compareLoose:R,compareBuild:N,sort:j,rsort:W,gt:q,lt:ne,eq:C,neq:x,gte:B,lte:P,cmp:Re,coerce:vt,truncate:St,Comparator:bt,Range:At,satisfies:It,toComparators:$t,maxSatisfying:Rt,minSatisfying:y,minVersion:g,validRange:S,outside:b,gtr:O,ltr:v,intersects:A,simplifyRange:L,subset:k,SemVer:n,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:o.SEMVER_SPEC_VERSION,RELEASE_TYPES:o.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}}),We=class extends Fr.ClientStorage{constructor(e){super(),X(this,"dirName"),X(this,"fileName"),this.dirName=(0,_t.resolve)((0,Wr.homedir)(),".medplum"),this.fileName=(0,_t.resolve)(this.dirName,e+".json")}clear(){this.writeFile({})}getString(e){return this.readFile()?.[e]}setString(e,t){let r=this.readFile()??{};t?r[e]=t:delete r[e],this.writeFile(r)}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?JSON.stringify(t):void 0)}readFile(){if((0,ie.existsSync)(this.fileName))return JSON.parse((0,ie.readFileSync)(this.fileName,"utf8"))}writeFile(e){(0,ie.existsSync)(this.dirName)||(0,ie.mkdirSync)(this.dirName),(0,ie.writeFileSync)(this.fileName,JSON.stringify(e,null,2),"utf8")}};async function U(e,t=!0){let r=e.profile??"default",o=new We(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:s,accessToken:l,tokenUrl:a,authorizeUrl:h,clientId:u,clientSecret:w}=yi(e,o),c=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await Ei(e.baseUrl,c);let m=new jr.MedplumClient({fetch:c,baseUrl:i,tokenUrl:a,fhirUrlPath:s,authorizeUrl:h,storage:o,onUnauthenticated:vi,verbose:e.verbose});return t&&(l?m.setAccessToken(l):u&&w&&(m.setBasicAuth(u,w),n?.authType!=="basic"&&await m.startClientLogin(u,w))),m}function yi(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,l=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,a=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,h=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:i,tokenUrl:s,authorizeUrl:l,clientId:a,clientSecret:h}}async function Ei(e,t){try{let r=new URL("healthcheck",e).toString(),o=await t(r);if(!o.ok)throw new Error(`Healthcheck returned status ${o.status}`);if((await o.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${o}`)}}function vi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Gr=new TextEncoder,dr=new TextDecoder,qa=new TextDecoder("utf-8",{fatal:!0}),Ya=2**32;function Si(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function jt(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=o}return t}var Ve=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function bi(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Ai(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Ii(e,t,r){let o=e.algorithm;if(o.name!==t.name)throw Ve(t.name);if(t.hash&&o.hash?.name!==t.hash)throw Ve(t.hash,"algorithm.hash");if(t.namedCurve&&o.namedCurve!==t.namedCurve)throw Ve(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&o.length!==t.length)throw Ve(t.length,"algorithm.length");bi(e,r)}function $i(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var ze=(e,t,...r)=>$i(`Key for the ${e} algorithm must be `,t,...r),Be=class extends Error{constructor(e,t){super(e,t),X(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};X(Be,"code","ERR_JOSE_GENERIC");var ke=class extends Be{constructor(){super(...arguments),X(this,"code","ERR_JOSE_NOT_SUPPORTED")}};X(ke,"code","ERR_JOSE_NOT_SUPPORTED");var pe=class extends Be{constructor(){super(...arguments),X(this,"code","ERR_JWS_INVALID")}};X(pe,"code","ERR_JWS_INVALID");var Kr=class extends Be{constructor(){super(...arguments),X(this,"code","ERR_JWT_INVALID")}};X(Kr,"code","ERR_JWT_INVALID");var mr,hr,Ri=class extends(hr=Be,mr=Symbol.asyncIterator,hr){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),X(this,mr,async function*(){}),X(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};X(Ri,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Hr=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ti=e=>e?.[Symbol.toStringTag]==="KeyObject",Pi=e=>Hr(e)||Ti(e);function Oi(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let o=0;o<e.length;o+=t)r.push(String.fromCharCode.apply(null,e.subarray(o,o+t)));return btoa(r.join(""))}function Ni(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}var Tt="The input to be decoded is not correctly encoded.";function Ci(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e=="string"?e:dr.decode(e),{alphabet:"base64url"})}catch(r){throw new TypeError(Tt,{cause:r})}let t=e;if(t instanceof Uint8Array&&(t=dr.decode(t)),t.includes("+")||t.includes("/"))throw new TypeError(Tt);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Ni(t)}catch{throw new TypeError(Tt)}}function Zt(e){let t=e;return typeof t=="string"&&(t=Gr.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):Oi(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function er(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Li(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}async function Mi(e,t){if(t.kty==="RSA"&&"oth"in t&&t.oth!==void 0)throw new ke('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');if(!e.kty.includes(t.kty))throw new ke('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,o=!!(t.d||t.priv),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,r,t.ext??!o,t.key_ops??e.usages[o?1:0])}function Di(e){return{__proto__:null,...e}}function ki(e){let t=Di(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=o}return t}var Pt=e=>e[Symbol.toStringTag],Ui=(e,t,r)=>{let{alg:o}=e;if(t.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(t.key_ops)){let n=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(n&&!t.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};function xi(e,t,r){let{alg:o,secret:n}=e,i=r==="decrypt"||r==="sign";if(n&&t instanceof Uint8Array)return[Jr,t];if(er(t)){let s=ki(t);if(typeof s.kty!="string")throw new TypeError(n?ze(o,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):ze(o,t,"CryptoKey","KeyObject","JSON Web Key"));if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);return Ui(e,s,r),[Xr,t,s]}if(!Pi(t))throw new TypeError(n?ze(o,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):ze(o,t,"CryptoKey","KeyObject","JSON Web Key"));if(n){if(t.type!=="secret")throw new TypeError(`${Pt(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type==="secret")throw new TypeError(`${Pt(t)} instances for asymmetric algorithms must not be of type "secret"`);let s=i?"private":"public";if((t.type==="public"||t.type==="private")&&t.type!==s){let l=r==="sign"?"signing":r==="verify"?"verifying":`${r.slice(0,-1)}tion`;throw new TypeError(`${Pt(t)} instances for asymmetric algorithm ${l} must be of type "${s}"`)}}return Hr(t)?[Vr,t]:[zr,t]}var Jr=0,Vr=1,zr=2,Xr=3,Ot,_i={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function Qe(e,t,r){Ot||=new WeakMap;let o=Ot.get(e);return r&&(o?o[t]=r:Ot.set(e,{[t]:r})),r??o?.[t]}var fr=async(e,t,r)=>Qe(e,r.alg)??Qe(e,r.alg,await Mi(r,{...t,alg:r.alg})),ji=(e,t)=>{let r=Qe(e,t.alg);if(r)return r;let o=e.type==="public",n=t.usages[o?0:1],{asymmetricKeyType:i}=e,s=_i[e.asymmetricKeyDetails?.namedCurve],l=t.resolve?.({crv:s,asymmetricKeyType:i})??t.subtle;return Qe(e,t.alg,e.toCryptoKey(l,o,n))};async function Fi(e,t,r){let o=xi(e,t,r);switch(o[0]){case Jr:case Vr:return o[1];case Xr:{let n=o[1],i=o[2];if(i.kty==="oct")return Ci(i.k);if(!Object.isFrozen(n)){let{key_ops:s}=n;Array.isArray(s)&&Object.freeze(s),Object.freeze(n)}return fr(n,i,e)}case zr:{let n=o[1];return n.type==="secret"?n.export():"toCryptoKey"in n&&typeof n.toCryptoKey=="function"?ji(n,e):fr(n,n.export({format:"jwk"}),e)}}}function Wi(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Bi={__proto__:null,b64:!0};function Gi(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Ki(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?t:{__proto__:null,...r,...t};for(let s of o.crit){if(!(s in i))throw new ke(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function Hi(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new pe('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Ji(e,t){let r,o;try{r=JSON.stringify(t),o=JSON.parse(r)}catch(n){throw new e("JOSE Header is not valid JSON",{cause:n})}if(!er(o))throw new e("JOSE Header is not a JSON object");return[o,r]}async function Vi(e,t,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,e.subtle,!1,[r]):(Ii(t,e.subtle,r),e.minRsaBits&&Ai(e.alg,t),t)}async function zi(e,t,r){let o=await Vi(e,t,"sign"),n=await crypto.subtle.sign(e.signing,o,r);return new Uint8Array(n)}var Ge=[["verify"],["sign"]];function Nt(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Ge}}function Ee(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Ge,minRsaBits:2048}}function Ct(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Ge}}function gr(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Ge}}function Lt(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Ge}}var Xi=Wi({HS256:Nt(256),HS384:Nt(384),HS512:Nt(512),RS256:Ee(256),RS384:Ee(384),RS512:Ee(512),PS256:Ee(256,32),PS384:Ee(384,48),PS512:Ee(512,64),ES256:Ct("P-256",256),ES384:Ct("P-384",384),ES512:Ct("P-521",512),EdDSA:gr(),Ed25519:gr(),"ML-DSA-44":Lt(44),"ML-DSA-65":Lt(65),"ML-DSA-87":Lt(87)});function qi(e){let t=typeof e=="string"?Xi[e]:void 0;if(!t)throw new ke(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var Ze=e=>Math.floor(e.getTime()/1e3),Yi={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Qi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Mt(){throw new TypeError("Invalid time period format")}function qr(e){typeof e!="string"&&Mt();let t=Qi.exec(e);(!t||t[4]&&t[1])&&Mt();let r=parseFloat(t[2]),o=Math.round(r*Yi[t[3][0].toLowerCase()]);return Number.isFinite(o)||Mt(),t[1]==="-"||t[4]==="ago"?-o:o}function Ft(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function Dt(e,t){if(typeof t!="string")throw new TypeError(`"${e}" claim must be a string`)}function Zi(e){if(typeof e!="string"&&(!Array.isArray(e)||Array.from(e).some(t=>typeof t!="string")))throw new TypeError('"aud" claim must be a string or an array of strings')}function kt(e,t){return typeof e=="number"?Ft(t,e):e instanceof Date?Ft(t,Ze(e)):Ze(new Date)+qr(e)}var Yr;function le(e){return Yr.get(e)}function es(e){let t=le(e);for(let r of["iat","nbf","exp"]){let o=t[r];if(typeof o=="number"&&!Number.isFinite(o))throw new TypeError(`"${r}" claim must be a finite number`)}return Gr.encode(JSON.stringify(t))}var ts=class{constructor(e={}){if(!er(e))throw new TypeError("JWT Claims Set MUST be an object");(Yr||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Dt("iss",e),le(this).iss=e,this}setSubject(e){return Dt("sub",e),le(this).sub=e,this}setAudience(e){return Zi(e),le(this).aud=e,this}setJti(e){return Dt("jti",e),le(this).jti=e,this}setNotBefore(e){return le(this).nbf=kt(e,"setNotBefore"),this}setExpirationTime(e){return le(this).exp=kt(e,"setExpirationTime"),this}setIssuedAt(e){let t=le(this);return e===void 0?t.iat=Ze(new Date):typeof e=="string"?t.iat=Ft("setIssuedAt",Ze(new Date)+qr(e)):t.iat=kt(e,"setIssuedAt"),this}};function rs(e){if(e===void 0)return[void 0,""];let t=Ji(pe,e);return[t[0],Zt(t[1])]}function os(e,t,r){return Gi(pe,e),Hi(e,Ki(pe,Bi,r,e,t))}function ns(e){let t=e.alg;if(typeof t!="string"||!t)throw new pe('JWS "alg" (Algorithm) Header Parameter missing or invalid');return qi(t)}async function is(e,t,r,o){let n=Si(jt(e),jt("."),t),i=await Fi(r,o,"sign");return Zt(await zi(r,i,n))}async function ss(e,t,r,o,n){let[i,s]=rs(t);if(!i)throw new pe("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");os(i,i,r)||n();let l=ns(i),a=Zt(e),h=await is(s,jt(a),l,o);return`${s}.${a}.${h}`}var as=ts,Ce,cs=class extends as{constructor(){super(...arguments),Hn(this,Ce)}setProtectedHeader(e){return Li(pr(this,Ce),"setProtectedHeader"),Jn(this,Ce,e),this}async sign(e,t){return ss(es(this),pr(this,Ce),t?.crit,e,()=>{throw new Kr("JWTs MUST NOT use unencoded payload")})}};Ce=new WeakMap;function de(e){console.log(JSON.stringify(e,null,2))}async function eo(e,t,r){let o=t.source,n=it(o);if(!n)return;console.log("Saving source code...");let i=await e.createAttachment({data:n,filename:(0,se.basename)(o),contentType:hs(o)});console.log("Updating bot...");let s=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+s.meta?.versionId)}async function to(e,t,r){let o=t.dist??t.source,n=it(o);if(!n)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,se.basename)(o)});if(console.log("Deploy result: "+i.issue?.[0]?.details?.text),!(0,J.isOk)(i))throw new Error(`Bot deploy failed: ${(0,J.normalizeErrorString)(i)}`)}async function ro(e,t,r,o,n,i,s){let l={name:t,description:"",runtimeVersion:i},a=await e.post("admin/projects/"+r+"/bot",l),h=await e.readResource("Bot",a.id),u={name:t,id:a.id,source:o,dist:n};await eo(e,u,h),await to(e,u,h),console.log(`Success! Bot created: ${h.id}`),s&&ps(u)}function ls(e){let t=new RegExp("^"+ds(e).replaceAll(String.raw`\*`,".*")+"$");return Ae()?.bots?.filter(o=>t.test(o.name))||[]}function fe(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function G(e,t){(0,ue.writeFileSync)((0,se.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function Ae(e,t){let r=fe(e,t),o=it(r);if(o)return JSON.parse(o)}function us(e){let t=it(fe(e,{server:!0}));if(t)return JSON.parse(t)}function it(e){let t=(0,se.resolve)(e);return(0,ue.existsSync)(t)?(0,ue.readFileSync)(t,"utf8"):""}function ps(e){let t=Ae()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ue.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ds(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function ms(e){let t=0,r=0;return(0,Zr.extract)({cwd:e,filter:(o,n)=>{if(t++,t>100)throw new Error("Tar extractor reached max number of files");if(r+=n.size,r>10485760)throw new Error("Tar extractor reached max size");return!0}})}function wr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function hs(e){let t=(0,se.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?J.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?J.ContentType.TYPESCRIPT:J.ContentType.TEXT}function oo(e,t){let r=new We(e),o={name:e,...t};return r.setObject("options",o),o}function fs(e){return new We(e).getObject("options")}async function gs(e,t){let r={typ:"JWT",alg:J.OAuthSigningAlgorithm.HS256},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},i=(0,J.encodeBase64)(JSON.stringify(r)),s=(0,J.encodeBase64)(JSON.stringify(n)),l=`${i}.${s}`,a=(0,be.createHmac)("sha256",t.clientSecret).update(l).digest("base64url"),h=`${l}.${a}`;await e.startJwtBearerLogin(t.clientId,h,t.scope??"")}async function ws(e,t){let r=(0,be.createPrivateKey)((0,ue.readFileSync)((0,se.resolve)(t.privateKeyPath))),o=await new cs({}).setProtectedHeader({typ:"JWT",alg:J.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,be.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function T(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var $=class extends Br.Command{action(e){let t=ys(this,e);return super._actionHandler=t,this}resetOptionDefaults(){this._optionValues={};for(let e of this.options)e.defaultValue!==void 0&&(this._optionValues[e.attributeName()]=e.defaultValue)}};function ys(e,t){return async r=>{let o=e.registeredArguments.length,n=r.slice(0,o);n[o]=e.optsWithGlobals();try{let i=t(...n);(0,Qr.isPromise)(i)&&await i}finally{e.resetOptionDefaults()}}}var no=new $("status").aliases(["info","list","ls"]),io=new $("ping"),so=new $("push"),ao=new $("reload-config"),co=new $("upgrade"),lo=new $("stats"),ge=new $("agent");T(ge,no);T(ge,io);T(ge,so);T(ge,ao);T(ge,co);T(ge,lo);no.description("Get the status of a specified agent").argument("[agentIds...]","The ID(s) of the agent(s) to get the status of").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg").addOption(new Fe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await st({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=po(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});io.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await U(r),n=await uo(o,t,r),i=Number.parseInt(r.count,10);if(Number.isNaN(i))throw new Error("--count <count> must be an integer if specified");try{let s=await o.pushToAgent(n,e,`PING ${i}`,re.ContentType.PING,!0,{maxRetries:0});console.info(s)}catch(s){throw new Error("Unexpected response from agent while pinging",{cause:s})}});so.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",re.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let n=await U(o),i=await uo(n,r,o),s;try{s=await n.pushToAgent(i,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(l){throw new Error("Unexpected response from agent while pushing message to agent",{cause:l})}console.info(s)});ao.description("Reload the config for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg").addOption(new Fe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await st({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});co.description("Upgrade the version for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg").option("--agentVersion <version>","An optional agent version to upgrade to. Defaults to the latest version if flag not included").option("--force","Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.").addOption(new Fe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await st({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});lo.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new Fe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await st({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:o}=po(r.result,{required:["stats"]}),n;try{n=JSON.parse(o)}catch(i){console.error(`Failed to parse stats for agent ${r.agent.id}: ${(0,re.normalizeErrorString)(i)}`)}return{id:r.agent.id,name:r.agent.name,stats:n}},renderSuccessfulRows:r=>{for(let o=0;o<r.length;o++)o>0&&console.info(),Es(r[o])}})});var yr=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function Er(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function vr(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function Es(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let s of yr)r[s]=Er(e.stats[s]);let o=new Set([...yr,"channelStats","clientStats"]);for(let[s,l]of Object.entries(e.stats))o.has(s)||(r[s]=Er(l));console.table(r);let n=vr(e.stats.channelStats);n.length&&(console.info("Channel Stats:"),console.table(n));let i=vr(e.stats.clientStats);i.length&&(console.info("Client Stats:"),console.table(i))}async function st({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n,renderSuccessfulRows:i}){let s=As(t,r),l=await U(r),a=s.type==="criteria"?s.criteria:`Agent?_id=${s.ids.join(",")}`,h=new URLSearchParams(a.split("?")[1]);for(let[d,E]of Object.entries(o))h.append(d,E.toString());let u;try{let d=l.fhirUrl("Agent",e);d.search=h.toString(),u=await l.get(d,{cache:"reload"})}catch(d){throw new Error(`Operation '${e}' failed`,{cause:d})}if(r.output==="json"){console.info(JSON.stringify(u,null,2));return}let w=[],c=[];switch(u.resourceType){case"Bundle":{let d=vs(u);for(let E of d)E.result.resourceType==="Parameters"||(0,re.isOk)(E.result)?w.push(E):c.push(E);break}case"Parameters":case"OperationOutcome":{let d=await l.searchOne("Agent",h,{cache:"reload"});if(!d)throw new Error("Agent not found");u.resourceType==="Parameters"?w.push({agent:d,result:u}):c.push({agent:d,result:u});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(u)}`)}let m=[];for(let d of w){let E=n(d);m.push(E)}let f=[];for(let d of c){let E=d.result.issue?.[0],R={id:d.agent.id,name:d.agent.name,severity:E.severity,code:E.code,details:E.details?.text??"No details to show"};f.push(R)}console.info(`
3
- ${m.length} successful response(s):
4
- `),i?m.length?i(m):console.info("No successful responses received"):console.table(m.length?m:"No successful responses received"),console.info(),f.length&&(console.info(`${f.length} failed response(s):`),console.info(),console.table(f))}async function uo(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(t)o=t;else{mo(r.criteria);let n=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!n?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(n.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=n.entry[0].resource?.id}return{reference:`Agent/${o}`}}function vs(e){let t=[];for(let r of e.entry??re.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(Ss(r.resource))}return t}function Ss(e){let t=e.parameter?.find(o=>o.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function po(e,t){let r={},o=t.required,n=t.optional;for(let i of o){let s=e.parameter?.find(a=>a.name===i);if(!s)throw new Error(`Failed to find parameter '${i}'`);let l;for(let a in s)if(a.startsWith("value")){if(l)throw new Error(`Found multiple values for parameter '${i}'`);l=a}if(!l)throw new Error(`Failed to find a value for parameter '${i}'`);r[i]=s[l]}if(n?.length)for(let i of n){let s=e.parameter?.find(a=>a.name===i);if(!s)continue;let l=bs(i,s);r[i]=l}return r}function bs(e,t){let r;for(let o in t)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function As(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!(0,re.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return mo(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function mo(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,o]=e.split("?");if(r!=="Agent"||!o)throw new Error(t);try{new URLSearchParams(o)}catch(n){throw new Error(t,{cause:n})}if(!o.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var Is=(0,wo.promisify)(ho.exec),yo=Z.MEDPLUM_CLI_CLIENT_ID,Eo="http://localhost:9615",vo=new $("login"),So=new $("whoami"),bo=new $("token");vo.action(async e=>{let t=e.profile??"default",r=oo(t,e),o=await U(e,!1);await $s(o,r)});So.action(async e=>{let t=await U(e);Ps(t)});bo.action(async e=>{let t=await U(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function $s(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Os(e,t);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await gs(e,t);break;case"jwt-assertion":await ws(e,t);break}}async function Rs(e){let t=(0,fo.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),i=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":Z.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let s=await e.processCode(i,{clientId:yo,redirectUri:Eo});o.writeHead(200,{"Content-Type":Z.ContentType.TEXT}),o.end(`Signed in as ${(0,Z.getDisplayString)(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Z.ContentType.TEXT}),o.end(`Error: ${(0,Z.normalizeErrorString)(s)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":Z.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function Ts(e){let t=(0,go.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}await Is(r)}function Ps(e){let t=e.getActiveLogin();t?(console.log(`Server: ${e.getBaseUrl()}`),console.log(`Profile: ${t.profile.display} (${t.profile.reference})`),console.log(`Project: ${t.project.display} (${t.project.reference})`)):console.log("Not logged in")}async function Os(e,t){await Rs(e);let r=new URL(e.getAuthorizeUrl());r.searchParams.set("client_id",yo),r.searchParams.set("redirect_uri",Eo),r.searchParams.set("scope",t.scope??"openid offline_access"),r.searchParams.set("response_type","code"),r.searchParams.set("prompt","login"),await Ts(r.toString())}var Pe="\x1B[0m",Ns="\x1B[1m",Cs="\x1B[31m",Ls="\x1B[32m",Ms="\x1B[33m",Ds="\x1B[34m",De={red:e=>`${Cs}${e}${Pe}`,green:e=>`${Ls}${e}${Pe}`,yellow:e=>`${Ms}${e}${Pe}`,blue:e=>`${Ds}${e}${Pe}`,bold:e=>`${Ns}${e}${Pe}`},Sr=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>De.bold(r)),ks=Cr(xr(),1),ut;function To(){ut=Ro.default.createInterface({input:process.stdin,output:process.stdout})}function Po(){ut.close()}function p(e){ut.write(e+`
5
- `)}function F(e){p(`
2
+ "use strict";var In=Object.create;var ar=Object.defineProperty;var $n=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var Tn=Object.getPrototypeOf,Pn=Object.prototype.hasOwnProperty;var On=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rn(t))!Pn.call(e,n)&&n!==r&&ar(e,n,{get:()=>t[n],enumerable:!(o=$n(t,n))||o.enumerable});return e};var le=(e,t,r)=>(r=e!=null?In(Tn(e)):{},On(t||!e||!e.__esModule?ar(r,"default",{value:e,enumerable:!0}):r,e));var ve=require("@medplum/core"),je=require("commander"),kr=le(require("dotenv"),1),re=require("@medplum/core"),_e=require("commander"),Ur=require("@medplum/core"),xr=require("@medplum/core"),se=require("node:fs"),jr=require("node:os"),xt=require("node:path"),V=require("@medplum/core"),_r=require("commander"),be=require("node:crypto"),pe=require("node:fs"),ae=require("node:path"),Hr=require("node:util/types"),Kr=require("tar"),Z=require("@medplum/core"),io=require("node:child_process"),so=require("node:http"),ao=require("node:os"),co=require("node:util"),ce=require("@aws-sdk/client-cloudformation"),at=require("@aws-sdk/client-cloudfront"),mo=require("@aws-sdk/client-ecs"),go=require("@aws-sdk/client-s3"),Ie=require("@aws-sdk/client-ssm"),ct=require("@aws-sdk/client-sts"),lt=require("@medplum/core"),wo=require("node:fs"),yo=le(require("node:readline"),1),we=require("@aws-sdk/client-acm"),dt=require("@aws-sdk/client-cloudfront"),ht=require("@aws-sdk/client-sts"),To=require("@medplum/core"),ke=require("node:crypto"),Po=require("node:fs"),No=require("@aws-sdk/client-s3"),Q=require("@medplum/core"),Co=le(require("fast-glob"),1),Y=require("node:fs"),Lo=require("node:os"),he=require("node:path"),Mo=require("node:stream"),Do=require("node:stream/promises"),ft=require("@aws-sdk/client-s3"),Uo=require("node:child_process"),z=require("@medplum/core"),wt=require("node:fs"),rr=require("node:path"),Go=require("node:readline"),Ho=require("node:stream"),Ko=require("node:stream/promises"),qe=le(require("fast-glob"),1),nr=require("node:events"),zo=require("node:fs"),yt=require("node:fs/promises"),$e=require("node:path"),Xo=require("node:stream"),Et=require("@medplum/core"),Le=le(require("node:assert"),1),Zo=le(require("node:net"),1),H=require("@medplum/core"),Wt=le(require("iconv-lite"),1),Ga=require("@medplum/core"),en=require("@medplum/core"),tn=le(require("node:net"),1),nn=require("node:fs"),sn=require("node:fs"),an=require("node:os"),cn=require("node:path"),hn=require("commander"),yn=require("@medplum/core"),Nn=Object.create,Ht=Object.defineProperty,Cn=Object.getOwnPropertyDescriptor,Ln=Object.getOwnPropertyNames,Mn=Object.getPrototypeOf,Dn=Object.prototype.hasOwnProperty,Tr=e=>{throw TypeError(e)},kn=(e,t,r)=>t in e?Ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Un=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ln(t))!Dn.call(e,n)&&n!==r&&Ht(e,n,{get:()=>t[n],enumerable:!(o=Cn(t,n))||o.enumerable});return e},Pr=(e,t,r)=>(r=e!=null?Nn(Mn(e)):{},Un(t||!e||!e.__esModule?Ht(r,"default",{value:e,enumerable:!0}):r,e)),X=(e,t,r)=>kn(e,typeof t!="symbol"?t+"":t,r),Or=(e,t,r)=>t.has(e)||Tr("Cannot "+r),cr=(e,t,r)=>(Or(e,t,"read from private field"),r?r.call(e):t.get(e)),xn=(e,t,r)=>t.has(e)?Tr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),jn=(e,t,r,o)=>(Or(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r),Ue=$((e,t)=>{"use strict";var r="2.0.0",o=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,i=250,s=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:o,RELEASE_TYPES:s,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}),Ze=$((e,t)=>{"use strict";var r=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...o)=>console.error("SEMVER",...o):()=>{};t.exports=r}),xe=$((e,t)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:n}=Ue(),i=Ze();e=t.exports={};var s=e.re=[],l=e.safeRe=[],a=e.src=[],f=e.safeSrc=[],u=e.t={},g=0,c="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",n],[c,o]],m=E=>{for(let[I,N]of h)E=E.split(`${I}*`).join(`${I}{0,${N}}`).split(`${I}+`).join(`${I}{1,${N}}`);return E},p=(E,I,N)=>{let _=m(I),W=g++;i(E,W,I),u[E]=W,a[W]=I,f[W]=_,s[W]=new RegExp(I,N?"g":void 0),l[W]=new RegExp(_,N?"g":void 0)};p("NUMERICIDENTIFIER","0|[1-9]\\d*"),p("NUMERICIDENTIFIERLOOSE","\\d+"),p("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${c}*`),p("MAINVERSION",`(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})`),p("MAINVERSIONLOOSE",`(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASEIDENTIFIER",`(?:${a[u.NONNUMERICIDENTIFIER]}|${a[u.NUMERICIDENTIFIER]})`),p("PRERELEASEIDENTIFIERLOOSE",`(?:${a[u.NONNUMERICIDENTIFIER]}|${a[u.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASE",`(?:-(${a[u.PRERELEASEIDENTIFIER]}(?:\\.${a[u.PRERELEASEIDENTIFIER]})*))`),p("PRERELEASELOOSE",`(?:-?(${a[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[u.PRERELEASEIDENTIFIERLOOSE]})*))`),p("BUILDIDENTIFIER",`${c}+`),p("BUILD",`(?:\\+(${a[u.BUILDIDENTIFIER]}(?:\\.${a[u.BUILDIDENTIFIER]})*))`),p("FULLPLAIN",`v?${a[u.MAINVERSION]}${a[u.PRERELEASE]}?${a[u.BUILD]}?`),p("FULL",`^${a[u.FULLPLAIN]}$`),p("LOOSEPLAIN",`[v=\\s]*${a[u.MAINVERSIONLOOSE]}${a[u.PRERELEASELOOSE]}?${a[u.BUILD]}?`),p("LOOSE",`^${a[u.LOOSEPLAIN]}$`),p("GTLT","((?:<|>)?=?)"),p("XRANGEIDENTIFIERLOOSE",`${a[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),p("XRANGEIDENTIFIER",`${a[u.NUMERICIDENTIFIER]}|x|X|\\*`),p("XRANGEPLAIN",`[v=\\s]*(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:${a[u.PRERELEASE]})?${a[u.BUILD]}?)?)?`),p("XRANGEPLAINLOOSE",`[v=\\s]*(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:${a[u.PRERELEASELOOSE]})?${a[u.BUILD]}?)?)?`),p("XRANGE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAIN]}$`),p("XRANGELOOSE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAINLOOSE]}$`),p("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),p("COERCE",`${a[u.COERCEPLAIN]}(?:$|[^\\d])`),p("COERCEFULL",a[u.COERCEPLAIN]+`(?:${a[u.PRERELEASE]})?(?:${a[u.BUILD]})?(?:$|[^\\d])`),p("COERCERTL",a[u.COERCE],!0),p("COERCERTLFULL",a[u.COERCEFULL],!0),p("LONETILDE","(?:~>?)"),p("TILDETRIM",`(\\s*)${a[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",p("TILDE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAIN]}$`),p("TILDELOOSE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAINLOOSE]}$`),p("LONECARET","(?:\\^)"),p("CARETTRIM",`(\\s*)${a[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",p("CARET",`^${a[u.LONECARET]}${a[u.XRANGEPLAIN]}$`),p("CARETLOOSE",`^${a[u.LONECARET]}${a[u.XRANGEPLAINLOOSE]}$`),p("COMPARATORLOOSE",`^${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]})$|^$`),p("COMPARATOR",`^${a[u.GTLT]}\\s*(${a[u.FULLPLAIN]})$|^$`),p("COMPARATORTRIM",`(\\s*)${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]}|${a[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",p("HYPHENRANGE",`^\\s*(${a[u.XRANGEPLAIN]})\\s+-\\s+(${a[u.XRANGEPLAIN]})\\s*$`),p("HYPHENRANGELOOSE",`^\\s*(${a[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[u.XRANGEPLAINLOOSE]})\\s*$`),p("STAR","(<|>)?=?\\s*\\*"),p("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),p("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}),Kt=$((e,t)=>{"use strict";var r=Object.freeze({loose:!0}),o=Object.freeze({}),n=i=>i?typeof i!="object"?r:i:o;t.exports=n}),Nr=$((e,t)=>{"use strict";var r=/^[0-9]+$/,o=(i,s)=>{if(typeof i=="number"&&typeof s=="number")return i===s?0:i<s?-1:1;let l=r.test(i),a=r.test(s);return l&&a&&(i=+i,s=+s),i===s?0:l&&!a?-1:a&&!l?1:i<s?-1:1},n=(i,s)=>o(s,i);t.exports={compareIdentifiers:o,rcompareIdentifiers:n}}),K=$((e,t)=>{"use strict";var r=Ze(),{MAX_LENGTH:o,MAX_SAFE_INTEGER:n}=Ue(),{safeRe:i,t:s}=xe(),l=Kt(),{compareIdentifiers:a}=Nr(),f=(g,c)=>{let h=c.split(".");if(h.length>g.length)return!1;for(let m=0;m<h.length;m++)if(a(g[m],h[m])!==0)return!1;return!0},u=class oe{constructor(c,h){if(h=l(h),c instanceof oe){if(c.loose===!!h.loose&&c.includePrerelease===!!h.includePrerelease)return c;c=c.version}else if(typeof c!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof c}".`);if(c.length>o)throw new TypeError(`version is longer than ${o} characters`);r("SemVer",c,h),this.options=h,this.loose=!!h.loose,this.includePrerelease=!!h.includePrerelease;let m=c.trim().match(h.loose?i[s.LOOSE]:i[s.FULL]);if(!m)throw new TypeError(`Invalid Version: ${c}`);if(this.raw=c,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(p=>{if(/^[0-9]+$/.test(p)){let E=+p;if(E>=0&&E<n)return E}return p}):this.prerelease=[],this.build=m[5]?m[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(c){if(r("SemVer.compare",this.version,this.options,c),!(c instanceof oe)){if(typeof c=="string"&&c===this.version)return 0;c=new oe(c,this.options)}return c.version===this.version?0:this.compareMain(c)||this.comparePre(c)}compareMain(c){return c instanceof oe||(c=new oe(c,this.options)),this.major<c.major?-1:this.major>c.major?1:this.minor<c.minor?-1:this.minor>c.minor?1:this.patch<c.patch?-1:this.patch>c.patch?1:0}comparePre(c){if(c instanceof oe||(c=new oe(c,this.options)),this.prerelease.length&&!c.prerelease.length)return-1;if(!this.prerelease.length&&c.prerelease.length)return 1;if(!this.prerelease.length&&!c.prerelease.length)return 0;let h=0;do{let m=this.prerelease[h],p=c.prerelease[h];if(r("prerelease compare",h,m,p),m===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(m===void 0)return-1;if(m!==p)return a(m,p)}while(++h)}compareBuild(c){c instanceof oe||(c=new oe(c,this.options));let h=0;do{let m=this.build[h],p=c.build[h];if(r("build compare",h,m,p),m===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(m===void 0)return-1;if(m!==p)return a(m,p)}while(++h)}inc(c,h,m){if(c.startsWith("pre")){if(!h&&m===!1)throw new Error("invalid increment argument: identifier is empty");if(h){let p=`-${h}`.match(this.options.loose?i[s.PRERELEASELOOSE]:i[s.PRERELEASE]);if(!p||p[1]!==h)throw new Error(`invalid identifier: ${h}`)}}switch(c){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",h,m);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",h,m);break;case"prepatch":this.prerelease.length=0,this.inc("patch",h,m),this.inc("pre",h,m);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",h,m),this.inc("pre",h,m);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let p=Number(m)?1:0;if(this.prerelease.length===0)this.prerelease=[p];else{let E=this.prerelease.length;for(;--E>=0;)typeof this.prerelease[E]=="number"&&(this.prerelease[E]++,E=-2);if(E===-1){if(h===this.prerelease.join(".")&&m===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(p)}}if(h){let E=[h,p];if(m===!1&&(E=[h]),f(this.prerelease,h)){let I=this.prerelease[h.split(".").length];isNaN(I)&&(this.prerelease=E)}else this.prerelease=E}break}default:throw new Error(`invalid increment argument: ${c}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t.exports=u}),fe=$((e,t)=>{"use strict";var r=K(),o=(n,i,s=!1)=>{if(n instanceof r)return n;try{return new r(n,i)}catch(l){if(!s)return null;throw l}};t.exports=o}),_n=$((e,t)=>{"use strict";var r=fe(),o=(n,i)=>{let s=r(n,i);return s?s.version:null};t.exports=o}),Fn=$((e,t)=>{"use strict";var r=fe(),o=(n,i)=>{let s=r(n.trim().replace(/^[=v]+/,""),i);return s?s.version:null};t.exports=o}),Wn=$((e,t)=>{"use strict";var r=K(),o=(n,i,s,l,a)=>{typeof s=="string"&&(a=l,l=s,s=void 0);try{return new r(n instanceof r?n.version:n,s).inc(i,l,a).version}catch{return null}};t.exports=o}),Bn=$((e,t)=>{"use strict";var r=fe(),o=(n,i)=>{let s=r(n,null,!0),l=r(i,null,!0),a=s.compare(l);if(a===0)return null;let f=a>0,u=f?s:l,g=f?l:s,c=!!u.prerelease.length;if(g.prerelease.length&&!c){if(!g.patch&&!g.minor)return"major";if(g.compareMain(u)===0)return g.minor&&!g.patch?"minor":"patch"}let h=c?"pre":"";return s.major!==l.major?h+"major":s.minor!==l.minor?h+"minor":s.patch!==l.patch?h+"patch":"prerelease"};t.exports=o}),Gn=$((e,t)=>{"use strict";var r=K(),o=(n,i)=>new r(n,i).major;t.exports=o}),Hn=$((e,t)=>{"use strict";var r=K(),o=(n,i)=>new r(n,i).minor;t.exports=o}),Kn=$((e,t)=>{"use strict";var r=K(),o=(n,i)=>new r(n,i).patch;t.exports=o}),Vn=$((e,t)=>{"use strict";var r=fe(),o=(n,i)=>{let s=r(n,i);return s&&s.prerelease.length?s.prerelease:null};t.exports=o}),ee=$((e,t)=>{"use strict";var r=K(),o=(n,i,s)=>new r(n,s).compare(new r(i,s));t.exports=o}),Jn=$((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(i,n,s);t.exports=o}),zn=$((e,t)=>{"use strict";var r=ee(),o=(n,i)=>r(n,i,!0);t.exports=o}),Vt=$((e,t)=>{"use strict";var r=K(),o=(n,i,s)=>{let l=new r(n,s),a=new r(i,s);return l.compare(a)||l.compareBuild(a)};t.exports=o}),Xn=$((e,t)=>{"use strict";var r=Vt(),o=(n,i)=>n.sort((s,l)=>r(s,l,i));t.exports=o}),qn=$((e,t)=>{"use strict";var r=Vt(),o=(n,i)=>n.sort((s,l)=>r(l,s,i));t.exports=o}),et=$((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)>0;t.exports=o}),Jt=$((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)<0;t.exports=o}),Cr=$((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)===0;t.exports=o}),Lr=$((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)!==0;t.exports=o}),zt=$((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)>=0;t.exports=o}),Xt=$((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)<=0;t.exports=o}),Mr=$((e,t)=>{"use strict";var r=Cr(),o=Lr(),n=et(),i=zt(),s=Jt(),l=Xt(),a=(f,u,g,c)=>{switch(u){case"===":return typeof f=="object"&&(f=f.version),typeof g=="object"&&(g=g.version),f===g;case"!==":return typeof f=="object"&&(f=f.version),typeof g=="object"&&(g=g.version),f!==g;case"":case"=":case"==":return r(f,g,c);case"!=":return o(f,g,c);case">":return n(f,g,c);case">=":return i(f,g,c);case"<":return s(f,g,c);case"<=":return l(f,g,c);default:throw new TypeError(`Invalid operator: ${u}`)}};t.exports=a}),Yn=$((e,t)=>{"use strict";var r=K(),o=fe(),{safeRe:n,t:i}=xe(),s=(l,a)=>{if(l instanceof r)return l;if(typeof l=="number"&&(l=String(l)),typeof l!="string")return null;a=a||{};let f=null;if(!a.rtl)f=l.match(a.includePrerelease?n[i.COERCEFULL]:n[i.COERCE]);else{let p=a.includePrerelease?n[i.COERCERTLFULL]:n[i.COERCERTL],E;for(;(E=p.exec(l))&&(!f||f.index+f[0].length!==l.length);)(!f||E.index+E[0].length!==f.index+f[0].length)&&(f=E),p.lastIndex=E.index+E[1].length+E[2].length;p.lastIndex=-1}if(f===null)return null;let u=f[2],g=f[3]||"0",c=f[4]||"0",h=a.includePrerelease&&f[5]?`-${f[5]}`:"",m=a.includePrerelease&&f[6]?`+${f[6]}`:"";return o(`${u}.${g}.${c}${h}${m}`,a)};t.exports=s}),Qn=$((e,t)=>{"use strict";var r=fe(),o=Ue(),n=K(),i=(f,u,g)=>{if(!o.RELEASE_TYPES.includes(u))return null;let c=s(f,g);return c&&l(c,u)},s=(f,u)=>{let g=f instanceof n?f.version:f;return r(g,u)},l=(f,u)=>{if(a(u))return f.version;switch(f.prerelease=[],u){case"major":f.minor=0,f.patch=0;break;case"minor":f.patch=0;break}return f.format()},a=f=>f.startsWith("pre");t.exports=i}),Zn=$((e,t)=>{"use strict";var r=class{constructor(){this.max=1e3,this.map=new Map}get(o){let n=this.map.get(o);if(n!==void 0)return this.map.delete(o),this.map.set(o,n),n}delete(o){return this.map.delete(o)}set(o,n){if(!this.delete(o)&&n!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(o,n)}return this}};t.exports=r}),te=$((e,t)=>{"use strict";var r=/\s+/g,o=class Xe{constructor(w,S){if(S=s(S),w instanceof Xe)return w.loose===!!S.loose&&w.includePrerelease===!!S.includePrerelease?w:new Xe(w.raw,S);if(w instanceof l)return this.raw=w.value,this.set=[[w]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=w.trim().replace(r," "),this.set=this.raw.split("||").map(b=>this.parseRange(b.trim())).filter(b=>b.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let b=this.set[0];if(this.set=this.set.filter(O=>!_(O[0])),this.set.length===0)this.set=[b];else if(this.set.length>1){for(let O of this.set)if(O.length===1&&W(O[0])){this.set=[O];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let w=0;w<this.set.length;w++){w>0&&(this.formatted+="||");let S=this.set[w];for(let b=0;b<S.length;b++)b>0&&(this.formatted+=" "),this.formatted+=S[b].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(w){w=w.replace(N,"");let S=((this.options.includePrerelease&&E)|(this.options.loose&&I))+":"+w,b=i.get(S);if(b)return b;let O=this.options.loose,v=O?u[c.HYPHENRANGELOOSE]:u[c.HYPHENRANGE];w=w.replace(v,$t(this.options.includePrerelease)),a("hyphen replace",w),w=w.replace(u[c.COMPARATORTRIM],h),a("comparator trim",w),w=w.replace(u[c.TILDETRIM],m),a("tilde trim",w),w=w.replace(u[c.CARETTRIM],p),a("caret trim",w);let A=w.split(" ").map(j=>ne(j,this.options)).join(" ").split(/\s+/).map(j=>It(j,this.options));O&&(A=A.filter(j=>(a("loose invalid filter",j,this.options),!!j.match(u[c.COMPARATORLOOSE])))),a("range list",A);let L=new Map,k=A.map(j=>new l(j,this.options));for(let j of k){if(_(j))return[j];L.set(j.value,j)}L.size>1&&L.has("")&&L.delete("");let M=[...L.values()];return i.set(S,M),M}intersects(w,S){if(!(w instanceof Xe))throw new TypeError("a Range is required");return this.set.some(b=>q(b,S)&&w.set.some(O=>q(O,S)&&b.every(v=>O.every(A=>v.intersects(A,S)))))}test(w){if(!w)return!1;if(typeof w=="string")try{w=new f(w,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(Rt(this.set[S],w,this.options))return!0;return!1}};t.exports=o;var n=Zn(),i=new n,s=Kt(),l=tt(),a=Ze(),f=K(),{safeRe:u,src:g,t:c,comparatorTrimReplace:h,tildeTrimReplace:m,caretTrimReplace:p}=xe(),{FLAG_INCLUDE_PRERELEASE:E,FLAG_LOOSE:I}=Ue(),N=new RegExp(g[c.BUILD],"g"),_=y=>y.value==="<0.0.0-0",W=y=>y.value==="",q=(y,w)=>{let S=!0,b=y.slice(),O=b.pop();for(;S&&b.length;)S=b.every(v=>O.intersects(v,w)),O=b.pop();return S},ne=(y,w)=>(y=y.replace(u[c.BUILD],""),a("comp",y,w),y=Re(y,w),a("caret",y),y=B(y,w),a("tildes",y),y=St(y,w),a("xrange",y),y=At(y,w),a("stars",y),y),C=y=>!y||y.toLowerCase()==="x"||y==="*",x=(y,w,S)=>C(y)&&!C(w)||C(w)&&S&&!C(S),B=(y,w)=>y.trim().split(/\s+/).map(S=>P(S,w)).join(" "),P=(y,w)=>{let S=w.loose?u[c.TILDELOOSE]:u[c.TILDE],b=w.includePrerelease?"-0":"";return y.replace(S,(O,v,A,L,k)=>{a("tilde",y,O,v,A,L,k);let M;return C(v)?M="":C(A)?M=`>=${v}.0.0${b} <${+v+1}.0.0-0`:C(L)?M=`>=${v}.${A}.0${b} <${v}.${+A+1}.0-0`:k?(a("replaceTilde pr",k),M=`>=${v}.${A}.${L}-${k} <${v}.${+A+1}.0-0`):M=`>=${v}.${A}.${L} <${v}.${+A+1}.0-0`,a("tilde return",M),M})},Re=(y,w)=>y.trim().split(/\s+/).map(S=>vt(S,w)).join(" "),vt=(y,w)=>{a("caret",y,w);let S=w.loose?u[c.CARETLOOSE]:u[c.CARET],b=w.includePrerelease?"-0":"";return y.replace(S,(O,v,A,L,k)=>{a("caret",y,O,v,A,L,k);let M;return C(v)?M="":C(A)?M=`>=${v}.0.0${b} <${+v+1}.0.0-0`:C(L)?v==="0"?M=`>=${v}.${A}.0${b} <${v}.${+A+1}.0-0`:M=`>=${v}.${A}.0${b} <${+v+1}.0.0-0`:k?(a("replaceCaret pr",k),v==="0"?A==="0"?M=`>=${v}.${A}.${L}-${k} <${v}.${A}.${+L+1}-0`:M=`>=${v}.${A}.${L}-${k} <${v}.${+A+1}.0-0`:M=`>=${v}.${A}.${L}-${k} <${+v+1}.0.0-0`):(a("no pr"),v==="0"?A==="0"?M=`>=${v}.${A}.${L} <${v}.${A}.${+L+1}-0`:M=`>=${v}.${A}.${L} <${v}.${+A+1}.0-0`:M=`>=${v}.${A}.${L} <${+v+1}.0.0-0`),a("caret return",M),M})},St=(y,w)=>(a("replaceXRanges",y,w),y.split(/\s+/).map(S=>bt(S,w)).join(" ")),bt=(y,w)=>{y=y.trim();let S=w.loose?u[c.XRANGELOOSE]:u[c.XRANGE];return y.replace(S,(b,O,v,A,L,k)=>{if(a("xRange",y,b,O,v,A,L,k),x(v,A,L))return y;let M=C(v),j=M||C(A),ye=j||C(L),Te=ye;return O==="="&&Te&&(O=""),k=w.includePrerelease?"-0":"",M?O===">"||O==="<"?b="<0.0.0-0":b="*":O&&Te?(j&&(A=0),L=0,O===">"?(O=">=",j?(v=+v+1,A=0,L=0):(A=+A+1,L=0)):O==="<="&&(O="<",j?v=+v+1:A=+A+1),O==="<"&&(k="-0"),b=`${O+v}.${A}.${L}${k}`):j?b=`>=${v}.0.0${k} <${+v+1}.0.0-0`:ye&&(b=`>=${v}.${A}.0${k} <${v}.${+A+1}.0-0`),a("xRange return",b),b})},At=(y,w)=>(a("replaceStars",y,w),y.trim().replace(u[c.STAR],"")),It=(y,w)=>(a("replaceGTE0",y,w),y.trim().replace(u[w.includePrerelease?c.GTE0PRE:c.GTE0],"")),$t=y=>(w,S,b,O,v,A,L,k,M,j,ye,Te)=>(C(b)?S="":C(O)?S=`>=${b}.0.0${y?"-0":""}`:C(v)?S=`>=${b}.${O}.0${y?"-0":""}`:A?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,C(M)?k="":C(j)?k=`<${+M+1}.0.0-0`:C(ye)?k=`<${M}.${+j+1}.0-0`:Te?k=`<=${M}.${j}.${ye}-${Te}`:y?k=`<${M}.${j}.${+ye+1}-0`:k=`<=${k}`,`${S} ${k}`.trim()),Rt=(y,w,S)=>{for(let b=0;b<y.length;b++)if(!y[b].test(w))return!1;if(w.prerelease.length&&!S.includePrerelease){for(let b=0;b<y.length;b++)if(a(y[b].semver),y[b].semver!==l.ANY&&y[b].semver.prerelease.length>0){let O=y[b].semver;if(O.major===w.major&&O.minor===w.minor&&O.patch===w.patch)return!0}return!1}return!0}}),tt=$((e,t)=>{"use strict";var r=Symbol("SemVer ANY"),o=class Ut{static get ANY(){return r}constructor(c,h){if(h=n(h),c instanceof Ut){if(c.loose===!!h.loose)return c;c=c.value}c=c.trim().split(/\s+/).join(" "),a("comparator",c,h),this.options=h,this.loose=!!h.loose,this.parse(c),this.semver===r?this.value="":this.value=this.operator+this.semver.version,a("comp",this)}parse(c){let h=this.options.loose?i[s.COMPARATORLOOSE]:i[s.COMPARATOR],m=c.match(h);if(!m)throw new TypeError(`Invalid comparator: ${c}`);this.operator=m[1]!==void 0?m[1]:"",this.operator==="="&&(this.operator=""),m[2]?this.semver=new f(m[2],this.options.loose):this.semver=r}toString(){return this.value}test(c){if(a("Comparator.test",c,this.options.loose),this.semver===r||c===r)return!0;if(typeof c=="string")try{c=new f(c,this.options)}catch{return!1}return l(c,this.operator,this.semver,this.options)}intersects(c,h){if(!(c instanceof Ut))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u(c.value,h).test(this.value):c.operator===""?c.value===""?!0:new u(this.value,h).test(c.semver):(h=n(h),h.includePrerelease&&(this.value==="<0.0.0-0"||c.value==="<0.0.0-0")||!h.includePrerelease&&(this.value.startsWith("<0.0.0")||c.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&c.operator.startsWith(">")||this.operator.startsWith("<")&&c.operator.startsWith("<")||this.semver.version===c.semver.version&&this.operator.includes("=")&&c.operator.includes("=")||l(this.semver,"<",c.semver,h)&&this.operator.startsWith(">")&&c.operator.startsWith("<")||l(this.semver,">",c.semver,h)&&this.operator.startsWith("<")&&c.operator.startsWith(">")))}};t.exports=o;var n=Kt(),{safeRe:i,t:s}=xe(),l=Mr(),a=Ze(),f=K(),u=te()}),rt=$((e,t)=>{"use strict";var r=te(),o=(n,i,s)=>{try{i=new r(i,s)}catch{return!1}return i.test(n)};t.exports=o}),ei=$((e,t)=>{"use strict";var r=te(),o=(n,i)=>new r(n,i).set.map(s=>s.map(l=>l.value).join(" ").trim().split(" "));t.exports=o}),ti=$((e,t)=>{"use strict";var r=K(),o=te(),n=(i,s,l)=>{let a=null,f=null,u=null;try{u=new o(s,l)}catch{return null}return i.forEach(g=>{u.test(g)&&(!a||f.compare(g)===-1)&&(a=g,f=new r(a,l))}),a};t.exports=n}),ri=$((e,t)=>{"use strict";var r=K(),o=te(),n=(i,s,l)=>{let a=null,f=null,u=null;try{u=new o(s,l)}catch{return null}return i.forEach(g=>{u.test(g)&&(!a||f.compare(g)===1)&&(a=g,f=new r(a,l))}),a};t.exports=n}),oi=$((e,t)=>{"use strict";var r=K(),o=te(),n=et(),i=(s,l)=>{s=new o(s,l);let a=new r("0.0.0");if(s.test(a)||(a=new r("0.0.0-0"),s.test(a)))return a;a=null;for(let f=0;f<s.set.length;++f){let u=s.set[f],g=null;u.forEach(c=>{let h=new r(c.semver.version);switch(c.operator){case">":h.prerelease.length===0?h.patch++:h.prerelease.push(0),h.raw=h.format();case"":case">=":(!g||n(h,g))&&(g=h);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${c.operator}`)}}),g&&(!a||n(a,g))&&(a=g)}return a&&s.test(a)?a:null};t.exports=i}),ni=$((e,t)=>{"use strict";var r=te(),o=(n,i)=>{try{return new r(n,i).range||"*"}catch{return null}};t.exports=o}),qt=$((e,t)=>{"use strict";var r=K(),o=tt(),{ANY:n}=o,i=te(),s=rt(),l=et(),a=Jt(),f=Xt(),u=zt(),g=(c,h,m,p)=>{c=new r(c,p),h=new i(h,p);let E,I,N,_,W;switch(m){case">":E=l,I=f,N=a,_=">",W=">=";break;case"<":E=a,I=u,N=l,_="<",W="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(c,h,p))return!1;for(let q=0;q<h.set.length;++q){let ne=h.set[q],C=null,x=null;if(ne.forEach(B=>{B.semver===n&&(B=new o(">=0.0.0")),C=C||B,x=x||B,E(B.semver,C.semver,p)?C=B:N(B.semver,x.semver,p)&&(x=B)}),C.operator===_||C.operator===W||(!x.operator||x.operator===_)&&I(c,x.semver)||x.operator===W&&N(c,x.semver))return!1}return!0};t.exports=g}),ii=$((e,t)=>{"use strict";var r=qt(),o=(n,i,s)=>r(n,i,">",s);t.exports=o}),si=$((e,t)=>{"use strict";var r=qt(),o=(n,i,s)=>r(n,i,"<",s);t.exports=o}),ai=$((e,t)=>{"use strict";var r=te(),o=(n,i,s)=>(n=new r(n,s),i=new r(i,s),n.intersects(i,s));t.exports=o}),ci=$((e,t)=>{"use strict";var r=rt(),o=ee();t.exports=(n,i,s)=>{let l=[],a=null,f=null,u=n.sort((m,p)=>o(m,p,s));for(let m of u)r(m,i,s)?(f=m,a||(a=m)):(f&&l.push([a,f]),f=null,a=null);a&&l.push([a,null]);let g=[];for(let[m,p]of l)m===p?g.push(m):!p&&m===u[0]?g.push("*"):p?m===u[0]?g.push(`<=${p}`):g.push(`${m} - ${p}`):g.push(`>=${m}`);let c=g.join(" || "),h=typeof i.raw=="string"?i.raw:String(i);return c.length<h.length?c:i}}),li=$((e,t)=>{"use strict";var r=te(),o=tt(),{ANY:n}=o,i=rt(),s=ee(),l=(h,m,p={})=>{if(h===m)return!0;h=new r(h,p),m=new r(m,p);let E=!1;e:for(let I of h.set){for(let N of m.set){let _=u(I,N,p);if(E=E||_!==null,_)continue e}if(E)return!1}return!0},a=[new o(">=0.0.0-0")],f=[new o(">=0.0.0")],u=(h,m,p)=>{if(h===m)return!0;if(h.length===1&&h[0].semver===n){if(m.length===1&&m[0].semver===n)return!0;p.includePrerelease?h=a:h=f}if(m.length===1&&m[0].semver===n){if(p.includePrerelease)return!0;m=f}let E=new Set,I,N;for(let P of h)P.operator===">"||P.operator===">="?I=g(I,P,p):P.operator==="<"||P.operator==="<="?N=c(N,P,p):E.add(P.semver);if(E.size>1)return null;let _;if(I&&N&&(_=s(I.semver,N.semver,p),_>0||_===0&&(I.operator!==">="||N.operator!=="<=")))return null;for(let P of E){if(I&&!i(P,String(I),p)||N&&!i(P,String(N),p))return null;for(let Re of m)if(!i(P,String(Re),p))return!1;return!0}let W,q,ne,C,x=N&&!p.includePrerelease&&N.semver.prerelease.length?N.semver:!1,B=I&&!p.includePrerelease&&I.semver.prerelease.length?I.semver:!1;x&&x.prerelease.length===1&&N.operator==="<"&&x.prerelease[0]===0&&(x=!1);for(let P of m){if(C=C||P.operator===">"||P.operator===">=",ne=ne||P.operator==="<"||P.operator==="<=",I){if(B&&P.semver.prerelease&&P.semver.prerelease.length&&P.semver.major===B.major&&P.semver.minor===B.minor&&P.semver.patch===B.patch&&(B=!1),P.operator===">"||P.operator===">="){if(W=g(I,P,p),W===P&&W!==I)return!1}else if(I.operator===">="&&!P.test(I.semver))return!1}if(N){if(x&&P.semver.prerelease&&P.semver.prerelease.length&&P.semver.major===x.major&&P.semver.minor===x.minor&&P.semver.patch===x.patch&&(x=!1),P.operator==="<"||P.operator==="<="){if(q=c(N,P,p),q===P&&q!==N)return!1}else if(N.operator==="<="&&!P.test(N.semver))return!1}if(!P.operator&&(N||I)&&_!==0)return!1}return!(I&&ne&&!N&&_!==0||N&&C&&!I&&_!==0||B||x)},g=(h,m,p)=>{if(!h)return m;let E=s(h.semver,m.semver,p);return E>0?h:E<0||m.operator===">"&&h.operator===">="?m:h},c=(h,m,p)=>{if(!h)return m;let E=s(h.semver,m.semver,p);return E<0?h:E>0||m.operator==="<"&&h.operator==="<="?m:h};t.exports=l}),Dr=$((e,t)=>{"use strict";var r=xe(),o=Ue(),n=K(),i=Nr(),s=fe(),l=_n(),a=Fn(),f=Wn(),u=Bn(),g=Gn(),c=Hn(),h=Kn(),m=Vn(),p=ee(),E=Jn(),I=zn(),N=Vt(),_=Xn(),W=qn(),q=et(),ne=Jt(),C=Cr(),x=Lr(),B=zt(),P=Xt(),Re=Mr(),vt=Yn(),St=Qn(),bt=tt(),At=te(),It=rt(),$t=ei(),Rt=ti(),y=ri(),w=oi(),S=ni(),b=qt(),O=ii(),v=si(),A=ai(),L=ci(),k=li();t.exports={parse:s,valid:l,clean:a,inc:f,diff:u,major:g,minor:c,patch:h,prerelease:m,compare:p,rcompare:E,compareLoose:I,compareBuild:N,sort:_,rsort:W,gt:q,lt:ne,eq:C,neq:x,gte:B,lte:P,cmp:Re,coerce:vt,truncate:St,Comparator:bt,Range:At,satisfies:It,toComparators:$t,maxSatisfying:Rt,minSatisfying:y,minVersion:w,validRange:S,outside:b,gtr:O,ltr:v,intersects:A,simplifyRange:L,subset:k,SemVer:n,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:o.SEMVER_SPEC_VERSION,RELEASE_TYPES:o.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}}),Fe=class extends xr.ClientStorage{constructor(e){super(),X(this,"dirName"),X(this,"fileName"),this.dirName=(0,xt.resolve)((0,jr.homedir)(),".medplum"),this.fileName=(0,xt.resolve)(this.dirName,e+".json")}clear(){this.writeFile({})}getString(e){return this.readFile()?.[e]}setString(e,t){let r=this.readFile()??{};t?r[e]=t:delete r[e],this.writeFile(r)}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?JSON.stringify(t):void 0)}readFile(){if((0,se.existsSync)(this.fileName))return JSON.parse((0,se.readFileSync)(this.fileName,"utf8"))}writeFile(e){(0,se.existsSync)(this.dirName)||(0,se.mkdirSync)(this.dirName),(0,se.writeFileSync)(this.fileName,JSON.stringify(e,null,2),"utf8")}};async function U(e,t=!0){let r=e.profile??"default",o=new Fe(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:s,accessToken:l,tokenUrl:a,authorizeUrl:f,clientId:u,clientSecret:g}=ui(e,o),c=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await pi(e.baseUrl,c);let h=new Ur.MedplumClient({fetch:c,baseUrl:i,tokenUrl:a,fhirUrlPath:s,authorizeUrl:f,storage:o,onUnauthenticated:di,verbose:e.verbose});return t&&(l?h.setAccessToken(l):u&&g&&(h.setBasicAuth(u,g),n?.authType!=="basic"&&await h.startClientLogin(u,g))),h}function ui(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,l=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,a=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:i,tokenUrl:s,authorizeUrl:l,clientId:a,clientSecret:f}}async function pi(e,t){try{let r=new URL("healthcheck",e).toString(),o=await t(r);if(!o.ok)throw new Error(`Healthcheck returned status ${o.status}`);if((await o.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${o}`)}}function di(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ot=new TextEncoder,hi=new TextDecoder,Fa=new TextDecoder("utf-8",{fatal:!0}),Wa=2**32;function fi(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var mi=/[^\x00-\x7f]/;function Tt(e){if(typeof e=="string"&&e.length>=128){if(mi.test(e))throw new TypeError("non-ASCII string encountered in encode()");return ot.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=o}return t}function gi(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,o=[];for(let i=0;i<e.length;i+=r)o.push(String.fromCharCode.apply(null,e.subarray(i,i+r)));let n=btoa(o.join(""));return t?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function wi(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}var We=class extends Error{constructor(e,t){super(e,t),X(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};X(We,"code","ERR_JOSE_GENERIC");var nt=class extends We{constructor(){super(...arguments),X(this,"code","ERR_JOSE_NOT_SUPPORTED")}};X(nt,"code","ERR_JOSE_NOT_SUPPORTED");var ie=class extends We{constructor(){super(...arguments),X(this,"code","ERR_JWS_INVALID")}};X(ie,"code","ERR_JWS_INVALID");var Fr=class extends We{constructor(){super(...arguments),X(this,"code","ERR_JWT_INVALID")}};X(Fr,"code","ERR_JWT_INVALID");var lr,ur,yi=class extends(ur=We,lr=Symbol.asyncIterator,ur){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),X(this,lr,async function*(){}),X(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};X(yi,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Ei="The input to be decoded is not correctly encoded.";function vi(e){try{return wi(typeof e=="string"?e:hi.decode(e),!0)}catch(t){throw new TypeError(Ei,{cause:t})}}function Ve(e){return gi(typeof e=="string"?ot.encode(e):e,!0)}function Yt(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Si(...e){let t=new Set;for(let r of e)if(r)for(let o of Object.keys(r)){if(t.has(o))return!1;t.add(o)}return!0}function bi(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}var Ai={__proto__:null,b64:!0};function Ii(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function $i(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?t:{__proto__:null,...r,...t};for(let s of o.crit){if(!(s in i))throw new nt(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function Ri(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new ie('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function pr(e,t){let r,o;try{r=JSON.stringify(t),o=JSON.parse(r)}catch(n){throw new e("JOSE Header is not valid JSON",{cause:n})}if(!Yt(o))throw new e("JOSE Header is not a JSON object");return[o,r]}var Ti=e=>e[Symbol.toStringTag],Pi=(e,t,r)=>{let{alg:o}=e;if(t.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(t.key_ops)){let n=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(n&&!t.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function Oi(e,t,r){let{alg:o,secret:n}=e,i=r==="decrypt"||r==="sign";if(n&&t instanceof Uint8Array)return t;let s,l;if(Yt(t)){if(s=ji(t),typeof s.kty!="string")throw dr(o,t,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(Pi(e,s,r),s.kty==="oct")return vi(s.k);if(!Object.isFrozen(t)){let{key_ops:u}=t;Array.isArray(u)&&Object.freeze(u),Object.freeze(t)}}else{if(!Li(t))throw dr(o,t,n);let u=n?"secret":i?"private":"public";if(t.type!==u&&(n||["secret","public","private"].includes(t.type)))throw new TypeError(`${Ti(t)} instances must be of type "${u}" for the ${o} algorithm`);if(Wr(t))return t;if(l=t,l.type==="secret")return l.export()}Pt||=new WeakMap;let a=t,f=Pt.get(a);if(f?.[o])return f[o];if(f||Pt.set(a,f={}),l&&typeof l.toCryptoKey=="function"){let u=l.type==="public",g=Ni[l.asymmetricKeyDetails?.namedCurve],c=e.resolve?.({crv:g,asymmetricKeyType:l.asymmetricKeyType})??e.subtle;return f[o]=l.toCryptoKey(c,u,e.usages[u?0:1])}return s??=l.export({format:"jwk"}),s.alg=o,f[o]=await _i(e,s)}var Pt,Ni={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"},Wr=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ci=e=>e?.[Symbol.toStringTag]==="KeyObject",Li=e=>Wr(e)||Ci(e);function Mi(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function dr(e,t,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(Mi(`Key for the ${e} algorithm must be `,t,...o))}var Je=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Di(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ki(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Ui(e,t,r){let o=e.algorithm;if(o.name!==t.name)throw Je(t.name);if(t.hash&&o.hash?.name!==t.hash)throw Je(t.hash,"algorithm.hash");if(t.namedCurve&&o.namedCurve!==t.namedCurve)throw Je(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&o.length!==t.length)throw Je(t.length,"algorithm.length");Di(e,r)}function xi(e){return{__proto__:null,...e}}function ji(e){let t=xi(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=o}return t}async function _i(e,t,r){if(!e.kty.includes(t.kty))throw new nt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),i={...t,ext:r??t.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,t.key_ops??e.usages[n?1:0])}async function Fi(e,t,r,o=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,o,[r])),Ui(e,t,r),e}function Wi(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Be=[["verify"],["sign"]];function Ot(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Be}}function Ee(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Be,minRsaBits:2048}}function Nt(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Be}}function hr(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Be}}function Ct(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Be}}var Bi=Wi({HS256:Ot(256),HS384:Ot(384),HS512:Ot(512),RS256:Ee(256),RS384:Ee(384),RS512:Ee(512),PS256:Ee(256,32),PS384:Ee(384,48),PS512:Ee(512,64),ES256:Nt("P-256",256),ES384:Nt("P-384",384),ES512:Nt("P-521",512),EdDSA:hr(),Ed25519:hr(),"ML-DSA-44":Ct(44),"ML-DSA-65":Ct(65),"ML-DSA-87":Ct(87)});function Gi(e){let t=typeof e=="string"?Bi[e]:void 0;if(!t)throw new nt(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var Ye=e=>Math.floor(e.getTime()/1e3),Hi={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Ki=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Lt(){throw new TypeError("Invalid time period format")}function Br(e){typeof e!="string"&&Lt();let t=Ki.exec(e);(!t||t[4]&&t[1])&&Lt();let r=parseFloat(t[2]),o=Math.round(r*Hi[t[3][0].toLowerCase()]);return Number.isFinite(o)||Lt(),t[1]==="-"||t[4]==="ago"?-o:o}function jt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function Mt(e,t){if(typeof t!="string")throw new TypeError(`"${e}" claim must be a string`)}function Vi(e){if(typeof e!="string"&&(!Array.isArray(e)||Array.from(e).some(t=>typeof t!="string")))throw new TypeError('"aud" claim must be a string or an array of strings')}function Dt(e,t){return typeof e=="number"?jt(t,e):e instanceof Date?jt(t,Ye(e)):Ye(new Date)+Br(e)}var Gr;function ue(e){return Gr.get(e)}function Ji(e){let t=ue(e);for(let r of["iat","nbf","exp"]){let o=t[r];if(typeof o=="number"&&!Number.isFinite(o))throw new TypeError(`"${r}" claim must be a finite number`)}return ot.encode(JSON.stringify(t))}var zi=class{constructor(e={}){if(!Yt(e))throw new TypeError("JWT Claims Set MUST be an object");(Gr||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Mt("iss",e),ue(this).iss=e,this}setSubject(e){return Mt("sub",e),ue(this).sub=e,this}setAudience(e){return Vi(e),ue(this).aud=e,this}setJti(e){return Mt("jti",e),ue(this).jti=e,this}setNotBefore(e){return ue(this).nbf=Dt(e,"setNotBefore"),this}setExpirationTime(e){return ue(this).exp=Dt(e,"setExpirationTime"),this}setIssuedAt(e){let t=ue(this);return e===void 0?t.iat=Ye(new Date):typeof e=="string"?t.iat=jt("setIssuedAt",Ye(new Date)+Br(e)):t.iat=Dt(e,"setIssuedAt"),this}};async function Xi(e,t,r){let[o,n,i,s]=e,l="";if(n!==void 0){let I=pr(ie,n);n=I[0],l=Ve(I[1])}if(i!==void 0&&(i=pr(ie,i)[0]),!n&&!i)throw new ie("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Si(n,i))throw new ie("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...n,...i};Ii(ie,n);let f=Ri(n,$i(ie,Ai,s,n,a));f||r?.();let{alg:u}=a;if(typeof u!="string"||!u)throw new ie('JWS "alg" (Algorithm) Header Parameter missing or invalid');let g=Gi(u),c="",h=o,m;if(f){let I=e[4];I?(c=I[0]??=Ve(o),h=I[1]??=Tt(c)):(c=Ve(o),m=ot.encode(`${l}.${c}`))}m??=fi(Tt(l),Tt("."),h);let p=await Fi(await Oi(g,t,"sign"),g.subtle,"sign");g.minRsaBits&&ki(g.alg,p);let E={signature:Ve(new Uint8Array(await crypto.subtle.sign(g.signing,p,m))),payload:c};return n&&(E.protected=l),i&&(E.header=i),[E,f]}async function qi(e,t,r,o,n){let[i]=await Xi([e,t,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Yi=zi,Ce,Qi=class extends Yi{constructor(){super(...arguments),xn(this,Ce)}setProtectedHeader(e){return bi(cr(this,Ce),"setProtectedHeader"),jn(this,Ce,e),this}async sign(e,t){return qi(Ji(this),cr(this,Ce),t?.crit,e,()=>{throw new Fr("JWTs MUST NOT use unencoded payload")})}};Ce=new WeakMap;function de(e){console.log(JSON.stringify(e,null,2))}async function Vr(e,t,r){let o=t.source,n=it(o);if(!n)return;console.log("Saving source code...");let i=await e.createAttachment({data:n,filename:(0,ae.basename)(o),contentType:ns(o)});console.log("Updating bot...");let s=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+s.meta?.versionId)}async function Jr(e,t,r){let o=t.dist??t.source,n=it(o);if(!n)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,ae.basename)(o)});if(console.log("Deploy result: "+i.issue?.[0]?.details?.text),!(0,V.isOk)(i))throw new Error(`Bot deploy failed: ${(0,V.normalizeErrorString)(i)}`)}async function zr(e,t,r,o,n,i,s){let l={name:t,description:"",runtimeVersion:i},a=await e.post("admin/projects/"+r+"/bot",l),f=await e.readResource("Bot",a.id),u={name:t,id:a.id,source:o,dist:n};await Vr(e,u,f),await Jr(e,u,f),console.log(`Success! Bot created: ${f.id}`),s&&ts(u)}function Zi(e){let t=new RegExp("^"+rs(e).replaceAll(String.raw`\*`,".*")+"$");return Ae()?.bots?.filter(o=>t.test(o.name))||[]}function me(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function G(e,t){(0,pe.writeFileSync)((0,ae.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function Ae(e,t){let r=me(e,t),o=it(r);if(o)return JSON.parse(o)}function es(e){let t=it(me(e,{server:!0}));if(t)return JSON.parse(t)}function it(e){let t=(0,ae.resolve)(e);return(0,pe.existsSync)(t)?(0,pe.readFileSync)(t,"utf8"):""}function ts(e){let t=Ae()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,pe.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function rs(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function os(e){let t=0,r=0;return(0,Kr.extract)({cwd:e,filter:(o,n)=>{if(t++,t>100)throw new Error("Tar extractor reached max number of files");if(r+=n.size,r>10485760)throw new Error("Tar extractor reached max size");return!0}})}function fr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ns(e){let t=(0,ae.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?V.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?V.ContentType.TYPESCRIPT:V.ContentType.TEXT}function Xr(e,t){let r=new Fe(e),o={name:e,...t};return r.setObject("options",o),o}function is(e){return new Fe(e).getObject("options")}async function ss(e,t){let r={typ:"JWT",alg:V.OAuthSigningAlgorithm.HS256},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},i=(0,V.encodeBase64)(JSON.stringify(r)),s=(0,V.encodeBase64)(JSON.stringify(n)),l=`${i}.${s}`,a=(0,be.createHmac)("sha256",t.clientSecret).update(l).digest("base64url"),f=`${l}.${a}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function as(e,t){let r=(0,be.createPrivateKey)((0,pe.readFileSync)((0,ae.resolve)(t.privateKeyPath))),o=await new Qi({}).setProtectedHeader({typ:"JWT",alg:V.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,be.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function T(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var R=class extends _r.Command{action(e){let t=cs(this,e);return super._actionHandler=t,this}resetOptionDefaults(){this._optionValues={};for(let e of this.options)e.defaultValue!==void 0&&(this._optionValues[e.attributeName()]=e.defaultValue)}};function cs(e,t){return async r=>{let o=e.registeredArguments.length,n=r.slice(0,o);n[o]=e.optsWithGlobals();try{let i=t(...n);(0,Hr.isPromise)(i)&&await i}finally{e.resetOptionDefaults()}}}var qr=new R("status").aliases(["info","list","ls"]),Yr=new R("ping"),Qr=new R("push"),Zr=new R("reload-config"),eo=new R("upgrade"),to=new R("stats"),ge=new R("agent");T(ge,qr);T(ge,Yr);T(ge,Qr);T(ge,Zr);T(ge,eo);T(ge,to);qr.description("Get the status of a specified agent").argument("[agentIds...]","The ID(s) of the agent(s) to get the status of").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg").addOption(new _e.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await st({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=oo(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});Yr.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await U(r),n=await ro(o,t,r),i=Number.parseInt(r.count,10);if(Number.isNaN(i))throw new Error("--count <count> must be an integer if specified");try{let s=await o.pushToAgent(n,e,`PING ${i}`,re.ContentType.PING,!0,{maxRetries:0});console.info(s)}catch(s){throw new Error("Unexpected response from agent while pinging",{cause:s})}});Qr.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",re.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let n=await U(o),i=await ro(n,r,o),s;try{s=await n.pushToAgent(i,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(l){throw new Error("Unexpected response from agent while pushing message to agent",{cause:l})}console.info(s)});Zr.description("Reload the config for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg").addOption(new _e.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await st({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});eo.description("Upgrade the version for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg").option("--agentVersion <version>","An optional agent version to upgrade to. Defaults to the latest version if flag not included").option("--force","Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.").addOption(new _e.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await st({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});to.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new _e.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await st({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:o}=oo(r.result,{required:["stats"]}),n;try{n=JSON.parse(o)}catch(i){console.error(`Failed to parse stats for agent ${r.agent.id}: ${(0,re.normalizeErrorString)(i)}`)}return{id:r.agent.id,name:r.agent.name,stats:n}},renderSuccessfulRows:r=>{for(let o=0;o<r.length;o++)o>0&&console.info(),ls(r[o])}})});var mr=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function gr(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function wr(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function ls(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let s of mr)r[s]=gr(e.stats[s]);let o=new Set([...mr,"channelStats","clientStats"]);for(let[s,l]of Object.entries(e.stats))o.has(s)||(r[s]=gr(l));console.table(r);let n=wr(e.stats.channelStats);n.length&&(console.info("Channel Stats:"),console.table(n));let i=wr(e.stats.clientStats);i.length&&(console.info("Client Stats:"),console.table(i))}async function st({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n,renderSuccessfulRows:i}){let s=hs(t,r),l=await U(r),a=s.type==="criteria"?s.criteria:`Agent?_id=${s.ids.join(",")}`,f=new URLSearchParams(a.split("?")[1]);for(let[p,E]of Object.entries(o))f.append(p,E.toString());let u;try{let p=l.fhirUrl("Agent",e);p.search=f.toString(),u=await l.get(p,{cache:"reload"})}catch(p){throw new Error(`Operation '${e}' failed`,{cause:p})}if(r.output==="json"){console.info(JSON.stringify(u,null,2));return}let g=[],c=[];switch(u.resourceType){case"Bundle":{let p=us(u);for(let E of p)E.result.resourceType==="Parameters"||(0,re.isOk)(E.result)?g.push(E):c.push(E);break}case"Parameters":case"OperationOutcome":{let p=await l.searchOne("Agent",f,{cache:"reload"});if(!p)throw new Error("Agent not found");u.resourceType==="Parameters"?g.push({agent:p,result:u}):c.push({agent:p,result:u});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(u)}`)}let h=[];for(let p of g){let E=n(p);h.push(E)}let m=[];for(let p of c){let E=p.result.issue?.[0],I={id:p.agent.id,name:p.agent.name,severity:E.severity,code:E.code,details:E.details?.text??"No details to show"};m.push(I)}console.info(`
3
+ ${h.length} successful response(s):
4
+ `),i?h.length?i(h):console.info("No successful responses received"):console.table(h.length?h:"No successful responses received"),console.info(),m.length&&(console.info(`${m.length} failed response(s):`),console.info(),console.table(m))}async function ro(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(t)o=t;else{no(r.criteria);let n=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!n?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(n.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=n.entry[0].resource?.id}return{reference:`Agent/${o}`}}function us(e){let t=[];for(let r of e.entry??re.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ps(r.resource))}return t}function ps(e){let t=e.parameter?.find(o=>o.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function oo(e,t){let r={},o=t.required,n=t.optional;for(let i of o){let s=e.parameter?.find(a=>a.name===i);if(!s)throw new Error(`Failed to find parameter '${i}'`);let l;for(let a in s)if(a.startsWith("value")){if(l)throw new Error(`Found multiple values for parameter '${i}'`);l=a}if(!l)throw new Error(`Failed to find a value for parameter '${i}'`);r[i]=s[l]}if(n?.length)for(let i of n){let s=e.parameter?.find(a=>a.name===i);if(!s)continue;let l=ds(i,s);r[i]=l}return r}function ds(e,t){let r;for(let o in t)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function hs(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!(0,re.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return no(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function no(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,o]=e.split("?");if(r!=="Agent"||!o)throw new Error(t);try{new URLSearchParams(o)}catch(n){throw new Error(t,{cause:n})}if(!o.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var fs=(0,co.promisify)(io.exec),lo=Z.MEDPLUM_CLI_CLIENT_ID,uo="http://localhost:9615",po=new R("login"),ho=new R("whoami"),fo=new R("token");po.action(async e=>{let t=e.profile??"default",r=Xr(t,e),o=await U(e,!1);await ms(o,r)});ho.action(async e=>{let t=await U(e);ys(t)});fo.action(async e=>{let t=await U(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function ms(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Es(e,t);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await ss(e,t);break;case"jwt-assertion":await as(e,t);break}}async function gs(e){let t=(0,so.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),i=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":Z.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let s=await e.processCode(i,{clientId:lo,redirectUri:uo});o.writeHead(200,{"Content-Type":Z.ContentType.TEXT}),o.end(`Signed in as ${(0,Z.getDisplayString)(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Z.ContentType.TEXT}),o.end(`Error: ${(0,Z.normalizeErrorString)(s)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":Z.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function ws(e){let t=(0,ao.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}await fs(r)}function ys(e){let t=e.getActiveLogin();t?(console.log(`Server: ${e.getBaseUrl()}`),console.log(`Profile: ${t.profile.display} (${t.profile.reference})`),console.log(`Project: ${t.project.display} (${t.project.reference})`)):console.log("Not logged in")}async function Es(e,t){await gs(e);let r=new URL(e.getAuthorizeUrl());r.searchParams.set("client_id",lo),r.searchParams.set("redirect_uri",uo),r.searchParams.set("scope",t.scope??"openid offline_access"),r.searchParams.set("response_type","code"),r.searchParams.set("prompt","login"),await ws(r.toString())}var Pe="\x1B[0m",vs="\x1B[1m",Ss="\x1B[31m",bs="\x1B[32m",As="\x1B[33m",Is="\x1B[34m",De={red:e=>`${Ss}${e}${Pe}`,green:e=>`${bs}${e}${Pe}`,yellow:e=>`${As}${e}${Pe}`,blue:e=>`${Is}${e}${Pe}`,bold:e=>`${vs}${e}${Pe}`},yr=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>De.bold(r)),$s=Pr(Dr(),1),ut;function Eo(){ut=yo.default.createInterface({input:process.stdin,output:process.stdout})}function vo(){ut.close()}function d(e){ut.write(e+`
5
+ `)}function F(e){d(`
6
6
  `+e+`
7
- `)}function V(e,t=""){return new Promise(r=>{ut.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function tr(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await V(o)||r;if(t.includes(n))return n;p("Please choose one of the following options: "+t.join(", "))}}async function Oe(e,t,r){return Number.parseInt(await tr(e,t.map(o=>o.toString()),r.toString()),10)}async function Se(e){return(await tr(e,["y","n"])).toLowerCase()==="y"}async function Wt(e){if(!await Se(e))throw p("Exiting..."),new Error("User cancelled")}var et=new ae.CloudFormationClient({}),Us=new at.CloudFrontClient({region:"us-east-1"}),Qa=new Ao.ECSClient({}),rr=new Io.S3Client({}),xs="medplum:environment";async function Oo(){let e=[],t=(0,ae.paginateListStacks)({client:et},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)for(let o of r.StackSummaries??lt.EMPTY)e.push(o);return e}async function or(e){let t=await Oo();for(let r of t){let o=r.StackName,n=await No(o);if(n?.tag===e)return n}}async function No(e){let t={};if(await br(et,e,t),await et.config.region()!=="us-east-1")try{await br(new ae.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function br(e,t,r){let o=new ae.DescribeStacksCommand({StackName:t}),n=(await e.send(o))?.Stacks?.[0],i=n?.Tags?.find(l=>l.Key===xs);if(!i)return;let s=await e.send(new ae.DescribeStackResourcesCommand({StackName:t}));if(s.StackResources){e===et&&(r.stack=n,r.tag=i.Value);for(let l of s.StackResources)_s(l,r)}}function _s(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function Co(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${js(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${e.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${e.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${e.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${e.storageOriginAccessIdentity?.PhysicalResourceId}`)}function js(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Lo(e){let t=await Us.send(new at.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Mo(e){let t=(await(await fetch("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(r=>r.tag_name.startsWith("v")?r.tag_name.slice(1):r.tag_name);return t.sort((r,o)=>ks.compare(o,r)),e?t.slice(0,t.indexOf(e)):t}async function Do(e,t,r){let o=new Ie.SSMClient({region:e});for(let[n,i]of Object.entries(r)){let s=t+n,l=typeof i=="object"?JSON.stringify(i):i.toString(),a=await Fs(o,s);a!==void 0&&a!==l&&(p(`Parameter "${s}" exists with different value.`),await Wt(`Do you want to overwrite "${s}"?`)),await Ws(o,s,l)}}async function Fs(e,t){let r=new Ie.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Ws(e,t,r){let o=new Ie.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function pt(e,t){if(console.log(`Config not found: ${e} (${fe(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,i]of o)console.log(` ${n}: ${i}`)}}console.log();let r=(0,$o.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function nr(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new ct.STSClient,r=new ct.GetCallerIdentityCommand({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,lt.normalizeErrorString)(t))}}async function Bs(e){let t=await or(e);if(!t)throw await nr(e),new Error(`Stack not found: ${e}`);Co(t)}var Gs=e=>`${e}DomainName`,xo=e=>`${e}SslCertArn`;async function Ks(){let e={apiPort:8103,region:"us-east-1"};To(),F("MEDPLUM"),p("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),p(""),p("Most Medplum infrastructure is deployed using the AWS CDK."),p("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),p("This tool will help you create those resources."),p(""),p("Upon completion, this tool will:"),p(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),p(" 2. Optionally generate an AWS CloudFront signing key"),p(" 3. Optionally request SSL certificates from AWS Certificate Manager"),p(" 4. Optionally write server config settings to AWS Parameter Store"),p(""),p("The Medplum infra config file is an input to the Medplum CDK."),p("The Medplum CDK will create and manage the necessary AWS resources."),p(""),p("We will ask a series of questions to generate your infra config file."),p("Some questions have predefined options in [square brackets]."),p("Some questions have default values in (parentheses), which you can accept by pressing Enter."),p("Press Ctrl+C at any time to exit.");let t=await Hs(e.region);t||(p("It appears that you do not have AWS credentials configured."),p("AWS credentials are not strictly required, but will enable some additional features."),p("If you intend to use AWS credentials, please configure them now."),await Wt("Do you want to continue without AWS credentials?")),F("ENVIRONMENT NAME"),p('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),p("The environment name is used in multiple places:"),p(" 1. As part of config file names (i.e., medplum.demo.config.json)"),p(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),p(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await V("What is your environment name?","demo"),p('Using environment name "'+e.name+'"...'),F("CONFIG FILE"),p("Medplum Infrastructure will create a config file in the current directory.");let r=await V("What is the config file name?",`medplum.${e.name}.config.json`);(0,Uo.existsSync)(r)&&(p("Config file already exists."),await Wt("Do you want to overwrite the config file?")),p('Using config file "'+r+'"...'),G(r,e),F("AWS REGION"),p("Most Medplum resources will be created in a single AWS region."),e.region=await V("Enter your AWS region:","us-east-1"),G(r,e),F("AWS ACCOUNT NUMBER"),p("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&p("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await V("What is your AWS account number?",t),G(r,e),F("STACK NAME"),p("Medplum will create a CloudFormation stack to manage AWS resources."),p("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await V("Enter your CloudFormation stack name?",o),G(r,e),F("BASE DOMAIN NAME"),p("Please enter the base domain name for your Medplum deployment."),p(""),p("Medplum deploys multiple subdomains for various services."),p(""),p('For example, "api." for the REST API and "app." for the web application.'),p("The base domain name is the common suffix for all subdomains."),p(""),p('For example, if your base domain name is "example.com",'),p('then the REST API will be "api.example.com".'),p(""),p('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),p(""),p("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await V("Enter your base domain name:");G(r,e),F("SUPPORT EMAIL"),p("Medplum sends transactional emails to users."),p("For example, emails to new users or for password reset."),p("Medplum will use the support email address to send these emails."),p("Note that you must verify the support email address in SES.");let n=await V("Enter your support email address:");F("API DOMAIN NAME"),p("Medplum deploys a REST API for the backend services."),e.apiDomainName=await V("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,G(r,e),F("APP DOMAIN NAME"),p("Medplum deploys a web application for the user interface."),e.appDomainName=await V("Enter your web application domain name:","app."+e.domainName),G(r,e),F("STORAGE DOMAIN NAME"),p("Medplum deploys a storage service for file uploads."),e.storageDomainName=await V("Enter your storage domain name:","storage."+e.domainName),G(r,e),F("STORAGE BUCKET"),p("Medplum uses an S3 bucket to store binary content such as file uploads."),p("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await V("Enter your storage bucket name:",e.storageDomainName),G(r,e),F("MAX AVAILABILITY ZONES"),p("Medplum API servers can be deployed in multiple availability zones."),p("This provides redundancy and high availability."),p("However, it also increases the cost of the deployment."),p("If you want to use all availability zones, choose a large number such as 99."),p("If you want to restrict the number, for example to manage EIP limits,"),p("then choose a small number such as 2 or 3."),e.maxAzs=await Oe("Enter the maximum number of availability zones:",[2,3,99],2),F("DATABASE INSTANCES"),p("Medplum uses a relational database to store data."),p("Medplum can create a new RDS database as part of the CloudFormation stack,"),p("or can set up your own database and enter the database name, username, and password."),await Se("Do you want to create a new RDS database as part of the CloudFormation stack?")?(p("Medplum will create a new RDS database as part of the CloudFormation stack."),p(""),p("If you need high availability, you can choose multiple instances."),p("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await Oe("Enter the number of database instances:",[1,2],1)):(p("Medplum will not create a new RDS database."),p("Please create a new RDS database and enter the database name, username, and password."),p('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),G(r,e),F("SERVER INSTANCES"),p("Medplum uses AWS Fargate to run the API servers."),p("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),p("Fargate will automatically scale the number of servers up and down."),p("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await Oe("Enter the number of server instances:",[1,2,3,4,6,8],1),G(r,e),F("SERVER MEMORY"),p("You can choose the amount of memory for each server instance."),p("The default is 512 MB, which is sufficient for getting started."),p("Note that only certain CPU units are compatible with memory units."),p('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await Oe("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),G(r,e),F("SERVER CPU"),p("You can choose the amount of CPU for each server instance."),p("CPU is expressed as an integer using AWS CPU units"),p("The default is 256, which is sufficient for getting started."),p("Note that only certain CPU units are compatible with memory units."),p('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await Oe("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),G(r,e),F("SERVER IMAGE"),p("Medplum uses Docker images for the API servers."),p("You can choose the image to use for the servers."),p("Docker images can be loaded from either Docker Hub or AWS ECR."),p("The default is the latest Medplum release.");let i=(await Mo())[0]??"latest";e.serverImage=await V("Enter the server image:",`medplum/medplum-server:${i}`),G(r,e),F("SIGNING KEY"),p("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let s=await Xs(e.region,e.stackName+"SigningKey");s?(e.signingKeyId=s.keyId,e.storagePublicKey=s.publicKey,G(r,e)):(p("Unable to generate signing key."),p("Please manually create a signing key and enter the key ID and public key in the config file."),p('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),F("SSL CERTIFICATES"),p("Medplum will now check for existing SSL certificates for the subdomains.");let l=await Js(e.region);p("Found "+l.length+" certificate(s).");for(let{region:h,certName:u}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){p("");let w=await Vs(e,l,h,u);e[xo(u)]=w,G(r,e)}F("AWS PARAMETER STORE"),p("Medplum uses AWS Parameter Store to store sensitive configuration values."),p("These values will be encrypted at rest."),p(`The values will be stored in the "/medplum/${e.name}" path.`);let a={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(s&&(a.signingKeyId=s.keyId,a.signingKey=s.privateKey,a.signingKeyPassphrase=s.passphrase),p(JSON.stringify({...a,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await Se("Do you want to store these values in AWS Parameter Store?"))await Do(e.region,`/medplum/${e.name}/`,a);else{let h=fe(e.name,{server:!0});G(h,a),p("Skipping AWS Parameter Store."),p(`Writing values to local config file: ${h}`),p("Please add these values to AWS Parameter Store manually.")}F("DONE!"),p("Medplum configuration complete."),p("You can now proceed to deploying the Medplum infrastructure with CDK."),p("Run:"),p(""),p(` npx cdk bootstrap -c config=${r}`),p(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?p(` npx cdk deploy -c config=${r}`):p(` npx cdk deploy -c config=${r} --all`),p(""),p("See Medplum documentation for more information:"),p(""),p(" https://www.medplum.com/docs/self-hosting/install-on-aws"),p(""),Po()}async function Hs(e){try{let t=new mt.STSClient({region:e}),r=new mt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Js(e){let t=await Ar(e);if(e!=="us-east-1"){let r=await Ar("us-east-1");t.push(...r)}return t}async function Ar(e){try{let t=new we.ACMClient({region:e}),r=new we.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Vs(e,t,r,o){let n=e[Gs(o)],i=t.find(l=>l.CertificateArn?.includes(r)&&l.DomainName===n);if(i)return p(`Found existing certificate for "${n}" in "${r}.`),i.CertificateArn;if(p(`No existing certificate found for "${n}" in "${r}.`),!await Se("Do you want to request a new certificate?"))return p(`Please add your certificate ARN to the config file in the "${xo(o)}" setting.`),"TODO";let s=await zs(r,n);return p("Certificate ARN: "+s),s}async function zs(e,t){try{let r=await tr("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new we.ACMClient({region:e}),n=new we.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Xs(e,t){let r=(0,Ue.randomUUID)(),o=(0,Ue.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new dt.CloudFrontClient({region:e}).send(new dt.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,Ue.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,ko.normalizeErrorString)(n));return}}async function qs(){let e=await Oo();for(let t of e){let r=t.StackName,o=await No(r);o&&(Co(o),console.log(""))}}async function Ys(e,t){let r=Ae(e,t);if(!r)throw pt(e,t),new Error(`Config not found: ${e}`);let o=await or(e);if(!o)throw await nr(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let i;if(t.tarPath)i=t.tarPath;else{let s=t?.toVersion??"latest";i=await Zs("@medplum/app",s)}Go(i,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await ta(i,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Lo(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Qs(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function Zs(e,t){let r=(await Qs(e,t)).dist.tarball,o=(0,Y.mkdtempSync)((0,me.join)((0,Fo.tmpdir)(),"tarball-"));try{let n=await fetch(r);if(!n.body)throw new Error("Received empty response body");let i=ms(o);return await(0,Bo.pipeline)(Wo.Readable.fromWeb(n.body),i),(0,me.join)(o,"package","dist")}catch(n){throw(0,Y.rmSync)(o,{recursive:!0,force:!0}),n}}function Go(e,t){for(let r of(0,Y.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Go(o,t):r.isFile()&&o.endsWith(".js")&&ea(o,t)}}function ea(e,t){let r=(0,Y.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,Y.writeFileSync)(e,r)}async function ta(e,t,r){let o=[["assets/**/*.css",Q.ContentType.CSS,!0],["assets/**/*.css.map",Q.ContentType.JSON,!0],["assets/**/*.js",Q.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",Q.ContentType.JSON,!0],["assets/**/*.txt",Q.ContentType.TEXT,!0],["assets/**/*.ico",Q.ContentType.FAVICON,!0],["img/**/*.png",Q.ContentType.PNG,!0],["img/**/*.svg",Q.ContentType.SVG,!0],["robots.txt",Q.ContentType.TEXT,!0],["index.html",Q.ContentType.HTML,!1]];for(let n of o)await ra({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function ra(e){let t=jo.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await oa((0,me.join)(e.rootDir,r),e)}async function oa(e,t){let r=(0,Y.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await rr.send(new _o.PutObjectCommand(n))}async function na(e,t){if(!Ae(e,t))throw pt(e,t),new Error(`Config not found: ${e}`);let r=await or(e);if(!r)throw await nr(e),new Error(`Stack not found: ${e}`);try{await Ir("App",r.appBucket,r.appDistribution,r.appOriginAccessIdentity,t)}catch(o){console.error(`Error updating App bucket policy: ${o.message}`)}try{await Ir("Storage",r.storageBucket,r.storageDistribution,r.storageOriginAccessIdentity,t)}catch(o){console.error(`Error updating Storage bucket policy: ${o.message}`)}console.log("Done")}async function Ir(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let i=t.PhysicalResourceId,s=o.PhysicalResourceId,l=await ia(i);if(aa(l,i,s))throw new Error(`${e} bucket already has policy statement`);ca(l,i,s),e==="Storage"&&n.guarddutyMalwareProtection&&la(l,i,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(l,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await sa(i,l),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Lo(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function ia(e){let t=await rr.send(new ht.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function sa(e,t){await rr.send(new ht.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function aa(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function ca(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}function la(e,t,r){e.Statement?.some(o=>o?.Effect==="Deny"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&$r(o,"s3:GetObject")&&$r(o,"s3:GetObjectVersion")&&o?.Condition?.StringNotEquals?.["s3:ExistingObjectTag/GuardDutyMalwareScanStatus"]==="NO_THREATS_FOUND")||e.Statement?.push({Sid:"GuardDutyMalwareProtectionReadGate",Effect:"Deny",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject","s3:GetObjectVersion"],Resource:`arn:aws:s3:::${t}/*`,Condition:{StringNotEquals:{"s3:ExistingObjectTag/GuardDutyMalwareScanStatus":"NO_THREATS_FOUND"}}})}function $r(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function ua(e,t){try{To();let r=Ae(e,t);if(!r)throw pt(e,t),new Error(`Config not found: ${e}`);let o=us(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=fe(e,{server:!0});if(console.log(De.yellow(`Config file ${n} not found!`)),!await Se("Do you want to proceed?")){console.log(De.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}pa(r,o),ma(r,o),p("Medplum uses AWS Parameter Store to store sensitive configuration values."),p("These values will be encrypted at rest."),p(`The values will be stored in the "/medplum/${r.name}" path.`),p(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(De.yellow("Dry run - skipping updates!")):(t.yes||await Se("Do you want to store these values in AWS Parameter Store?"))&&await Do(r.region,`/medplum/${r.name}/`,o)}finally{Po()}}function pa(e,t){Xe(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Xe(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Xe(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Xe(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Xe(e,t,r){if(da(e,t))throw new Error(r)}function da(e,t){return e!==void 0&&t!==void 0&&e!==t}function ma(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/binary/`)}var Bt=Cr(xr(),1);async function ha(e,t){let r=await U(t),o=Ae(e,t);if(!o)throw console.log(`Configuration file ${fe(e)} not found`),pt(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),s=await fa(r,o),l=await Rr(s);for(;l;){if(t.toVersion&&Bt.gt(l,t.toVersion)){console.log(`Skipping update to v${l}`);break}console.log(`Performing update to v${l}`),o.serverImage=`${i}:${l}`,ga(e,o),await r.startAsyncRequest("/admin/super/migrate"),l=await Rr(l)}}async function fa(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let n=o.indexOf("-");n>-1&&(o=o.slice(0,n))}return o}async function Rr(e,t){let r=await Mo(e),o=r[0];return r.filter(n=>n===o||n===t||Bt.gte(n,Bt.inc(e,"minor"))).pop()}function ga(e,t){let r=fe(e);G(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Ko.spawnSync)(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function wa(){let e=new $("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Ks),e.command("list").description("List Medplum AWS CloudFormation stacks").action(qs),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Bs),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(Sr(`Update the AWS Parameter Store config values.
7
+ `)}function J(e,t=""){return new Promise(r=>{ut.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Qt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await J(o)||r;if(t.includes(n))return n;d("Please choose one of the following options: "+t.join(", "))}}async function Oe(e,t,r){return Number.parseInt(await Qt(e,t.map(o=>o.toString()),r.toString()),10)}async function Se(e){return(await Qt(e,["y","n"])).toLowerCase()==="y"}async function _t(e){if(!await Se(e))throw d("Exiting..."),new Error("User cancelled")}var Qe=new ce.CloudFormationClient({}),Rs=new at.CloudFrontClient({region:"us-east-1"}),Ba=new mo.ECSClient({}),Zt=new go.S3Client({}),Ts="medplum:environment";async function So(){let e=[],t=(0,ce.paginateListStacks)({client:Qe},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)for(let o of r.StackSummaries??lt.EMPTY)e.push(o);return e}async function er(e){let t=await So();for(let r of t){let o=r.StackName,n=await bo(o);if(n?.tag===e)return n}}async function bo(e){let t={};if(await Er(Qe,e,t),await Qe.config.region()!=="us-east-1")try{await Er(new ce.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Er(e,t,r){let o=new ce.DescribeStacksCommand({StackName:t}),n=(await e.send(o))?.Stacks?.[0],i=n?.Tags?.find(l=>l.Key===Ts);if(!i)return;let s=await e.send(new ce.DescribeStackResourcesCommand({StackName:t}));if(s.StackResources){e===Qe&&(r.stack=n,r.tag=i.Value);for(let l of s.StackResources)Ps(l,r)}}function Ps(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function Ao(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${Os(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${e.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${e.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${e.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${e.storageOriginAccessIdentity?.PhysicalResourceId}`)}function Os(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Io(e){let t=await Rs.send(new at.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function $o(e){let t=(await(await fetch("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(r=>r.tag_name.startsWith("v")?r.tag_name.slice(1):r.tag_name);return t.sort((r,o)=>$s.compare(o,r)),e?t.slice(0,t.indexOf(e)):t}async function Ro(e,t,r){let o=new Ie.SSMClient({region:e});for(let[n,i]of Object.entries(r)){let s=t+n,l=typeof i=="object"?JSON.stringify(i):i.toString(),a=await Ns(o,s);a!==void 0&&a!==l&&(d(`Parameter "${s}" exists with different value.`),await _t(`Do you want to overwrite "${s}"?`)),await Cs(o,s,l)}}async function Ns(e,t){let r=new Ie.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Cs(e,t,r){let o=new Ie.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function pt(e,t){if(console.log(`Config not found: ${e} (${me(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,i]of o)console.log(` ${n}: ${i}`)}}console.log();let r=(0,wo.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function tr(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new ct.STSClient,r=new ct.GetCallerIdentityCommand({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,lt.normalizeErrorString)(t))}}async function Ls(e){let t=await er(e);if(!t)throw await tr(e),new Error(`Stack not found: ${e}`);Ao(t)}var Ms=e=>`${e}DomainName`,Oo=e=>`${e}SslCertArn`;async function Ds(){let e={apiPort:8103,region:"us-east-1"};Eo(),F("MEDPLUM"),d("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),d(""),d("Most Medplum infrastructure is deployed using the AWS CDK."),d("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),d("This tool will help you create those resources."),d(""),d("Upon completion, this tool will:"),d(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),d(" 2. Optionally generate an AWS CloudFront signing key"),d(" 3. Optionally request SSL certificates from AWS Certificate Manager"),d(" 4. Optionally write server config settings to AWS Parameter Store"),d(""),d("The Medplum infra config file is an input to the Medplum CDK."),d("The Medplum CDK will create and manage the necessary AWS resources."),d(""),d("We will ask a series of questions to generate your infra config file."),d("Some questions have predefined options in [square brackets]."),d("Some questions have default values in (parentheses), which you can accept by pressing Enter."),d("Press Ctrl+C at any time to exit.");let t=await ks(e.region);t||(d("It appears that you do not have AWS credentials configured."),d("AWS credentials are not strictly required, but will enable some additional features."),d("If you intend to use AWS credentials, please configure them now."),await _t("Do you want to continue without AWS credentials?")),F("ENVIRONMENT NAME"),d('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),d("The environment name is used in multiple places:"),d(" 1. As part of config file names (i.e., medplum.demo.config.json)"),d(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),d(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await J("What is your environment name?","demo"),d('Using environment name "'+e.name+'"...'),F("CONFIG FILE"),d("Medplum Infrastructure will create a config file in the current directory.");let r=await J("What is the config file name?",`medplum.${e.name}.config.json`);(0,Po.existsSync)(r)&&(d("Config file already exists."),await _t("Do you want to overwrite the config file?")),d('Using config file "'+r+'"...'),G(r,e),F("AWS REGION"),d("Most Medplum resources will be created in a single AWS region."),e.region=await J("Enter your AWS region:","us-east-1"),G(r,e),F("AWS ACCOUNT NUMBER"),d("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&d("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await J("What is your AWS account number?",t),G(r,e),F("STACK NAME"),d("Medplum will create a CloudFormation stack to manage AWS resources."),d("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await J("Enter your CloudFormation stack name?",o),G(r,e),F("BASE DOMAIN NAME"),d("Please enter the base domain name for your Medplum deployment."),d(""),d("Medplum deploys multiple subdomains for various services."),d(""),d('For example, "api." for the REST API and "app." for the web application.'),d("The base domain name is the common suffix for all subdomains."),d(""),d('For example, if your base domain name is "example.com",'),d('then the REST API will be "api.example.com".'),d(""),d('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),d(""),d("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await J("Enter your base domain name:");G(r,e),F("SUPPORT EMAIL"),d("Medplum sends transactional emails to users."),d("For example, emails to new users or for password reset."),d("Medplum will use the support email address to send these emails."),d("Note that you must verify the support email address in SES.");let n=await J("Enter your support email address:");F("API DOMAIN NAME"),d("Medplum deploys a REST API for the backend services."),e.apiDomainName=await J("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,G(r,e),F("APP DOMAIN NAME"),d("Medplum deploys a web application for the user interface."),e.appDomainName=await J("Enter your web application domain name:","app."+e.domainName),G(r,e),F("STORAGE DOMAIN NAME"),d("Medplum deploys a storage service for file uploads."),e.storageDomainName=await J("Enter your storage domain name:","storage."+e.domainName),G(r,e),F("STORAGE BUCKET"),d("Medplum uses an S3 bucket to store binary content such as file uploads."),d("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await J("Enter your storage bucket name:",e.storageDomainName),G(r,e),F("MAX AVAILABILITY ZONES"),d("Medplum API servers can be deployed in multiple availability zones."),d("This provides redundancy and high availability."),d("However, it also increases the cost of the deployment."),d("If you want to use all availability zones, choose a large number such as 99."),d("If you want to restrict the number, for example to manage EIP limits,"),d("then choose a small number such as 2 or 3."),e.maxAzs=await Oe("Enter the maximum number of availability zones:",[2,3,99],2),F("DATABASE INSTANCES"),d("Medplum uses a relational database to store data."),d("Medplum can create a new RDS database as part of the CloudFormation stack,"),d("or can set up your own database and enter the database name, username, and password."),await Se("Do you want to create a new RDS database as part of the CloudFormation stack?")?(d("Medplum will create a new RDS database as part of the CloudFormation stack."),d(""),d("If you need high availability, you can choose multiple instances."),d("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await Oe("Enter the number of database instances:",[1,2],1)):(d("Medplum will not create a new RDS database."),d("Please create a new RDS database and enter the database name, username, and password."),d('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),G(r,e),F("SERVER INSTANCES"),d("Medplum uses AWS Fargate to run the API servers."),d("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),d("Fargate will automatically scale the number of servers up and down."),d("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await Oe("Enter the number of server instances:",[1,2,3,4,6,8],1),G(r,e),F("SERVER MEMORY"),d("You can choose the amount of memory for each server instance."),d("The default is 512 MB, which is sufficient for getting started."),d("Note that only certain CPU units are compatible with memory units."),d('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await Oe("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),G(r,e),F("SERVER CPU"),d("You can choose the amount of CPU for each server instance."),d("CPU is expressed as an integer using AWS CPU units"),d("The default is 256, which is sufficient for getting started."),d("Note that only certain CPU units are compatible with memory units."),d('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await Oe("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),G(r,e),F("SERVER IMAGE"),d("Medplum uses Docker images for the API servers."),d("You can choose the image to use for the servers."),d("Docker images can be loaded from either Docker Hub or AWS ECR."),d("The default is the latest Medplum release.");let i=(await $o())[0]??"latest";e.serverImage=await J("Enter the server image:",`medplum/medplum-server:${i}`),G(r,e),F("SIGNING KEY"),d("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let s=await _s(e.region,e.stackName+"SigningKey");s?(e.signingKeyId=s.keyId,e.storagePublicKey=s.publicKey,G(r,e)):(d("Unable to generate signing key."),d("Please manually create a signing key and enter the key ID and public key in the config file."),d('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),F("SSL CERTIFICATES"),d("Medplum will now check for existing SSL certificates for the subdomains.");let l=await Us(e.region);d("Found "+l.length+" certificate(s).");for(let{region:f,certName:u}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){d("");let g=await xs(e,l,f,u);e[Oo(u)]=g,G(r,e)}F("AWS PARAMETER STORE"),d("Medplum uses AWS Parameter Store to store sensitive configuration values."),d("These values will be encrypted at rest."),d(`The values will be stored in the "/medplum/${e.name}" path.`);let a={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(s&&(a.signingKeyId=s.keyId,a.signingKey=s.privateKey,a.signingKeyPassphrase=s.passphrase),d(JSON.stringify({...a,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await Se("Do you want to store these values in AWS Parameter Store?"))await Ro(e.region,`/medplum/${e.name}/`,a);else{let f=me(e.name,{server:!0});G(f,a),d("Skipping AWS Parameter Store."),d(`Writing values to local config file: ${f}`),d("Please add these values to AWS Parameter Store manually.")}F("DONE!"),d("Medplum configuration complete."),d("You can now proceed to deploying the Medplum infrastructure with CDK."),d("Run:"),d(""),d(` npx cdk bootstrap -c config=${r}`),d(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?d(` npx cdk deploy -c config=${r}`):d(` npx cdk deploy -c config=${r} --all`),d(""),d("See Medplum documentation for more information:"),d(""),d(" https://www.medplum.com/docs/self-hosting/install-on-aws"),d(""),vo()}async function ks(e){try{let t=new ht.STSClient({region:e}),r=new ht.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Us(e){let t=await vr(e);if(e!=="us-east-1"){let r=await vr("us-east-1");t.push(...r)}return t}async function vr(e){try{let t=new we.ACMClient({region:e}),r=new we.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function xs(e,t,r,o){let n=e[Ms(o)],i=t.find(l=>l.CertificateArn?.includes(r)&&l.DomainName===n);if(i)return d(`Found existing certificate for "${n}" in "${r}.`),i.CertificateArn;if(d(`No existing certificate found for "${n}" in "${r}.`),!await Se("Do you want to request a new certificate?"))return d(`Please add your certificate ARN to the config file in the "${Oo(o)}" setting.`),"TODO";let s=await js(r,n);return d("Certificate ARN: "+s),s}async function js(e,t){try{let r=await Qt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new we.ACMClient({region:e}),n=new we.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function _s(e,t){let r=(0,ke.randomUUID)(),o=(0,ke.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new dt.CloudFrontClient({region:e}).send(new dt.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,ke.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,To.normalizeErrorString)(n));return}}async function Fs(){let e=await So();for(let t of e){let r=t.StackName,o=await bo(r);o&&(Ao(o),console.log(""))}}async function Ws(e,t){let r=Ae(e,t);if(!r)throw pt(e,t),new Error(`Config not found: ${e}`);let o=await er(e);if(!o)throw await tr(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let i;if(t.tarPath)i=t.tarPath;else{let s=t?.toVersion??"latest";i=await Gs("@medplum/app",s)}ko(i,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await Ks(i,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Io(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Bs(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function Gs(e,t){let r=(await Bs(e,t)).dist.tarball,o=(0,Y.mkdtempSync)((0,he.join)((0,Lo.tmpdir)(),"tarball-"));try{let n=await fetch(r);if(!n.body)throw new Error("Received empty response body");let i=os(o);return await(0,Do.pipeline)(Mo.Readable.fromWeb(n.body),i),(0,he.join)(o,"package","dist")}catch(n){throw(0,Y.rmSync)(o,{recursive:!0,force:!0}),n}}function ko(e,t){for(let r of(0,Y.readdirSync)(e,{withFileTypes:!0})){let o=(0,he.join)(e,r.name);r.isDirectory()?ko(o,t):r.isFile()&&o.endsWith(".js")&&Hs(o,t)}}function Hs(e,t){let r=(0,Y.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,Y.writeFileSync)(e,r)}async function Ks(e,t,r){let o=[["assets/**/*.css",Q.ContentType.CSS,!0],["assets/**/*.css.map",Q.ContentType.JSON,!0],["assets/**/*.js",Q.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",Q.ContentType.JSON,!0],["assets/**/*.txt",Q.ContentType.TEXT,!0],["assets/**/*.ico",Q.ContentType.FAVICON,!0],["img/**/*.png",Q.ContentType.PNG,!0],["img/**/*.svg",Q.ContentType.SVG,!0],["robots.txt",Q.ContentType.TEXT,!0],["index.html",Q.ContentType.HTML,!1]];for(let n of o)await Vs({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Vs(e){let t=Co.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Js((0,he.join)(e.rootDir,r),e)}async function Js(e,t){let r=(0,Y.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(he.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await Zt.send(new No.PutObjectCommand(n))}async function zs(e,t){if(!Ae(e,t))throw pt(e,t),new Error(`Config not found: ${e}`);let r=await er(e);if(!r)throw await tr(e),new Error(`Stack not found: ${e}`);try{await Sr("App",r.appBucket,r.appDistribution,r.appOriginAccessIdentity,t)}catch(o){console.error(`Error updating App bucket policy: ${o.message}`)}try{await Sr("Storage",r.storageBucket,r.storageDistribution,r.storageOriginAccessIdentity,t)}catch(o){console.error(`Error updating Storage bucket policy: ${o.message}`)}console.log("Done")}async function Sr(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let i=t.PhysicalResourceId,s=o.PhysicalResourceId,l=await Xs(i);if(Ys(l,i,s))throw new Error(`${e} bucket already has policy statement`);Qs(l,i,s),e==="Storage"&&n.guarddutyMalwareProtection&&Zs(l,i,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(l,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await qs(i,l),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Io(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Xs(e){let t=await Zt.send(new ft.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function qs(e,t){await Zt.send(new ft.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Ys(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Qs(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}function Zs(e,t,r){e.Statement?.some(o=>o?.Effect==="Deny"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&br(o,"s3:GetObject")&&br(o,"s3:GetObjectVersion")&&o?.Condition?.StringNotEquals?.["s3:ExistingObjectTag/GuardDutyMalwareScanStatus"]==="NO_THREATS_FOUND")||e.Statement?.push({Sid:"GuardDutyMalwareProtectionReadGate",Effect:"Deny",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject","s3:GetObjectVersion"],Resource:`arn:aws:s3:::${t}/*`,Condition:{StringNotEquals:{"s3:ExistingObjectTag/GuardDutyMalwareScanStatus":"NO_THREATS_FOUND"}}})}function br(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function ea(e,t){try{Eo();let r=Ae(e,t);if(!r)throw pt(e,t),new Error(`Config not found: ${e}`);let o=es(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=me(e,{server:!0});if(console.log(De.yellow(`Config file ${n} not found!`)),!await Se("Do you want to proceed?")){console.log(De.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}ta(r,o),oa(r,o),d("Medplum uses AWS Parameter Store to store sensitive configuration values."),d("These values will be encrypted at rest."),d(`The values will be stored in the "/medplum/${r.name}" path.`),d(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(De.yellow("Dry run - skipping updates!")):(t.yes||await Se("Do you want to store these values in AWS Parameter Store?"))&&await Ro(r.region,`/medplum/${r.name}/`,o)}finally{vo()}}function ta(e,t){ze(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),ze(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),ze(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),ze(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function ze(e,t,r){if(ra(e,t))throw new Error(r)}function ra(e,t){return e!==void 0&&t!==void 0&&e!==t}function oa(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/binary/`)}var Ft=Pr(Dr(),1);async function na(e,t){let r=await U(t),o=Ae(e,t);if(!o)throw console.log(`Configuration file ${me(e)} not found`),pt(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),s=await ia(r,o),l=await Ar(s);for(;l;){if(t.toVersion&&Ft.gt(l,t.toVersion)){console.log(`Skipping update to v${l}`);break}console.log(`Performing update to v${l}`),o.serverImage=`${i}:${l}`,sa(e,o),await r.startAsyncRequest("/admin/super/migrate"),l=await Ar(l)}}async function ia(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let n=o.indexOf("-");n>-1&&(o=o.slice(0,n))}return o}async function Ar(e,t){let r=await $o(e),o=r[0];return r.filter(n=>n===o||n===t||Ft.gte(n,Ft.inc(e,"minor"))).pop()}function sa(e,t){let r=me(e);G(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Uo.spawnSync)(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function aa(){let e=new R("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Ds),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Fs),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Ls),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(yr(`Update the AWS Parameter Store config values.
8
8
 
9
9
  Configuration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.
10
10
 
11
- `+De.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",Sr("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(ua),T(e,new $("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(ha)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(Ys),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--guardduty-malware-protection","Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(na),e}var Ho=new $("save"),Jo=new $("deploy"),Vo=new $("create"),ft=new $("bot");T(ft,Ho);T(ft,Jo);T(ft,Vo);var zo=new $("save-bot"),Xo=new $("deploy-bot"),qo=new $("create-bot");Ho.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await U(t);await gt(r,e)});Jo.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await U(t);await gt(r,e,!0)});Vo.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,n)=>{let i=await U(n);await ro(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function gt(e,t,r=!1){let o=ls(t),n=[],i=[],s=0,l=0;for(let a of o)try{let h=await e.readResource("Bot",a.id);await eo(e,a,h),s++,r&&(await to(e,a,h),l++)}catch(h){n.push(h),i.push(`${a.name} [${a.id}]`)}if(console.log(`Number of bots saved: ${s}`),console.log(`Number of bots deployed: ${l}`),console.log(`Number of errors: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
11
+ `+De.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",yr("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(ea),T(e,new R("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(na)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(Ws),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--guardduty-malware-protection","Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(zs),e}var xo=new R("save"),jo=new R("deploy"),_o=new R("create"),mt=new R("bot");T(mt,xo);T(mt,jo);T(mt,_o);var Fo=new R("save-bot"),Wo=new R("deploy-bot"),Bo=new R("create-bot");xo.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await U(t);await gt(r,e)});jo.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await U(t);await gt(r,e,!0)});_o.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,n)=>{let i=await U(n);await zr(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function gt(e,t,r=!1){let o=Zi(t),n=[],i=[],s=0,l=0;for(let a of o)try{let f=await e.readResource("Bot",a.id);await Vr(e,a,f),s++,r&&(await Jr(e,a,f),l++)}catch(f){n.push(f),i.push(`${a.name} [${a.id}]`)}if(console.log(`Number of bots saved: ${s}`),console.log(`Number of bots deployed: ${l}`),console.log(`Number of errors: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
12
12
 
13
13
  ${i.join(`
14
- `)}`,{cause:n})}zo.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await U(t);await gt(r,e)});Xo.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await U(t);await gt(r,e,!0)});qo.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await U(n);await ro(i,e,t,r,o)});var en=new $("export"),tn=new $("import"),sr=new $("bulk");T(sr,en);T(sr,tn);en.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,i=await U(e),s=await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0});for(let{type:l,url:a}of s.output??z.EMPTY){let h=new URL(a),u=`${l}_${h.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",w=(0,ir.resolve)(n??"",u),c=await i.downloadResponse(a);if(!c.ok)throw new Error(`Download failed: ${c.status} ${c.statusText}`);if(!c.body)throw new Error("Download response missing body");let m=Qo.Readable.fromWeb(c.body);await(0,Zo.pipeline)(m,(0,wt.createWriteStream)(w)),console.log(`${w} is created`)}});tn.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,i=(0,ir.resolve)(n??process.cwd(),e),s=await U(t);await ya(i,Number.parseInt(r,10),s,o)});async function ya(e,t,r,o){let n=[],i=(0,wt.createReadStream)(e),s=(0,Yo.createInterface)({input:i});for await(let l of s){let a=Ea(l,o);n.push({resource:a,request:{method:"POST",url:a.resourceType}}),n.length%t===0&&(await Tr(n,r),n=[])}n.length>0&&await Tr(n,r)}async function Tr(e,t){let r=e;for(;r.length>0;){let o;try{o=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:r},{maxRetries:0})}catch(i){if(!(i instanceof z.OperationOutcomeError)||(0,z.getStatus)(i.outcome)!==429)throw i;await(0,z.sleep)(Pr(i.outcome,t));continue}let n=[];for(let i=0;i<r.length;i++){let s=o.entry?.[i];s?.response?.outcome&&(0,z.getStatus)(s.response.outcome)===429?n.push(r[i]):de(s?.response)}if(n.length>0){let i=o.entry?.find(s=>s.response?.outcome&&(0,z.getStatus)(s.response.outcome)===429)?.response?.outcome;await(0,z.sleep)(Pr(i,t))}r=n}}function Pr(e,t){let r=e&&(0,z.getRateLimitReset)(e);return r!==void 0?r:Math.max(500,...t.rateLimitStatus().filter(o=>o.remainingUnits===0).map(o=>o.secondsUntilReset*1e3))}function Ea(e,t){let r=JSON.parse(e);return t?va(r):r}function va(e){return e.resourceType==="ExplanationOfBenefit"?Sa(e):e}function Sa(e){return e.provider||(e.provider=wr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=wr())}),e}var ba=25,Aa=new Set([".dcm",".dicom",".ima"]),nn=Buffer.from("DICM"),sn=128,Ia=sn+nn.length,$a=2;async function Ra(e){if((0,$e.basename)(e).toUpperCase()==="DICOMDIR")return!1;let t=await(0,yt.open)(e,"r");try{let r=Buffer.alloc(Ia),{bytesRead:o}=await t.read(r,0,r.length,0);if(o===r.length&&r.subarray(sn).equals(nn)||o>=2&&r.readUInt16LE(0)===$a)return!0}finally{await t.close()}return Aa.has((0,$e.extname)(e).toLowerCase())}async function Ta(e){let t=new Set;for(let r of e){let o=await(0,yt.stat)(r).catch(()=>{});if(o?.isFile()){t.add((0,$e.resolve)(r));continue}let n;if(o?.isDirectory())n=await(0,Ye.default)("**/*",{cwd:r,onlyFiles:!0,absolute:!0});else if(Ye.default.isDynamicPattern(r))n=await(0,Ye.default)(r,{onlyFiles:!0,absolute:!0,caseSensitiveMatch:!1});else throw new Error(`File not found: ${r}`);let i=0;for(let s of n)await Ra(s)?t.add(s):i++;i>0&&console.log(`Skipped ${i} non-DICOM file(s) in "${r}"`)}return Array.from(t).sort((r,o)=>r.localeCompare(o))}async function Ne(e,t){e.write(t)||await(0,ar.once)(e,"drain")}async function Pa(e,t){let r=(0,rn.createReadStream)(e);try{for await(let o of r)t.write(o)||await(0,ar.once)(t,"drain")}finally{r.destroy()}}async function Oa(e,t,r){try{for(let o of t)await Ne(e,Buffer.from(`--${r}\r
14
+ `)}`,{cause:n})}Fo.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await U(t);await gt(r,e)});Wo.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await U(t);await gt(r,e,!0)});Bo.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await U(n);await zr(i,e,t,r,o)});var Vo=new R("export"),Jo=new R("import"),or=new R("bulk");T(or,Vo);T(or,Jo);Vo.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,i=await U(e),s=await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0});for(let{type:l,url:a}of s.output??z.EMPTY){let f=new URL(a),u=`${l}_${f.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",g=(0,rr.resolve)(n??"",u),c=await i.downloadResponse(a);if(!c.ok)throw new Error(`Download failed: ${c.status} ${c.statusText}`);if(!c.body)throw new Error("Download response missing body");let h=Ho.Readable.fromWeb(c.body);await(0,Ko.pipeline)(h,(0,wt.createWriteStream)(g)),console.log(`${g} is created`)}});Jo.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,i=(0,rr.resolve)(n??process.cwd(),e),s=await U(t);await ca(i,Number.parseInt(r,10),s,o)});async function ca(e,t,r,o){let n=[],i=(0,wt.createReadStream)(e),s=(0,Go.createInterface)({input:i});for await(let l of s){let a=la(l,o);n.push({resource:a,request:{method:"POST",url:a.resourceType}}),n.length%t===0&&(await Ir(n,r),n=[])}n.length>0&&await Ir(n,r)}async function Ir(e,t){let r=e;for(;r.length>0;){let o;try{o=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:r},{maxRetries:0})}catch(i){if(!(i instanceof z.OperationOutcomeError)||(0,z.getStatus)(i.outcome)!==429)throw i;await(0,z.sleep)($r(i.outcome,t));continue}let n=[];for(let i=0;i<r.length;i++){let s=o.entry?.[i];s?.response?.outcome&&(0,z.getStatus)(s.response.outcome)===429?n.push(r[i]):de(s?.response)}if(n.length>0){let i=o.entry?.find(s=>s.response?.outcome&&(0,z.getStatus)(s.response.outcome)===429)?.response?.outcome;await(0,z.sleep)($r(i,t))}r=n}}function $r(e,t){let r=e&&(0,z.getRateLimitReset)(e);return r!==void 0?r:Math.max(500,...t.rateLimitStatus().filter(o=>o.remainingUnits===0).map(o=>o.secondsUntilReset*1e3))}function la(e,t){let r=JSON.parse(e);return t?ua(r):r}function ua(e){return e.resourceType==="ExplanationOfBenefit"?pa(e):e}function pa(e){return e.provider||(e.provider=fr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=fr())}),e}var da=25,ha=new Set([".dcm",".dicom",".ima"]),qo=Buffer.from("DICM"),Yo=128,fa=Yo+qo.length,ma=2;async function ga(e){if((0,$e.basename)(e).toUpperCase()==="DICOMDIR")return!1;let t=await(0,yt.open)(e,"r");try{let r=Buffer.alloc(fa),{bytesRead:o}=await t.read(r,0,r.length,0);if(o===r.length&&r.subarray(Yo).equals(qo)||o>=2&&r.readUInt16LE(0)===ma)return!0}finally{await t.close()}return ha.has((0,$e.extname)(e).toLowerCase())}async function wa(e){let t=new Set;for(let r of e){let o=await(0,yt.stat)(r).catch(()=>{});if(o?.isFile()){t.add((0,$e.resolve)(r));continue}let n;if(o?.isDirectory())n=await(0,qe.default)("**/*",{cwd:r,onlyFiles:!0,absolute:!0});else if(qe.default.isDynamicPattern(r))n=await(0,qe.default)(r,{onlyFiles:!0,absolute:!0,caseSensitiveMatch:!1});else throw new Error(`File not found: ${r}`);let i=0;for(let s of n)await ga(s)?t.add(s):i++;i>0&&console.log(`Skipped ${i} non-DICOM file(s) in "${r}"`)}return Array.from(t).sort((r,o)=>r.localeCompare(o))}async function Ne(e,t){e.write(t)||await(0,nr.once)(e,"drain")}async function ya(e,t){let r=(0,zo.createReadStream)(e);try{for await(let o of r)t.write(o)||await(0,nr.once)(t,"drain")}finally{r.destroy()}}async function Ea(e,t,r){try{for(let o of t)await Ne(e,Buffer.from(`--${r}\r
15
15
  `)),await Ne(e,Buffer.from(`Content-Type: application/dicom\r
16
16
  `)),await Ne(e,Buffer.from(`\r
17
- `)),await Pa(o,e),await Ne(e,Buffer.from(`\r
17
+ `)),await ya(o,e),await Ne(e,Buffer.from(`\r
18
18
  `));await Ne(e,Buffer.from(`--${r}--\r
19
- `)),e.end()}catch(o){throw e.destroy(o),o}}var Na=new $("stow").description("Send DICOM instances via DICOMweb STOW-RS").argument("<files...>","DICOM files, directories, or quoted glob patterns to send").option("--batch-size <count>","Maximum number of instances per STOW-RS request",String(ba)).action(async(e,t)=>{let r=Number.parseInt(t.batchSize,10);if(!Number.isInteger(r)||r<1)throw new Error(`Invalid batch size: ${t.batchSize}`);let o=await Ta(e);if(o.length===0)throw new Error("No DICOM files found");console.log(`Sending ${o.length} DICOM file(s)`);let n=await U(t);for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r),l=`medplum-${Date.now()}`,a=`multipart/related; type=application/dicom; boundary=${l}`,h=new on.PassThrough,u=Oa(h,s,l),w=n.post("/dicomweb/studies",h,a);await u;let c=await w;console.log("STOW-RS response received",c)}}),an=new $("dicomweb");T(an,Na);var Ca=Object.defineProperty,La=(e,t,r)=>t in e?Ca(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,D=(e,t,r)=>La(e,typeof t!="symbol"?t+"":t,r),pn=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Ma=class extends Event{constructor(e,t){super("message"),D(this,"connection"),D(this,"message"),this.connection=e,this.message=t}},Da=class extends Event{constructor(e,t){super("enhancedAckSent"),D(this,"connection"),D(this,"message"),this.connection=e,this.message=t}},Me=class extends Event{constructor(e){super("error"),D(this,"error"),this.error=e}},Kt=class extends Event{constructor(e){super("warning"),D(this,"error"),this.error=e}},Ht=class extends Event{constructor(){super("close")}},Or="utf-8",ka=5e3,Ua=60*1e3,dn=class extends pn{constructor(e,t=Or,r,o={}){super(),D(this,"socket"),D(this,"encoding"),D(this,"enhancedMode"),D(this,"messagesPerMin"),D(this,"gracefulCloseTimeoutMs"),D(this,"chunks",[]),D(this,"pendingMessages",new Map),D(this,"responseQueue",[]),D(this,"lastMessageDispatchedTime",0),D(this,"responseQueueProcessing",!1),D(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,this.gracefulCloseTimeoutMs=o.gracefulCloseTimeoutMs??ka,e.on("data",n=>{if(this.closing){this.dispatchEvent(new Kt(new K.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(n);let i=this.parseMessages();for(let s of i)this.responseQueue.push(new Ma(this,s));this.processResponseQueue().catch(s=>{this.dispatchEvent(new Me(s))})}catch(i){this.dispatchEvent(new Me(i))}}),e.on("error",n=>{this.resetBuffer(),this.dispatchEvent(new Me(n))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new Ht)}),this.addEventListener("message",n=>{let i;this.enhancedMode==="standard"?i=n.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=n.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new Da(this,i)));let s=n.message.getSegment("MSA")?.getField(2)?.toString();if(!s)return;let l=this.getPendingMessage(s);if(!l){this.dispatchEvent(new Kt(new K.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${s}' but there was no pending message with this control ID`}]})));return}let a=n.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();a&&(l.returnAck===K.ReturnAckCategory.APPLICATION&&a==="CA"||(l.timer&&clearTimeout(l.timer),l.resolve(n.message),this.deletePendingMessage(s)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Gt.default.encode(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=Ua/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,K.sleep)(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let o=-1;for(let l=r+1;l<t.length-1;l++)if(t[l]===28&&t[l+1]===13){o=l+1;break}if(o===-1)break;let n=t.subarray(r,o+1).subarray(1,-2),i=Gt.default.decode(n,this.encoding),s=K.Hl7Message.parse(i);e.push(s),r=o+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,o)=>{let n=e.getSegment("MSH")?.getField(10)?.toString();if(!n){o(new K.OperationOutcomeError((0,K.validationError)("Required field missing: MSH.10")));return}let i;t?.timeoutMs&&(i=setTimeout(()=>{this.deletePendingMessage(n),o(new K.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.setPendingMessage(n,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??K.ReturnAckCategory.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new K.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Me(new K.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${e} messages were pending`}]}))),this.pendingMessages.clear()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??Or}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},xa=class extends pn{constructor(e){super(),D(this,"options"),D(this,"host"),D(this,"port"),D(this,"encoding"),D(this,"connection"),D(this,"keepAlive"),D(this,"socket"),D(this,"connectTimeout"),D(this,"deferredConnectionPromise"),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1,this.connectTimeout=this.options.connectTimeout??3e4}connect(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=cn.default.connect({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){(0,Le.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let o=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,o)};t.on("timeout",r)}registerSocketConnectListener(e){(0,Le.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){(0,Le.default)(this.socket);let t=this.socket,r=o=>{this.cleanupSocket(t),o.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,o.errors[0]):this.rejectDeferredPromise(e,o)};t.on("error",r)}registerSocketCloseListener(e){(0,Le.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new Ht)}),e.addEventListener("error",t=>{this.dispatchEvent(new Me(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Kt(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}createConnection(e,t,r,o){return new dn(e,t,r,o)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new Ht);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},_a=1e4,ja=class{constructor(e){D(this,"handler"),D(this,"server"),D(this,"encoding"),D(this,"enhancedMode"),D(this,"messagesPerMin"),D(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let n=un.default.createServer(i=>{let s=new dn(i,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(s),this.connections.add(s),s.addEventListener("close",()=>{this.connections.delete(s)})});return new Promise((i,s)=>{let l=h=>{n.listen(h,()=>{let u=n.address().port;i(u)})},a=h=>{h?.code==="EADDRINUSE"?n.close(()=>(0,ln.sleep)(50).then(()=>l(e))):s(h)};n.on("error",a),n.once("listening",()=>{n.off("error",a)}),l(e),this.server=n})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let n of this.connections)n.close().catch(console.error)},e?.forceDrainTimeoutMs??_a)),this.server.close(n=>{if(n){r(n);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}},Fa=new $("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=Ba():o.file&&(r=(0,mn.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new xa({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await n.sendAndWait(Et.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
20
- `))}finally{await n.close()}}),Wa=new $("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new ja(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
21
- `)),r.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),cr=new $("hl7");T(cr,Fa);T(cr,Wa);function Ba(){let e=(0,Et.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
19
+ `)),e.end()}catch(o){throw e.destroy(o),o}}var va=new R("stow").description("Send DICOM instances via DICOMweb STOW-RS").argument("<files...>","DICOM files, directories, or quoted glob patterns to send").option("--batch-size <count>","Maximum number of instances per STOW-RS request",String(da)).action(async(e,t)=>{let r=Number.parseInt(t.batchSize,10);if(!Number.isInteger(r)||r<1)throw new Error(`Invalid batch size: ${t.batchSize}`);let o=await wa(e);if(o.length===0)throw new Error("No DICOM files found");console.log(`Sending ${o.length} DICOM file(s)`);let n=await U(t);for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r),l=`medplum-${Date.now()}`,a=`multipart/related; type=application/dicom; boundary=${l}`,f=new Xo.PassThrough,u=Ea(f,s,l),g=n.post("/dicomweb/studies",f,a);await u;let c=await g;console.log("STOW-RS response received",c)}}),Qo=new R("dicomweb");T(Qo,va);var Sa=Object.defineProperty,ba=(e,t,r)=>t in e?Sa(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,D=(e,t,r)=>ba(e,typeof t!="symbol"?t+"":t,r),rn=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Aa=class extends Event{constructor(e,t){super("message"),D(this,"connection"),D(this,"message"),this.connection=e,this.message=t}},Ia=class extends Event{constructor(e,t){super("enhancedAckSent"),D(this,"connection"),D(this,"message"),this.connection=e,this.message=t}},Me=class extends Event{constructor(e){super("error"),D(this,"error"),this.error=e}},Bt=class extends Event{constructor(e){super("warning"),D(this,"error"),this.error=e}},Gt=class extends Event{constructor(){super("close")}},Rr="utf-8",$a=5e3,Ra=60*1e3,on=class extends rn{constructor(e,t=Rr,r,o={}){super(),D(this,"socket"),D(this,"encoding"),D(this,"enhancedMode"),D(this,"messagesPerMin"),D(this,"gracefulCloseTimeoutMs"),D(this,"chunks",[]),D(this,"pendingMessages",new Map),D(this,"responseQueue",[]),D(this,"lastMessageDispatchedTime",0),D(this,"responseQueueProcessing",!1),D(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,this.gracefulCloseTimeoutMs=o.gracefulCloseTimeoutMs??$a,e.on("data",n=>{if(this.closing){this.dispatchEvent(new Bt(new H.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(n);let i=this.parseMessages();for(let s of i)this.responseQueue.push(new Aa(this,s));this.processResponseQueue().catch(s=>{this.dispatchEvent(new Me(s))})}catch(i){this.dispatchEvent(new Me(i))}}),e.on("error",n=>{this.resetBuffer(),this.dispatchEvent(new Me(n))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new Gt)}),this.addEventListener("message",n=>{let i;this.enhancedMode==="standard"?i=n.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=n.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new Ia(this,i)));let s=n.message.getSegment("MSA")?.getField(2)?.toString();if(!s)return;let l=this.getPendingMessage(s);if(!l){this.dispatchEvent(new Bt(new H.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${s}' but there was no pending message with this control ID`}]})));return}let a=n.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();a&&(l.returnAck===H.ReturnAckCategory.APPLICATION&&a==="CA"||(l.timer&&clearTimeout(l.timer),l.resolve(n.message),this.deletePendingMessage(s)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Wt.default.encode(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=Ra/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,H.sleep)(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let o=-1;for(let l=r+1;l<t.length-1;l++)if(t[l]===28&&t[l+1]===13){o=l+1;break}if(o===-1)break;let n=t.subarray(r,o+1).subarray(1,-2),i=Wt.default.decode(n,this.encoding),s=H.Hl7Message.parse(i);e.push(s),r=o+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,o)=>{let n=e.getSegment("MSH")?.getField(10)?.toString();if(!n){o(new H.OperationOutcomeError((0,H.validationError)("Required field missing: MSH.10")));return}let i;t?.timeoutMs&&(i=setTimeout(()=>{this.deletePendingMessage(n),o(new H.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.setPendingMessage(n,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??H.ReturnAckCategory.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new H.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Me(new H.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${e} messages were pending`}]}))),this.pendingMessages.clear()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??Rr}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},Ta=class extends rn{constructor(e){super(),D(this,"options"),D(this,"host"),D(this,"port"),D(this,"encoding"),D(this,"connection"),D(this,"keepAlive"),D(this,"socket"),D(this,"connectTimeout"),D(this,"deferredConnectionPromise"),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1,this.connectTimeout=this.options.connectTimeout??3e4}connect(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=Zo.default.connect({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){(0,Le.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let o=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,o)};t.on("timeout",r)}registerSocketConnectListener(e){(0,Le.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){(0,Le.default)(this.socket);let t=this.socket,r=o=>{this.cleanupSocket(t),o.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,o.errors[0]):this.rejectDeferredPromise(e,o)};t.on("error",r)}registerSocketCloseListener(e){(0,Le.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new Gt)}),e.addEventListener("error",t=>{this.dispatchEvent(new Me(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Bt(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}createConnection(e,t,r,o){return new on(e,t,r,o)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new Gt);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Pa=1e4,Oa=class{constructor(e){D(this,"handler"),D(this,"server"),D(this,"encoding"),D(this,"enhancedMode"),D(this,"messagesPerMin"),D(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let n=tn.default.createServer(i=>{let s=new on(i,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(s),this.connections.add(s),s.addEventListener("close",()=>{this.connections.delete(s)})});return new Promise((i,s)=>{let l=f=>{n.listen(f,()=>{let u=n.address().port;i(u)})},a=f=>{f?.code==="EADDRINUSE"?n.close(()=>(0,en.sleep)(50).then(()=>l(e))):s(f)};n.on("error",a),n.once("listening",()=>{n.off("error",a)}),l(e),this.server=n})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let n of this.connections)n.close().catch(console.error)},e?.forceDrainTimeoutMs??Pa)),this.server.close(n=>{if(n){r(n);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}},Na=new R("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=La():o.file&&(r=(0,nn.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new Ta({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await n.sendAndWait(Et.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
20
+ `))}finally{await n.close()}}),Ca=new R("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new Oa(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
21
+ `)),r.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),ir=new R("hl7");T(ir,Na);T(ir,Ca);function La(){let e=(0,Et.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
22
22
  EVN|A01|${e}||
23
23
  PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|
24
- PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var wn=new $("set"),yn=new $("remove"),En=new $("list"),vn=new $("describe"),Ke=new $("profile");T(Ke,wn);T(Ke,yn);T(Ke,En);T(Ke,vn);wn.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{oo(e,t)});yn.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new We(e).setObject("options",void 0),console.log(`${e} profile removed`)});En.description("List all profiles saved").action(async()=>{let e=(0,gn.resolve)((0,fn.homedir)(),".medplum"),t=(0,hn.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],i=new We(n).getObject("options");i&&r.push({profileName:n,profile:i})}),console.log(r)});vn.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=fs(e);console.log(t)});var bn=new $("list"),An=new $("current"),In=new $("switch"),$n=new $("invite"),He=new $("project");T(He,bn);T(He,An);T(He,In);T(He,$n);bn.description("List of current projects").action(async e=>{let t=await U(e);Ga(t)});function Ga(e){let t=e.getLogins().map(r=>`${r.project.display} (${r.project.reference})`).join(`
24
+ PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var ln=new R("set"),un=new R("remove"),pn=new R("list"),dn=new R("describe"),Ge=new R("profile");T(Ge,ln);T(Ge,un);T(Ge,pn);T(Ge,dn);ln.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{Xr(e,t)});un.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new Fe(e).setObject("options",void 0),console.log(`${e} profile removed`)});pn.description("List all profiles saved").action(async()=>{let e=(0,cn.resolve)((0,an.homedir)(),".medplum"),t=(0,sn.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],i=new Fe(n).getObject("options");i&&r.push({profileName:n,profile:i})}),console.log(r)});dn.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=is(e);console.log(t)});var fn=new R("list"),mn=new R("current"),gn=new R("switch"),wn=new R("invite"),He=new R("project");T(He,fn);T(He,mn);T(He,gn);T(He,wn);fn.description("List of current projects").action(async e=>{let t=await U(e);Ma(t)});function Ma(e){let t=e.getLogins().map(r=>`${r.project.display} (${r.project.reference})`).join(`
25
25
 
26
- `);console.log(t)}An.description("Project you are currently on").action(async e=>{let t=(await U(e)).getActiveLogin();if(!t)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${t.project.display} (${t.project.reference})`)});In.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await U(t);await Ka(r,e)});$n.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new Sn.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await U(o),i=n.getActiveLogin();if(!i)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!i?.project?.reference)throw new Error("No current project to invite user to");let s=i.project.reference.split("/")[1],l={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await Ha(s,l,n)});async function Ka(e,t){let r=e.getLogins().find(o=>o.project.reference?.includes(t));if(!r)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(r),console.log(`Switched to project ${t}
27
- `)}async function Ha(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var Tn=new $("delete"),Pn=new $("get"),On=new $("patch"),Nn=new $("post"),Cn=new $("put");Tn.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await U(t);de(await r.delete(Je(r,e)))});Pn.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await U(t),o=await r.get(Je(r,e));t.asTransaction?de((0,Rn.convertToTransactionBundle)(o)):de(o)});On.arguments("<url> <body>").action(async(e,t,r)=>{let o=await U(r);de(await o.patch(Je(o,e),lr(t)))});Nn.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let o=await U(r),n=r.preferAsync?{Prefer:"respond-async"}:void 0;de(await o.post(Je(o,e),lr(t),void 0,{headers:n}))});Cn.arguments("<url> <body>").action(async(e,t,r)=>{let o=await U(r);de(await o.put(Je(o,e),lr(t)))});function lr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Je(e,t){return["admin/","auth/","fhir/R4"].some(r=>t.startsWith(r))?t:e.fhirUrl(t).toString()}async function Ja(e){let t=new $("medplum").description("Command to access Medplum CLI").option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>",'OAuth scope (e.g., "openid offline_access")').option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new je.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});t.exitOverride(),t.version(ve.MEDPLUM_VERSION),t.configureHelp({showGlobalOptions:!0}),T(t,vo),T(t,So),T(t,bo),T(t,Pn),T(t,Nn),T(t,On),T(t,Cn),T(t,Tn),T(t,He),T(t,sr),T(t,ft),T(t,ge),T(t,zo),T(t,Xo),T(t,qo),T(t,Ke),T(t,wa()),T(t,cr),T(t,an);try{await t.parseAsync(e)}catch(r){Va(r)}}function Va(e){let t=1,r=!0;if(e instanceof je.CommanderError&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){Ut(e,!!process.env.VERBOSE);let o=e.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let n of o)Ut(n,!0);else o instanceof Error&&Ut(o,!0)}process.exit(t)}function Ut(e,t=!1){if(t){console.error(e);return}e instanceof je.CommanderError?process.stderr.write(`${(0,ve.normalizeErrorString)(e)}
26
+ `);console.log(t)}mn.description("Project you are currently on").action(async e=>{let t=(await U(e)).getActiveLogin();if(!t)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${t.project.display} (${t.project.reference})`)});gn.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await U(t);await Da(r,e)});wn.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new hn.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await U(o),i=n.getActiveLogin();if(!i)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!i?.project?.reference)throw new Error("No current project to invite user to");let s=i.project.reference.split("/")[1],l={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await ka(s,l,n)});async function Da(e,t){let r=e.getLogins().find(o=>o.project.reference?.includes(t));if(!r)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(r),console.log(`Switched to project ${t}
27
+ `)}async function ka(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var En=new R("delete"),vn=new R("get"),Sn=new R("patch"),bn=new R("post"),An=new R("put");En.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await U(t);de(await r.delete(Ke(r,e)))});vn.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await U(t),o=await r.get(Ke(r,e));t.asTransaction?de((0,yn.convertToTransactionBundle)(o)):de(o)});Sn.arguments("<url> <body>").action(async(e,t,r)=>{let o=await U(r);de(await o.patch(Ke(o,e),sr(t)))});bn.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let o=await U(r),n=r.preferAsync?{Prefer:"respond-async"}:void 0;de(await o.post(Ke(o,e),sr(t),void 0,{headers:n}))});An.arguments("<url> <body>").action(async(e,t,r)=>{let o=await U(r);de(await o.put(Ke(o,e),sr(t)))});function sr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Ke(e,t){return["admin/","auth/","fhir/R4"].some(r=>t.startsWith(r))?t:e.fhirUrl(t).toString()}async function Ua(e){let t=new R("medplum").description("Command to access Medplum CLI").option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>",'OAuth scope (e.g., "openid offline_access")').option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new je.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});t.exitOverride(),t.version(ve.MEDPLUM_VERSION),t.configureHelp({showGlobalOptions:!0}),T(t,po),T(t,ho),T(t,fo),T(t,vn),T(t,bn),T(t,Sn),T(t,An),T(t,En),T(t,He),T(t,or),T(t,mt),T(t,ge),T(t,Fo),T(t,Wo),T(t,Bo),T(t,Ge),T(t,aa()),T(t,ir),T(t,Qo);try{await t.parseAsync(e)}catch(r){xa(r)}}function xa(e){let t=1,r=!0;if(e instanceof je.CommanderError&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){kt(e,!!process.env.VERBOSE);let o=e.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let n of o)kt(n,!0);else o instanceof Error&&kt(o,!0)}process.exit(t)}function kt(e,t=!1){if(t){console.error(e);return}e instanceof je.CommanderError?process.stderr.write(`${(0,ve.normalizeErrorString)(e)}
28
28
  `):process.stderr.write(`Error: ${(0,ve.normalizeErrorString)(e)}
29
- `)}async function za(){_r.default.config({quiet:!0}),await Ja(process.argv)}za().catch(e=>{console.error("Unhandled error:",(0,ve.normalizeErrorString)(e)),process.exit(1)});
29
+ `)}async function ja(){kr.default.config({quiet:!0}),await Ua(process.argv)}ja().catch(e=>{console.error("Unhandled error:",(0,ve.normalizeErrorString)(e)),process.exit(1)});
30
30
  //# sourceMappingURL=index.cjs.map