@medplum/cli 5.1.16 → 5.1.18

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,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- var ei=Object.create;var gt=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ri=Object.getOwnPropertyNames;var ni=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var oi=(e,t,r)=>t in e?gt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ii=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ri(t))!si.call(e,s)&&s!==r&&gt(e,s,{get:()=>t[s],enumerable:!(n=ti(t,s))||n.enumerable});return e};var Sr=(e,t,r)=>(r=e!=null?ei(ni(e)):{},ii(t||!e||!e.__esModule?gt(r,"default",{value:e,enumerable:!0}):r,e));var P=(e,t,r)=>oi(e,typeof t!="symbol"?t+"":t,r);var oe=w((kf,wn)=>{"use strict";var Ea="2.0.0",Sa=Number.MAX_SAFE_INTEGER||9007199254740991,Ra=16,Aa=250,Pa=["major","premajor","minor","preminor","patch","prepatch","prerelease"];wn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Ra,MAX_SAFE_BUILD_LENGTH:Aa,MAX_SAFE_INTEGER:Sa,RELEASE_TYPES:Pa,SEMVER_SPEC_VERSION:Ea,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Se=w((Lf,En)=>{"use strict";var ba=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};En.exports=ba});var ie=w((F,Sn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ut,MAX_SAFE_BUILD_LENGTH:Ia,MAX_LENGTH:va}=oe(),Ca=Se();F=Sn.exports={};var Ta=F.re=[],Oa=F.safeRe=[],p=F.src=[],xa=F.safeSrc=[],d=F.t={},$a=0,jt="[a-zA-Z0-9-]",Na=[["\\s",1],["\\d",va],[jt,Ia]],ka=e=>{for(let[t,r]of Na)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=ka(t),s=$a++;Ca(e,s,t),d[e]=s,p[s]=t,xa[s]=n,Ta[s]=new RegExp(t,r?"g":void 0),Oa[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${jt}*`);E("MAINVERSION",`(${p[d.NUMERICIDENTIFIER]})\\.(${p[d.NUMERICIDENTIFIER]})\\.(${p[d.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${p[d.NUMERICIDENTIFIERLOOSE]})\\.(${p[d.NUMERICIDENTIFIERLOOSE]})\\.(${p[d.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${p[d.NONNUMERICIDENTIFIER]}|${p[d.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${p[d.NONNUMERICIDENTIFIER]}|${p[d.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${p[d.PRERELEASEIDENTIFIER]}(?:\\.${p[d.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${p[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${p[d.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${jt}+`);E("BUILD",`(?:\\+(${p[d.BUILDIDENTIFIER]}(?:\\.${p[d.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${p[d.MAINVERSION]}${p[d.PRERELEASE]}?${p[d.BUILD]}?`);E("FULL",`^${p[d.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${p[d.MAINVERSIONLOOSE]}${p[d.PRERELEASELOOSE]}?${p[d.BUILD]}?`);E("LOOSE",`^${p[d.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${p[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${p[d.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${p[d.XRANGEIDENTIFIER]})(?:\\.(${p[d.XRANGEIDENTIFIER]})(?:\\.(${p[d.XRANGEIDENTIFIER]})(?:${p[d.PRERELEASE]})?${p[d.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${p[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[d.XRANGEIDENTIFIERLOOSE]})(?:${p[d.PRERELEASELOOSE]})?${p[d.BUILD]}?)?)?`);E("XRANGE",`^${p[d.GTLT]}\\s*${p[d.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${p[d.GTLT]}\\s*${p[d.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Ut}})(?:\\.(\\d{1,${Ut}}))?(?:\\.(\\d{1,${Ut}}))?`);E("COERCE",`${p[d.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",p[d.COERCEPLAIN]+`(?:${p[d.PRERELEASE]})?(?:${p[d.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",p[d.COERCE],!0);E("COERCERTLFULL",p[d.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${p[d.LONETILDE]}\\s+`,!0);F.tildeTrimReplace="$1~";E("TILDE",`^${p[d.LONETILDE]}${p[d.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${p[d.LONETILDE]}${p[d.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${p[d.LONECARET]}\\s+`,!0);F.caretTrimReplace="$1^";E("CARET",`^${p[d.LONECARET]}${p[d.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${p[d.LONECARET]}${p[d.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${p[d.GTLT]}\\s*(${p[d.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${p[d.GTLT]}\\s*(${p[d.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${p[d.GTLT]}\\s*(${p[d.LOOSEPLAIN]}|${p[d.XRANGEPLAIN]})`,!0);F.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${p[d.XRANGEPLAIN]})\\s+-\\s+(${p[d.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${p[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${p[d.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var We=w((Mf,Rn)=>{"use strict";var La=Object.freeze({loose:!0}),Ma=Object.freeze({}),Da=e=>e?typeof e!="object"?La:e:Ma;Rn.exports=Da});var Ft=w((Df,bn)=>{"use strict";var An=/^[0-9]+$/,Pn=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=An.test(e),n=An.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},_a=(e,t)=>Pn(t,e);bn.exports={compareIdentifiers:Pn,rcompareIdentifiers:_a}});var T=w((_f,vn)=>{"use strict";var Ke=Se(),{MAX_LENGTH:In,MAX_SAFE_INTEGER:qe}=oe(),{safeRe:He,t:Ge}=ie(),Ua=We(),{compareIdentifiers:Bt}=Ft(),ja=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(Bt(e[n],r[n])!==0)return!1;return!0},Wt=class e{constructor(t,r){if(r=Ua(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>In)throw new TypeError(`version is longer than ${In} characters`);Ke("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?He[Ge.LOOSE]:He[Ge.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>qe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qe||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&o<qe)return o}return s}):this.prerelease=[],this.build=n[5]?n[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(t){if(Ke("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(Ke("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Bt(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(Ke("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Bt(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?He[Ge.PRERELEASELOOSE]:He[Ge.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);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 s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];if(n===!1&&(o=[r]),ja(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};vn.exports=Wt});var X=w((Uf,Tn)=>{"use strict";var Cn=T(),Fa=(e,t,r=!1)=>{if(e instanceof Cn)return e;try{return new Cn(e,t)}catch(n){if(!r)return null;throw n}};Tn.exports=Fa});var xn=w((jf,On)=>{"use strict";var Ba=X(),Wa=(e,t)=>{let r=Ba(e,t);return r?r.version:null};On.exports=Wa});var Nn=w((Ff,$n)=>{"use strict";var Ka=X(),qa=(e,t)=>{let r=Ka(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};$n.exports=qa});var Mn=w((Bf,Ln)=>{"use strict";var kn=T(),Ha=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new kn(e instanceof kn?e.version:e,r).inc(t,n,s).version}catch{return null}};Ln.exports=Ha});var Un=w((Wf,_n)=>{"use strict";var Dn=X(),Ga=(e,t)=>{let r=Dn(e,null,!0),n=Dn(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,a=o?n:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let f=l?"pre":"";return r.major!==n.major?f+"major":r.minor!==n.minor?f+"minor":r.patch!==n.patch?f+"patch":"prerelease"};_n.exports=Ga});var Fn=w((Kf,jn)=>{"use strict";var Va=T(),Ja=(e,t)=>new Va(e,t).major;jn.exports=Ja});var Wn=w((qf,Bn)=>{"use strict";var Xa=T(),za=(e,t)=>new Xa(e,t).minor;Bn.exports=za});var qn=w((Hf,Kn)=>{"use strict";var Ya=T(),Qa=(e,t)=>new Ya(e,t).patch;Kn.exports=Qa});var Gn=w((Gf,Hn)=>{"use strict";var Za=X(),ec=(e,t)=>{let r=Za(e,t);return r&&r.prerelease.length?r.prerelease:null};Hn.exports=ec});var L=w((Vf,Jn)=>{"use strict";var Vn=T(),tc=(e,t,r)=>new Vn(e,r).compare(new Vn(t,r));Jn.exports=tc});var zn=w((Jf,Xn)=>{"use strict";var rc=L(),nc=(e,t,r)=>rc(t,e,r);Xn.exports=nc});var Qn=w((Xf,Yn)=>{"use strict";var sc=L(),oc=(e,t)=>sc(e,t,!0);Yn.exports=oc});var Ve=w((zf,es)=>{"use strict";var Zn=T(),ic=(e,t,r)=>{let n=new Zn(e,r),s=new Zn(t,r);return n.compare(s)||n.compareBuild(s)};es.exports=ic});var rs=w((Yf,ts)=>{"use strict";var ac=Ve(),cc=(e,t)=>e.sort((r,n)=>ac(r,n,t));ts.exports=cc});var ss=w((Qf,ns)=>{"use strict";var lc=Ve(),uc=(e,t)=>e.sort((r,n)=>lc(n,r,t));ns.exports=uc});var Re=w((Zf,os)=>{"use strict";var pc=L(),dc=(e,t,r)=>pc(e,t,r)>0;os.exports=dc});var Je=w((eh,is)=>{"use strict";var mc=L(),fc=(e,t,r)=>mc(e,t,r)<0;is.exports=fc});var Kt=w((th,as)=>{"use strict";var hc=L(),gc=(e,t,r)=>hc(e,t,r)===0;as.exports=gc});var qt=w((rh,cs)=>{"use strict";var yc=L(),wc=(e,t,r)=>yc(e,t,r)!==0;cs.exports=wc});var Xe=w((nh,ls)=>{"use strict";var Ec=L(),Sc=(e,t,r)=>Ec(e,t,r)>=0;ls.exports=Sc});var ze=w((sh,us)=>{"use strict";var Rc=L(),Ac=(e,t,r)=>Rc(e,t,r)<=0;us.exports=Ac});var Ht=w((oh,ps)=>{"use strict";var Pc=Kt(),bc=qt(),Ic=Re(),vc=Xe(),Cc=Je(),Tc=ze(),Oc=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return Pc(e,r,n);case"!=":return bc(e,r,n);case">":return Ic(e,r,n);case">=":return vc(e,r,n);case"<":return Cc(e,r,n);case"<=":return Tc(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};ps.exports=Oc});var ms=w((ih,ds)=>{"use strict";var xc=T(),$c=X(),{safeRe:Ye,t:Qe}=ie(),Nc=(e,t)=>{if(e instanceof xc)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?Ye[Qe.COERCEFULL]:Ye[Qe.COERCE]);else{let l=t.includePrerelease?Ye[Qe.COERCERTLFULL]:Ye[Qe.COERCERTL],u;for(;(u=l.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return $c(`${n}.${s}.${o}${i}${a}`,t)};ds.exports=Nc});var hs=w((ah,fs)=>{"use strict";var kc=X(),Lc=oe(),Mc=T(),Dc=(e,t,r)=>{if(!Lc.RELEASE_TYPES.includes(t))return null;let n=_c(e,r);return n&&Uc(n,t)},_c=(e,t)=>{let r=e instanceof Mc?e.version:e;return kc(r,t)},Uc=(e,t)=>{if(jc(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},jc=e=>e.startsWith("pre");fs.exports=Dc});var ys=w((ch,gs)=>{"use strict";var Gt=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};gs.exports=Gt});var M=w((lh,Rs)=>{"use strict";var Fc=/\s+/g,Vt=class e{constructor(t,r){if(r=Wc(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Jt)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(Fc," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Es(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&Yc(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(zc,"");let n=((this.options.includePrerelease&&Jc)|(this.options.loose&&Xc))+":"+t,s=ws.get(n);if(s)return s;let o=this.options.loose,i=o?x[O.HYPHENRANGELOOSE]:x[O.HYPHENRANGE];t=t.replace(i,al(this.options.includePrerelease)),b("hyphen replace",t),t=t.replace(x[O.COMPARATORTRIM],Hc),b("comparator trim",t),t=t.replace(x[O.TILDETRIM],Gc),b("tilde trim",t),t=t.replace(x[O.CARETTRIM],Vc),b("caret trim",t);let a=t.split(" ").map(m=>Qc(m,this.options)).join(" ").split(/\s+/).map(m=>il(m,this.options));o&&(a=a.filter(m=>(b("loose invalid filter",m,this.options),!!m.match(x[O.COMPARATORLOOSE])))),b("range list",a);let l=new Map,u=a.map(m=>new Jt(m,this.options));for(let m of u){if(Es(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return ws.set(n,f),f}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Ss(n,r)&&t.set.some(s=>Ss(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Kc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(cl(this.set[r],t,this.options))return!0;return!1}};Rs.exports=Vt;var Bc=ys(),ws=new Bc,Wc=We(),Jt=Ae(),b=Se(),Kc=T(),{safeRe:x,src:qc,t:O,comparatorTrimReplace:Hc,tildeTrimReplace:Gc,caretTrimReplace:Vc}=ie(),{FLAG_INCLUDE_PRERELEASE:Jc,FLAG_LOOSE:Xc}=oe(),zc=new RegExp(qc[O.BUILD],"g"),Es=e=>e.value==="<0.0.0-0",Yc=e=>e.value==="",Ss=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},Qc=(e,t)=>(e=e.replace(x[O.BUILD],""),b("comp",e,t),e=tl(e,t),b("caret",e),e=Zc(e,t),b("tildes",e),e=nl(e,t),b("xrange",e),e=ol(e,t),b("stars",e),e),$=e=>!e||e.toLowerCase()==="x"||e==="*",Zc=(e,t)=>e.trim().split(/\s+/).map(r=>el(r,t)).join(" "),el=(e,t)=>{let r=t.loose?x[O.TILDELOOSE]:x[O.TILDE];return e.replace(r,(n,s,o,i,a)=>{b("tilde",e,n,s,o,i,a);let l;return $(s)?l="":$(o)?l=`>=${s}.0.0 <${+s+1}.0.0-0`:$(i)?l=`>=${s}.${o}.0 <${s}.${+o+1}.0-0`:a?(b("replaceTilde pr",a),l=`>=${s}.${o}.${i}-${a} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${i} <${s}.${+o+1}.0-0`,b("tilde return",l),l})},tl=(e,t)=>e.trim().split(/\s+/).map(r=>rl(r,t)).join(" "),rl=(e,t)=>{b("caret",e,t);let r=t.loose?x[O.CARETLOOSE]:x[O.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{b("caret",e,s,o,i,a,l);let u;return $(o)?u="":$(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:$(a)?o==="0"?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:l?(b("replaceCaret pr",l),o==="0"?i==="0"?u=`>=${o}.${i}.${a}-${l} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a}-${l} <${+o+1}.0.0-0`):(b("no pr"),o==="0"?i==="0"?u=`>=${o}.${i}.${a}${n} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a}${n} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a} <${+o+1}.0.0-0`),b("caret return",u),u})},nl=(e,t)=>(b("replaceXRanges",e,t),e.split(/\s+/).map(r=>sl(r,t)).join(" ")),sl=(e,t)=>{e=e.trim();let r=t.loose?x[O.XRANGELOOSE]:x[O.XRANGE];return e.replace(r,(n,s,o,i,a,l)=>{b("xRange",e,n,s,o,i,a,l);let u=$(o),f=u||$(i),m=f||$(a),S=m;return s==="="&&S&&(s=""),l=t.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&S?(f&&(i=0),a=0,s===">"?(s=">=",f?(o=+o+1,i=0,a=0):(i=+i+1,a=0)):s==="<="&&(s="<",f?o=+o+1:i=+i+1),s==="<"&&(l="-0"),n=`${s+o}.${i}.${a}${l}`):f?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${i}.0${l} <${o}.${+i+1}.0-0`),b("xRange return",n),n})},ol=(e,t)=>(b("replaceStars",e,t),e.trim().replace(x[O.STAR],"")),il=(e,t)=>(b("replaceGTE0",e,t),e.trim().replace(x[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),al=e=>(t,r,n,s,o,i,a,l,u,f,m,S)=>($(n)?r="":$(s)?r=`>=${n}.0.0${e?"-0":""}`:$(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,$(u)?l="":$(f)?l=`<${+u+1}.0.0-0`:$(m)?l=`<${u}.${+f+1}.0-0`:S?l=`<=${u}.${f}.${m}-${S}`:e?l=`<${u}.${f}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),cl=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(b(e[n].semver),e[n].semver!==Jt.ANY&&e[n].semver.prerelease.length>0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var Ae=w((uh,Cs)=>{"use strict";var Pe=Symbol("SemVer ANY"),Yt=class e{static get ANY(){return Pe}constructor(t,r){if(r=As(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),zt("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Pe?this.value="":this.value=this.operator+this.semver.version,zt("comp",this)}parse(t){let r=this.options.loose?Ps[bs.COMPARATORLOOSE]:Ps[bs.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Is(n[2],this.options.loose):this.semver=Pe}toString(){return this.value}test(t){if(zt("Comparator.test",t,this.options.loose),this.semver===Pe||t===Pe)return!0;if(typeof t=="string")try{t=new Is(t,this.options)}catch{return!1}return Xt(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new vs(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new vs(this.value,r).test(t.semver):(r=As(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Xt(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Xt(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Cs.exports=Yt;var As=We(),{safeRe:Ps,t:bs}=ie(),Xt=Ht(),zt=Se(),Is=T(),vs=M()});var be=w((ph,Ts)=>{"use strict";var ll=M(),ul=(e,t,r)=>{try{t=new ll(t,r)}catch{return!1}return t.test(e)};Ts.exports=ul});var xs=w((dh,Os)=>{"use strict";var pl=M(),dl=(e,t)=>new pl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));Os.exports=dl});var Ns=w((mh,$s)=>{"use strict";var ml=T(),fl=M(),hl=(e,t,r)=>{let n=null,s=null,o=null;try{o=new fl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new ml(n,r))}),n};$s.exports=hl});var Ls=w((fh,ks)=>{"use strict";var gl=T(),yl=M(),wl=(e,t,r)=>{let n=null,s=null,o=null;try{o=new yl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new gl(n,r))}),n};ks.exports=wl});var _s=w((hh,Ds)=>{"use strict";var Qt=T(),El=M(),Ms=Re(),Sl=(e,t)=>{e=new El(e,t);let r=new Qt("0.0.0");if(e.test(r)||(r=new Qt("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let s=e.set[n],o=null;s.forEach(i=>{let a=new Qt(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||Ms(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||Ms(r,o))&&(r=o)}return r&&e.test(r)?r:null};Ds.exports=Sl});var js=w((gh,Us)=>{"use strict";var Rl=M(),Al=(e,t)=>{try{return new Rl(e,t).range||"*"}catch{return null}};Us.exports=Al});var Ze=w((yh,Ks)=>{"use strict";var Pl=T(),Ws=Ae(),{ANY:bl}=Ws,Il=M(),vl=be(),Fs=Re(),Bs=Je(),Cl=ze(),Tl=Xe(),Ol=(e,t,r,n)=>{e=new Pl(e,n),t=new Il(t,n);let s,o,i,a,l;switch(r){case">":s=Fs,o=Cl,i=Bs,a=">",l=">=";break;case"<":s=Bs,o=Tl,i=Fs,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(vl(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let f=t.set[u],m=null,S=null;if(f.forEach(h=>{h.semver===bl&&(h=new Ws(">=0.0.0")),m=m||h,S=S||h,s(h.semver,m.semver,n)?m=h:i(h.semver,S.semver,n)&&(S=h)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&o(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};Ks.exports=Ol});var Hs=w((wh,qs)=>{"use strict";var xl=Ze(),$l=(e,t,r)=>xl(e,t,">",r);qs.exports=$l});var Vs=w((Eh,Gs)=>{"use strict";var Nl=Ze(),kl=(e,t,r)=>Nl(e,t,"<",r);Gs.exports=kl});var zs=w((Sh,Xs)=>{"use strict";var Js=M(),Ll=(e,t,r)=>(e=new Js(e,r),t=new Js(t,r),e.intersects(t,r));Xs.exports=Ll});var Qs=w((Rh,Ys)=>{"use strict";var Ml=be(),Dl=L();Ys.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((f,m)=>Dl(f,m,r));for(let f of i)Ml(f,t,r)?(o=f,s||(s=f)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let a=[];for(let[f,m]of n)f===m?a.push(f):!m&&f===i[0]?a.push("*"):m?f===i[0]?a.push(`<=${m}`):a.push(`${f} - ${m}`):a.push(`>=${f}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var so=w((Ah,no)=>{"use strict";var Zs=M(),tr=Ae(),{ANY:Zt}=tr,er=be(),rr=L(),_l=(e,t,r={})=>{if(e===t)return!0;e=new Zs(e,r),t=new Zs(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=jl(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},Ul=[new tr(">=0.0.0-0")],eo=[new tr(">=0.0.0")],jl=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Zt){if(t.length===1&&t[0].semver===Zt)return!0;r.includePrerelease?e=Ul:e=eo}if(t.length===1&&t[0].semver===Zt){if(r.includePrerelease)return!0;t=eo}let n=new Set,s,o;for(let h of e)h.operator===">"||h.operator===">="?s=to(s,h,r):h.operator==="<"||h.operator==="<="?o=ro(o,h,r):n.add(h.semver);if(n.size>1)return null;let i;if(s&&o){if(i=rr(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let h of n){if(s&&!er(h,String(s),r)||o&&!er(h,String(o),r))return null;for(let re of t)if(!er(h,String(re),r))return!1;return!0}let a,l,u,f,m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,S=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;m&&m.prerelease.length===1&&o.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let h of t){if(f=f||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",s){if(S&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===S.major&&h.semver.minor===S.minor&&h.semver.patch===S.patch&&(S=!1),h.operator===">"||h.operator===">="){if(a=to(s,h,r),a===h&&a!==s)return!1}else if(s.operator===">="&&!h.test(s.semver))return!1}if(o){if(m&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===m.major&&h.semver.minor===m.minor&&h.semver.patch===m.patch&&(m=!1),h.operator==="<"||h.operator==="<="){if(l=ro(o,h,r),l===h&&l!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||s)&&i!==0)return!1}return!(s&&u&&!o&&i!==0||o&&f&&!s&&i!==0||S||m)},to=(e,t,r)=>{if(!e)return t;let n=rr(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},ro=(e,t,r)=>{if(!e)return t;let n=rr(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};no.exports=_l});var sr=w((Ph,ao)=>{"use strict";var nr=ie(),oo=oe(),Fl=T(),io=Ft(),Bl=X(),Wl=xn(),Kl=Nn(),ql=Mn(),Hl=Un(),Gl=Fn(),Vl=Wn(),Jl=qn(),Xl=Gn(),zl=L(),Yl=zn(),Ql=Qn(),Zl=Ve(),eu=rs(),tu=ss(),ru=Re(),nu=Je(),su=Kt(),ou=qt(),iu=Xe(),au=ze(),cu=Ht(),lu=ms(),uu=hs(),pu=Ae(),du=M(),mu=be(),fu=xs(),hu=Ns(),gu=Ls(),yu=_s(),wu=js(),Eu=Ze(),Su=Hs(),Ru=Vs(),Au=zs(),Pu=Qs(),bu=so();ao.exports={parse:Bl,valid:Wl,clean:Kl,inc:ql,diff:Hl,major:Gl,minor:Vl,patch:Jl,prerelease:Xl,compare:zl,rcompare:Yl,compareLoose:Ql,compareBuild:Zl,sort:eu,rsort:tu,gt:ru,lt:nu,eq:su,neq:ou,gte:iu,lte:au,cmp:cu,coerce:lu,truncate:uu,Comparator:pu,Range:du,satisfies:mu,toComparators:fu,maxSatisfying:hu,minSatisfying:gu,minVersion:yu,validRange:wu,outside:Eu,gtr:Su,ltr:Ru,intersects:Au,simplifyRange:Pu,subset:bu,SemVer:Fl,re:nr.re,src:nr.src,tokens:nr.t,SEMVER_SPEC_VERSION:oo.SEMVER_SPEC_VERSION,RELEASE_TYPES:oo.RELEASE_TYPES,compareIdentifiers:io.compareIdentifiers,rcompareIdentifiers:io.rcompareIdentifiers}});import{MEDPLUM_VERSION as Rd,normalizeErrorString as Er}from"@medplum/core";import{CommanderError as Qo,Option as Ad}from"commander";import Pd from"dotenv";import{ContentType as on,EMPTY as Ji,isOk as Xi,isUUID as zi,normalizeErrorString as Yi}from"@medplum/core";import{Option as je}from"commander";import{MedplumClient as di}from"@medplum/core";import{ClientStorage as ai}from"@medplum/core";import{existsSync as Rr,mkdirSync as ci,readFileSync as li,writeFileSync as ui}from"node:fs";import{homedir as pi}from"node:os";import{resolve as Ar}from"node:path";var _=class extends ai{constructor(r){super();P(this,"dirName");P(this,"fileName");this.dirName=Ar(pi(),".medplum"),this.fileName=Ar(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let s=this.readFile()??{};n?s[r]=n:delete s[r],this.writeFile(s)}getObject(r){let n=this.getString(r);return n?JSON.parse(n):void 0}setObject(r,n){this.setString(r,n?JSON.stringify(n):void 0)}readFile(){if(Rr(this.fileName))return JSON.parse(li(this.fileName,"utf8"))}writeFile(r){Rr(this.dirName)||ci(this.dirName),ui(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function A(e,t=!0){let r=e.profile??"default",n=new _(r),s=n.getObject("options");if(r!=="default"&&!s)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:o,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:f,clientSecret:m}=mi(e,n),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await fi(e.baseUrl,S);let h=new di({fetch:S,baseUrl:o,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:hi,verbose:e.verbose});return t&&(a?h.setAccessToken(a):f&&m&&(h.setBasicAuth(f,m),s?.authType!=="basic"&&await h.startClientLogin(f,m))),h}function mi(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",s=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,o=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,a=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:n,fhirUrlPath:s,accessToken:o,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function fi(e,t){try{let r=new URL("healthcheck",e).toString(),n=await t(r);if(!n.ok)throw new Error(`Healthcheck returned status ${n.status}`);if((await n.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${n}`)}}function hi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{ContentType as Tt,encodeBase64 as Hr,OAuthSigningAlgorithm as Gr}from"@medplum/core";import{Command as Di}from"commander";import{Buffer as gi}from"node:buffer";var Q=new TextEncoder,yt=new TextDecoder,_d=2**32;function Pr(...e){let t=e.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}var xe=e=>gi.from(e).toString("base64url");var Z=class extends Error{constructor(r,n){super(r,n);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};P(Z,"code","ERR_JOSE_GENERIC");var k=class extends Z{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}};P(k,"code","ERR_JOSE_NOT_SUPPORTED");var K=class extends Z{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}};P(K,"code","ERR_JWS_INVALID");var fe=class extends Z{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}};P(fe,"code","ERR_JWT_INVALID");var br,Ir,wt=class extends(Ir=Z,br=Symbol.asyncIterator,Ir){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);P(this,br);P(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};P(wt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");import*as vr from"node:util";var $e=e=>vr.types.isKeyObject(e);import*as Cr from"node:crypto";import*as Tr from"node:util";var wi=Cr.webcrypto,Or=wi,ne=e=>Tr.types.isCryptoKey(e);function U(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function he(e,t){return e.name===t}function Et(e){return parseInt(e.name.slice(4),10)}function Ei(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Si(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function xr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!he(e.algorithm,"HMAC"))throw U("HMAC");let n=parseInt(t.slice(2),10);if(Et(e.algorithm.hash)!==n)throw U(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!he(e.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Et(e.algorithm.hash)!==n)throw U(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!he(e.algorithm,"RSA-PSS"))throw U("RSA-PSS");let n=parseInt(t.slice(2),10);if(Et(e.algorithm.hash)!==n)throw U(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw U("Ed25519 or Ed448");break}case"Ed25519":{if(!he(e.algorithm,"Ed25519"))throw U("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!he(e.algorithm,"ECDSA"))throw U("ECDSA");let n=Ei(t);if(e.algorithm.namedCurve!==n)throw U(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Si(e,r)}function $r(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}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 ge=(e,...t)=>$r("Key must be ",e,...t);function St(e,t,...r){return $r(`Key for the ${e} algorithm must be `,t,...r)}var Rt=e=>$e(e)||ne(e),q=["KeyObject"];(globalThis.CryptoKey||Or?.CryptoKey)&&q.push("CryptoKey");var Ri=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0},Nr=Ri;function Ai(e){return typeof e=="object"&&e!==null}function ye(e){if(!Ai(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{KeyObject as Pi}from"node:crypto";function G(e){return ye(e)&&typeof e.kty=="string"}function kr(e){return e.kty!=="oct"&&typeof e.d=="string"}function Lr(e){return e.kty!=="oct"&&typeof e.d>"u"}function Mr(e){return G(e)&&e.kty==="oct"&&typeof e.k=="string"}var bi=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new k("Unsupported key curve for this operation")}},Ii=(e,t)=>{let r;if(ne(e))r=Pi.from(e);else if($e(e))r=e;else{if(G(e))return e.crv;throw new TypeError(ge(e,...q))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let n=r.asymmetricKeyDetails.namedCurve;return t?n:bi(n)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},_r=Ii;import{KeyObject as vi}from"node:crypto";var At=(e,t)=>{let r;try{e instanceof vi?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var se=e=>e?.[Symbol.toStringTag],Pt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Ci=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&G(t)){if(Mr(t)&&Pt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Rt(t))throw new TypeError(St(e,t,...q,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${se(t)} instances for symmetric algorithms must be of type "secret"`)}},Ti=(e,t,r,n)=>{if(n&&G(t))switch(r){case"sign":if(kr(t)&&Pt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Lr(t)&&Pt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Rt(t))throw new TypeError(St(e,t,...q,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${se(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${se(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${se(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${se(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${se(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ur(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Ci(t,r,n,e):Ti(t,r,n,e)}var um=Ur.bind(void 0,!1),jr=Ur.bind(void 0,!0);function Oi(e,t,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let i of n.crit){if(!o.has(i))throw new k(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var Fr=Oi;function bt(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as Br,KeyObject as xi}from"node:crypto";var $i=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function It(e,t){let r,n,s;if(t instanceof xi)r=t.asymmetricKeyType,n=t.asymmetricKeyDetails;else switch(s=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let o;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");At(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=n,u=parseInt(e.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||a!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");At(t,e),o={padding:Br.RSA_PKCS1_PSS_PADDING,saltLength:Br.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let i=_r(t),a=$i.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);o={dsaEncoding:"ieee-p1363"};break}default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...o}:o?{...o,key:t}:t}import*as Ne from"node:crypto";import{promisify as Ni}from"node:util";function vt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Wr,createSecretKey as Kr}from"node:crypto";function Ct(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ge(t,...q));return Kr(t)}if(t instanceof Wr)return t;if(ne(t))return xr(t,e,r),Wr.from(t);if(G(t))return e.startsWith("HS")?Kr(Buffer.from(t.k,"base64url")):t;throw new TypeError(ge(t,...q,"Uint8Array","JSON Web Key"))}var ki=Ni(Ne.sign),Li=async(e,t,r)=>{let n=Ct(e,t,"sign");if(e.startsWith("HS")){let s=Ne.createHmac(vt(e),n);return s.update(r),s.digest()}return ki(bt(e),r,It(e,n))},qr=Li;var V=e=>Math.floor(e.getTime()/1e3);var Mi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ke=e=>{let t=Mi.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-s:s};var Le=class{constructor(t){P(this,"_payload");P(this,"_protectedHeader");P(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new K("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Nr(this._protectedHeader,this._unprotectedHeader))throw new K("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},s=Fr(K,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new K('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new K('JWS "alg" (Algorithm) Header Parameter missing or invalid');jr(i,t,"sign");let a=this._payload;o&&(a=Q.encode(xe(a)));let l;this._protectedHeader?l=Q.encode(xe(JSON.stringify(this._protectedHeader))):l=Q.encode("");let u=Pr(l,Q.encode("."),a),f=await qr(i,t,u),m={signature:xe(f),payload:""};return o&&(m.payload=yt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=yt.decode(l)),m}};var Me=class{constructor(t){P(this,"_flattened");this._flattened=new Le(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function ee(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var De=class{constructor(t={}){P(this,"_payload");if(!ye(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:ee("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ee("setNotBefore",V(t))}:this._payload={...this._payload,nbf:V(new Date)+ke(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ee("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ee("setExpirationTime",V(t))}:this._payload={...this._payload,exp:V(new Date)+ke(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:V(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ee("setIssuedAt",V(t))}:typeof t=="string"?this._payload={...this._payload,iat:ee("setIssuedAt",V(new Date)+ke(t))}:this._payload={...this._payload,iat:ee("setIssuedAt",t)},this}};var we=class extends De{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,n){let s=new Me(Q.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new fe("JWTs MUST NOT use unencoded payload");return s.sign(r,n)}};import{createHmac as _i,createPrivateKey as Ui,randomBytes as ji}from"node:crypto";import{existsSync as Fi,readFileSync as Vr,writeFileSync as Jr}from"node:fs";import{basename as Xr,extname as Bi,resolve as Ot}from"node:path";import{isPromise as Wi}from"node:util/types";import{extract as Ki}from"tar";function H(e){console.log(JSON.stringify(e,null,2))}async function xt(e,t,r){let n=t.source,s=_e(n);if(!s)return;console.log("Saving source code...");let o=await e.createAttachment({data:s,filename:Xr(n),contentType:Gi(n)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:o});console.log("Success! New bot version: "+i.meta?.versionId)}async function $t(e,t,r){let n=t.dist??t.source,s=_e(n);if(!s)return;console.log("Deploying bot...");let o=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:Xr(n)});console.log("Deploy result: "+o.issue?.[0]?.details?.text)}async function Nt(e,t,r,n,s,o,i){let a={name:t,description:"",runtimeVersion:o},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),f={name:t,id:l.id,source:n,dist:s};await xt(e,f,u),await $t(e,f,u),console.log(`Success! Bot created: ${u.id}`),i&&qi(f)}function zr(e){let t=new RegExp("^"+Hi(e).replaceAll(String.raw`\*`,".*")+"$"),r=j()?.bots?.filter(n=>t.test(n.name));return r||[]}function D(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 v(e,t){Jr(Ot(e),JSON.stringify(t,void 0,2),"utf-8")}function j(e,t){let r=D(e,t),n=_e(r);if(n)return JSON.parse(n)}function Yr(e){let t=_e(D(e,{server:!0}));if(t)return JSON.parse(t)}function _e(e){let t=Ot(e);return Fi(t)?Vr(t,"utf8"):""}function qi(e){let t=j()??{};t.bots||(t.bots=[]),t.bots.push(e),Jr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Hi(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Qr(e){let n=0,s=0;return Ki({cwd:e,filter:(o,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(s+=i.size,s>10485760)throw new Error("Tar extractor reached max size");return!0}})}function kt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Gi(e){let t=Bi(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Tt.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Tt.TYPESCRIPT:Tt.TEXT}function Ue(e,t){let r=new _(e),n={name:e,...t};return r.setObject("options",n),n}function Zr(e){return new _(e).getObject("options")}async function en(e,t){let r={typ:"JWT",alg:Gr.HS256},n=Math.floor(Date.now()/1e3),s={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},o=Hr(JSON.stringify(r)),i=Hr(JSON.stringify(s)),a=`${o}.${i}`,l=_i("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function tn(e,t){let r=Ui(Vr(Ot(t.privateKeyPath))),n=await new we({}).setProtectedHeader({typ:"JWT",alg:Gr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(ji(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends Di{action(t){let r=Vi(this,t);return super._actionHandler=r,this}resetOptionDefaults(){this._optionValues={};for(let t of this.options)t.defaultValue!==void 0&&(this._optionValues[t.attributeName()]=t.defaultValue)}};function Vi(e,t){return async r=>{let n=e.registeredArguments.length,s=r.slice(0,n);s[n]=e.optsWithGlobals();try{let o=t(...s);Wi(o)&&await o}finally{e.resetOptionDefaults()}}}var an=new g("status").aliases(["info","list","ls"]),cn=new g("ping"),ln=new g("push"),un=new g("reload-config"),pn=new g("upgrade"),dn=new g("stats"),J=new g("agent");y(J,an);y(J,cn);y(J,ln);y(J,un);y(J,pn);y(J,dn);an.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 je("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Fe({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=fn(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:n.version,connectionStatus:n.status,statusLastUpdated:n.lastUpdated??"N/A"}}})});cn.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 n=await A(r),s=await mn(n,t,r),o=Number.parseInt(r.count,10);if(Number.isNaN(o))throw new Error("--count <count> must be an integer if specified");try{let i=await n.pushToAgent(s,e,`PING ${o}`,on.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});ln.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",on.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,n)=>{let s=await A(n),o=await mn(s,r,n),i;try{i=await s.pushToAgent(o,{reference:`Device/${e}`},t,n.contentType,n.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});un.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 je("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Fe({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});pn.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 je("--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 Fe({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});dn.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 je("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Fe({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=fn(r.result,{required:["stats"]}),s;try{s=JSON.parse(n)}catch(o){console.error(`Failed to parse stats for agent ${r.agent.id}: ${Yi(o)}`)}return{id:r.agent.id,name:r.agent.name,stats:s}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),Qi(r[n])}})});var rn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function nn(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function sn(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 Qi(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 i of rn)r[i]=nn(e.stats[i]);let n=new Set([...rn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=nn(a));console.table(r);let s=sn(e.stats.channelStats);s.length&&(console.info("Channel Stats:"),console.table(s));let o=sn(e.stats.clientStats);o.length&&(console.info("Client Stats:"),console.table(o))}async function Fe({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:s,renderSuccessfulRows:o}){let i=ra(t,r),a=await A(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[C,W]of Object.entries(n))u.append(C,W.toString());let f;try{let C=a.fhirUrl("Agent",e);C.search=u.toString(),f=await a.get(C,{cache:"reload"})}catch(C){throw new Error(`Operation '${e}' failed`,{cause:C})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let m=[],S=[];switch(f.resourceType){case"Bundle":{let C=Zi(f);for(let W of C)W.result.resourceType==="Parameters"||Xi(W.result)?m.push(W):S.push(W);break}case"Parameters":case"OperationOutcome":{let C=await a.searchOne("Agent",u,{cache:"reload"});if(!C)throw new Error("Agent not found");f.resourceType==="Parameters"?m.push({agent:C,result:f}):S.push({agent:C,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let h=[];for(let C of m){let W=s(C);h.push(W)}let re=[];for(let C of S){let ht=C.result.issue?.[0],Zo={id:C.agent.id,name:C.agent.name,severity:ht.severity,code:ht.code,details:ht.details?.text??"No details to show"};re.push(Zo)}console.info(`
2
+ var ei=Object.create;var gt=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ri=Object.getOwnPropertyNames;var ni=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var oi=(e,t,r)=>t in e?gt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var ii=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ri(t))!si.call(e,s)&&s!==r&&gt(e,s,{get:()=>t[s],enumerable:!(n=ti(t,s))||n.enumerable});return e};var Sr=(e,t,r)=>(r=e!=null?ei(ni(e)):{},ii(t||!e||!e.__esModule?gt(r,"default",{value:e,enumerable:!0}):r,e));var P=(e,t,r)=>oi(e,typeof t!="symbol"?t+"":t,r);var oe=w((Lf,wn)=>{"use strict";var Ea="2.0.0",Sa=Number.MAX_SAFE_INTEGER||9007199254740991,Ra=16,Aa=250,Pa=["major","premajor","minor","preminor","patch","prepatch","prerelease"];wn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Ra,MAX_SAFE_BUILD_LENGTH:Aa,MAX_SAFE_INTEGER:Sa,RELEASE_TYPES:Pa,SEMVER_SPEC_VERSION:Ea,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Se=w((Mf,En)=>{"use strict";var ba=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};En.exports=ba});var ie=w((F,Sn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ut,MAX_SAFE_BUILD_LENGTH:Ia,MAX_LENGTH:va}=oe(),Ca=Se();F=Sn.exports={};var Ta=F.re=[],Oa=F.safeRe=[],p=F.src=[],xa=F.safeSrc=[],d=F.t={},$a=0,jt="[a-zA-Z0-9-]",Na=[["\\s",1],["\\d",va],[jt,Ia]],ka=e=>{for(let[t,r]of Na)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=ka(t),s=$a++;Ca(e,s,t),d[e]=s,p[s]=t,xa[s]=n,Ta[s]=new RegExp(t,r?"g":void 0),Oa[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${jt}*`);E("MAINVERSION",`(${p[d.NUMERICIDENTIFIER]})\\.(${p[d.NUMERICIDENTIFIER]})\\.(${p[d.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${p[d.NUMERICIDENTIFIERLOOSE]})\\.(${p[d.NUMERICIDENTIFIERLOOSE]})\\.(${p[d.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${p[d.NONNUMERICIDENTIFIER]}|${p[d.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${p[d.NONNUMERICIDENTIFIER]}|${p[d.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${p[d.PRERELEASEIDENTIFIER]}(?:\\.${p[d.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${p[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${p[d.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${jt}+`);E("BUILD",`(?:\\+(${p[d.BUILDIDENTIFIER]}(?:\\.${p[d.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${p[d.MAINVERSION]}${p[d.PRERELEASE]}?${p[d.BUILD]}?`);E("FULL",`^${p[d.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${p[d.MAINVERSIONLOOSE]}${p[d.PRERELEASELOOSE]}?${p[d.BUILD]}?`);E("LOOSE",`^${p[d.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${p[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${p[d.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${p[d.XRANGEIDENTIFIER]})(?:\\.(${p[d.XRANGEIDENTIFIER]})(?:\\.(${p[d.XRANGEIDENTIFIER]})(?:${p[d.PRERELEASE]})?${p[d.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${p[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[d.XRANGEIDENTIFIERLOOSE]})(?:${p[d.PRERELEASELOOSE]})?${p[d.BUILD]}?)?)?`);E("XRANGE",`^${p[d.GTLT]}\\s*${p[d.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${p[d.GTLT]}\\s*${p[d.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Ut}})(?:\\.(\\d{1,${Ut}}))?(?:\\.(\\d{1,${Ut}}))?`);E("COERCE",`${p[d.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",p[d.COERCEPLAIN]+`(?:${p[d.PRERELEASE]})?(?:${p[d.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",p[d.COERCE],!0);E("COERCERTLFULL",p[d.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${p[d.LONETILDE]}\\s+`,!0);F.tildeTrimReplace="$1~";E("TILDE",`^${p[d.LONETILDE]}${p[d.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${p[d.LONETILDE]}${p[d.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${p[d.LONECARET]}\\s+`,!0);F.caretTrimReplace="$1^";E("CARET",`^${p[d.LONECARET]}${p[d.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${p[d.LONECARET]}${p[d.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${p[d.GTLT]}\\s*(${p[d.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${p[d.GTLT]}\\s*(${p[d.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${p[d.GTLT]}\\s*(${p[d.LOOSEPLAIN]}|${p[d.XRANGEPLAIN]})`,!0);F.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${p[d.XRANGEPLAIN]})\\s+-\\s+(${p[d.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${p[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${p[d.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var We=w((Df,Rn)=>{"use strict";var La=Object.freeze({loose:!0}),Ma=Object.freeze({}),Da=e=>e?typeof e!="object"?La:e:Ma;Rn.exports=Da});var Ft=w((_f,bn)=>{"use strict";var An=/^[0-9]+$/,Pn=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=An.test(e),n=An.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},_a=(e,t)=>Pn(t,e);bn.exports={compareIdentifiers:Pn,rcompareIdentifiers:_a}});var O=w((Uf,vn)=>{"use strict";var Ke=Se(),{MAX_LENGTH:In,MAX_SAFE_INTEGER:qe}=oe(),{safeRe:He,t:Ge}=ie(),Ua=We(),{compareIdentifiers:Bt}=Ft(),ja=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(Bt(e[n],r[n])!==0)return!1;return!0},Wt=class e{constructor(t,r){if(r=Ua(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>In)throw new TypeError(`version is longer than ${In} characters`);Ke("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?He[Ge.LOOSE]:He[Ge.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>qe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qe||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&o<qe)return o}return s}):this.prerelease=[],this.build=n[5]?n[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(t){if(Ke("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(Ke("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Bt(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(Ke("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Bt(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?He[Ge.PRERELEASELOOSE]:He[Ge.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);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 s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];if(n===!1&&(o=[r]),ja(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};vn.exports=Wt});var X=w((jf,Tn)=>{"use strict";var Cn=O(),Fa=(e,t,r=!1)=>{if(e instanceof Cn)return e;try{return new Cn(e,t)}catch(n){if(!r)return null;throw n}};Tn.exports=Fa});var xn=w((Ff,On)=>{"use strict";var Ba=X(),Wa=(e,t)=>{let r=Ba(e,t);return r?r.version:null};On.exports=Wa});var Nn=w((Bf,$n)=>{"use strict";var Ka=X(),qa=(e,t)=>{let r=Ka(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};$n.exports=qa});var Mn=w((Wf,Ln)=>{"use strict";var kn=O(),Ha=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new kn(e instanceof kn?e.version:e,r).inc(t,n,s).version}catch{return null}};Ln.exports=Ha});var Un=w((Kf,_n)=>{"use strict";var Dn=X(),Ga=(e,t)=>{let r=Dn(e,null,!0),n=Dn(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,a=o?n:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let f=l?"pre":"";return r.major!==n.major?f+"major":r.minor!==n.minor?f+"minor":r.patch!==n.patch?f+"patch":"prerelease"};_n.exports=Ga});var Fn=w((qf,jn)=>{"use strict";var Va=O(),Ja=(e,t)=>new Va(e,t).major;jn.exports=Ja});var Wn=w((Hf,Bn)=>{"use strict";var Xa=O(),za=(e,t)=>new Xa(e,t).minor;Bn.exports=za});var qn=w((Gf,Kn)=>{"use strict";var Ya=O(),Qa=(e,t)=>new Ya(e,t).patch;Kn.exports=Qa});var Gn=w((Vf,Hn)=>{"use strict";var Za=X(),ec=(e,t)=>{let r=Za(e,t);return r&&r.prerelease.length?r.prerelease:null};Hn.exports=ec});var L=w((Jf,Jn)=>{"use strict";var Vn=O(),tc=(e,t,r)=>new Vn(e,r).compare(new Vn(t,r));Jn.exports=tc});var zn=w((Xf,Xn)=>{"use strict";var rc=L(),nc=(e,t,r)=>rc(t,e,r);Xn.exports=nc});var Qn=w((zf,Yn)=>{"use strict";var sc=L(),oc=(e,t)=>sc(e,t,!0);Yn.exports=oc});var Ve=w((Yf,es)=>{"use strict";var Zn=O(),ic=(e,t,r)=>{let n=new Zn(e,r),s=new Zn(t,r);return n.compare(s)||n.compareBuild(s)};es.exports=ic});var rs=w((Qf,ts)=>{"use strict";var ac=Ve(),cc=(e,t)=>e.sort((r,n)=>ac(r,n,t));ts.exports=cc});var ss=w((Zf,ns)=>{"use strict";var lc=Ve(),uc=(e,t)=>e.sort((r,n)=>lc(n,r,t));ns.exports=uc});var Re=w((eh,os)=>{"use strict";var pc=L(),dc=(e,t,r)=>pc(e,t,r)>0;os.exports=dc});var Je=w((th,is)=>{"use strict";var mc=L(),fc=(e,t,r)=>mc(e,t,r)<0;is.exports=fc});var Kt=w((rh,as)=>{"use strict";var hc=L(),gc=(e,t,r)=>hc(e,t,r)===0;as.exports=gc});var qt=w((nh,cs)=>{"use strict";var yc=L(),wc=(e,t,r)=>yc(e,t,r)!==0;cs.exports=wc});var Xe=w((sh,ls)=>{"use strict";var Ec=L(),Sc=(e,t,r)=>Ec(e,t,r)>=0;ls.exports=Sc});var ze=w((oh,us)=>{"use strict";var Rc=L(),Ac=(e,t,r)=>Rc(e,t,r)<=0;us.exports=Ac});var Ht=w((ih,ps)=>{"use strict";var Pc=Kt(),bc=qt(),Ic=Re(),vc=Xe(),Cc=Je(),Tc=ze(),Oc=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return Pc(e,r,n);case"!=":return bc(e,r,n);case">":return Ic(e,r,n);case">=":return vc(e,r,n);case"<":return Cc(e,r,n);case"<=":return Tc(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};ps.exports=Oc});var ms=w((ah,ds)=>{"use strict";var xc=O(),$c=X(),{safeRe:Ye,t:Qe}=ie(),Nc=(e,t)=>{if(e instanceof xc)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?Ye[Qe.COERCEFULL]:Ye[Qe.COERCE]);else{let l=t.includePrerelease?Ye[Qe.COERCERTLFULL]:Ye[Qe.COERCERTL],u;for(;(u=l.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return $c(`${n}.${s}.${o}${i}${a}`,t)};ds.exports=Nc});var hs=w((ch,fs)=>{"use strict";var kc=X(),Lc=oe(),Mc=O(),Dc=(e,t,r)=>{if(!Lc.RELEASE_TYPES.includes(t))return null;let n=_c(e,r);return n&&Uc(n,t)},_c=(e,t)=>{let r=e instanceof Mc?e.version:e;return kc(r,t)},Uc=(e,t)=>{if(jc(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},jc=e=>e.startsWith("pre");fs.exports=Dc});var ys=w((lh,gs)=>{"use strict";var Gt=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};gs.exports=Gt});var M=w((uh,Rs)=>{"use strict";var Fc=/\s+/g,Vt=class e{constructor(t,r){if(r=Wc(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Jt)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(Fc," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Es(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&Yc(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(zc,"");let n=((this.options.includePrerelease&&Jc)|(this.options.loose&&Xc))+":"+t,s=ws.get(n);if(s)return s;let o=this.options.loose,i=o?$[x.HYPHENRANGELOOSE]:$[x.HYPHENRANGE];t=t.replace(i,cl(this.options.includePrerelease)),b("hyphen replace",t),t=t.replace($[x.COMPARATORTRIM],Hc),b("comparator trim",t),t=t.replace($[x.TILDETRIM],Gc),b("tilde trim",t),t=t.replace($[x.CARETTRIM],Vc),b("caret trim",t);let a=t.split(" ").map(m=>Qc(m,this.options)).join(" ").split(/\s+/).map(m=>al(m,this.options));o&&(a=a.filter(m=>(b("loose invalid filter",m,this.options),!!m.match($[x.COMPARATORLOOSE])))),b("range list",a);let l=new Map,u=a.map(m=>new Jt(m,this.options));for(let m of u){if(Es(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return ws.set(n,f),f}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Ss(n,r)&&t.set.some(s=>Ss(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Kc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(ll(this.set[r],t,this.options))return!0;return!1}};Rs.exports=Vt;var Bc=ys(),ws=new Bc,Wc=We(),Jt=Ae(),b=Se(),Kc=O(),{safeRe:$,src:qc,t:x,comparatorTrimReplace:Hc,tildeTrimReplace:Gc,caretTrimReplace:Vc}=ie(),{FLAG_INCLUDE_PRERELEASE:Jc,FLAG_LOOSE:Xc}=oe(),zc=new RegExp(qc[x.BUILD],"g"),Es=e=>e.value==="<0.0.0-0",Yc=e=>e.value==="",Ss=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},Qc=(e,t)=>(e=e.replace($[x.BUILD],""),b("comp",e,t),e=rl(e,t),b("caret",e),e=el(e,t),b("tildes",e),e=sl(e,t),b("xrange",e),e=il(e,t),b("stars",e),e),C=e=>!e||e.toLowerCase()==="x"||e==="*",Zc=(e,t,r)=>C(e)&&!C(t)||C(t)&&r&&!C(r),el=(e,t)=>e.trim().split(/\s+/).map(r=>tl(r,t)).join(" "),tl=(e,t)=>{let r=t.loose?$[x.TILDELOOSE]:$[x.TILDE];return e.replace(r,(n,s,o,i,a)=>{b("tilde",e,n,s,o,i,a);let l;return C(s)?l="":C(o)?l=`>=${s}.0.0 <${+s+1}.0.0-0`:C(i)?l=`>=${s}.${o}.0 <${s}.${+o+1}.0-0`:a?(b("replaceTilde pr",a),l=`>=${s}.${o}.${i}-${a} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${i} <${s}.${+o+1}.0-0`,b("tilde return",l),l})},rl=(e,t)=>e.trim().split(/\s+/).map(r=>nl(r,t)).join(" "),nl=(e,t)=>{b("caret",e,t);let r=t.loose?$[x.CARETLOOSE]:$[x.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{b("caret",e,s,o,i,a,l);let u;return C(o)?u="":C(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:C(a)?o==="0"?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:l?(b("replaceCaret pr",l),o==="0"?i==="0"?u=`>=${o}.${i}.${a}-${l} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a}-${l} <${+o+1}.0.0-0`):(b("no pr"),o==="0"?i==="0"?u=`>=${o}.${i}.${a} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a} <${+o+1}.0.0-0`),b("caret return",u),u})},sl=(e,t)=>(b("replaceXRanges",e,t),e.split(/\s+/).map(r=>ol(r,t)).join(" ")),ol=(e,t)=>{e=e.trim();let r=t.loose?$[x.XRANGELOOSE]:$[x.XRANGE];return e.replace(r,(n,s,o,i,a,l)=>{if(b("xRange",e,n,s,o,i,a,l),Zc(o,i,a))return e;let u=C(o),f=u||C(i),m=f||C(a),S=m;return s==="="&&S&&(s=""),l=t.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&S?(f&&(i=0),a=0,s===">"?(s=">=",f?(o=+o+1,i=0,a=0):(i=+i+1,a=0)):s==="<="&&(s="<",f?o=+o+1:i=+i+1),s==="<"&&(l="-0"),n=`${s+o}.${i}.${a}${l}`):f?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${i}.0${l} <${o}.${+i+1}.0-0`),b("xRange return",n),n})},il=(e,t)=>(b("replaceStars",e,t),e.trim().replace($[x.STAR],"")),al=(e,t)=>(b("replaceGTE0",e,t),e.trim().replace($[t.includePrerelease?x.GTE0PRE:x.GTE0],"")),cl=e=>(t,r,n,s,o,i,a,l,u,f,m,S)=>(C(n)?r="":C(s)?r=`>=${n}.0.0${e?"-0":""}`:C(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,C(u)?l="":C(f)?l=`<${+u+1}.0.0-0`:C(m)?l=`<${u}.${+f+1}.0-0`:S?l=`<=${u}.${f}.${m}-${S}`:e?l=`<${u}.${f}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),ll=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(b(e[n].semver),e[n].semver!==Jt.ANY&&e[n].semver.prerelease.length>0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var Ae=w((ph,Cs)=>{"use strict";var Pe=Symbol("SemVer ANY"),Yt=class e{static get ANY(){return Pe}constructor(t,r){if(r=As(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),zt("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Pe?this.value="":this.value=this.operator+this.semver.version,zt("comp",this)}parse(t){let r=this.options.loose?Ps[bs.COMPARATORLOOSE]:Ps[bs.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Is(n[2],this.options.loose):this.semver=Pe}toString(){return this.value}test(t){if(zt("Comparator.test",t,this.options.loose),this.semver===Pe||t===Pe)return!0;if(typeof t=="string")try{t=new Is(t,this.options)}catch{return!1}return Xt(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new vs(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new vs(this.value,r).test(t.semver):(r=As(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Xt(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Xt(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Cs.exports=Yt;var As=We(),{safeRe:Ps,t:bs}=ie(),Xt=Ht(),zt=Se(),Is=O(),vs=M()});var be=w((dh,Ts)=>{"use strict";var ul=M(),pl=(e,t,r)=>{try{t=new ul(t,r)}catch{return!1}return t.test(e)};Ts.exports=pl});var xs=w((mh,Os)=>{"use strict";var dl=M(),ml=(e,t)=>new dl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));Os.exports=ml});var Ns=w((fh,$s)=>{"use strict";var fl=O(),hl=M(),gl=(e,t,r)=>{let n=null,s=null,o=null;try{o=new hl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new fl(n,r))}),n};$s.exports=gl});var Ls=w((hh,ks)=>{"use strict";var yl=O(),wl=M(),El=(e,t,r)=>{let n=null,s=null,o=null;try{o=new wl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new yl(n,r))}),n};ks.exports=El});var _s=w((gh,Ds)=>{"use strict";var Qt=O(),Sl=M(),Ms=Re(),Rl=(e,t)=>{e=new Sl(e,t);let r=new Qt("0.0.0");if(e.test(r)||(r=new Qt("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let s=e.set[n],o=null;s.forEach(i=>{let a=new Qt(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||Ms(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||Ms(r,o))&&(r=o)}return r&&e.test(r)?r:null};Ds.exports=Rl});var js=w((yh,Us)=>{"use strict";var Al=M(),Pl=(e,t)=>{try{return new Al(e,t).range||"*"}catch{return null}};Us.exports=Pl});var Ze=w((wh,Ks)=>{"use strict";var bl=O(),Ws=Ae(),{ANY:Il}=Ws,vl=M(),Cl=be(),Fs=Re(),Bs=Je(),Tl=ze(),Ol=Xe(),xl=(e,t,r,n)=>{e=new bl(e,n),t=new vl(t,n);let s,o,i,a,l;switch(r){case">":s=Fs,o=Tl,i=Bs,a=">",l=">=";break;case"<":s=Bs,o=Ol,i=Fs,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Cl(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let f=t.set[u],m=null,S=null;if(f.forEach(h=>{h.semver===Il&&(h=new Ws(">=0.0.0")),m=m||h,S=S||h,s(h.semver,m.semver,n)?m=h:i(h.semver,S.semver,n)&&(S=h)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&o(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};Ks.exports=xl});var Hs=w((Eh,qs)=>{"use strict";var $l=Ze(),Nl=(e,t,r)=>$l(e,t,">",r);qs.exports=Nl});var Vs=w((Sh,Gs)=>{"use strict";var kl=Ze(),Ll=(e,t,r)=>kl(e,t,"<",r);Gs.exports=Ll});var zs=w((Rh,Xs)=>{"use strict";var Js=M(),Ml=(e,t,r)=>(e=new Js(e,r),t=new Js(t,r),e.intersects(t,r));Xs.exports=Ml});var Qs=w((Ah,Ys)=>{"use strict";var Dl=be(),_l=L();Ys.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((f,m)=>_l(f,m,r));for(let f of i)Dl(f,t,r)?(o=f,s||(s=f)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let a=[];for(let[f,m]of n)f===m?a.push(f):!m&&f===i[0]?a.push("*"):m?f===i[0]?a.push(`<=${m}`):a.push(`${f} - ${m}`):a.push(`>=${f}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var so=w((Ph,no)=>{"use strict";var Zs=M(),tr=Ae(),{ANY:Zt}=tr,er=be(),rr=L(),Ul=(e,t,r={})=>{if(e===t)return!0;e=new Zs(e,r),t=new Zs(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=Fl(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},jl=[new tr(">=0.0.0-0")],eo=[new tr(">=0.0.0")],Fl=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Zt){if(t.length===1&&t[0].semver===Zt)return!0;r.includePrerelease?e=jl:e=eo}if(t.length===1&&t[0].semver===Zt){if(r.includePrerelease)return!0;t=eo}let n=new Set,s,o;for(let h of e)h.operator===">"||h.operator===">="?s=to(s,h,r):h.operator==="<"||h.operator==="<="?o=ro(o,h,r):n.add(h.semver);if(n.size>1)return null;let i;if(s&&o){if(i=rr(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let h of n){if(s&&!er(h,String(s),r)||o&&!er(h,String(o),r))return null;for(let re of t)if(!er(h,String(re),r))return!1;return!0}let a,l,u,f,m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,S=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;m&&m.prerelease.length===1&&o.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let h of t){if(f=f||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",s){if(S&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===S.major&&h.semver.minor===S.minor&&h.semver.patch===S.patch&&(S=!1),h.operator===">"||h.operator===">="){if(a=to(s,h,r),a===h&&a!==s)return!1}else if(s.operator===">="&&!h.test(s.semver))return!1}if(o){if(m&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===m.major&&h.semver.minor===m.minor&&h.semver.patch===m.patch&&(m=!1),h.operator==="<"||h.operator==="<="){if(l=ro(o,h,r),l===h&&l!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||s)&&i!==0)return!1}return!(s&&u&&!o&&i!==0||o&&f&&!s&&i!==0||S||m)},to=(e,t,r)=>{if(!e)return t;let n=rr(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},ro=(e,t,r)=>{if(!e)return t;let n=rr(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};no.exports=Ul});var sr=w((bh,ao)=>{"use strict";var nr=ie(),oo=oe(),Bl=O(),io=Ft(),Wl=X(),Kl=xn(),ql=Nn(),Hl=Mn(),Gl=Un(),Vl=Fn(),Jl=Wn(),Xl=qn(),zl=Gn(),Yl=L(),Ql=zn(),Zl=Qn(),eu=Ve(),tu=rs(),ru=ss(),nu=Re(),su=Je(),ou=Kt(),iu=qt(),au=Xe(),cu=ze(),lu=Ht(),uu=ms(),pu=hs(),du=Ae(),mu=M(),fu=be(),hu=xs(),gu=Ns(),yu=Ls(),wu=_s(),Eu=js(),Su=Ze(),Ru=Hs(),Au=Vs(),Pu=zs(),bu=Qs(),Iu=so();ao.exports={parse:Wl,valid:Kl,clean:ql,inc:Hl,diff:Gl,major:Vl,minor:Jl,patch:Xl,prerelease:zl,compare:Yl,rcompare:Ql,compareLoose:Zl,compareBuild:eu,sort:tu,rsort:ru,gt:nu,lt:su,eq:ou,neq:iu,gte:au,lte:cu,cmp:lu,coerce:uu,truncate:pu,Comparator:du,Range:mu,satisfies:fu,toComparators:hu,maxSatisfying:gu,minSatisfying:yu,minVersion:wu,validRange:Eu,outside:Su,gtr:Ru,ltr:Au,intersects:Pu,simplifyRange:bu,subset:Iu,SemVer:Bl,re:nr.re,src:nr.src,tokens:nr.t,SEMVER_SPEC_VERSION:oo.SEMVER_SPEC_VERSION,RELEASE_TYPES:oo.RELEASE_TYPES,compareIdentifiers:io.compareIdentifiers,rcompareIdentifiers:io.rcompareIdentifiers}});import{MEDPLUM_VERSION as Ad,normalizeErrorString as Er}from"@medplum/core";import{CommanderError as Qo,Option as Pd}from"commander";import bd from"dotenv";import{ContentType as on,EMPTY as Ji,isOk as Xi,isUUID as zi,normalizeErrorString as Yi}from"@medplum/core";import{Option as je}from"commander";import{MedplumClient as di}from"@medplum/core";import{ClientStorage as ai}from"@medplum/core";import{existsSync as Rr,mkdirSync as ci,readFileSync as li,writeFileSync as ui}from"node:fs";import{homedir as pi}from"node:os";import{resolve as Ar}from"node:path";var _=class extends ai{constructor(r){super();P(this,"dirName");P(this,"fileName");this.dirName=Ar(pi(),".medplum"),this.fileName=Ar(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let s=this.readFile()??{};n?s[r]=n:delete s[r],this.writeFile(s)}getObject(r){let n=this.getString(r);return n?JSON.parse(n):void 0}setObject(r,n){this.setString(r,n?JSON.stringify(n):void 0)}readFile(){if(Rr(this.fileName))return JSON.parse(li(this.fileName,"utf8"))}writeFile(r){Rr(this.dirName)||ci(this.dirName),ui(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function A(e,t=!0){let r=e.profile??"default",n=new _(r),s=n.getObject("options");if(r!=="default"&&!s)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:o,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:f,clientSecret:m}=mi(e,n),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await fi(e.baseUrl,S);let h=new di({fetch:S,baseUrl:o,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:hi,verbose:e.verbose});return t&&(a?h.setAccessToken(a):f&&m&&(h.setBasicAuth(f,m),s?.authType!=="basic"&&await h.startClientLogin(f,m))),h}function mi(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",s=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,o=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,a=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:n,fhirUrlPath:s,accessToken:o,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function fi(e,t){try{let r=new URL("healthcheck",e).toString(),n=await t(r);if(!n.ok)throw new Error(`Healthcheck returned status ${n.status}`);if((await n.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${n}`)}}function hi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{ContentType as Tt,encodeBase64 as Hr,OAuthSigningAlgorithm as Gr}from"@medplum/core";import{Command as Di}from"commander";import{Buffer as gi}from"node:buffer";var Q=new TextEncoder,yt=new TextDecoder,Ud=2**32;function Pr(...e){let t=e.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}var xe=e=>gi.from(e).toString("base64url");var Z=class extends Error{constructor(r,n){super(r,n);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};P(Z,"code","ERR_JOSE_GENERIC");var k=class extends Z{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}};P(k,"code","ERR_JOSE_NOT_SUPPORTED");var K=class extends Z{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}};P(K,"code","ERR_JWS_INVALID");var fe=class extends Z{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}};P(fe,"code","ERR_JWT_INVALID");var br,Ir,wt=class extends(Ir=Z,br=Symbol.asyncIterator,Ir){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);P(this,br);P(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};P(wt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");import*as vr from"node:util";var $e=e=>vr.types.isKeyObject(e);import*as Cr from"node:crypto";import*as Tr from"node:util";var wi=Cr.webcrypto,Or=wi,ne=e=>Tr.types.isCryptoKey(e);function U(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function he(e,t){return e.name===t}function Et(e){return parseInt(e.name.slice(4),10)}function Ei(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Si(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function xr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!he(e.algorithm,"HMAC"))throw U("HMAC");let n=parseInt(t.slice(2),10);if(Et(e.algorithm.hash)!==n)throw U(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!he(e.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Et(e.algorithm.hash)!==n)throw U(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!he(e.algorithm,"RSA-PSS"))throw U("RSA-PSS");let n=parseInt(t.slice(2),10);if(Et(e.algorithm.hash)!==n)throw U(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw U("Ed25519 or Ed448");break}case"Ed25519":{if(!he(e.algorithm,"Ed25519"))throw U("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!he(e.algorithm,"ECDSA"))throw U("ECDSA");let n=Ei(t);if(e.algorithm.namedCurve!==n)throw U(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Si(e,r)}function $r(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}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 ge=(e,...t)=>$r("Key must be ",e,...t);function St(e,t,...r){return $r(`Key for the ${e} algorithm must be `,t,...r)}var Rt=e=>$e(e)||ne(e),q=["KeyObject"];(globalThis.CryptoKey||Or?.CryptoKey)&&q.push("CryptoKey");var Ri=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0},Nr=Ri;function Ai(e){return typeof e=="object"&&e!==null}function ye(e){if(!Ai(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{KeyObject as Pi}from"node:crypto";function G(e){return ye(e)&&typeof e.kty=="string"}function kr(e){return e.kty!=="oct"&&typeof e.d=="string"}function Lr(e){return e.kty!=="oct"&&typeof e.d>"u"}function Mr(e){return G(e)&&e.kty==="oct"&&typeof e.k=="string"}var bi=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new k("Unsupported key curve for this operation")}},Ii=(e,t)=>{let r;if(ne(e))r=Pi.from(e);else if($e(e))r=e;else{if(G(e))return e.crv;throw new TypeError(ge(e,...q))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let n=r.asymmetricKeyDetails.namedCurve;return t?n:bi(n)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},_r=Ii;import{KeyObject as vi}from"node:crypto";var At=(e,t)=>{let r;try{e instanceof vi?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var se=e=>e?.[Symbol.toStringTag],Pt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Ci=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&G(t)){if(Mr(t)&&Pt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Rt(t))throw new TypeError(St(e,t,...q,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${se(t)} instances for symmetric algorithms must be of type "secret"`)}},Ti=(e,t,r,n)=>{if(n&&G(t))switch(r){case"sign":if(kr(t)&&Pt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Lr(t)&&Pt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Rt(t))throw new TypeError(St(e,t,...q,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${se(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${se(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${se(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${se(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${se(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ur(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Ci(t,r,n,e):Ti(t,r,n,e)}var pm=Ur.bind(void 0,!1),jr=Ur.bind(void 0,!0);function Oi(e,t,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let i of n.crit){if(!o.has(i))throw new k(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var Fr=Oi;function bt(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as Br,KeyObject as xi}from"node:crypto";var $i=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function It(e,t){let r,n,s;if(t instanceof xi)r=t.asymmetricKeyType,n=t.asymmetricKeyDetails;else switch(s=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let o;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");At(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=n,u=parseInt(e.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||a!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");At(t,e),o={padding:Br.RSA_PKCS1_PSS_PADDING,saltLength:Br.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let i=_r(t),a=$i.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);o={dsaEncoding:"ieee-p1363"};break}default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...o}:o?{...o,key:t}:t}import*as Ne from"node:crypto";import{promisify as Ni}from"node:util";function vt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Wr,createSecretKey as Kr}from"node:crypto";function Ct(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ge(t,...q));return Kr(t)}if(t instanceof Wr)return t;if(ne(t))return xr(t,e,r),Wr.from(t);if(G(t))return e.startsWith("HS")?Kr(Buffer.from(t.k,"base64url")):t;throw new TypeError(ge(t,...q,"Uint8Array","JSON Web Key"))}var ki=Ni(Ne.sign),Li=async(e,t,r)=>{let n=Ct(e,t,"sign");if(e.startsWith("HS")){let s=Ne.createHmac(vt(e),n);return s.update(r),s.digest()}return ki(bt(e),r,It(e,n))},qr=Li;var V=e=>Math.floor(e.getTime()/1e3);var Mi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ke=e=>{let t=Mi.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-s:s};var Le=class{constructor(t){P(this,"_payload");P(this,"_protectedHeader");P(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new K("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Nr(this._protectedHeader,this._unprotectedHeader))throw new K("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},s=Fr(K,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new K('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new K('JWS "alg" (Algorithm) Header Parameter missing or invalid');jr(i,t,"sign");let a=this._payload;o&&(a=Q.encode(xe(a)));let l;this._protectedHeader?l=Q.encode(xe(JSON.stringify(this._protectedHeader))):l=Q.encode("");let u=Pr(l,Q.encode("."),a),f=await qr(i,t,u),m={signature:xe(f),payload:""};return o&&(m.payload=yt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=yt.decode(l)),m}};var Me=class{constructor(t){P(this,"_flattened");this._flattened=new Le(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function ee(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var De=class{constructor(t={}){P(this,"_payload");if(!ye(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:ee("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ee("setNotBefore",V(t))}:this._payload={...this._payload,nbf:V(new Date)+ke(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ee("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ee("setExpirationTime",V(t))}:this._payload={...this._payload,exp:V(new Date)+ke(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:V(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ee("setIssuedAt",V(t))}:typeof t=="string"?this._payload={...this._payload,iat:ee("setIssuedAt",V(new Date)+ke(t))}:this._payload={...this._payload,iat:ee("setIssuedAt",t)},this}};var we=class extends De{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,n){let s=new Me(Q.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new fe("JWTs MUST NOT use unencoded payload");return s.sign(r,n)}};import{createHmac as _i,createPrivateKey as Ui,randomBytes as ji}from"node:crypto";import{existsSync as Fi,readFileSync as Vr,writeFileSync as Jr}from"node:fs";import{basename as Xr,extname as Bi,resolve as Ot}from"node:path";import{isPromise as Wi}from"node:util/types";import{extract as Ki}from"tar";function H(e){console.log(JSON.stringify(e,null,2))}async function xt(e,t,r){let n=t.source,s=_e(n);if(!s)return;console.log("Saving source code...");let o=await e.createAttachment({data:s,filename:Xr(n),contentType:Gi(n)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:o});console.log("Success! New bot version: "+i.meta?.versionId)}async function $t(e,t,r){let n=t.dist??t.source,s=_e(n);if(!s)return;console.log("Deploying bot...");let o=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:Xr(n)});console.log("Deploy result: "+o.issue?.[0]?.details?.text)}async function Nt(e,t,r,n,s,o,i){let a={name:t,description:"",runtimeVersion:o},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),f={name:t,id:l.id,source:n,dist:s};await xt(e,f,u),await $t(e,f,u),console.log(`Success! Bot created: ${u.id}`),i&&qi(f)}function zr(e){let t=new RegExp("^"+Hi(e).replaceAll(String.raw`\*`,".*")+"$"),r=j()?.bots?.filter(n=>t.test(n.name));return r||[]}function D(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 v(e,t){Jr(Ot(e),JSON.stringify(t,void 0,2),"utf-8")}function j(e,t){let r=D(e,t),n=_e(r);if(n)return JSON.parse(n)}function Yr(e){let t=_e(D(e,{server:!0}));if(t)return JSON.parse(t)}function _e(e){let t=Ot(e);return Fi(t)?Vr(t,"utf8"):""}function qi(e){let t=j()??{};t.bots||(t.bots=[]),t.bots.push(e),Jr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Hi(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Qr(e){let n=0,s=0;return Ki({cwd:e,filter:(o,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(s+=i.size,s>10485760)throw new Error("Tar extractor reached max size");return!0}})}function kt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Gi(e){let t=Bi(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Tt.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Tt.TYPESCRIPT:Tt.TEXT}function Ue(e,t){let r=new _(e),n={name:e,...t};return r.setObject("options",n),n}function Zr(e){return new _(e).getObject("options")}async function en(e,t){let r={typ:"JWT",alg:Gr.HS256},n=Math.floor(Date.now()/1e3),s={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},o=Hr(JSON.stringify(r)),i=Hr(JSON.stringify(s)),a=`${o}.${i}`,l=_i("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function tn(e,t){let r=Ui(Vr(Ot(t.privateKeyPath))),n=await new we({}).setProtectedHeader({typ:"JWT",alg:Gr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(ji(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends Di{action(t){let r=Vi(this,t);return super._actionHandler=r,this}resetOptionDefaults(){this._optionValues={};for(let t of this.options)t.defaultValue!==void 0&&(this._optionValues[t.attributeName()]=t.defaultValue)}};function Vi(e,t){return async r=>{let n=e.registeredArguments.length,s=r.slice(0,n);s[n]=e.optsWithGlobals();try{let o=t(...s);Wi(o)&&await o}finally{e.resetOptionDefaults()}}}var an=new g("status").aliases(["info","list","ls"]),cn=new g("ping"),ln=new g("push"),un=new g("reload-config"),pn=new g("upgrade"),dn=new g("stats"),J=new g("agent");y(J,an);y(J,cn);y(J,ln);y(J,un);y(J,pn);y(J,dn);an.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 je("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Fe({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=fn(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:n.version,connectionStatus:n.status,statusLastUpdated:n.lastUpdated??"N/A"}}})});cn.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 n=await A(r),s=await mn(n,t,r),o=Number.parseInt(r.count,10);if(Number.isNaN(o))throw new Error("--count <count> must be an integer if specified");try{let i=await n.pushToAgent(s,e,`PING ${o}`,on.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});ln.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",on.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,n)=>{let s=await A(n),o=await mn(s,r,n),i;try{i=await s.pushToAgent(o,{reference:`Device/${e}`},t,n.contentType,n.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});un.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 je("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Fe({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});pn.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 je("--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 Fe({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});dn.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 je("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Fe({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=fn(r.result,{required:["stats"]}),s;try{s=JSON.parse(n)}catch(o){console.error(`Failed to parse stats for agent ${r.agent.id}: ${Yi(o)}`)}return{id:r.agent.id,name:r.agent.name,stats:s}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),Qi(r[n])}})});var rn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function nn(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function sn(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 Qi(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 i of rn)r[i]=nn(e.stats[i]);let n=new Set([...rn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=nn(a));console.table(r);let s=sn(e.stats.channelStats);s.length&&(console.info("Channel Stats:"),console.table(s));let o=sn(e.stats.clientStats);o.length&&(console.info("Client Stats:"),console.table(o))}async function Fe({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:s,renderSuccessfulRows:o}){let i=ra(t,r),a=await A(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[T,W]of Object.entries(n))u.append(T,W.toString());let f;try{let T=a.fhirUrl("Agent",e);T.search=u.toString(),f=await a.get(T,{cache:"reload"})}catch(T){throw new Error(`Operation '${e}' failed`,{cause:T})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let m=[],S=[];switch(f.resourceType){case"Bundle":{let T=Zi(f);for(let W of T)W.result.resourceType==="Parameters"||Xi(W.result)?m.push(W):S.push(W);break}case"Parameters":case"OperationOutcome":{let T=await a.searchOne("Agent",u,{cache:"reload"});if(!T)throw new Error("Agent not found");f.resourceType==="Parameters"?m.push({agent:T,result:f}):S.push({agent:T,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let h=[];for(let T of m){let W=s(T);h.push(W)}let re=[];for(let T of S){let ht=T.result.issue?.[0],Zo={id:T.agent.id,name:T.agent.name,severity:ht.severity,code:ht.code,details:ht.details?.text??"No details to show"};re.push(Zo)}console.info(`
3
3
  ${h.length} successful response(s):
4
- `),o?h.length?o(h):console.info("No successful responses received"):console.table(h.length?h:"No successful responses received"),console.info(),re.length&&(console.info(`${re.length} failed response(s):`),console.info(),console.table(re))}async function mn(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 n;if(t)n=t;else{hn(r.criteria);let s=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!s?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(s.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");n=s.entry[0].resource?.id}return{reference:`Agent/${n}`}}function Zi(e){let t=[];for(let r of e.entry??Ji){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ea(r.resource))}return t}function ea(e){let t=e.parameter?.find(n=>n.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(n=>n.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 fn(e,t){let r={},n=t.required,s=t.optional;for(let o of n){let i=e.parameter?.find(l=>l.name===o);if(!i)throw new Error(`Failed to find parameter '${o}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${o}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${o}'`);r[o]=i[a]}if(s?.length)for(let o of s){let i=e.parameter?.find(l=>l.name===o);if(!i)continue;let a=ta(o,i);r[o]=a}return r}function ta(e,t){let r;for(let n in t)if(n.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=n}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function ra(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(!zi(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return hn(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function hn(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,n]=e.split("?");if(r!=="Agent"||!n)throw new Error(t);try{new URLSearchParams(n)}catch(s){throw new Error(t,{cause:s})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}import{ContentType as Be,getDisplayString as na,MEDPLUM_CLI_CLIENT_ID as sa,normalizeErrorString as oa}from"@medplum/core";import{exec as ia}from"node:child_process";import{createServer as aa}from"node:http";import{platform as ca}from"node:os";var gn=sa,yn="http://localhost:9615",Lt=new g("login"),Mt=new g("whoami"),Dt=new g("token");Lt.action(async e=>{let t=e.profile??"default",r=Ue(t,e),n=await A(e,!1);await la(n,r)});Mt.action(async e=>{let t=await A(e);da(t)});Dt.action(async e=>{let t=await A(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function la(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await ma(e);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 en(e,t);break;case"jwt-assertion":await tn(e,t);break}}async function ua(e){let t=aa(async(r,n)=>{let s=new URL(r.url,"http://localhost:9615"),o=s.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":Be.TEXT}),n.end("OK");return}if(s.pathname==="/"&&o)try{let i=await e.processCode(o,{clientId:gn,redirectUri:yn});n.writeHead(200,{"Content-Type":Be.TEXT}),n.end(`Signed in as ${na(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":Be.TEXT}),n.end(`Error: ${oa(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":Be.TEXT}),n.end("Not found")}).listen(9615)}async function pa(e){let t=ca(),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)}return new Promise((n,s)=>{ia(r,(o,i,a)=>{if(o){s(o);return}if(a){s(new Error("Could not open browser: "+a));return}n()})})}function da(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 ma(e){await ua(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",gn),t.searchParams.set("redirect_uri",yn),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await pa(t.toString())}var Ee="\x1B[0m",fa="\x1B[1m",ha="\x1B[31m",ga="\x1B[32m",ya="\x1B[33m",wa="\x1B[34m",te={red:e=>`${ha}${e}${Ee}`,green:e=>`${ga}${e}${Ee}`,yellow:e=>`${ya}${e}${Ee}`,blue:e=>`${wa}${e}${Ee}`,bold:e=>`${fa}${e}${Ee}`},_t=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>te.bold(r));var uo=Sr(sr(),1);import{CloudFormationClient as lo,DescribeStackResourcesCommand as vu,DescribeStacksCommand as Cu,paginateListStacks as Tu}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Ou,CreateInvalidationCommand as xu}from"@aws-sdk/client-cloudfront";import{ECSClient as $u}from"@aws-sdk/client-ecs";import{S3Client as Nu}from"@aws-sdk/client-s3";import{GetParameterCommand as ku,PutParameterCommand as Lu,SSMClient as Mu}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Du,STSClient as _u}from"@aws-sdk/client-sts";import{EMPTY as Uu,normalizeErrorString as ju}from"@medplum/core";import Fu from"node-fetch";import{readdirSync as Bu}from"node:fs";import Iu from"node:readline";var et;function tt(){et=Iu.createInterface({input:process.stdin,output:process.stdout})}function rt(){et.close()}function c(e){et.write(e+`
4
+ `),o?h.length?o(h):console.info("No successful responses received"):console.table(h.length?h:"No successful responses received"),console.info(),re.length&&(console.info(`${re.length} failed response(s):`),console.info(),console.table(re))}async function mn(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 n;if(t)n=t;else{hn(r.criteria);let s=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!s?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(s.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");n=s.entry[0].resource?.id}return{reference:`Agent/${n}`}}function Zi(e){let t=[];for(let r of e.entry??Ji){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ea(r.resource))}return t}function ea(e){let t=e.parameter?.find(n=>n.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(n=>n.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 fn(e,t){let r={},n=t.required,s=t.optional;for(let o of n){let i=e.parameter?.find(l=>l.name===o);if(!i)throw new Error(`Failed to find parameter '${o}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${o}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${o}'`);r[o]=i[a]}if(s?.length)for(let o of s){let i=e.parameter?.find(l=>l.name===o);if(!i)continue;let a=ta(o,i);r[o]=a}return r}function ta(e,t){let r;for(let n in t)if(n.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=n}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function ra(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(!zi(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return hn(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function hn(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,n]=e.split("?");if(r!=="Agent"||!n)throw new Error(t);try{new URLSearchParams(n)}catch(s){throw new Error(t,{cause:s})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}import{ContentType as Be,getDisplayString as na,MEDPLUM_CLI_CLIENT_ID as sa,normalizeErrorString as oa}from"@medplum/core";import{exec as ia}from"node:child_process";import{createServer as aa}from"node:http";import{platform as ca}from"node:os";var gn=sa,yn="http://localhost:9615",Lt=new g("login"),Mt=new g("whoami"),Dt=new g("token");Lt.action(async e=>{let t=e.profile??"default",r=Ue(t,e),n=await A(e,!1);await la(n,r)});Mt.action(async e=>{let t=await A(e);da(t)});Dt.action(async e=>{let t=await A(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function la(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await ma(e);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 en(e,t);break;case"jwt-assertion":await tn(e,t);break}}async function ua(e){let t=aa(async(r,n)=>{let s=new URL(r.url,"http://localhost:9615"),o=s.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":Be.TEXT}),n.end("OK");return}if(s.pathname==="/"&&o)try{let i=await e.processCode(o,{clientId:gn,redirectUri:yn});n.writeHead(200,{"Content-Type":Be.TEXT}),n.end(`Signed in as ${na(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":Be.TEXT}),n.end(`Error: ${oa(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":Be.TEXT}),n.end("Not found")}).listen(9615)}async function pa(e){let t=ca(),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)}return new Promise((n,s)=>{ia(r,(o,i,a)=>{if(o){s(o);return}if(a){s(new Error("Could not open browser: "+a));return}n()})})}function da(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 ma(e){await ua(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",gn),t.searchParams.set("redirect_uri",yn),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await pa(t.toString())}var Ee="\x1B[0m",fa="\x1B[1m",ha="\x1B[31m",ga="\x1B[32m",ya="\x1B[33m",wa="\x1B[34m",te={red:e=>`${ha}${e}${Ee}`,green:e=>`${ga}${e}${Ee}`,yellow:e=>`${ya}${e}${Ee}`,blue:e=>`${wa}${e}${Ee}`,bold:e=>`${fa}${e}${Ee}`},_t=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>te.bold(r));var uo=Sr(sr(),1);import{CloudFormationClient as lo,DescribeStackResourcesCommand as Cu,DescribeStacksCommand as Tu,paginateListStacks as Ou}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as xu,CreateInvalidationCommand as $u}from"@aws-sdk/client-cloudfront";import{ECSClient as Nu}from"@aws-sdk/client-ecs";import{S3Client as ku}from"@aws-sdk/client-s3";import{GetParameterCommand as Lu,PutParameterCommand as Mu,SSMClient as Du}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as _u,STSClient as Uu}from"@aws-sdk/client-sts";import{EMPTY as ju,normalizeErrorString as Fu}from"@medplum/core";import Bu from"node-fetch";import{readdirSync as Wu}from"node:fs";import vu from"node:readline";var et;function tt(){et=vu.createInterface({input:process.stdin,output:process.stdout})}function rt(){et.close()}function c(e){et.write(e+`
5
5
  `)}function I(e){c(`
6
6
  `+e+`
7
- `)}function N(e,t=""){return new Promise(r=>{et.question(e+(t?" ("+t+")":"")+" ",n=>{r(n||t.toString())})})}async function nt(e,t,r=""){let n=e+" ["+t.map(s=>s===r?"("+s+")":s).join("|")+"]";for(;;){let s=await N(n)||r;if(t.includes(s))return s;c("Please choose one of the following options: "+t.join(", "))}}async function ae(e,t,r){return Number.parseInt(await nt(e,t.map(n=>n.toString()),r.toString()),10)}async function z(e){return(await nt(e,["y","n"])).toLowerCase()==="y"}async function Ie(e){if(!await z(e))throw c("Exiting..."),new Error("User cancelled")}var st=new lo({}),Wu=new Ou({region:"us-east-1"}),_h=new $u({}),ve=new Nu({}),Ku="medplum:environment";async function or(){let e=[],t=Tu({client:st},{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 n of r.StackSummaries??Uu)e.push(n);return e}async function ce(e){let t=await or();for(let r of t){let n=r.StackName,s=await ir(n);if(s?.tag===e)return s}}async function ir(e){let t={};if(await co(st,e,t),await st.config.region()!=="us-east-1")try{await co(new lo({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function co(e,t,r){let n=new Cu({StackName:t}),o=(await e.send(n))?.Stacks?.[0],i=o?.Tags?.find(l=>l.Key===Ku);if(!i)return;let a=await e.send(new vu({StackName:t}));if(a.StackResources){e===st&&(r.stack=o,r.tag=i.Value);for(let l of a.StackResources)qu(l,r)}}function qu(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 ot(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: ${Hu(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 Hu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function it(e){let t=await Wu.send(new xu({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function at(e){let n=(await(await Fu("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(s=>s.tag_name.startsWith("v")?s.tag_name.slice(1):s.tag_name);return n.sort((s,o)=>uo.compare(o,s)),e?n.slice(0,n.indexOf(e)):n}async function ct(e,t,r){let n=new Mu({region:e});for(let[s,o]of Object.entries(r)){let i=t+s,a=typeof o=="object"?JSON.stringify(o):o.toString(),l=await Gu(n,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ie(`Do you want to overwrite "${i}"?`)),await Vu(n,i,a)}}async function Gu(e,t){let r=new ku({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function Vu(e,t,r){let n=new Lu({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(n)}function Y(e,t){if(console.log(`Config not found: ${e} (${D(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[s,o]of n)console.log(` ${s}: ${o}`)}}console.log();let r=Bu(".",{withFileTypes:!0});if(r=r.filter(n=>n.isFile()&&n.name.startsWith("medplum.")&&n.name.endsWith(".json")).map(n=>n.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let n of r)console.log(` ${n.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${n})`)}}async function le(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new _u,r=new Du({}),n=await t.send(r),s=await t.config.region();console.log("AWS Region: ",s),console.log("AWS Account ID: ",n.Account),console.log("AWS Account ARN: ",n.Arn),console.log("AWS User ID: ",n.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",ju(t))}}async function po(e){let t=await ce(e);if(!t)throw await le(e),new Error(`Stack not found: ${e}`);ot(t)}import{ACMClient as ho,ListCertificatesCommand as Ju,RequestCertificateCommand as Xu}from"@aws-sdk/client-acm";import{CloudFrontClient as zu,CreatePublicKeyCommand as Yu}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as Qu,STSClient as Zu}from"@aws-sdk/client-sts";import{normalizeErrorString as ep}from"@medplum/core";import{generateKeyPairSync as tp,randomUUID as mo}from"node:crypto";import{existsSync as rp}from"node:fs";var np=e=>`${e}DomainName`,go=e=>`${e}SslCertArn`;async function yo(){let e={apiPort:8103,region:"us-east-1"};tt(),I("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await sp(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await Ie("Do you want to continue without AWS credentials?")),I("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await N("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),I("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await N("What is the config file name?",`medplum.${e.name}.config.json`);rp(r)&&(c("Config file already exists."),await Ie("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),v(r,e),I("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await N("Enter your AWS region:","us-east-1"),v(r,e),I("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await N("What is your AWS account number?",t),v(r,e),I("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let n="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",n),v(r,e),I("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await N("Enter your base domain name:");v(r,e),I("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let s=await N("Enter your support email address:");I("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await N("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,v(r,e),I("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await N("Enter your web application domain name:","app."+e.domainName),v(r,e),I("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),v(r,e),I("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await N("Enter your storage bucket name:",e.storageDomainName),v(r,e),I("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await ae("Enter the maximum number of availability zones:",[2,3,99],2),I("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await z("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await ae("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),v(r,e),I("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await ae("Enter the number of server instances:",[1,2,3,4,6,8],1),v(r,e),I("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await ae("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),v(r,e),I("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await ae("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),v(r,e),I("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let o=(await at())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${o}`),v(r,e),I("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await cp(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,v(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),I("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await op(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:f}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await ip(e,a,u,f);e[go(f)]=m,v(r,e)}I("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:s};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await z("Do you want to store these values in AWS Parameter Store?"))await ct(e.region,`/medplum/${e.name}/`,l);else{let u=D(e.name,{server:!0});v(u,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${u}`),c("Please add these values to AWS Parameter Store manually.")}I("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),rt()}async function sp(e){try{let t=new Zu({region:e}),r=new Qu({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function op(e){let t=await fo(e);if(e!=="us-east-1"){let r=await fo("us-east-1");t.push(...r)}return t}async function fo(e){try{let t=new ho({region:e}),r=new Ju({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function ip(e,t,r,n){let s=e[np(n)],o=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===s);if(o)return c(`Found existing certificate for "${s}" in "${r}.`),o.CertificateArn;if(c(`No existing certificate found for "${s}" in "${r}.`),!await z("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${go(n)}" setting.`),"TODO";let i=await ap(r,s);return c("Certificate ARN: "+i),i}async function ap(e,t){try{let r=await nt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new ho({region:e}),s=new Xu({DomainName:t,ValidationMethod:r.toUpperCase()});return(await n.send(s)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function cp(e,t){let r=mo(),n=tp("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new zu({region:e}).send(new Yu({PublicKeyConfig:{Name:t,CallerReference:mo(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:r}}catch(s){console.log("Error: Unable to create signing key: ",ep(s));return}}async function wo(){let e=await or();for(let t of e){let r=t.StackName,n=await ir(r);n&&(ot(n),console.log(""))}}import{PutObjectCommand as lp}from"@aws-sdk/client-s3";import{ContentType as B}from"@medplum/core";import up from"fast-glob";import Eo from"node-fetch";import{createReadStream as pp,mkdtempSync as dp,readdirSync as mp,readFileSync as fp,rmSync as hp,writeFileSync as gp}from"node:fs";import{tmpdir as yp}from"node:os";import{join as lt,sep as wp}from"node:path";import{pipeline as Ep}from"node:stream/promises";async function So(e,t){let r=j(e,t);if(!r)throw Y(e,t),new Error(`Config not found: ${e}`);let n=await ce(e);if(!n)throw await le(e),new Error(`Stack not found: ${e}`);let s=n.appBucket;if(!s)throw new Error(`App bucket not found for stack ${e}`);let o;if(t.tarPath)o=t.tarPath;else{let i=t?.toVersion??"latest";o=await Rp("@medplum/app",i)}Ro(o,{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 Pp(o,s.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await it(n.appDistribution.PhysicalResourceId),console.log("Done")}async function Sp(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Eo(r)).json()}async function Rp(e,t){let n=(await Sp(e,t)).dist.tarball,s=dp(lt(yp(),"tarball-"));try{let o=await Eo(n),i=Qr(s);return await Ep(o.body,i),lt(s,"package","dist")}catch(o){throw hp(s,{recursive:!0,force:!0}),o}}function Ro(e,t){for(let r of mp(e,{withFileTypes:!0})){let n=lt(e,r.name);r.isDirectory()?Ro(n,t):r.isFile()&&n.endsWith(".js")&&Ap(n,t)}}function Ap(e,t){let r=fp(e,"utf-8");for(let[n,s]of Object.entries(t))r=r.replaceAll(`__${n}__`,s);gp(e,r)}async function Pp(e,t,r){let n=[["assets/**/*.css",B.CSS,!0],["assets/**/*.css.map",B.JSON,!0],["assets/**/*.js",B.JAVASCRIPT,!0],["assets/**/*.js.map",B.JSON,!0],["assets/**/*.txt",B.TEXT,!0],["assets/**/*.ico",B.FAVICON,!0],["img/**/*.png",B.PNG,!0],["img/**/*.svg",B.SVG,!0],["robots.txt",B.TEXT,!0],["index.html",B.HTML,!1]];for(let s of n)await bp({rootDir:e,bucketName:t,fileNamePattern:s[0],contentType:s[1],cached:s[2],dryrun:r.dryrun})}async function bp(e){let t=up.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Ip(lt(e.rootDir,r),e)}async function Ip(e,t){let r=pp(e),n=e.substring(t.rootDir.length+1).split(wp).join("/"),s={Bucket:t.bucketName,Key:n,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${n} to ${t.bucketName}...`),t.dryrun||await ve.send(new lp(s))}import{GetBucketPolicyCommand as vp,PutBucketPolicyCommand as Cp}from"@aws-sdk/client-s3";async function bo(e,t){if(!j(e,t))throw Y(e,t),new Error(`Config not found: ${e}`);let n=await ce(e);if(!n)throw await le(e),new Error(`Stack not found: ${e}`);try{await Ao("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t)}catch(s){console.error(`Error updating App bucket policy: ${s.message}`)}try{await Ao("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t)}catch(s){console.error(`Error updating Storage bucket policy: ${s.message}`)}console.log("Done")}async function Ao(e,t,r,n,s){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!n?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let o=t.PhysicalResourceId,i=n.PhysicalResourceId,a=await Tp(o);if(xp(a,o,i))throw new Error(`${e} bucket already has policy statement`);$p(a,o,i),e==="Storage"&&s.guarddutyMalwareProtection&&Np(a,o,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),s.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Op(o,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await it(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Tp(e){let t=await ve.send(new vp({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Op(e,t){await ve.send(new Cp({Bucket:e,Policy:JSON.stringify(t)}))}function xp(e,t,r){return!!e?.Statement?.some(n=>n?.Effect==="Allow"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(n?.Action)&&n?.Action?.includes("s3:GetObject*")&&n?.Action?.includes("s3:GetBucket*")&&n?.Action?.includes("s3:List*")&&Array.isArray(n?.Resource)&&n?.Resource?.includes(`arn:aws:s3:::${t}`)&&n?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function $p(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 Np(e,t,r){e.Statement?.some(n=>n?.Effect==="Deny"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Po(n,"s3:GetObject")&&Po(n,"s3:GetObjectVersion")&&n?.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 Po(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function Io(e,t){try{tt();let r=j(e,t);if(!r)throw Y(e,t),new Error(`Config not found: ${e}`);let n=Yr(e)??{};if(!t.yes&&Object.keys(n).length===0){let s=D(e,{server:!0});if(console.log(te.yellow(`Config file ${s} not found!`)),!await z("Do you want to proceed?")){console.log(te.red(`Run Aborted, please ensure ${s} is present and try again.`));return}}kp(r,n),Mp(r,n),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(te.yellow("Dry run - skipping updates!")):(t.yes||await z("Do you want to store these values in AWS Parameter Store?"))&&await ct(r.region,`/medplum/${r.name}/`,n)}finally{rt()}}function kp(e,t){ut(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),ut(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),ut(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),ut(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function ut(e,t,r){if(Lp(e,t))throw new Error(r)}function Lp(e,t){return e!==void 0&&t!==void 0&&e!==t}function Mp(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 ue=Sr(sr(),1);import{spawnSync as Dp}from"node:child_process";async function Co(e,t){let r=await A(t),n=j(e,t);if(!n)throw console.log(`Configuration file ${D(e)} not found`),Y(e,t),new Error(`Config not found: ${e}`);let s=n.serverImage.lastIndexOf(":"),o=n.serverImage.slice(0,s),i=await _p(r,n),a=await vo(i);for(;a;){if(t.toVersion&&ue.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),n.serverImage=`${o}:${a}`,Up(e,n),await r.startAsyncRequest("/admin/super/migrate"),a=await vo(a)}}async function _p(e,t){let r=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(r+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let o=n.indexOf("-");o>-1&&(n=n.slice(0,o))}return n}async function vo(e,t){let r=await at(e),n=r[0];return r.filter(s=>s===n||s===t||ue.gte(s,ue.inc(e,"minor"))).pop()}function Up(e,t){let r=D(e);v(r,t);let n=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let s=Dp(n,{stdio:"inherit"});if(s.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${s.status}): ${s.stderr}`);console.log(s.stdout)}function To(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(yo),e.command("list").description("List Medplum AWS CloudFormation stacks").action(wo),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(po),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(_t(`Update the AWS Parameter Store config values.
7
+ `)}function N(e,t=""){return new Promise(r=>{et.question(e+(t?" ("+t+")":"")+" ",n=>{r(n||t.toString())})})}async function nt(e,t,r=""){let n=e+" ["+t.map(s=>s===r?"("+s+")":s).join("|")+"]";for(;;){let s=await N(n)||r;if(t.includes(s))return s;c("Please choose one of the following options: "+t.join(", "))}}async function ae(e,t,r){return Number.parseInt(await nt(e,t.map(n=>n.toString()),r.toString()),10)}async function z(e){return(await nt(e,["y","n"])).toLowerCase()==="y"}async function Ie(e){if(!await z(e))throw c("Exiting..."),new Error("User cancelled")}var st=new lo({}),Ku=new xu({region:"us-east-1"}),Uh=new Nu({}),ve=new ku({}),qu="medplum:environment";async function or(){let e=[],t=Ou({client:st},{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 n of r.StackSummaries??ju)e.push(n);return e}async function ce(e){let t=await or();for(let r of t){let n=r.StackName,s=await ir(n);if(s?.tag===e)return s}}async function ir(e){let t={};if(await co(st,e,t),await st.config.region()!=="us-east-1")try{await co(new lo({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function co(e,t,r){let n=new Tu({StackName:t}),o=(await e.send(n))?.Stacks?.[0],i=o?.Tags?.find(l=>l.Key===qu);if(!i)return;let a=await e.send(new Cu({StackName:t}));if(a.StackResources){e===st&&(r.stack=o,r.tag=i.Value);for(let l of a.StackResources)Hu(l,r)}}function Hu(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 ot(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: ${Gu(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 Gu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function it(e){let t=await Ku.send(new $u({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function at(e){let n=(await(await Bu("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(s=>s.tag_name.startsWith("v")?s.tag_name.slice(1):s.tag_name);return n.sort((s,o)=>uo.compare(o,s)),e?n.slice(0,n.indexOf(e)):n}async function ct(e,t,r){let n=new Du({region:e});for(let[s,o]of Object.entries(r)){let i=t+s,a=typeof o=="object"?JSON.stringify(o):o.toString(),l=await Vu(n,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ie(`Do you want to overwrite "${i}"?`)),await Ju(n,i,a)}}async function Vu(e,t){let r=new Lu({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function Ju(e,t,r){let n=new Mu({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(n)}function Y(e,t){if(console.log(`Config not found: ${e} (${D(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[s,o]of n)console.log(` ${s}: ${o}`)}}console.log();let r=Wu(".",{withFileTypes:!0});if(r=r.filter(n=>n.isFile()&&n.name.startsWith("medplum.")&&n.name.endsWith(".json")).map(n=>n.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let n of r)console.log(` ${n.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${n})`)}}async function le(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new Uu,r=new _u({}),n=await t.send(r),s=await t.config.region();console.log("AWS Region: ",s),console.log("AWS Account ID: ",n.Account),console.log("AWS Account ARN: ",n.Arn),console.log("AWS User ID: ",n.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",Fu(t))}}async function po(e){let t=await ce(e);if(!t)throw await le(e),new Error(`Stack not found: ${e}`);ot(t)}import{ACMClient as ho,ListCertificatesCommand as Xu,RequestCertificateCommand as zu}from"@aws-sdk/client-acm";import{CloudFrontClient as Yu,CreatePublicKeyCommand as Qu}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as Zu,STSClient as ep}from"@aws-sdk/client-sts";import{normalizeErrorString as tp}from"@medplum/core";import{generateKeyPairSync as rp,randomUUID as mo}from"node:crypto";import{existsSync as np}from"node:fs";var sp=e=>`${e}DomainName`,go=e=>`${e}SslCertArn`;async function yo(){let e={apiPort:8103,region:"us-east-1"};tt(),I("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await op(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await Ie("Do you want to continue without AWS credentials?")),I("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await N("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),I("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await N("What is the config file name?",`medplum.${e.name}.config.json`);np(r)&&(c("Config file already exists."),await Ie("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),v(r,e),I("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await N("Enter your AWS region:","us-east-1"),v(r,e),I("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await N("What is your AWS account number?",t),v(r,e),I("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let n="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",n),v(r,e),I("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await N("Enter your base domain name:");v(r,e),I("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let s=await N("Enter your support email address:");I("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await N("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,v(r,e),I("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await N("Enter your web application domain name:","app."+e.domainName),v(r,e),I("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),v(r,e),I("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await N("Enter your storage bucket name:",e.storageDomainName),v(r,e),I("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await ae("Enter the maximum number of availability zones:",[2,3,99],2),I("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await z("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await ae("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),v(r,e),I("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await ae("Enter the number of server instances:",[1,2,3,4,6,8],1),v(r,e),I("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await ae("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),v(r,e),I("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await ae("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),v(r,e),I("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let o=(await at())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${o}`),v(r,e),I("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await lp(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,v(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),I("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await ip(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:f}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await ap(e,a,u,f);e[go(f)]=m,v(r,e)}I("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:s};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await z("Do you want to store these values in AWS Parameter Store?"))await ct(e.region,`/medplum/${e.name}/`,l);else{let u=D(e.name,{server:!0});v(u,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${u}`),c("Please add these values to AWS Parameter Store manually.")}I("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),rt()}async function op(e){try{let t=new ep({region:e}),r=new Zu({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function ip(e){let t=await fo(e);if(e!=="us-east-1"){let r=await fo("us-east-1");t.push(...r)}return t}async function fo(e){try{let t=new ho({region:e}),r=new Xu({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function ap(e,t,r,n){let s=e[sp(n)],o=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===s);if(o)return c(`Found existing certificate for "${s}" in "${r}.`),o.CertificateArn;if(c(`No existing certificate found for "${s}" in "${r}.`),!await z("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${go(n)}" setting.`),"TODO";let i=await cp(r,s);return c("Certificate ARN: "+i),i}async function cp(e,t){try{let r=await nt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new ho({region:e}),s=new zu({DomainName:t,ValidationMethod:r.toUpperCase()});return(await n.send(s)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function lp(e,t){let r=mo(),n=rp("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Yu({region:e}).send(new Qu({PublicKeyConfig:{Name:t,CallerReference:mo(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:r}}catch(s){console.log("Error: Unable to create signing key: ",tp(s));return}}async function wo(){let e=await or();for(let t of e){let r=t.StackName,n=await ir(r);n&&(ot(n),console.log(""))}}import{PutObjectCommand as up}from"@aws-sdk/client-s3";import{ContentType as B}from"@medplum/core";import pp from"fast-glob";import Eo from"node-fetch";import{createReadStream as dp,mkdtempSync as mp,readdirSync as fp,readFileSync as hp,rmSync as gp,writeFileSync as yp}from"node:fs";import{tmpdir as wp}from"node:os";import{join as lt,sep as Ep}from"node:path";import{pipeline as Sp}from"node:stream/promises";async function So(e,t){let r=j(e,t);if(!r)throw Y(e,t),new Error(`Config not found: ${e}`);let n=await ce(e);if(!n)throw await le(e),new Error(`Stack not found: ${e}`);let s=n.appBucket;if(!s)throw new Error(`App bucket not found for stack ${e}`);let o;if(t.tarPath)o=t.tarPath;else{let i=t?.toVersion??"latest";o=await Ap("@medplum/app",i)}Ro(o,{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 bp(o,s.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await it(n.appDistribution.PhysicalResourceId),console.log("Done")}async function Rp(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Eo(r)).json()}async function Ap(e,t){let n=(await Rp(e,t)).dist.tarball,s=mp(lt(wp(),"tarball-"));try{let o=await Eo(n),i=Qr(s);return await Sp(o.body,i),lt(s,"package","dist")}catch(o){throw gp(s,{recursive:!0,force:!0}),o}}function Ro(e,t){for(let r of fp(e,{withFileTypes:!0})){let n=lt(e,r.name);r.isDirectory()?Ro(n,t):r.isFile()&&n.endsWith(".js")&&Pp(n,t)}}function Pp(e,t){let r=hp(e,"utf-8");for(let[n,s]of Object.entries(t))r=r.replaceAll(`__${n}__`,s);yp(e,r)}async function bp(e,t,r){let n=[["assets/**/*.css",B.CSS,!0],["assets/**/*.css.map",B.JSON,!0],["assets/**/*.js",B.JAVASCRIPT,!0],["assets/**/*.js.map",B.JSON,!0],["assets/**/*.txt",B.TEXT,!0],["assets/**/*.ico",B.FAVICON,!0],["img/**/*.png",B.PNG,!0],["img/**/*.svg",B.SVG,!0],["robots.txt",B.TEXT,!0],["index.html",B.HTML,!1]];for(let s of n)await Ip({rootDir:e,bucketName:t,fileNamePattern:s[0],contentType:s[1],cached:s[2],dryrun:r.dryrun})}async function Ip(e){let t=pp.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await vp(lt(e.rootDir,r),e)}async function vp(e,t){let r=dp(e),n=e.substring(t.rootDir.length+1).split(Ep).join("/"),s={Bucket:t.bucketName,Key:n,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${n} to ${t.bucketName}...`),t.dryrun||await ve.send(new up(s))}import{GetBucketPolicyCommand as Cp,PutBucketPolicyCommand as Tp}from"@aws-sdk/client-s3";async function bo(e,t){if(!j(e,t))throw Y(e,t),new Error(`Config not found: ${e}`);let n=await ce(e);if(!n)throw await le(e),new Error(`Stack not found: ${e}`);try{await Ao("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t)}catch(s){console.error(`Error updating App bucket policy: ${s.message}`)}try{await Ao("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t)}catch(s){console.error(`Error updating Storage bucket policy: ${s.message}`)}console.log("Done")}async function Ao(e,t,r,n,s){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!n?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let o=t.PhysicalResourceId,i=n.PhysicalResourceId,a=await Op(o);if($p(a,o,i))throw new Error(`${e} bucket already has policy statement`);Np(a,o,i),e==="Storage"&&s.guarddutyMalwareProtection&&kp(a,o,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),s.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await xp(o,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await it(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Op(e){let t=await ve.send(new Cp({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function xp(e,t){await ve.send(new Tp({Bucket:e,Policy:JSON.stringify(t)}))}function $p(e,t,r){return!!e?.Statement?.some(n=>n?.Effect==="Allow"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(n?.Action)&&n?.Action?.includes("s3:GetObject*")&&n?.Action?.includes("s3:GetBucket*")&&n?.Action?.includes("s3:List*")&&Array.isArray(n?.Resource)&&n?.Resource?.includes(`arn:aws:s3:::${t}`)&&n?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Np(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 kp(e,t,r){e.Statement?.some(n=>n?.Effect==="Deny"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Po(n,"s3:GetObject")&&Po(n,"s3:GetObjectVersion")&&n?.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 Po(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function Io(e,t){try{tt();let r=j(e,t);if(!r)throw Y(e,t),new Error(`Config not found: ${e}`);let n=Yr(e)??{};if(!t.yes&&Object.keys(n).length===0){let s=D(e,{server:!0});if(console.log(te.yellow(`Config file ${s} not found!`)),!await z("Do you want to proceed?")){console.log(te.red(`Run Aborted, please ensure ${s} is present and try again.`));return}}Lp(r,n),Dp(r,n),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(te.yellow("Dry run - skipping updates!")):(t.yes||await z("Do you want to store these values in AWS Parameter Store?"))&&await ct(r.region,`/medplum/${r.name}/`,n)}finally{rt()}}function Lp(e,t){ut(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),ut(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),ut(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),ut(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function ut(e,t,r){if(Mp(e,t))throw new Error(r)}function Mp(e,t){return e!==void 0&&t!==void 0&&e!==t}function Dp(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 ue=Sr(sr(),1);import{spawnSync as _p}from"node:child_process";async function Co(e,t){let r=await A(t),n=j(e,t);if(!n)throw console.log(`Configuration file ${D(e)} not found`),Y(e,t),new Error(`Config not found: ${e}`);let s=n.serverImage.lastIndexOf(":"),o=n.serverImage.slice(0,s),i=await Up(r,n),a=await vo(i);for(;a;){if(t.toVersion&&ue.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),n.serverImage=`${o}:${a}`,jp(e,n),await r.startAsyncRequest("/admin/super/migrate"),a=await vo(a)}}async function Up(e,t){let r=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(r+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let o=n.indexOf("-");o>-1&&(n=n.slice(0,o))}return n}async function vo(e,t){let r=await at(e),n=r[0];return r.filter(s=>s===n||s===t||ue.gte(s,ue.inc(e,"minor"))).pop()}function jp(e,t){let r=D(e);v(r,t);let n=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let s=_p(n,{stdio:"inherit"});if(s.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${s.status}): ${s.stderr}`);console.log(s.stdout)}function To(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(yo),e.command("list").description("List Medplum AWS CloudFormation stacks").action(wo),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(po),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(_t(`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
11
  `+te.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",_t("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(Io),y(e,new g("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(Co)),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(So),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(bo),e}var Oo=new g("save"),xo=new g("deploy"),$o=new g("create"),Ce=new g("bot");y(Ce,Oo);y(Ce,xo);y(Ce,$o);var ar=new g("save-bot"),cr=new g("deploy-bot"),lr=new g("create-bot");Oo.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await pt(r,e)});xo.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await pt(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,n,s)=>{let o=await A(s);await Nt(o,e,t,r,n,s.runtimeVersion,!!s.writeConfig)});async function pt(e,t,r=!1){let n=zr(t),s=[],o=[],i=0,a=0;for(let l of n)try{let u=await e.readResource("Bot",l.id);await xt(e,l,u),i++,r&&(await $t(e,l,u),a++)}catch(u){s.push(u),o.push(`${l.name} [${l.id}]`)}if(console.log(`Number of bots saved: ${i}`),console.log(`Number of bots deployed: ${a}`),console.log(`Number of errors: ${s.length}`),s.length)throw new Error(`${s.length} bot(s) had failures. Bots with failures:
12
12
 
13
13
  ${o.join(`
14
- `)}`,{cause:s})}ar.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await pt(r,e)});cr.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await pt(r,e,!0)});lr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,n,s)=>{let o=await A(s);await Nt(o,e,t,r,n)});import{EMPTY as ko}from"@medplum/core";import{createReadStream as jp,createWriteStream as Fp}from"node:fs";import{resolve as Lo}from"node:path";import{createInterface as Bp}from"node:readline";import{Readable as Wp}from"node:stream";import{pipeline as Kp}from"node:stream/promises";var Mo=new g("export"),Do=new g("import"),dt=new g("bulk");y(dt,Mo);y(dt,Do);Mo.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:n,targetDirectory:s}=e,o=await A(e),i=await o.bulkExport(t,r,n,{pollStatusOnAccepted:!0});for(let{type:a,url:l}of i.output??ko){let u=new URL(l),f=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",m=Lo(s??"",f),S=await o.downloadResponse(l);if(!S.ok)throw new Error(`Download failed: ${S.status} ${S.statusText}`);if(!S.body)throw new Error("Download response missing body");let h=Wp.fromWeb(S.body);await Kp(h,Fp(m)),console.log(`${m} is created`)}});Do.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:n,targetDirectory:s}=t,o=Lo(s??process.cwd(),e),i=await A(t);await qp(o,Number.parseInt(r,10),i,n)});async function qp(e,t,r,n){let s=[],o=jp(e),i=Bp({input:o});for await(let a of i){let l=Hp(a,n);s.push({resource:l,request:{method:"POST",url:l.resourceType}}),s.length%t===0&&(await No(s,r),s=[])}s.length>0&&await No(s,r)}async function No(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let n of r.entry??ko)H(n.response)}function Hp(e,t){let r=JSON.parse(e);return t?Gp(r):r}function Gp(e){return e.resourceType==="ExplanationOfBenefit"?Vp(e):e}function Vp(e){return e.provider||(e.provider=kt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=kt())}),e}import{formatHl7DateTime as ad,Hl7Message as cd}from"@medplum/core";import mt from"node:assert";import zp from"node:net";import{Hl7Message as Yp,OperationOutcomeError as pe,ReturnAckCategory as _o,sleep as Qp,validationError as Zp}from"@medplum/core";import Uo from"iconv-lite";import{ReturnAckCategory as Yg}from"@medplum/core";import{sleep as sd}from"@medplum/core";import od from"node:net";var Jp=Object.defineProperty,Xp=(e,t,r)=>t in e?Jp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,R=(e,t,r)=>Xp(e,typeof t!="symbol"?t+"":t,r),Fo=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var ed=class extends Event{constructor(e,t){super("message"),R(this,"connection"),R(this,"message"),this.connection=e,this.message=t}},td=class extends Event{constructor(e,t){super("enhancedAckSent"),R(this,"connection"),R(this,"message"),this.connection=e,this.message=t}},Te=class extends Event{constructor(e){super("error"),R(this,"error"),this.error=e}},ur=class extends Event{constructor(e){super("warning"),R(this,"error"),this.error=e}},pr=class extends Event{constructor(){super("close")}},jo="utf-8",rd=5e3,nd=60*1e3,Bo=class extends Fo{constructor(e,t=jo,r,n={}){super(),R(this,"socket"),R(this,"encoding"),R(this,"enhancedMode"),R(this,"messagesPerMin"),R(this,"gracefulCloseTimeoutMs"),R(this,"chunks",[]),R(this,"pendingMessages",new Map),R(this,"responseQueue",[]),R(this,"lastMessageDispatchedTime",0),R(this,"responseQueueProcessing",!1),R(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=n.messagesPerMin,this.gracefulCloseTimeoutMs=n.gracefulCloseTimeoutMs??rd,e.on("data",s=>{if(this.closing){this.dispatchEvent(new ur(new pe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(s);let o=this.parseMessages();for(let i of o)this.responseQueue.push(new ed(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Te(i))})}catch(o){this.dispatchEvent(new Te(o))}}),e.on("error",s=>{this.resetBuffer(),this.dispatchEvent(new Te(s))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new pr)}),this.addEventListener("message",s=>{let o;this.enhancedMode==="standard"?o=s.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(o=s.message.buildAck({ackCode:"AA"})),o&&(this.send(o),this.dispatchEvent(new td(this,o)));let i=s.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.getPendingMessage(i);if(!a){this.dispatchEvent(new ur(new pe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${i}' but there was no pending message with this control ID`}]})));return}let l=s.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===_o.APPLICATION&&l==="CA"||(a.timer&&clearTimeout(a.timer),a.resolve(s.message),this.deletePendingMessage(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Uo.encode(t,this.encoding),n=Buffer.alloc(r.length+3);n.writeInt8(11,0),r.copy(n,1),n.writeInt8(28,r.length+1),n.writeInt8(13,r.length+2),this.socket.write(n)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=nd/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await Qp(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 n=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){n=a+1;break}if(n===-1)break;let s=t.subarray(r,n+1).subarray(1,-2),o=Uo.decode(s,this.encoding),i=Yp.parse(o);e.push(i),r=n+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,n)=>{let s=e.getSegment("MSH")?.getField(10)?.toString();if(!s){n(new pe(Zp("Required field missing: MSH.10")));return}let o;t?.timeoutMs&&(o=setTimeout(()=>{this.deletePendingMessage(s),n(new pe({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(s,{message:e,resolve:r,reject:n,returnAck:t?.returnAck??_o.APPLICATION,timer:o}),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 pe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Te(new pe({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??jo}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)}},Wo=class extends Fo{constructor(e){super(),R(this,"options"),R(this,"host"),R(this,"port"),R(this,"encoding"),R(this,"connection"),R(this,"keepAlive"),R(this,"socket"),R(this,"connectTimeout"),R(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=zp.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){mt(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let n=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,n)};t.on("timeout",r)}registerSocketConnectListener(e){mt(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let n;this.connection=n=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(n),e.resolve(n)};t.on("connect",r)}registerSocketErrorListener(e){mt(this.socket);let t=this.socket,r=n=>{this.cleanupSocket(t),n.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,n.errors[0]):this.rejectDeferredPromise(e,n)};t.on("error",r)}registerSocketCloseListener(e){mt(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 pr)}),e.addEventListener("error",t=>{this.dispatchEvent(new Te(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new ur(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),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,n){return new Bo(e,t,r,n)}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 pr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},id=1e4,Ko=class{constructor(e){R(this,"handler"),R(this,"server"),R(this,"encoding"),R(this,"enhancedMode"),R(this,"messagesPerMin"),R(this,"connections",new Set),this.handler=e}async start(e,t,r,n){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),n?.messagesPerMin!==void 0&&this.setMessagesPerMin(n.messagesPerMin);let s=od.createServer(o=>{let i=new Bo(o,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});return new Promise((o,i)=>{let a=u=>{s.listen(u,()=>{let f=s.address().port;o(f)})},l=u=>{u?.code==="EADDRINUSE"?s.close(()=>sd(50).then(()=>a(e))):i(u)};s.on("error",l),s.once("listening",()=>{s.off("error",l)}),a(e),this.server=s})}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 n;e?.forceDrainTimeoutMs!==-1&&(n=setTimeout(()=>{for(let s of this.connections)s.close().catch(console.error)},e?.forceDrainTimeoutMs??id)),this.server.close(s=>{if(s){r(s);return}n&&clearTimeout(n),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}};import{readFileSync as ld}from"node:fs";var ud=new g("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,n)=>{if(n.generateExample?r=dd():n.file&&(r=ld(n.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new Wo({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let o=await s.sendAndWait(cd.parse(r));console.log(o.toString().replaceAll("\r",`
15
- `))}finally{await s.close()}}),pd=new g("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new Ko(n=>{n.addEventListener("message",({message:s})=>{console.log(s.toString().replaceAll("\r",`
16
- `)),n.send(s.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),ft=new g("hl7");y(ft,ud);y(ft,pd);function dd(){let e=ad(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
14
+ `)}`,{cause:s})}ar.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await pt(r,e)});cr.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await pt(r,e,!0)});lr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,n,s)=>{let o=await A(s);await Nt(o,e,t,r,n)});import{EMPTY as ko}from"@medplum/core";import{createReadStream as Fp,createWriteStream as Bp}from"node:fs";import{resolve as Lo}from"node:path";import{createInterface as Wp}from"node:readline";import{Readable as Kp}from"node:stream";import{pipeline as qp}from"node:stream/promises";var Mo=new g("export"),Do=new g("import"),dt=new g("bulk");y(dt,Mo);y(dt,Do);Mo.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:n,targetDirectory:s}=e,o=await A(e),i=await o.bulkExport(t,r,n,{pollStatusOnAccepted:!0});for(let{type:a,url:l}of i.output??ko){let u=new URL(l),f=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",m=Lo(s??"",f),S=await o.downloadResponse(l);if(!S.ok)throw new Error(`Download failed: ${S.status} ${S.statusText}`);if(!S.body)throw new Error("Download response missing body");let h=Kp.fromWeb(S.body);await qp(h,Bp(m)),console.log(`${m} is created`)}});Do.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:n,targetDirectory:s}=t,o=Lo(s??process.cwd(),e),i=await A(t);await Hp(o,Number.parseInt(r,10),i,n)});async function Hp(e,t,r,n){let s=[],o=Fp(e),i=Wp({input:o});for await(let a of i){let l=Gp(a,n);s.push({resource:l,request:{method:"POST",url:l.resourceType}}),s.length%t===0&&(await No(s,r),s=[])}s.length>0&&await No(s,r)}async function No(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let n of r.entry??ko)H(n.response)}function Gp(e,t){let r=JSON.parse(e);return t?Vp(r):r}function Vp(e){return e.resourceType==="ExplanationOfBenefit"?Jp(e):e}function Jp(e){return e.provider||(e.provider=kt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=kt())}),e}import{formatHl7DateTime as cd,Hl7Message as ld}from"@medplum/core";import mt from"node:assert";import Yp from"node:net";import{Hl7Message as Qp,OperationOutcomeError as pe,ReturnAckCategory as _o,sleep as Zp,validationError as ed}from"@medplum/core";import Uo from"iconv-lite";import{ReturnAckCategory as Qg}from"@medplum/core";import{sleep as od}from"@medplum/core";import id from"node:net";var Xp=Object.defineProperty,zp=(e,t,r)=>t in e?Xp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,R=(e,t,r)=>zp(e,typeof t!="symbol"?t+"":t,r),Fo=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var td=class extends Event{constructor(e,t){super("message"),R(this,"connection"),R(this,"message"),this.connection=e,this.message=t}},rd=class extends Event{constructor(e,t){super("enhancedAckSent"),R(this,"connection"),R(this,"message"),this.connection=e,this.message=t}},Te=class extends Event{constructor(e){super("error"),R(this,"error"),this.error=e}},ur=class extends Event{constructor(e){super("warning"),R(this,"error"),this.error=e}},pr=class extends Event{constructor(){super("close")}},jo="utf-8",nd=5e3,sd=60*1e3,Bo=class extends Fo{constructor(e,t=jo,r,n={}){super(),R(this,"socket"),R(this,"encoding"),R(this,"enhancedMode"),R(this,"messagesPerMin"),R(this,"gracefulCloseTimeoutMs"),R(this,"chunks",[]),R(this,"pendingMessages",new Map),R(this,"responseQueue",[]),R(this,"lastMessageDispatchedTime",0),R(this,"responseQueueProcessing",!1),R(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=n.messagesPerMin,this.gracefulCloseTimeoutMs=n.gracefulCloseTimeoutMs??nd,e.on("data",s=>{if(this.closing){this.dispatchEvent(new ur(new pe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(s);let o=this.parseMessages();for(let i of o)this.responseQueue.push(new td(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Te(i))})}catch(o){this.dispatchEvent(new Te(o))}}),e.on("error",s=>{this.resetBuffer(),this.dispatchEvent(new Te(s))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new pr)}),this.addEventListener("message",s=>{let o;this.enhancedMode==="standard"?o=s.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(o=s.message.buildAck({ackCode:"AA"})),o&&(this.send(o),this.dispatchEvent(new rd(this,o)));let i=s.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.getPendingMessage(i);if(!a){this.dispatchEvent(new ur(new pe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${i}' but there was no pending message with this control ID`}]})));return}let l=s.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===_o.APPLICATION&&l==="CA"||(a.timer&&clearTimeout(a.timer),a.resolve(s.message),this.deletePendingMessage(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Uo.encode(t,this.encoding),n=Buffer.alloc(r.length+3);n.writeInt8(11,0),r.copy(n,1),n.writeInt8(28,r.length+1),n.writeInt8(13,r.length+2),this.socket.write(n)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=sd/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await Zp(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 n=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){n=a+1;break}if(n===-1)break;let s=t.subarray(r,n+1).subarray(1,-2),o=Uo.decode(s,this.encoding),i=Qp.parse(o);e.push(i),r=n+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,n)=>{let s=e.getSegment("MSH")?.getField(10)?.toString();if(!s){n(new pe(ed("Required field missing: MSH.10")));return}let o;t?.timeoutMs&&(o=setTimeout(()=>{this.deletePendingMessage(s),n(new pe({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(s,{message:e,resolve:r,reject:n,returnAck:t?.returnAck??_o.APPLICATION,timer:o}),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 pe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Te(new pe({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??jo}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)}},Wo=class extends Fo{constructor(e){super(),R(this,"options"),R(this,"host"),R(this,"port"),R(this,"encoding"),R(this,"connection"),R(this,"keepAlive"),R(this,"socket"),R(this,"connectTimeout"),R(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=Yp.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){mt(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let n=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,n)};t.on("timeout",r)}registerSocketConnectListener(e){mt(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let n;this.connection=n=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(n),e.resolve(n)};t.on("connect",r)}registerSocketErrorListener(e){mt(this.socket);let t=this.socket,r=n=>{this.cleanupSocket(t),n.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,n.errors[0]):this.rejectDeferredPromise(e,n)};t.on("error",r)}registerSocketCloseListener(e){mt(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 pr)}),e.addEventListener("error",t=>{this.dispatchEvent(new Te(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new ur(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),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,n){return new Bo(e,t,r,n)}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 pr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},ad=1e4,Ko=class{constructor(e){R(this,"handler"),R(this,"server"),R(this,"encoding"),R(this,"enhancedMode"),R(this,"messagesPerMin"),R(this,"connections",new Set),this.handler=e}async start(e,t,r,n){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),n?.messagesPerMin!==void 0&&this.setMessagesPerMin(n.messagesPerMin);let s=id.createServer(o=>{let i=new Bo(o,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});return new Promise((o,i)=>{let a=u=>{s.listen(u,()=>{let f=s.address().port;o(f)})},l=u=>{u?.code==="EADDRINUSE"?s.close(()=>od(50).then(()=>a(e))):i(u)};s.on("error",l),s.once("listening",()=>{s.off("error",l)}),a(e),this.server=s})}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 n;e?.forceDrainTimeoutMs!==-1&&(n=setTimeout(()=>{for(let s of this.connections)s.close().catch(console.error)},e?.forceDrainTimeoutMs??ad)),this.server.close(s=>{if(s){r(s);return}n&&clearTimeout(n),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}};import{readFileSync as ud}from"node:fs";var pd=new g("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,n)=>{if(n.generateExample?r=md():n.file&&(r=ud(n.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new Wo({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let o=await s.sendAndWait(ld.parse(r));console.log(o.toString().replaceAll("\r",`
15
+ `))}finally{await s.close()}}),dd=new g("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new Ko(n=>{n.addEventListener("message",({message:s})=>{console.log(s.toString().replaceAll("\r",`
16
+ `)),n.send(s.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),ft=new g("hl7");y(ft,pd);y(ft,dd);function md(){let e=cd(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
17
17
  EVN|A01|${e}||
18
18
  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|
19
- PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}import{readdirSync as md}from"node:fs";import{homedir as fd}from"node:os";import{resolve as hd}from"node:path";var qo=new g("set"),Ho=new g("remove"),Go=new g("list"),Vo=new g("describe"),de=new g("profile");y(de,qo);y(de,Ho);y(de,Go);y(de,Vo);qo.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)=>{Ue(e,t)});Ho.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new _(e).setObject("options",void 0),console.log(`${e} profile removed`)});Go.description("List all profiles saved").action(async()=>{let e=hd(fd(),".medplum"),t=md(e),r=[];t.forEach(n=>{let s=n.split(".")[0],i=new _(s).getObject("options");i&&r.push({profileName:s,profile:i})}),console.log(r)});Vo.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Zr(e);console.log(t)});import{Option as gd}from"commander";var Jo=new g("list"),Xo=new g("current"),zo=new g("switch"),Yo=new g("invite"),me=new g("project");y(me,Jo);y(me,Xo);y(me,zo);y(me,Yo);Jo.description("List of current projects").action(async e=>{let t=await A(e);yd(t)});function yd(e){let r=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
19
+ PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}import{readdirSync as fd}from"node:fs";import{homedir as hd}from"node:os";import{resolve as gd}from"node:path";var qo=new g("set"),Ho=new g("remove"),Go=new g("list"),Vo=new g("describe"),de=new g("profile");y(de,qo);y(de,Ho);y(de,Go);y(de,Vo);qo.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)=>{Ue(e,t)});Ho.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new _(e).setObject("options",void 0),console.log(`${e} profile removed`)});Go.description("List all profiles saved").action(async()=>{let e=gd(hd(),".medplum"),t=fd(e),r=[];t.forEach(n=>{let s=n.split(".")[0],i=new _(s).getObject("options");i&&r.push({profileName:s,profile:i})}),console.log(r)});Vo.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Zr(e);console.log(t)});import{Option as yd}from"commander";var Jo=new g("list"),Xo=new g("current"),zo=new g("switch"),Yo=new g("invite"),me=new g("project");y(me,Jo);y(me,Xo);y(me,zo);y(me,Yo);Jo.description("List of current projects").action(async e=>{let t=await A(e);wd(t)});function wd(e){let r=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
20
20
 
21
- `);console.log(r)}Xo.description("Project you are currently on").action(async e=>{let r=(await A(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});zo.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await A(t);await wd(r,e)});Yo.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 gd("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,n)=>{let s=await A(n),o=s.getActiveLogin();if(!o)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!o?.project?.reference)throw new Error("No current project to invite user to");let i=o.project.reference.split("/")[1],a={resourceType:n.role,firstName:e,lastName:t,email:r,sendEmail:!!n.sendEmail,admin:!!n.admin};await Ed(i,a,s)});async function wd(e,t){let n=e.getLogins().find(s=>s.project.reference?.includes(t));if(!n)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(n),console.log(`Switched to project ${t}
22
- `)}async function Ed(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")}import{convertToTransactionBundle as Sd}from"@medplum/core";var dr=new g("delete"),mr=new g("get"),fr=new g("patch"),hr=new g("post"),gr=new g("put");dr.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await A(t);H(await r.delete(Oe(r,e)))});mr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await A(t),n=await r.get(Oe(r,e));t.asTransaction?H(Sd(n)):H(n)});fr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await A(r);H(await n.patch(Oe(n,e),yr(t)))});hr.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let n=await A(r),s=r.preferAsync?{Prefer:"respond-async"}:void 0;H(await n.post(Oe(n,e),yr(t),void 0,{headers:s}))});gr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await A(r);H(await n.put(Oe(n,e),yr(t)))});function yr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Oe(e,t){return["admin/","auth/","fhir/R4"].some(n=>t.startsWith(n))?t:e.fhirUrl(t).toString()}async function bd(e){let t=new g("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>","JWT scope").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 Ad("--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(Rd),t.configureHelp({showGlobalOptions:!0}),y(t,Lt),y(t,Mt),y(t,Dt),y(t,mr),y(t,hr),y(t,fr),y(t,gr),y(t,dr),y(t,me),y(t,dt),y(t,Ce),y(t,J),y(t,ar),y(t,cr),y(t,lr),y(t,de),y(t,To()),y(t,ft);try{await t.parseAsync(e)}catch(r){Id(r)}}function Id(e){let t=1,r=!0;if(e instanceof Qo&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){wr(e,!!process.env.VERBOSE);let n=e.cause;if(process.env.VERBOSE)if(Array.isArray(n))for(let s of n)wr(s,!0);else n instanceof Error&&wr(n,!0)}process.exit(t)}function wr(e,t=!1){if(t){console.error(e);return}e instanceof Qo?process.stderr.write(`${Er(e)}
21
+ `);console.log(r)}Xo.description("Project you are currently on").action(async e=>{let r=(await A(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});zo.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await A(t);await Ed(r,e)});Yo.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 yd("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,n)=>{let s=await A(n),o=s.getActiveLogin();if(!o)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!o?.project?.reference)throw new Error("No current project to invite user to");let i=o.project.reference.split("/")[1],a={resourceType:n.role,firstName:e,lastName:t,email:r,sendEmail:!!n.sendEmail,admin:!!n.admin};await Sd(i,a,s)});async function Ed(e,t){let n=e.getLogins().find(s=>s.project.reference?.includes(t));if(!n)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(n),console.log(`Switched to project ${t}
22
+ `)}async function Sd(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")}import{convertToTransactionBundle as Rd}from"@medplum/core";var dr=new g("delete"),mr=new g("get"),fr=new g("patch"),hr=new g("post"),gr=new g("put");dr.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await A(t);H(await r.delete(Oe(r,e)))});mr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await A(t),n=await r.get(Oe(r,e));t.asTransaction?H(Rd(n)):H(n)});fr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await A(r);H(await n.patch(Oe(n,e),yr(t)))});hr.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let n=await A(r),s=r.preferAsync?{Prefer:"respond-async"}:void 0;H(await n.post(Oe(n,e),yr(t),void 0,{headers:s}))});gr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await A(r);H(await n.put(Oe(n,e),yr(t)))});function yr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Oe(e,t){return["admin/","auth/","fhir/R4"].some(n=>t.startsWith(n))?t:e.fhirUrl(t).toString()}async function Id(e){let t=new g("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>","JWT scope").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 Pd("--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(Ad),t.configureHelp({showGlobalOptions:!0}),y(t,Lt),y(t,Mt),y(t,Dt),y(t,mr),y(t,hr),y(t,fr),y(t,gr),y(t,dr),y(t,me),y(t,dt),y(t,Ce),y(t,J),y(t,ar),y(t,cr),y(t,lr),y(t,de),y(t,To()),y(t,ft);try{await t.parseAsync(e)}catch(r){vd(r)}}function vd(e){let t=1,r=!0;if(e instanceof Qo&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){wr(e,!!process.env.VERBOSE);let n=e.cause;if(process.env.VERBOSE)if(Array.isArray(n))for(let s of n)wr(s,!0);else n instanceof Error&&wr(n,!0)}process.exit(t)}function wr(e,t=!1){if(t){console.error(e);return}e instanceof Qo?process.stderr.write(`${Er(e)}
23
23
  `):process.stderr.write(`Error: ${Er(e)}
24
- `)}async function vd(){Pd.config({quiet:!0}),await bd(process.argv)}import.meta.main&&vd().catch(e=>{console.error("Unhandled error:",Er(e)),process.exit(1)});export{Id as handleError,bd as main,vd as run};
24
+ `)}async function Cd(){bd.config({quiet:!0}),await Id(process.argv)}import.meta.main&&Cd().catch(e=>{console.error("Unhandled error:",Er(e)),process.exit(1)});export{vd as handleError,Id as main,Cd as run};
25
25
  //# sourceMappingURL=index.mjs.map