@medplum/cli 5.0.10 → 5.0.12

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 Ks=Object.create;var ft=Object.defineProperty;var qs=Object.getOwnPropertyDescriptor;var Hs=Object.getOwnPropertyNames;var Gs=Object.getPrototypeOf,Vs=Object.prototype.hasOwnProperty;var Js=(e,t,r)=>t in e?ft(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 Xs=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Hs(t))!Vs.call(e,n)&&n!==r&&ft(e,n,{get:()=>t[n],enumerable:!(o=qs(t,n))||o.enumerable});return e};var wr=(e,t,r)=>(r=e!=null?Ks(Gs(e)):{},Xs(t||!e||!e.__esModule?ft(r,"default",{value:e,enumerable:!0}):r,e));var P=(e,t,r)=>Js(e,typeof t!="symbol"?t+"":t,r);var we=w((tf,uo)=>{"use strict";var sa="2.0.0",ia=Number.MAX_SAFE_INTEGER||9007199254740991,aa=16,ca=250,la=["major","premajor","minor","preminor","patch","prepatch","prerelease"];uo.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:aa,MAX_SAFE_BUILD_LENGTH:ca,MAX_SAFE_INTEGER:ia,RELEASE_TYPES:la,SEMVER_SPEC_VERSION:sa,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ee=w((rf,po)=>{"use strict";var ua=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};po.exports=ua});var ne=w((F,mo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ut,MAX_SAFE_BUILD_LENGTH:pa,MAX_LENGTH:da}=we(),ma=Ee();F=mo.exports={};var fa=F.re=[],ha=F.safeRe=[],p=F.src=[],ga=F.safeSrc=[],d=F.t={},ya=0,jt="[a-zA-Z0-9-]",wa=[["\\s",1],["\\d",da],[jt,pa]],Ea=e=>{for(let[t,r]of wa)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let o=Ea(t),n=ya++;ma(e,n,t),d[e]=n,p[n]=t,ga[n]=o,fa[n]=new RegExp(t,r?"g":void 0),ha[n]=new RegExp(o,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 Fe=w((of,fo)=>{"use strict";var Sa=Object.freeze({loose:!0}),Ra=Object.freeze({}),Aa=e=>e?typeof e!="object"?Sa:e:Ra;fo.exports=Aa});var Ft=w((nf,yo)=>{"use strict";var ho=/^[0-9]+$/,go=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=ho.test(e),o=ho.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1},Pa=(e,t)=>go(t,e);yo.exports={compareIdentifiers:go,rcompareIdentifiers:Pa}});var T=w((sf,Eo)=>{"use strict";var Be=Ee(),{MAX_LENGTH:wo,MAX_SAFE_INTEGER:We}=we(),{safeRe:Ke,t:qe}=ne(),Ia=Fe(),{compareIdentifiers:Bt}=Ft(),Wt=class e{constructor(t,r){if(r=Ia(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>wo)throw new TypeError(`version is longer than ${wo} characters`);Be("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=t.trim().match(r.loose?Ke[qe.LOOSE]:Ke[qe.FULL]);if(!o)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>We||this.major<0)throw new TypeError("Invalid major version");if(this.minor>We||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>We||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<We)return s}return n}):this.prerelease=[],this.build=o[5]?o[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(Be("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 o=this.prerelease[r],n=t.prerelease[r];if(Be("prerelease compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return Bt(o,n)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let o=this.build[r],n=t.build[r];if(Be("build compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return Bt(o,n)}while(++r)}inc(t,r,o){if(t.startsWith("pre")){if(!r&&o===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=`-${r}`.match(this.options.loose?Ke[qe.PRERELEASELOOSE]:Ke[qe.PRERELEASE]);if(!n||n[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,o);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,o);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,o),this.inc("pre",r,o);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,o),this.inc("pre",r,o);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 n=Number(o)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&o===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];o===!1&&(s=[r]),Bt(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Eo.exports=Wt});var te=w((af,Ro)=>{"use strict";var So=T(),va=(e,t,r=!1)=>{if(e instanceof So)return e;try{return new So(e,t)}catch(o){if(!r)return null;throw o}};Ro.exports=va});var Po=w((cf,Ao)=>{"use strict";var ba=te(),Ca=(e,t)=>{let r=ba(e,t);return r?r.version:null};Ao.exports=Ca});var vo=w((lf,Io)=>{"use strict";var Ta=te(),Oa=(e,t)=>{let r=Ta(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Io.exports=Oa});var To=w((uf,Co)=>{"use strict";var bo=T(),xa=(e,t,r,o,n)=>{typeof r=="string"&&(n=o,o=r,r=void 0);try{return new bo(e instanceof bo?e.version:e,r).inc(t,o,n).version}catch{return null}};Co.exports=xa});var $o=w((pf,xo)=>{"use strict";var Oo=te(),$a=(e,t)=>{let r=Oo(e,null,!0),o=Oo(t,null,!0),n=r.compare(o);if(n===0)return null;let s=n>0,i=s?r:o,a=s?o: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 h=l?"pre":"";return r.major!==o.major?h+"major":r.minor!==o.minor?h+"minor":r.patch!==o.patch?h+"patch":"prerelease"};xo.exports=$a});var Lo=w((df,No)=>{"use strict";var Na=T(),La=(e,t)=>new Na(e,t).major;No.exports=La});var Do=w((mf,ko)=>{"use strict";var ka=T(),Da=(e,t)=>new ka(e,t).minor;ko.exports=Da});var _o=w((ff,Mo)=>{"use strict";var Ma=T(),_a=(e,t)=>new Ma(e,t).patch;Mo.exports=_a});var jo=w((hf,Uo)=>{"use strict";var Ua=te(),ja=(e,t)=>{let r=Ua(e,t);return r&&r.prerelease.length?r.prerelease:null};Uo.exports=ja});var k=w((gf,Bo)=>{"use strict";var Fo=T(),Fa=(e,t,r)=>new Fo(e,r).compare(new Fo(t,r));Bo.exports=Fa});var Ko=w((yf,Wo)=>{"use strict";var Ba=k(),Wa=(e,t,r)=>Ba(t,e,r);Wo.exports=Wa});var Ho=w((wf,qo)=>{"use strict";var Ka=k(),qa=(e,t)=>Ka(e,t,!0);qo.exports=qa});var He=w((Ef,Vo)=>{"use strict";var Go=T(),Ha=(e,t,r)=>{let o=new Go(e,r),n=new Go(t,r);return o.compare(n)||o.compareBuild(n)};Vo.exports=Ha});var Xo=w((Sf,Jo)=>{"use strict";var Ga=He(),Va=(e,t)=>e.sort((r,o)=>Ga(r,o,t));Jo.exports=Va});var Yo=w((Rf,zo)=>{"use strict";var Ja=He(),Xa=(e,t)=>e.sort((r,o)=>Ja(o,r,t));zo.exports=Xa});var Se=w((Af,Qo)=>{"use strict";var za=k(),Ya=(e,t,r)=>za(e,t,r)>0;Qo.exports=Ya});var Ge=w((Pf,Zo)=>{"use strict";var Qa=k(),Za=(e,t,r)=>Qa(e,t,r)<0;Zo.exports=Za});var Kt=w((If,en)=>{"use strict";var ec=k(),tc=(e,t,r)=>ec(e,t,r)===0;en.exports=tc});var qt=w((vf,tn)=>{"use strict";var rc=k(),oc=(e,t,r)=>rc(e,t,r)!==0;tn.exports=oc});var Ve=w((bf,rn)=>{"use strict";var nc=k(),sc=(e,t,r)=>nc(e,t,r)>=0;rn.exports=sc});var Je=w((Cf,on)=>{"use strict";var ic=k(),ac=(e,t,r)=>ic(e,t,r)<=0;on.exports=ac});var Ht=w((Tf,nn)=>{"use strict";var cc=Kt(),lc=qt(),uc=Se(),pc=Ve(),dc=Ge(),mc=Je(),fc=(e,t,r,o)=>{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 cc(e,r,o);case"!=":return lc(e,r,o);case">":return uc(e,r,o);case">=":return pc(e,r,o);case"<":return dc(e,r,o);case"<=":return mc(e,r,o);default:throw new TypeError(`Invalid operator: ${t}`)}};nn.exports=fc});var an=w((Of,sn)=>{"use strict";var hc=T(),gc=te(),{safeRe:Xe,t:ze}=ne(),yc=(e,t)=>{if(e instanceof hc)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?Xe[ze.COERCEFULL]:Xe[ze.COERCE]);else{let l=t.includePrerelease?Xe[ze.COERCERTLFULL]:Xe[ze.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 o=r[2],n=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return gc(`${o}.${n}.${s}${i}${a}`,t)};sn.exports=yc});var ln=w((xf,cn)=>{"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 n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};cn.exports=Gt});var D=w(($f,mn)=>{"use strict";var wc=/\s+/g,Vt=class e{constructor(t,r){if(r=Sc(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(wc," "),this.set=this.raw.split("||").map(o=>this.parseRange(o.trim())).filter(o=>o.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let o=this.set[0];if(this.set=this.set.filter(n=>!pn(n[0])),this.set.length===0)this.set=[o];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&Cc(n[0])){this.set=[n];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 o=0;o<r.length;o++)o>0&&(this.formatted+=" "),this.formatted+=r[o].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let o=((this.options.includePrerelease&&vc)|(this.options.loose&&bc))+":"+t,n=un.get(o);if(n)return n;let s=this.options.loose,i=s?x[O.HYPHENRANGELOOSE]:x[O.HYPHENRANGE];t=t.replace(i,_c(this.options.includePrerelease)),I("hyphen replace",t),t=t.replace(x[O.COMPARATORTRIM],Ac),I("comparator trim",t),t=t.replace(x[O.TILDETRIM],Pc),I("tilde trim",t),t=t.replace(x[O.CARETTRIM],Ic),I("caret trim",t);let a=t.split(" ").map(m=>Tc(m,this.options)).join(" ").split(/\s+/).map(m=>Mc(m,this.options));s&&(a=a.filter(m=>(I("loose invalid filter",m,this.options),!!m.match(x[O.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(m=>new Jt(m,this.options));for(let m of u){if(pn(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let h=[...l.values()];return un.set(o,h),h}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(o=>dn(o,r)&&t.set.some(n=>dn(n,r)&&o.every(s=>n.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Rc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Uc(this.set[r],t,this.options))return!0;return!1}};mn.exports=Vt;var Ec=ln(),un=new Ec,Sc=Fe(),Jt=Re(),I=Ee(),Rc=T(),{safeRe:x,t:O,comparatorTrimReplace:Ac,tildeTrimReplace:Pc,caretTrimReplace:Ic}=ne(),{FLAG_INCLUDE_PRERELEASE:vc,FLAG_LOOSE:bc}=we(),pn=e=>e.value==="<0.0.0-0",Cc=e=>e.value==="",dn=(e,t)=>{let r=!0,o=e.slice(),n=o.pop();for(;r&&o.length;)r=o.every(s=>n.intersects(s,t)),n=o.pop();return r},Tc=(e,t)=>(e=e.replace(x[O.BUILD],""),I("comp",e,t),e=$c(e,t),I("caret",e),e=Oc(e,t),I("tildes",e),e=Lc(e,t),I("xrange",e),e=Dc(e,t),I("stars",e),e),$=e=>!e||e.toLowerCase()==="x"||e==="*",Oc=(e,t)=>e.trim().split(/\s+/).map(r=>xc(r,t)).join(" "),xc=(e,t)=>{let r=t.loose?x[O.TILDELOOSE]:x[O.TILDE];return e.replace(r,(o,n,s,i,a)=>{I("tilde",e,o,n,s,i,a);let l;return $(n)?l="":$(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:$(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${n}.${s}.${i}-${a} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,I("tilde return",l),l})},$c=(e,t)=>e.trim().split(/\s+/).map(r=>Nc(r,t)).join(" "),Nc=(e,t)=>{I("caret",e,t);let r=t.loose?x[O.CARETLOOSE]:x[O.CARET],o=t.includePrerelease?"-0":"";return e.replace(r,(n,s,i,a,l)=>{I("caret",e,n,s,i,a,l);let u;return $(s)?u="":$(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:$(a)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(I("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(I("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a}${o} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),I("caret return",u),u})},Lc=(e,t)=>(I("replaceXRanges",e,t),e.split(/\s+/).map(r=>kc(r,t)).join(" ")),kc=(e,t)=>{e=e.trim();let r=t.loose?x[O.XRANGELOOSE]:x[O.XRANGE];return e.replace(r,(o,n,s,i,a,l)=>{I("xRange",e,o,n,s,i,a,l);let u=$(s),h=u||$(i),m=h||$(a),S=m;return n==="="&&S&&(n=""),l=t.includePrerelease?"-0":"",u?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&S?(h&&(i=0),a=0,n===">"?(n=">=",h?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):n==="<="&&(n="<",h?s=+s+1:i=+i+1),n==="<"&&(l="-0"),o=`${n+s}.${i}.${a}${l}`):h?o=`>=${s}.0.0${l} <${+s+1}.0.0-0`:m&&(o=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),I("xRange return",o),o})},Dc=(e,t)=>(I("replaceStars",e,t),e.trim().replace(x[O.STAR],"")),Mc=(e,t)=>(I("replaceGTE0",e,t),e.trim().replace(x[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),_c=e=>(t,r,o,n,s,i,a,l,u,h,m,S)=>($(o)?r="":$(n)?r=`>=${o}.0.0${e?"-0":""}`:$(s)?r=`>=${o}.${n}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,$(u)?l="":$(h)?l=`<${+u+1}.0.0-0`:$(m)?l=`<${u}.${+h+1}.0-0`:S?l=`<=${u}.${h}.${m}-${S}`:e?l=`<${u}.${h}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),Uc=(e,t,r)=>{for(let o=0;o<e.length;o++)if(!e[o].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let o=0;o<e.length;o++)if(I(e[o].semver),e[o].semver!==Jt.ANY&&e[o].semver.prerelease.length>0){let n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}});var Re=w((Nf,En)=>{"use strict";var Ae=Symbol("SemVer ANY"),Yt=class e{static get ANY(){return Ae}constructor(t,r){if(r=fn(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===Ae?this.value="":this.value=this.operator+this.semver.version,zt("comp",this)}parse(t){let r=this.options.loose?hn[gn.COMPARATORLOOSE]:hn[gn.COMPARATOR],o=t.match(r);if(!o)throw new TypeError(`Invalid comparator: ${t}`);this.operator=o[1]!==void 0?o[1]:"",this.operator==="="&&(this.operator=""),o[2]?this.semver=new yn(o[2],this.options.loose):this.semver=Ae}toString(){return this.value}test(t){if(zt("Comparator.test",t,this.options.loose),this.semver===Ae||t===Ae)return!0;if(typeof t=="string")try{t=new yn(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 wn(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new wn(this.value,r).test(t.semver):(r=fn(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(">")))}};En.exports=Yt;var fn=Fe(),{safeRe:hn,t:gn}=ne(),Xt=Ht(),zt=Ee(),yn=T(),wn=D()});var Pe=w((Lf,Sn)=>{"use strict";var jc=D(),Fc=(e,t,r)=>{try{t=new jc(t,r)}catch{return!1}return t.test(e)};Sn.exports=Fc});var An=w((kf,Rn)=>{"use strict";var Bc=D(),Wc=(e,t)=>new Bc(e,t).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Rn.exports=Wc});var In=w((Df,Pn)=>{"use strict";var Kc=T(),qc=D(),Hc=(e,t,r)=>{let o=null,n=null,s=null;try{s=new qc(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new Kc(o,r))}),o};Pn.exports=Hc});var bn=w((Mf,vn)=>{"use strict";var Gc=T(),Vc=D(),Jc=(e,t,r)=>{let o=null,n=null,s=null;try{s=new Vc(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new Gc(o,r))}),o};vn.exports=Jc});var On=w((_f,Tn)=>{"use strict";var Qt=T(),Xc=D(),Cn=Se(),zc=(e,t)=>{e=new Xc(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 o=0;o<e.set.length;++o){let n=e.set[o],s=null;n.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">=":(!s||Cn(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||Cn(r,s))&&(r=s)}return r&&e.test(r)?r:null};Tn.exports=zc});var $n=w((Uf,xn)=>{"use strict";var Yc=D(),Qc=(e,t)=>{try{return new Yc(e,t).range||"*"}catch{return null}};xn.exports=Qc});var Ye=w((jf,Dn)=>{"use strict";var Zc=T(),kn=Re(),{ANY:el}=kn,tl=D(),rl=Pe(),Nn=Se(),Ln=Ge(),ol=Je(),nl=Ve(),sl=(e,t,r,o)=>{e=new Zc(e,o),t=new tl(t,o);let n,s,i,a,l;switch(r){case">":n=Nn,s=ol,i=Ln,a=">",l=">=";break;case"<":n=Ln,s=nl,i=Nn,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(rl(e,t,o))return!1;for(let u=0;u<t.set.length;++u){let h=t.set[u],m=null,S=null;if(h.forEach(f=>{f.semver===el&&(f=new kn(">=0.0.0")),m=m||f,S=S||f,n(f.semver,m.semver,o)?m=f:i(f.semver,S.semver,o)&&(S=f)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&s(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};Dn.exports=sl});var _n=w((Ff,Mn)=>{"use strict";var il=Ye(),al=(e,t,r)=>il(e,t,">",r);Mn.exports=al});var jn=w((Bf,Un)=>{"use strict";var cl=Ye(),ll=(e,t,r)=>cl(e,t,"<",r);Un.exports=ll});var Wn=w((Wf,Bn)=>{"use strict";var Fn=D(),ul=(e,t,r)=>(e=new Fn(e,r),t=new Fn(t,r),e.intersects(t,r));Bn.exports=ul});var qn=w((Kf,Kn)=>{"use strict";var pl=Pe(),dl=k();Kn.exports=(e,t,r)=>{let o=[],n=null,s=null,i=e.sort((h,m)=>dl(h,m,r));for(let h of i)pl(h,t,r)?(s=h,n||(n=h)):(s&&o.push([n,s]),s=null,n=null);n&&o.push([n,null]);let a=[];for(let[h,m]of o)h===m?a.push(h):!m&&h===i[0]?a.push("*"):m?h===i[0]?a.push(`<=${m}`):a.push(`${h} - ${m}`):a.push(`>=${h}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var zn=w((qf,Xn)=>{"use strict";var Hn=D(),er=Re(),{ANY:Zt}=er,Ie=Pe(),tr=k(),ml=(e,t,r={})=>{if(e===t)return!0;e=new Hn(e,r),t=new Hn(t,r);let o=!1;e:for(let n of e.set){for(let s of t.set){let i=hl(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},fl=[new er(">=0.0.0-0")],Gn=[new er(">=0.0.0")],hl=(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=fl:e=Gn}if(t.length===1&&t[0].semver===Zt){if(r.includePrerelease)return!0;t=Gn}let o=new Set,n,s;for(let f of e)f.operator===">"||f.operator===">="?n=Vn(n,f,r):f.operator==="<"||f.operator==="<="?s=Jn(s,f,r):o.add(f.semver);if(o.size>1)return null;let i;if(n&&s){if(i=tr(n.semver,s.semver,r),i>0)return null;if(i===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let f of o){if(n&&!Ie(f,String(n),r)||s&&!Ie(f,String(s),r))return null;for(let b of t)if(!Ie(f,String(b),r))return!1;return!0}let a,l,u,h,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1;m&&m.prerelease.length===1&&s.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let f of t){if(h=h||f.operator===">"||f.operator===">=",u=u||f.operator==="<"||f.operator==="<=",n){if(S&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===S.major&&f.semver.minor===S.minor&&f.semver.patch===S.patch&&(S=!1),f.operator===">"||f.operator===">="){if(a=Vn(n,f,r),a===f&&a!==n)return!1}else if(n.operator===">="&&!Ie(n.semver,String(f),r))return!1}if(s){if(m&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===m.major&&f.semver.minor===m.minor&&f.semver.patch===m.patch&&(m=!1),f.operator==="<"||f.operator==="<="){if(l=Jn(s,f,r),l===f&&l!==s)return!1}else if(s.operator==="<="&&!Ie(s.semver,String(f),r))return!1}if(!f.operator&&(s||n)&&i!==0)return!1}return!(n&&u&&!s&&i!==0||s&&h&&!n&&i!==0||S||m)},Vn=(e,t,r)=>{if(!e)return t;let o=tr(e.semver,t.semver,r);return o>0?e:o<0||t.operator===">"&&e.operator===">="?t:e},Jn=(e,t,r)=>{if(!e)return t;let o=tr(e.semver,t.semver,r);return o<0?e:o>0||t.operator==="<"&&e.operator==="<="?t:e};Xn.exports=ml});var or=w((Hf,Zn)=>{"use strict";var rr=ne(),Yn=we(),gl=T(),Qn=Ft(),yl=te(),wl=Po(),El=vo(),Sl=To(),Rl=$o(),Al=Lo(),Pl=Do(),Il=_o(),vl=jo(),bl=k(),Cl=Ko(),Tl=Ho(),Ol=He(),xl=Xo(),$l=Yo(),Nl=Se(),Ll=Ge(),kl=Kt(),Dl=qt(),Ml=Ve(),_l=Je(),Ul=Ht(),jl=an(),Fl=Re(),Bl=D(),Wl=Pe(),Kl=An(),ql=In(),Hl=bn(),Gl=On(),Vl=$n(),Jl=Ye(),Xl=_n(),zl=jn(),Yl=Wn(),Ql=qn(),Zl=zn();Zn.exports={parse:yl,valid:wl,clean:El,inc:Sl,diff:Rl,major:Al,minor:Pl,patch:Il,prerelease:vl,compare:bl,rcompare:Cl,compareLoose:Tl,compareBuild:Ol,sort:xl,rsort:$l,gt:Nl,lt:Ll,eq:kl,neq:Dl,gte:Ml,lte:_l,cmp:Ul,coerce:jl,Comparator:Fl,Range:Bl,satisfies:Wl,toComparators:Kl,maxSatisfying:ql,minSatisfying:Hl,minVersion:Gl,validRange:Vl,outside:Jl,gtr:Xl,ltr:zl,intersects:Yl,simplifyRange:Ql,subset:Zl,SemVer:gl,re:rr.re,src:rr.src,tokens:rr.t,SEMVER_SPEC_VERSION:Yn.SEMVER_SPEC_VERSION,RELEASE_TYPES:Yn.RELEASE_TYPES,compareIdentifiers:Qn.compareIdentifiers,rcompareIdentifiers:Qn.rcompareIdentifiers}});import{MEDPLUM_VERSION as qp,normalizeErrorString as yr}from"@medplum/core";import{CommanderError as Bs,Option as Hp}from"commander";import Gp from"dotenv";import{ContentType as eo,isOk as Mi,isUUID as _i}from"@medplum/core";import{Option as Nt}from"commander";import{MedplumClient as ti}from"@medplum/core";import{ClientStorage as zs}from"@medplum/core";import{existsSync as Er,mkdirSync as Ys,readFileSync as Qs,writeFileSync as Zs}from"node:fs";import{homedir as ei}from"node:os";import{resolve as Sr}from"node:path";var _=class extends zs{constructor(r){super();P(this,"dirName");P(this,"fileName");this.dirName=Sr(ei(),".medplum"),this.fileName=Sr(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if(Er(this.fileName))return JSON.parse(Qs(this.fileName,"utf8"))}writeFile(r){Er(this.dirName)||Ys(this.dirName),Zs(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",o=new _(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:h,clientSecret:m}=ri(e,o),S=e.fetch??fetch,f=new ti({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:oi,verbose:e.verbose});return t&&(a?f.setAccessToken(a):h&&m&&(f.setBasicAuth(h,m),n?.authType!=="basic"&&await f.startClientLogin(h,m))),f}function ri(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,s=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:o,fhirUrlPath:n,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}function oi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{ContentType as bt,encodeBase64 as Kr,OAuthSigningAlgorithm as qr}from"@medplum/core";import{Command as Ii}from"commander";import{Buffer as ni}from"node:buffer";var z=new TextEncoder,ht=new TextDecoder,id=2**32;function Rr(...e){let t=e.reduce((n,{length:s})=>n+s,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var xe=e=>ni.from(e).toString("base64url");var Y=class extends Error{constructor(r,o){super(r,o);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};P(Y,"code","ERR_JOSE_GENERIC");var L=class extends Y{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}};P(L,"code","ERR_JOSE_NOT_SUPPORTED");var K=class extends Y{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}};P(K,"code","ERR_JWS_INVALID");var de=class extends Y{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}};P(de,"code","ERR_JWT_INVALID");var Ar,Pr,gt=class extends(Pr=Y,Ar=Symbol.asyncIterator,Pr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);P(this,Ar);P(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};P(gt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");import*as Ir from"node:util";var $e=e=>Ir.types.isKeyObject(e);import*as vr from"node:crypto";import*as br from"node:util";var ii=vr.webcrypto,Cr=ii,re=e=>br.types.isCryptoKey(e);function U(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function me(e,t){return e.name===t}function yt(e){return parseInt(e.name.slice(4),10)}function ai(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ci(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 o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Tr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!me(e.algorithm,"HMAC"))throw U("HMAC");let o=parseInt(t.slice(2),10);if(yt(e.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!me(e.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(yt(e.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!me(e.algorithm,"RSA-PSS"))throw U("RSA-PSS");let o=parseInt(t.slice(2),10);if(yt(e.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw U("Ed25519 or Ed448");break}case"Ed25519":{if(!me(e.algorithm,"Ed25519"))throw U("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!me(e.algorithm,"ECDSA"))throw U("ECDSA");let o=ai(t);if(e.algorithm.namedCurve!==o)throw U(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ci(e,r)}function Or(e,t,...r){if(r=r.filter(Boolean),r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var fe=(e,...t)=>Or("Key must be ",e,...t);function wt(e,t,...r){return Or(`Key for the ${e} algorithm must be `,t,...r)}var Et=e=>$e(e)||re(e),q=["KeyObject"];(globalThis.CryptoKey||Cr?.CryptoKey)&&q.push("CryptoKey");var li=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let s of n){if(r.has(s))return!1;r.add(s)}}return!0},xr=li;function ui(e){return typeof e=="object"&&e!==null}function he(e){if(!ui(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 he(e)&&typeof e.kty=="string"}function $r(e){return e.kty!=="oct"&&typeof e.d=="string"}function Nr(e){return e.kty!=="oct"&&typeof e.d>"u"}function Lr(e){return G(e)&&e.kty==="oct"&&typeof e.k=="string"}var di=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 L("Unsupported key curve for this operation")}},mi=(e,t)=>{let r;if(re(e))r=pi.from(e);else if($e(e))r=e;else{if(G(e))return e.crv;throw new TypeError(fe(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 o=r.asymmetricKeyDetails.namedCurve;return t?o:di(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Dr=mi;import{KeyObject as fi}from"node:crypto";var St=(e,t)=>{let r;try{e instanceof fi?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 oe=e=>e?.[Symbol.toStringTag],Rt=(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},hi=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&G(t)){if(Lr(t)&&Rt(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(!Et(t))throw new TypeError(wt(e,t,...q,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${oe(t)} instances for symmetric algorithms must be of type "secret"`)}},gi=(e,t,r,o)=>{if(o&&G(t))switch(r){case"sign":if($r(t)&&Rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Nr(t)&&Rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Et(t))throw new TypeError(wt(e,t,...q,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${oe(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${oe(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${oe(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${oe(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${oe(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Mr(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?hi(t,r,o,e):gi(t,r,o,e)}var Ld=Mr.bind(void 0,!1),_r=Mr.bind(void 0,!0);function yi(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.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 s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let i of o.crit){if(!s.has(i))throw new L(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&o[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}var Ur=yi;function At(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 L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as jr,KeyObject as wi}from"node:crypto";var Ei=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Pt(e,t){let r,o,n;if(t instanceof wi)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(n=!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 s;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");St(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=o,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");St(t,e),s={padding:jr.RSA_PKCS1_PSS_PADDING,saltLength:jr.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=Dr(t),a=Ei.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);s={dsaEncoding:"ieee-p1363"};break}default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return n?{format:"jwk",key:t,...s}:s?{...s,key:t}:t}import*as Ne from"node:crypto";import{promisify as Si}from"node:util";function It(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Fr,createSecretKey as Br}from"node:crypto";function vt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(fe(t,...q));return Br(t)}if(t instanceof Fr)return t;if(re(t))return Tr(t,e,r),Fr.from(t);if(G(t))return e.startsWith("HS")?Br(Buffer.from(t.k,"base64url")):t;throw new TypeError(fe(t,...q,"Uint8Array","JSON Web Key"))}var Ri=Si(Ne.sign),Ai=async(e,t,r)=>{let o=vt(e,t,"sign");if(e.startsWith("HS")){let n=Ne.createHmac(It(e),o);return n.update(r),n.digest()}return Ri(At(e),r,Pt(e,o))},Wr=Ai;var V=e=>Math.floor(e.getTime()/1e3);var Pi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Le=e=>{let t=Pi.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-n:n};var ke=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(!xr(this._protectedHeader,this._unprotectedHeader))throw new K("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=Ur(K,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new K('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new K('JWS "alg" (Algorithm) Header Parameter missing or invalid');_r(i,t,"sign");let a=this._payload;s&&(a=z.encode(xe(a)));let l;this._protectedHeader?l=z.encode(xe(JSON.stringify(this._protectedHeader))):l=z.encode("");let u=Rr(l,z.encode("."),a),h=await Wr(i,t,u),m={signature:xe(h),payload:""};return s&&(m.payload=ht.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=ht.decode(l)),m}};var De=class{constructor(t){P(this,"_flattened");this._flattened=new ke(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function Q(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Me=class{constructor(t={}){P(this,"_payload");if(!he(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:Q("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:Q("setNotBefore",V(t))}:this._payload={...this._payload,nbf:V(new Date)+Le(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:Q("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:Q("setExpirationTime",V(t))}:this._payload={...this._payload,exp:V(new Date)+Le(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:V(new Date)}:t instanceof Date?this._payload={...this._payload,iat:Q("setIssuedAt",V(t))}:typeof t=="string"?this._payload={...this._payload,iat:Q("setIssuedAt",V(new Date)+Le(t))}:this._payload={...this._payload,iat:Q("setIssuedAt",t)},this}};var ge=class extends Me{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new De(z.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new de("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};import{createHmac as vi,createPrivateKey as bi,randomBytes as Ci}from"node:crypto";import{existsSync as Ti,readFileSync as Hr,writeFileSync as Gr}from"node:fs";import{basename as Vr,extname as Oi,resolve as Ct}from"node:path";import{isPromise as xi}from"node:util/types";import{extract as $i}from"tar";function H(e){console.log(JSON.stringify(e,null,2))}async function Tt(e,t,r){let o=t.source,n=_e(o);if(!n)return;console.log("Saving source code...");let s=await e.createAttachment({data:n,filename:Vr(o),contentType:ki(o)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Ot(e,t,r){let o=t.dist??t.source,n=_e(o);if(!n)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:Vr(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function xt(e,t,r,o,n,s,i){let a={name:t,description:"",runtimeVersion:s},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),h={name:t,id:l.id,source:o,dist:n};await Tt(e,h,u),await Ot(e,h,u),console.log(`Success! Bot created: ${u.id}`),i&&Ni(h)}function Jr(e){let t=new RegExp("^"+Li(e).replaceAll(String.raw`\*`,".*")+"$"),r=j()?.bots?.filter(o=>t.test(o.name));return r||[]}function M(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 C(e,t){Gr(Ct(e),JSON.stringify(t,void 0,2),"utf-8")}function j(e,t){let r=M(e,t),o=_e(r);if(o)return JSON.parse(o)}function Xr(e){let t=_e(M(e,{server:!0}));if(t)return JSON.parse(t)}function _e(e){let t=Ct(e);return Ti(t)?Hr(t,"utf8"):""}function Ni(e){let t=j()??{};t.bots||(t.bots=[]),t.bots.push(e),Gr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Li(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function zr(e){let o=0,n=0;return $i({cwd:e,filter:(s,i)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=i.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function $t(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ki(e){let t=Oi(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?bt.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?bt.TYPESCRIPT:bt.TEXT}function Ue(e,t){let r=new _(e),o={name:e,...t};return r.setObject("options",o),o}function Yr(e){return new _(e).getObject("options")}async function Qr(e,t){let r={typ:"JWT",alg:qr.HS256},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},s=Kr(JSON.stringify(r)),i=Kr(JSON.stringify(n)),a=`${s}.${i}`,l=vi("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Zr(e,t){let r=bi(Hr(Ct(t.privateKeyPath))),o=await new ge({}).setProtectedHeader({typ:"JWT",alg:qr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Ci(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends Ii{action(t){let r=Di(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 Di(e,t){return async r=>{let o=e.registeredArguments.length,n=r.slice(0,o);n[o]=e.optsWithGlobals();try{let s=t(...n);xi(s)&&await s}finally{e.resetOptionDefaults()}}}var to=new g("status").aliases(["info","list","ls"]),ro=new g("ping"),oo=new g("push"),no=new g("reload-config"),so=new g("upgrade"),Z=new g("agent");y(Z,to);y(Z,ro);y(Z,oo);y(Z,no);y(Z,so);to.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 Nt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Lt({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=Fi(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});ro.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await R(r),n=await io(o,t,r),s=Number.parseInt(r.count,10);if(Number.isNaN(s))throw new Error("--count <count> must be an integer if specified");try{let i=await o.pushToAgent(n,e,`PING ${s}`,eo.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});oo.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",eo.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let n=await R(o),s=await io(n,r,o),i;try{i=await n.pushToAgent(s,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});no.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 Nt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Lt({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});so.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 Nt("--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 Lt({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function Lt({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n}){let s=Wi(t,r),i=await R(r),a=s.type==="criteria"?s.criteria:`Agent?_id=${s.ids.join(",")}`,l=new URLSearchParams(a.split("?")[1]);for(let[b,W]of Object.entries(o))l.append(b,W.toString());let u;try{let b=i.fhirUrl("Agent",e);b.search=l.toString(),u=await i.get(b,{cache:"reload"})}catch(b){throw new Error(`Operation '${e}' failed`,{cause:b})}if(r.output==="json"){console.info(JSON.stringify(u,null,2));return}let h=[],m=[];switch(u.resourceType){case"Bundle":{let b=Ui(u);for(let W of b)W.result.resourceType==="Parameters"||Mi(W.result)?h.push(W):m.push(W);break}case"Parameters":case"OperationOutcome":{let b=await i.searchOne("Agent",l,{cache:"reload"});if(!b)throw new Error("Agent not found");u.resourceType==="Parameters"?h.push({agent:b,result:u}):m.push({agent:b,result:u});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(u)}`)}let S=[];for(let b of h){let W=n(b);S.push(W)}let f=[];for(let b of m){let mt=b.result.issue?.[0],Ws={id:b.agent.id,name:b.agent.name,severity:mt.severity,code:mt.code,details:mt.details?.text??"No details to show"};f.push(Ws)}console.info(`
2
+ var Ks=Object.create;var ft=Object.defineProperty;var qs=Object.getOwnPropertyDescriptor;var Hs=Object.getOwnPropertyNames;var Gs=Object.getPrototypeOf,Vs=Object.prototype.hasOwnProperty;var Js=(e,t,r)=>t in e?ft(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 Xs=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Hs(t))!Vs.call(e,n)&&n!==r&&ft(e,n,{get:()=>t[n],enumerable:!(o=qs(t,n))||o.enumerable});return e};var wr=(e,t,r)=>(r=e!=null?Ks(Gs(e)):{},Xs(t||!e||!e.__esModule?ft(r,"default",{value:e,enumerable:!0}):r,e));var P=(e,t,r)=>Js(e,typeof t!="symbol"?t+"":t,r);var we=w((sf,uo)=>{"use strict";var ia="2.0.0",aa=Number.MAX_SAFE_INTEGER||9007199254740991,ca=16,la=250,ua=["major","premajor","minor","preminor","patch","prepatch","prerelease"];uo.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ca,MAX_SAFE_BUILD_LENGTH:la,MAX_SAFE_INTEGER:aa,RELEASE_TYPES:ua,SEMVER_SPEC_VERSION:ia,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ee=w((af,po)=>{"use strict";var pa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};po.exports=pa});var ne=w((F,mo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ut,MAX_SAFE_BUILD_LENGTH:da,MAX_LENGTH:ma}=we(),fa=Ee();F=mo.exports={};var ha=F.re=[],ga=F.safeRe=[],p=F.src=[],ya=F.safeSrc=[],d=F.t={},wa=0,jt="[a-zA-Z0-9-]",Ea=[["\\s",1],["\\d",ma],[jt,da]],Sa=e=>{for(let[t,r]of Ea)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let o=Sa(t),n=wa++;fa(e,n,t),d[e]=n,p[n]=t,ya[n]=o,ha[n]=new RegExp(t,r?"g":void 0),ga[n]=new RegExp(o,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 Fe=w((cf,fo)=>{"use strict";var Ra=Object.freeze({loose:!0}),Aa=Object.freeze({}),Pa=e=>e?typeof e!="object"?Ra:e:Aa;fo.exports=Pa});var Ft=w((lf,yo)=>{"use strict";var ho=/^[0-9]+$/,go=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=ho.test(e),o=ho.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1},Ia=(e,t)=>go(t,e);yo.exports={compareIdentifiers:go,rcompareIdentifiers:Ia}});var T=w((uf,Eo)=>{"use strict";var Be=Ee(),{MAX_LENGTH:wo,MAX_SAFE_INTEGER:We}=we(),{safeRe:Ke,t:qe}=ne(),va=Fe(),{compareIdentifiers:Bt}=Ft(),Wt=class e{constructor(t,r){if(r=va(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>wo)throw new TypeError(`version is longer than ${wo} characters`);Be("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=t.trim().match(r.loose?Ke[qe.LOOSE]:Ke[qe.FULL]);if(!o)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>We||this.major<0)throw new TypeError("Invalid major version");if(this.minor>We||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>We||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<We)return s}return n}):this.prerelease=[],this.build=o[5]?o[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(Be("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 o=this.prerelease[r],n=t.prerelease[r];if(Be("prerelease compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return Bt(o,n)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let o=this.build[r],n=t.build[r];if(Be("build compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return Bt(o,n)}while(++r)}inc(t,r,o){if(t.startsWith("pre")){if(!r&&o===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=`-${r}`.match(this.options.loose?Ke[qe.PRERELEASELOOSE]:Ke[qe.PRERELEASE]);if(!n||n[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,o);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,o);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,o),this.inc("pre",r,o);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,o),this.inc("pre",r,o);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 n=Number(o)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&o===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];o===!1&&(s=[r]),Bt(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Eo.exports=Wt});var te=w((pf,Ro)=>{"use strict";var So=T(),ba=(e,t,r=!1)=>{if(e instanceof So)return e;try{return new So(e,t)}catch(o){if(!r)return null;throw o}};Ro.exports=ba});var Po=w((df,Ao)=>{"use strict";var Ca=te(),Ta=(e,t)=>{let r=Ca(e,t);return r?r.version:null};Ao.exports=Ta});var vo=w((mf,Io)=>{"use strict";var Oa=te(),xa=(e,t)=>{let r=Oa(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Io.exports=xa});var To=w((ff,Co)=>{"use strict";var bo=T(),$a=(e,t,r,o,n)=>{typeof r=="string"&&(n=o,o=r,r=void 0);try{return new bo(e instanceof bo?e.version:e,r).inc(t,o,n).version}catch{return null}};Co.exports=$a});var $o=w((hf,xo)=>{"use strict";var Oo=te(),Na=(e,t)=>{let r=Oo(e,null,!0),o=Oo(t,null,!0),n=r.compare(o);if(n===0)return null;let s=n>0,i=s?r:o,a=s?o: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 h=l?"pre":"";return r.major!==o.major?h+"major":r.minor!==o.minor?h+"minor":r.patch!==o.patch?h+"patch":"prerelease"};xo.exports=Na});var Lo=w((gf,No)=>{"use strict";var La=T(),ka=(e,t)=>new La(e,t).major;No.exports=ka});var Mo=w((yf,ko)=>{"use strict";var Ma=T(),Da=(e,t)=>new Ma(e,t).minor;ko.exports=Da});var _o=w((wf,Do)=>{"use strict";var _a=T(),Ua=(e,t)=>new _a(e,t).patch;Do.exports=Ua});var jo=w((Ef,Uo)=>{"use strict";var ja=te(),Fa=(e,t)=>{let r=ja(e,t);return r&&r.prerelease.length?r.prerelease:null};Uo.exports=Fa});var k=w((Sf,Bo)=>{"use strict";var Fo=T(),Ba=(e,t,r)=>new Fo(e,r).compare(new Fo(t,r));Bo.exports=Ba});var Ko=w((Rf,Wo)=>{"use strict";var Wa=k(),Ka=(e,t,r)=>Wa(t,e,r);Wo.exports=Ka});var Ho=w((Af,qo)=>{"use strict";var qa=k(),Ha=(e,t)=>qa(e,t,!0);qo.exports=Ha});var He=w((Pf,Vo)=>{"use strict";var Go=T(),Ga=(e,t,r)=>{let o=new Go(e,r),n=new Go(t,r);return o.compare(n)||o.compareBuild(n)};Vo.exports=Ga});var Xo=w((If,Jo)=>{"use strict";var Va=He(),Ja=(e,t)=>e.sort((r,o)=>Va(r,o,t));Jo.exports=Ja});var Yo=w((vf,zo)=>{"use strict";var Xa=He(),za=(e,t)=>e.sort((r,o)=>Xa(o,r,t));zo.exports=za});var Se=w((bf,Qo)=>{"use strict";var Ya=k(),Qa=(e,t,r)=>Ya(e,t,r)>0;Qo.exports=Qa});var Ge=w((Cf,Zo)=>{"use strict";var Za=k(),ec=(e,t,r)=>Za(e,t,r)<0;Zo.exports=ec});var Kt=w((Tf,en)=>{"use strict";var tc=k(),rc=(e,t,r)=>tc(e,t,r)===0;en.exports=rc});var qt=w((Of,tn)=>{"use strict";var oc=k(),nc=(e,t,r)=>oc(e,t,r)!==0;tn.exports=nc});var Ve=w((xf,rn)=>{"use strict";var sc=k(),ic=(e,t,r)=>sc(e,t,r)>=0;rn.exports=ic});var Je=w(($f,on)=>{"use strict";var ac=k(),cc=(e,t,r)=>ac(e,t,r)<=0;on.exports=cc});var Ht=w((Nf,nn)=>{"use strict";var lc=Kt(),uc=qt(),pc=Se(),dc=Ve(),mc=Ge(),fc=Je(),hc=(e,t,r,o)=>{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 lc(e,r,o);case"!=":return uc(e,r,o);case">":return pc(e,r,o);case">=":return dc(e,r,o);case"<":return mc(e,r,o);case"<=":return fc(e,r,o);default:throw new TypeError(`Invalid operator: ${t}`)}};nn.exports=hc});var an=w((Lf,sn)=>{"use strict";var gc=T(),yc=te(),{safeRe:Xe,t:ze}=ne(),wc=(e,t)=>{if(e instanceof gc)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?Xe[ze.COERCEFULL]:Xe[ze.COERCE]);else{let l=t.includePrerelease?Xe[ze.COERCERTLFULL]:Xe[ze.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 o=r[2],n=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return yc(`${o}.${n}.${s}${i}${a}`,t)};sn.exports=wc});var ln=w((kf,cn)=>{"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 n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};cn.exports=Gt});var M=w((Mf,mn)=>{"use strict";var Ec=/\s+/g,Vt=class e{constructor(t,r){if(r=Rc(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(Ec," "),this.set=this.raw.split("||").map(o=>this.parseRange(o.trim())).filter(o=>o.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let o=this.set[0];if(this.set=this.set.filter(n=>!pn(n[0])),this.set.length===0)this.set=[o];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&Tc(n[0])){this.set=[n];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 o=0;o<r.length;o++)o>0&&(this.formatted+=" "),this.formatted+=r[o].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let o=((this.options.includePrerelease&&bc)|(this.options.loose&&Cc))+":"+t,n=un.get(o);if(n)return n;let s=this.options.loose,i=s?x[O.HYPHENRANGELOOSE]:x[O.HYPHENRANGE];t=t.replace(i,Uc(this.options.includePrerelease)),I("hyphen replace",t),t=t.replace(x[O.COMPARATORTRIM],Pc),I("comparator trim",t),t=t.replace(x[O.TILDETRIM],Ic),I("tilde trim",t),t=t.replace(x[O.CARETTRIM],vc),I("caret trim",t);let a=t.split(" ").map(m=>Oc(m,this.options)).join(" ").split(/\s+/).map(m=>_c(m,this.options));s&&(a=a.filter(m=>(I("loose invalid filter",m,this.options),!!m.match(x[O.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(m=>new Jt(m,this.options));for(let m of u){if(pn(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let h=[...l.values()];return un.set(o,h),h}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(o=>dn(o,r)&&t.set.some(n=>dn(n,r)&&o.every(s=>n.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Ac(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(jc(this.set[r],t,this.options))return!0;return!1}};mn.exports=Vt;var Sc=ln(),un=new Sc,Rc=Fe(),Jt=Re(),I=Ee(),Ac=T(),{safeRe:x,t:O,comparatorTrimReplace:Pc,tildeTrimReplace:Ic,caretTrimReplace:vc}=ne(),{FLAG_INCLUDE_PRERELEASE:bc,FLAG_LOOSE:Cc}=we(),pn=e=>e.value==="<0.0.0-0",Tc=e=>e.value==="",dn=(e,t)=>{let r=!0,o=e.slice(),n=o.pop();for(;r&&o.length;)r=o.every(s=>n.intersects(s,t)),n=o.pop();return r},Oc=(e,t)=>(e=e.replace(x[O.BUILD],""),I("comp",e,t),e=Nc(e,t),I("caret",e),e=xc(e,t),I("tildes",e),e=kc(e,t),I("xrange",e),e=Dc(e,t),I("stars",e),e),$=e=>!e||e.toLowerCase()==="x"||e==="*",xc=(e,t)=>e.trim().split(/\s+/).map(r=>$c(r,t)).join(" "),$c=(e,t)=>{let r=t.loose?x[O.TILDELOOSE]:x[O.TILDE];return e.replace(r,(o,n,s,i,a)=>{I("tilde",e,o,n,s,i,a);let l;return $(n)?l="":$(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:$(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${n}.${s}.${i}-${a} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,I("tilde return",l),l})},Nc=(e,t)=>e.trim().split(/\s+/).map(r=>Lc(r,t)).join(" "),Lc=(e,t)=>{I("caret",e,t);let r=t.loose?x[O.CARETLOOSE]:x[O.CARET],o=t.includePrerelease?"-0":"";return e.replace(r,(n,s,i,a,l)=>{I("caret",e,n,s,i,a,l);let u;return $(s)?u="":$(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:$(a)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(I("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(I("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a}${o} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),I("caret return",u),u})},kc=(e,t)=>(I("replaceXRanges",e,t),e.split(/\s+/).map(r=>Mc(r,t)).join(" ")),Mc=(e,t)=>{e=e.trim();let r=t.loose?x[O.XRANGELOOSE]:x[O.XRANGE];return e.replace(r,(o,n,s,i,a,l)=>{I("xRange",e,o,n,s,i,a,l);let u=$(s),h=u||$(i),m=h||$(a),S=m;return n==="="&&S&&(n=""),l=t.includePrerelease?"-0":"",u?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&S?(h&&(i=0),a=0,n===">"?(n=">=",h?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):n==="<="&&(n="<",h?s=+s+1:i=+i+1),n==="<"&&(l="-0"),o=`${n+s}.${i}.${a}${l}`):h?o=`>=${s}.0.0${l} <${+s+1}.0.0-0`:m&&(o=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),I("xRange return",o),o})},Dc=(e,t)=>(I("replaceStars",e,t),e.trim().replace(x[O.STAR],"")),_c=(e,t)=>(I("replaceGTE0",e,t),e.trim().replace(x[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),Uc=e=>(t,r,o,n,s,i,a,l,u,h,m,S)=>($(o)?r="":$(n)?r=`>=${o}.0.0${e?"-0":""}`:$(s)?r=`>=${o}.${n}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,$(u)?l="":$(h)?l=`<${+u+1}.0.0-0`:$(m)?l=`<${u}.${+h+1}.0-0`:S?l=`<=${u}.${h}.${m}-${S}`:e?l=`<${u}.${h}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),jc=(e,t,r)=>{for(let o=0;o<e.length;o++)if(!e[o].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let o=0;o<e.length;o++)if(I(e[o].semver),e[o].semver!==Jt.ANY&&e[o].semver.prerelease.length>0){let n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}});var Re=w((Df,En)=>{"use strict";var Ae=Symbol("SemVer ANY"),Yt=class e{static get ANY(){return Ae}constructor(t,r){if(r=fn(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===Ae?this.value="":this.value=this.operator+this.semver.version,zt("comp",this)}parse(t){let r=this.options.loose?hn[gn.COMPARATORLOOSE]:hn[gn.COMPARATOR],o=t.match(r);if(!o)throw new TypeError(`Invalid comparator: ${t}`);this.operator=o[1]!==void 0?o[1]:"",this.operator==="="&&(this.operator=""),o[2]?this.semver=new yn(o[2],this.options.loose):this.semver=Ae}toString(){return this.value}test(t){if(zt("Comparator.test",t,this.options.loose),this.semver===Ae||t===Ae)return!0;if(typeof t=="string")try{t=new yn(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 wn(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new wn(this.value,r).test(t.semver):(r=fn(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(">")))}};En.exports=Yt;var fn=Fe(),{safeRe:hn,t:gn}=ne(),Xt=Ht(),zt=Ee(),yn=T(),wn=M()});var Pe=w((_f,Sn)=>{"use strict";var Fc=M(),Bc=(e,t,r)=>{try{t=new Fc(t,r)}catch{return!1}return t.test(e)};Sn.exports=Bc});var An=w((Uf,Rn)=>{"use strict";var Wc=M(),Kc=(e,t)=>new Wc(e,t).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Rn.exports=Kc});var In=w((jf,Pn)=>{"use strict";var qc=T(),Hc=M(),Gc=(e,t,r)=>{let o=null,n=null,s=null;try{s=new Hc(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new qc(o,r))}),o};Pn.exports=Gc});var bn=w((Ff,vn)=>{"use strict";var Vc=T(),Jc=M(),Xc=(e,t,r)=>{let o=null,n=null,s=null;try{s=new Jc(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new Vc(o,r))}),o};vn.exports=Xc});var On=w((Bf,Tn)=>{"use strict";var Qt=T(),zc=M(),Cn=Se(),Yc=(e,t)=>{e=new zc(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 o=0;o<e.set.length;++o){let n=e.set[o],s=null;n.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">=":(!s||Cn(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||Cn(r,s))&&(r=s)}return r&&e.test(r)?r:null};Tn.exports=Yc});var $n=w((Wf,xn)=>{"use strict";var Qc=M(),Zc=(e,t)=>{try{return new Qc(e,t).range||"*"}catch{return null}};xn.exports=Zc});var Ye=w((Kf,Mn)=>{"use strict";var el=T(),kn=Re(),{ANY:tl}=kn,rl=M(),ol=Pe(),Nn=Se(),Ln=Ge(),nl=Je(),sl=Ve(),il=(e,t,r,o)=>{e=new el(e,o),t=new rl(t,o);let n,s,i,a,l;switch(r){case">":n=Nn,s=nl,i=Ln,a=">",l=">=";break;case"<":n=Ln,s=sl,i=Nn,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ol(e,t,o))return!1;for(let u=0;u<t.set.length;++u){let h=t.set[u],m=null,S=null;if(h.forEach(f=>{f.semver===tl&&(f=new kn(">=0.0.0")),m=m||f,S=S||f,n(f.semver,m.semver,o)?m=f:i(f.semver,S.semver,o)&&(S=f)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&s(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};Mn.exports=il});var _n=w((qf,Dn)=>{"use strict";var al=Ye(),cl=(e,t,r)=>al(e,t,">",r);Dn.exports=cl});var jn=w((Hf,Un)=>{"use strict";var ll=Ye(),ul=(e,t,r)=>ll(e,t,"<",r);Un.exports=ul});var Wn=w((Gf,Bn)=>{"use strict";var Fn=M(),pl=(e,t,r)=>(e=new Fn(e,r),t=new Fn(t,r),e.intersects(t,r));Bn.exports=pl});var qn=w((Vf,Kn)=>{"use strict";var dl=Pe(),ml=k();Kn.exports=(e,t,r)=>{let o=[],n=null,s=null,i=e.sort((h,m)=>ml(h,m,r));for(let h of i)dl(h,t,r)?(s=h,n||(n=h)):(s&&o.push([n,s]),s=null,n=null);n&&o.push([n,null]);let a=[];for(let[h,m]of o)h===m?a.push(h):!m&&h===i[0]?a.push("*"):m?h===i[0]?a.push(`<=${m}`):a.push(`${h} - ${m}`):a.push(`>=${h}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var zn=w((Jf,Xn)=>{"use strict";var Hn=M(),er=Re(),{ANY:Zt}=er,Ie=Pe(),tr=k(),fl=(e,t,r={})=>{if(e===t)return!0;e=new Hn(e,r),t=new Hn(t,r);let o=!1;e:for(let n of e.set){for(let s of t.set){let i=gl(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},hl=[new er(">=0.0.0-0")],Gn=[new er(">=0.0.0")],gl=(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=hl:e=Gn}if(t.length===1&&t[0].semver===Zt){if(r.includePrerelease)return!0;t=Gn}let o=new Set,n,s;for(let f of e)f.operator===">"||f.operator===">="?n=Vn(n,f,r):f.operator==="<"||f.operator==="<="?s=Jn(s,f,r):o.add(f.semver);if(o.size>1)return null;let i;if(n&&s){if(i=tr(n.semver,s.semver,r),i>0)return null;if(i===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let f of o){if(n&&!Ie(f,String(n),r)||s&&!Ie(f,String(s),r))return null;for(let b of t)if(!Ie(f,String(b),r))return!1;return!0}let a,l,u,h,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1;m&&m.prerelease.length===1&&s.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let f of t){if(h=h||f.operator===">"||f.operator===">=",u=u||f.operator==="<"||f.operator==="<=",n){if(S&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===S.major&&f.semver.minor===S.minor&&f.semver.patch===S.patch&&(S=!1),f.operator===">"||f.operator===">="){if(a=Vn(n,f,r),a===f&&a!==n)return!1}else if(n.operator===">="&&!Ie(n.semver,String(f),r))return!1}if(s){if(m&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===m.major&&f.semver.minor===m.minor&&f.semver.patch===m.patch&&(m=!1),f.operator==="<"||f.operator==="<="){if(l=Jn(s,f,r),l===f&&l!==s)return!1}else if(s.operator==="<="&&!Ie(s.semver,String(f),r))return!1}if(!f.operator&&(s||n)&&i!==0)return!1}return!(n&&u&&!s&&i!==0||s&&h&&!n&&i!==0||S||m)},Vn=(e,t,r)=>{if(!e)return t;let o=tr(e.semver,t.semver,r);return o>0?e:o<0||t.operator===">"&&e.operator===">="?t:e},Jn=(e,t,r)=>{if(!e)return t;let o=tr(e.semver,t.semver,r);return o<0?e:o>0||t.operator==="<"&&e.operator==="<="?t:e};Xn.exports=fl});var or=w((Xf,Zn)=>{"use strict";var rr=ne(),Yn=we(),yl=T(),Qn=Ft(),wl=te(),El=Po(),Sl=vo(),Rl=To(),Al=$o(),Pl=Lo(),Il=Mo(),vl=_o(),bl=jo(),Cl=k(),Tl=Ko(),Ol=Ho(),xl=He(),$l=Xo(),Nl=Yo(),Ll=Se(),kl=Ge(),Ml=Kt(),Dl=qt(),_l=Ve(),Ul=Je(),jl=Ht(),Fl=an(),Bl=Re(),Wl=M(),Kl=Pe(),ql=An(),Hl=In(),Gl=bn(),Vl=On(),Jl=$n(),Xl=Ye(),zl=_n(),Yl=jn(),Ql=Wn(),Zl=qn(),eu=zn();Zn.exports={parse:wl,valid:El,clean:Sl,inc:Rl,diff:Al,major:Pl,minor:Il,patch:vl,prerelease:bl,compare:Cl,rcompare:Tl,compareLoose:Ol,compareBuild:xl,sort:$l,rsort:Nl,gt:Ll,lt:kl,eq:Ml,neq:Dl,gte:_l,lte:Ul,cmp:jl,coerce:Fl,Comparator:Bl,Range:Wl,satisfies:Kl,toComparators:ql,maxSatisfying:Hl,minSatisfying:Gl,minVersion:Vl,validRange:Jl,outside:Xl,gtr:zl,ltr:Yl,intersects:Ql,simplifyRange:Zl,subset:eu,SemVer:yl,re:rr.re,src:rr.src,tokens:rr.t,SEMVER_SPEC_VERSION:Yn.SEMVER_SPEC_VERSION,RELEASE_TYPES:Yn.RELEASE_TYPES,compareIdentifiers:Qn.compareIdentifiers,rcompareIdentifiers:Qn.rcompareIdentifiers}});import{MEDPLUM_VERSION as Jp,normalizeErrorString as yr}from"@medplum/core";import{CommanderError as Bs,Option as Xp}from"commander";import zp from"dotenv";import{ContentType as eo,EMPTY as Di,isOk as _i,isUUID as Ui}from"@medplum/core";import{Option as Nt}from"commander";import{MedplumClient as ti}from"@medplum/core";import{ClientStorage as zs}from"@medplum/core";import{existsSync as Er,mkdirSync as Ys,readFileSync as Qs,writeFileSync as Zs}from"node:fs";import{homedir as ei}from"node:os";import{resolve as Sr}from"node:path";var _=class extends zs{constructor(r){super();P(this,"dirName");P(this,"fileName");this.dirName=Sr(ei(),".medplum"),this.fileName=Sr(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if(Er(this.fileName))return JSON.parse(Qs(this.fileName,"utf8"))}writeFile(r){Er(this.dirName)||Ys(this.dirName),Zs(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",o=new _(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:h,clientSecret:m}=ri(e,o),S=e.fetch??fetch,f=new ti({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:oi,verbose:e.verbose});return t&&(a?f.setAccessToken(a):h&&m&&(f.setBasicAuth(h,m),n?.authType!=="basic"&&await f.startClientLogin(h,m))),f}function ri(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,s=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:o,fhirUrlPath:n,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}function oi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{ContentType as bt,encodeBase64 as Kr,OAuthSigningAlgorithm as qr}from"@medplum/core";import{Command as Ii}from"commander";import{Buffer as ni}from"node:buffer";var z=new TextEncoder,ht=new TextDecoder,ud=2**32;function Rr(...e){let t=e.reduce((n,{length:s})=>n+s,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var xe=e=>ni.from(e).toString("base64url");var Y=class extends Error{constructor(r,o){super(r,o);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};P(Y,"code","ERR_JOSE_GENERIC");var L=class extends Y{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}};P(L,"code","ERR_JOSE_NOT_SUPPORTED");var K=class extends Y{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}};P(K,"code","ERR_JWS_INVALID");var de=class extends Y{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}};P(de,"code","ERR_JWT_INVALID");var Ar,Pr,gt=class extends(Pr=Y,Ar=Symbol.asyncIterator,Pr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);P(this,Ar);P(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};P(gt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");import*as Ir from"node:util";var $e=e=>Ir.types.isKeyObject(e);import*as vr from"node:crypto";import*as br from"node:util";var ii=vr.webcrypto,Cr=ii,re=e=>br.types.isCryptoKey(e);function U(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function me(e,t){return e.name===t}function yt(e){return parseInt(e.name.slice(4),10)}function ai(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ci(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 o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Tr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!me(e.algorithm,"HMAC"))throw U("HMAC");let o=parseInt(t.slice(2),10);if(yt(e.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!me(e.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(yt(e.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!me(e.algorithm,"RSA-PSS"))throw U("RSA-PSS");let o=parseInt(t.slice(2),10);if(yt(e.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw U("Ed25519 or Ed448");break}case"Ed25519":{if(!me(e.algorithm,"Ed25519"))throw U("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!me(e.algorithm,"ECDSA"))throw U("ECDSA");let o=ai(t);if(e.algorithm.namedCurve!==o)throw U(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ci(e,r)}function Or(e,t,...r){if(r=r.filter(Boolean),r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var fe=(e,...t)=>Or("Key must be ",e,...t);function wt(e,t,...r){return Or(`Key for the ${e} algorithm must be `,t,...r)}var Et=e=>$e(e)||re(e),q=["KeyObject"];(globalThis.CryptoKey||Cr?.CryptoKey)&&q.push("CryptoKey");var li=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let s of n){if(r.has(s))return!1;r.add(s)}}return!0},xr=li;function ui(e){return typeof e=="object"&&e!==null}function he(e){if(!ui(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 he(e)&&typeof e.kty=="string"}function $r(e){return e.kty!=="oct"&&typeof e.d=="string"}function Nr(e){return e.kty!=="oct"&&typeof e.d>"u"}function Lr(e){return G(e)&&e.kty==="oct"&&typeof e.k=="string"}var di=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 L("Unsupported key curve for this operation")}},mi=(e,t)=>{let r;if(re(e))r=pi.from(e);else if($e(e))r=e;else{if(G(e))return e.crv;throw new TypeError(fe(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 o=r.asymmetricKeyDetails.namedCurve;return t?o:di(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Mr=mi;import{KeyObject as fi}from"node:crypto";var St=(e,t)=>{let r;try{e instanceof fi?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 oe=e=>e?.[Symbol.toStringTag],Rt=(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},hi=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&G(t)){if(Lr(t)&&Rt(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(!Et(t))throw new TypeError(wt(e,t,...q,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${oe(t)} instances for symmetric algorithms must be of type "secret"`)}},gi=(e,t,r,o)=>{if(o&&G(t))switch(r){case"sign":if($r(t)&&Rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Nr(t)&&Rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Et(t))throw new TypeError(wt(e,t,...q,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${oe(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${oe(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${oe(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${oe(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${oe(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Dr(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?hi(t,r,o,e):gi(t,r,o,e)}var _d=Dr.bind(void 0,!1),_r=Dr.bind(void 0,!0);function yi(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.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 s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let i of o.crit){if(!s.has(i))throw new L(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&o[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}var Ur=yi;function At(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 L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as jr,KeyObject as wi}from"node:crypto";var Ei=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Pt(e,t){let r,o,n;if(t instanceof wi)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(n=!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 s;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");St(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=o,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");St(t,e),s={padding:jr.RSA_PKCS1_PSS_PADDING,saltLength:jr.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=Mr(t),a=Ei.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);s={dsaEncoding:"ieee-p1363"};break}default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return n?{format:"jwk",key:t,...s}:s?{...s,key:t}:t}import*as Ne from"node:crypto";import{promisify as Si}from"node:util";function It(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Fr,createSecretKey as Br}from"node:crypto";function vt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(fe(t,...q));return Br(t)}if(t instanceof Fr)return t;if(re(t))return Tr(t,e,r),Fr.from(t);if(G(t))return e.startsWith("HS")?Br(Buffer.from(t.k,"base64url")):t;throw new TypeError(fe(t,...q,"Uint8Array","JSON Web Key"))}var Ri=Si(Ne.sign),Ai=async(e,t,r)=>{let o=vt(e,t,"sign");if(e.startsWith("HS")){let n=Ne.createHmac(It(e),o);return n.update(r),n.digest()}return Ri(At(e),r,Pt(e,o))},Wr=Ai;var V=e=>Math.floor(e.getTime()/1e3);var Pi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Le=e=>{let t=Pi.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-n:n};var ke=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(!xr(this._protectedHeader,this._unprotectedHeader))throw new K("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=Ur(K,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new K('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new K('JWS "alg" (Algorithm) Header Parameter missing or invalid');_r(i,t,"sign");let a=this._payload;s&&(a=z.encode(xe(a)));let l;this._protectedHeader?l=z.encode(xe(JSON.stringify(this._protectedHeader))):l=z.encode("");let u=Rr(l,z.encode("."),a),h=await Wr(i,t,u),m={signature:xe(h),payload:""};return s&&(m.payload=ht.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=ht.decode(l)),m}};var Me=class{constructor(t){P(this,"_flattened");this._flattened=new ke(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function Q(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var De=class{constructor(t={}){P(this,"_payload");if(!he(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:Q("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:Q("setNotBefore",V(t))}:this._payload={...this._payload,nbf:V(new Date)+Le(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:Q("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:Q("setExpirationTime",V(t))}:this._payload={...this._payload,exp:V(new Date)+Le(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:V(new Date)}:t instanceof Date?this._payload={...this._payload,iat:Q("setIssuedAt",V(t))}:typeof t=="string"?this._payload={...this._payload,iat:Q("setIssuedAt",V(new Date)+Le(t))}:this._payload={...this._payload,iat:Q("setIssuedAt",t)},this}};var ge=class extends De{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new Me(z.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new de("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};import{createHmac as vi,createPrivateKey as bi,randomBytes as Ci}from"node:crypto";import{existsSync as Ti,readFileSync as Hr,writeFileSync as Gr}from"node:fs";import{basename as Vr,extname as Oi,resolve as Ct}from"node:path";import{isPromise as xi}from"node:util/types";import{extract as $i}from"tar";function H(e){console.log(JSON.stringify(e,null,2))}async function Tt(e,t,r){let o=t.source,n=_e(o);if(!n)return;console.log("Saving source code...");let s=await e.createAttachment({data:n,filename:Vr(o),contentType:ki(o)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Ot(e,t,r){let o=t.dist??t.source,n=_e(o);if(!n)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:Vr(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function xt(e,t,r,o,n,s,i){let a={name:t,description:"",runtimeVersion:s},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),h={name:t,id:l.id,source:o,dist:n};await Tt(e,h,u),await Ot(e,h,u),console.log(`Success! Bot created: ${u.id}`),i&&Ni(h)}function Jr(e){let t=new RegExp("^"+Li(e).replaceAll(String.raw`\*`,".*")+"$"),r=j()?.bots?.filter(o=>t.test(o.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 C(e,t){Gr(Ct(e),JSON.stringify(t,void 0,2),"utf-8")}function j(e,t){let r=D(e,t),o=_e(r);if(o)return JSON.parse(o)}function Xr(e){let t=_e(D(e,{server:!0}));if(t)return JSON.parse(t)}function _e(e){let t=Ct(e);return Ti(t)?Hr(t,"utf8"):""}function Ni(e){let t=j()??{};t.bots||(t.bots=[]),t.bots.push(e),Gr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Li(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function zr(e){let o=0,n=0;return $i({cwd:e,filter:(s,i)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=i.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function $t(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ki(e){let t=Oi(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?bt.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?bt.TYPESCRIPT:bt.TEXT}function Ue(e,t){let r=new _(e),o={name:e,...t};return r.setObject("options",o),o}function Yr(e){return new _(e).getObject("options")}async function Qr(e,t){let r={typ:"JWT",alg:qr.HS256},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},s=Kr(JSON.stringify(r)),i=Kr(JSON.stringify(n)),a=`${s}.${i}`,l=vi("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Zr(e,t){let r=bi(Hr(Ct(t.privateKeyPath))),o=await new ge({}).setProtectedHeader({typ:"JWT",alg:qr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Ci(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends Ii{action(t){let r=Mi(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 Mi(e,t){return async r=>{let o=e.registeredArguments.length,n=r.slice(0,o);n[o]=e.optsWithGlobals();try{let s=t(...n);xi(s)&&await s}finally{e.resetOptionDefaults()}}}var to=new g("status").aliases(["info","list","ls"]),ro=new g("ping"),oo=new g("push"),no=new g("reload-config"),so=new g("upgrade"),Z=new g("agent");y(Z,to);y(Z,ro);y(Z,oo);y(Z,no);y(Z,so);to.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 Nt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Lt({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=Bi(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});ro.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await R(r),n=await io(o,t,r),s=Number.parseInt(r.count,10);if(Number.isNaN(s))throw new Error("--count <count> must be an integer if specified");try{let i=await o.pushToAgent(n,e,`PING ${s}`,eo.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});oo.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",eo.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let n=await R(o),s=await io(n,r,o),i;try{i=await n.pushToAgent(s,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});no.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 Nt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Lt({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});so.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 Nt("--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 Lt({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function Lt({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n}){let s=Ki(t,r),i=await R(r),a=s.type==="criteria"?s.criteria:`Agent?_id=${s.ids.join(",")}`,l=new URLSearchParams(a.split("?")[1]);for(let[b,W]of Object.entries(o))l.append(b,W.toString());let u;try{let b=i.fhirUrl("Agent",e);b.search=l.toString(),u=await i.get(b,{cache:"reload"})}catch(b){throw new Error(`Operation '${e}' failed`,{cause:b})}if(r.output==="json"){console.info(JSON.stringify(u,null,2));return}let h=[],m=[];switch(u.resourceType){case"Bundle":{let b=ji(u);for(let W of b)W.result.resourceType==="Parameters"||_i(W.result)?h.push(W):m.push(W);break}case"Parameters":case"OperationOutcome":{let b=await i.searchOne("Agent",l,{cache:"reload"});if(!b)throw new Error("Agent not found");u.resourceType==="Parameters"?h.push({agent:b,result:u}):m.push({agent:b,result:u});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(u)}`)}let S=[];for(let b of h){let W=n(b);S.push(W)}let f=[];for(let b of m){let mt=b.result.issue?.[0],Ws={id:b.agent.id,name:b.agent.name,severity:mt.severity,code:mt.code,details:mt.details?.text??"No details to show"};f.push(Ws)}console.info(`
3
3
  ${S.length} successful response(s):
4
- `),console.table(S.length?S:"No successful responses received"),console.info(),f.length&&(console.info(`${f.length} failed response(s):`),console.info(),console.table(f))}async function io(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(t)o=t;else{ao(r.criteria);let n=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!n?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(n.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=n.entry[0].resource?.id}return{reference:`Agent/${o}`}}function Ui(e){let t=[];for(let r of e.entry??[]){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ji(r.resource))}return t}function ji(e){let t=e.parameter?.find(o=>o.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function Fi(e,t){let r={},o=t.required,n=t.optional;for(let s of o){let i=e.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${s}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[a]}if(n?.length)for(let s of n){let i=e.parameter?.find(l=>l.name===s);if(!i)continue;let a=Bi(s,i);r[s]=a}return r}function Bi(e,t){let r;for(let o in t)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function Wi(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(!_i(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return ao(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function ao(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,o]=e.split("?");if(r!=="Agent"||!o)throw new Error(t);try{new URLSearchParams(o)}catch(n){throw new Error(t,{cause:n})}if(!o.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}import{ContentType as je,getDisplayString as Ki,MEDPLUM_CLI_CLIENT_ID as qi,normalizeErrorString as Hi}from"@medplum/core";import{exec as Gi}from"node:child_process";import{createServer as Vi}from"node:http";import{platform as Ji}from"node:os";var co=qi,lo="http://localhost:9615",kt=new g("login"),Dt=new g("whoami"),Mt=new g("token");kt.action(async e=>{let t=e.profile??"default",r=Ue(t,e),o=await R(e,!1);await Xi(o,r)});Dt.action(async e=>{let t=await R(e);Qi(t)});Mt.action(async e=>{let t=await R(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function Xi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Zi(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 Qr(e,t);break;case"jwt-assertion":await Zr(e,t);break}}async function zi(e){let t=Vi(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),s=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":je.TEXT}),o.end("OK");return}if(n.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:co,redirectUri:lo});o.writeHead(200,{"Content-Type":je.TEXT}),o.end(`Signed in as ${Ki(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":je.TEXT}),o.end(`Error: ${Hi(i)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":je.TEXT}),o.end("Not found")}).listen(9615)}async function Yi(e){let t=Ji(),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((o,n)=>{Gi(r,(s,i,a)=>{if(s){n(s);return}if(a){n(new Error("Could not open browser: "+a));return}o()})})}function Qi(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 Zi(e){await zi(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",co),t.searchParams.set("redirect_uri",lo),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Yi(t.toString())}var ye="\x1B[0m",ea="\x1B[1m",ta="\x1B[31m",ra="\x1B[32m",oa="\x1B[33m",na="\x1B[34m",ee={red:e=>`${ta}${e}${ye}`,green:e=>`${ra}${e}${ye}`,yellow:e=>`${oa}${e}${ye}`,blue:e=>`${na}${e}${ye}`,bold:e=>`${ea}${e}${ye}`},_t=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>ee.bold(r));var rs=wr(or(),1);import{CloudFormationClient as ts,DescribeStackResourcesCommand as tu,DescribeStacksCommand as ru,paginateListStacks as ou}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as nu,CreateInvalidationCommand as su}from"@aws-sdk/client-cloudfront";import{ECSClient as iu}from"@aws-sdk/client-ecs";import{S3Client as au}from"@aws-sdk/client-s3";import{GetParameterCommand as cu,PutParameterCommand as lu,SSMClient as uu}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as pu,STSClient as du}from"@aws-sdk/client-sts";import{normalizeErrorString as mu}from"@medplum/core";import fu from"node-fetch";import{readdirSync as hu}from"node:fs";import eu from"node:readline";var Qe;function Ze(){Qe=eu.createInterface({input:process.stdin,output:process.stdout})}function et(){Qe.close()}function c(e){Qe.write(e+`
4
+ `),console.table(S.length?S:"No successful responses received"),console.info(),f.length&&(console.info(`${f.length} failed response(s):`),console.info(),console.table(f))}async function io(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(t)o=t;else{ao(r.criteria);let n=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!n?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(n.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=n.entry[0].resource?.id}return{reference:`Agent/${o}`}}function ji(e){let t=[];for(let r of e.entry??Di){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(Fi(r.resource))}return t}function Fi(e){let t=e.parameter?.find(o=>o.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function Bi(e,t){let r={},o=t.required,n=t.optional;for(let s of o){let i=e.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${s}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[a]}if(n?.length)for(let s of n){let i=e.parameter?.find(l=>l.name===s);if(!i)continue;let a=Wi(s,i);r[s]=a}return r}function Wi(e,t){let r;for(let o in t)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function Ki(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(!Ui(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return ao(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function ao(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,o]=e.split("?");if(r!=="Agent"||!o)throw new Error(t);try{new URLSearchParams(o)}catch(n){throw new Error(t,{cause:n})}if(!o.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}import{ContentType as je,getDisplayString as qi,MEDPLUM_CLI_CLIENT_ID as Hi,normalizeErrorString as Gi}from"@medplum/core";import{exec as Vi}from"node:child_process";import{createServer as Ji}from"node:http";import{platform as Xi}from"node:os";var co=Hi,lo="http://localhost:9615",kt=new g("login"),Mt=new g("whoami"),Dt=new g("token");kt.action(async e=>{let t=e.profile??"default",r=Ue(t,e),o=await R(e,!1);await zi(o,r)});Mt.action(async e=>{let t=await R(e);Zi(t)});Dt.action(async e=>{let t=await R(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function zi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await ea(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 Qr(e,t);break;case"jwt-assertion":await Zr(e,t);break}}async function Yi(e){let t=Ji(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),s=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":je.TEXT}),o.end("OK");return}if(n.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:co,redirectUri:lo});o.writeHead(200,{"Content-Type":je.TEXT}),o.end(`Signed in as ${qi(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":je.TEXT}),o.end(`Error: ${Gi(i)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":je.TEXT}),o.end("Not found")}).listen(9615)}async function Qi(e){let t=Xi(),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((o,n)=>{Vi(r,(s,i,a)=>{if(s){n(s);return}if(a){n(new Error("Could not open browser: "+a));return}o()})})}function Zi(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 ea(e){await Yi(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",co),t.searchParams.set("redirect_uri",lo),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Qi(t.toString())}var ye="\x1B[0m",ta="\x1B[1m",ra="\x1B[31m",oa="\x1B[32m",na="\x1B[33m",sa="\x1B[34m",ee={red:e=>`${ra}${e}${ye}`,green:e=>`${oa}${e}${ye}`,yellow:e=>`${na}${e}${ye}`,blue:e=>`${sa}${e}${ye}`,bold:e=>`${ta}${e}${ye}`},_t=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>ee.bold(r));var rs=wr(or(),1);import{CloudFormationClient as ts,DescribeStackResourcesCommand as ru,DescribeStacksCommand as ou,paginateListStacks as nu}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as su,CreateInvalidationCommand as iu}from"@aws-sdk/client-cloudfront";import{ECSClient as au}from"@aws-sdk/client-ecs";import{S3Client as cu}from"@aws-sdk/client-s3";import{GetParameterCommand as lu,PutParameterCommand as uu,SSMClient as pu}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as du,STSClient as mu}from"@aws-sdk/client-sts";import{EMPTY as fu,normalizeErrorString as hu}from"@medplum/core";import gu from"node-fetch";import{readdirSync as yu}from"node:fs";import tu from"node:readline";var Qe;function Ze(){Qe=tu.createInterface({input:process.stdin,output:process.stdout})}function et(){Qe.close()}function c(e){Qe.write(e+`
5
5
  `)}function v(e){c(`
6
6
  `+e+`
7
- `)}function N(e,t=""){return new Promise(r=>{Qe.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function tt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await N(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function se(e,t,r){return Number.parseInt(await tt(e,t.map(o=>o.toString()),r.toString()),10)}async function J(e){return(await tt(e,["y","n"])).toLowerCase()==="y"}async function ve(e){if(!await J(e))throw c("Exiting..."),new Error("User cancelled")}var rt=new ts({}),gu=new nu({region:"us-east-1"}),sh=new iu({}),be=new au({}),yu="medplum:environment";async function nr(){let e=[],t=ou({client:rt},{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)if(r.StackSummaries)for(let o of r.StackSummaries)e.push(o);return e}async function ie(e){let t=await nr();for(let r of t){let o=r.StackName,n=await sr(o);if(n?.tag===e)return n}}async function sr(e){let t={};if(await es(rt,e,t),await rt.config.region()!=="us-east-1")try{await es(new ts({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function es(e,t,r){let o=new ru({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===yu);if(!i)return;let a=await e.send(new tu({StackName:t}));if(a.StackResources){e===rt&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)wu(l,r)}}function wu(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: ${Eu(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 Eu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function nt(e){let t=await gu.send(new su({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function st(e){let o=(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(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>rs.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function it(e,t,r){let o=new uu({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await Su(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await ve(`Do you want to overwrite "${i}"?`)),await Ru(o,i,a)}}async function Su(e,t){let r=new cu({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Ru(e,t,r){let o=new lu({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function X(e,t){if(console.log(`Config not found: ${e} (${M(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=hu(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function ae(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new du,r=new pu({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",mu(t))}}async function os(e){let t=await ie(e);if(!t)throw await ae(e),new Error(`Stack not found: ${e}`);ot(t)}import{ACMClient as is,ListCertificatesCommand as Au,RequestCertificateCommand as Pu}from"@aws-sdk/client-acm";import{CloudFrontClient as Iu,CreatePublicKeyCommand as vu}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as bu,STSClient as Cu}from"@aws-sdk/client-sts";import{normalizeErrorString as Tu}from"@medplum/core";import{generateKeyPairSync as Ou,randomUUID as ns}from"node:crypto";import{existsSync as xu}from"node:fs";var $u=e=>`${e}DomainName`,as=e=>`${e}SslCertArn`;async function cs(){let e={apiPort:8103,region:"us-east-1"};Ze(),v("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 Nu(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 ve("Do you want to continue without AWS credentials?")),v("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+'"...'),v("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`);xu(r)&&(c("Config file already exists."),await ve("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),v("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"),C(r,e),v("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),C(r,e),v("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",o),C(r,e),v("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:");C(r,e),v("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 n=await N("Enter your support email address:");v("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}/`,C(r,e),v("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),C(r,e),v("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),C(r,e),v("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),C(r,e),v("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 se("Enter the maximum number of availability zones:",[2,3,99],2),v("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 J("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 se("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"),C(r,e),v("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 se("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),v("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 se("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),v("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 se("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),v("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 s=(await st())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${s}`),C(r,e),v("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await Mu(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,C(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.')),v("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Lu(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:h}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await ku(e,a,u,h);e[as(h)]=m,C(r,e)}v("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:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await J("Do you want to store these values in AWS Parameter Store?"))await it(e.region,`/medplum/${e.name}/`,l);else{let u=M(e.name,{server:!0});C(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.")}v("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(""),et()}async function Nu(e){try{let t=new Cu({region:e}),r=new bu({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Lu(e){let t=await ss(e);if(e!=="us-east-1"){let r=await ss("us-east-1");t.push(...r)}return t}async function ss(e){try{let t=new is({region:e}),r=new Au({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function ku(e,t,r,o){let n=e[$u(o)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===n);if(s)return c(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await J("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${as(o)}" setting.`),"TODO";let i=await Du(r,n);return c("Certificate ARN: "+i),i}async function Du(e,t){try{let r=await tt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new is({region:e}),n=new Pu({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Mu(e,t){let r=ns(),o=Ou("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Iu({region:e}).send(new vu({PublicKeyConfig:{Name:t,CallerReference:ns(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",Tu(n));return}}async function ls(){let e=await nr();for(let t of e){let r=t.StackName,o=await sr(r);o&&(ot(o),console.log(""))}}import{PutObjectCommand as _u}from"@aws-sdk/client-s3";import{ContentType as B}from"@medplum/core";import Uu from"fast-glob";import us from"node-fetch";import{createReadStream as ju,mkdtempSync as Fu,readdirSync as Bu,readFileSync as Wu,rmSync as Ku,writeFileSync as qu}from"node:fs";import{tmpdir as Hu}from"node:os";import{join as at,sep as Gu}from"node:path";import{pipeline as Vu}from"node:stream/promises";async function ps(e,t){let r=j(e,t);if(!r)throw X(e,t),new Error(`Config not found: ${e}`);let o=await ie(e);if(!o)throw await ae(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let s;if(t.tarPath)s=t.tarPath;else{let i=t?.toVersion??"latest";s=await Xu("@medplum/app",i)}ds(s,{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 Yu(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await nt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Ju(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await us(r)).json()}async function Xu(e,t){let o=(await Ju(e,t)).dist.tarball,n=Fu(at(Hu(),"tarball-"));try{let s=await us(o),i=zr(n);return await Vu(s.body,i),at(n,"package","dist")}catch(s){throw Ku(n,{recursive:!0,force:!0}),s}}function ds(e,t){for(let r of Bu(e,{withFileTypes:!0})){let o=at(e,r.name);r.isDirectory()?ds(o,t):r.isFile()&&o.endsWith(".js")&&zu(o,t)}}function zu(e,t){let r=Wu(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);qu(e,r)}async function Yu(e,t,r){let o=[["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 n of o)await Qu({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Qu(e){let t=Uu.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Zu(at(e.rootDir,r),e)}async function Zu(e,t){let r=ju(e),o=e.substring(t.rootDir.length+1).split(Gu).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await be.send(new _u(n))}import{GetBucketPolicyCommand as ep,PutBucketPolicyCommand as tp}from"@aws-sdk/client-s3";async function fs(e,t){if(!j(e,t))throw X(e,t),new Error(`Config not found: ${e}`);let o=await ie(e);if(!o)throw await ae(e),new Error(`Stack not found: ${e}`);await ms("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await ms("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function ms(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=o.PhysicalResourceId,a=await rp(s);if(np(a,s,i))throw new Error(`${e} bucket already has policy statement`);sp(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await op(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await nt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function rp(e){let t=await be.send(new ep({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function op(e,t){await be.send(new tp({Bucket:e,Policy:JSON.stringify(t)}))}function np(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function sp(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}/*`]})}async function hs(e,t){try{Ze();let r=j(e,t);if(!r)throw X(e,t),new Error(`Config not found: ${e}`);let o=Xr(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=M(e,{server:!0});if(console.log(ee.yellow(`Config file ${n} not found!`)),!await J("Do you want to proceed?")){console.log(ee.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}ip(r,o),cp(r,o),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({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(ee.yellow("Dry run - skipping updates!")):(t.yes||await J("Do you want to store these values in AWS Parameter Store?"))&&await it(r.region,`/medplum/${r.name}/`,o)}finally{et()}}function ip(e,t){ct(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),ct(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),ct(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),ct(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function ct(e,t,r){if(ap(e,t))throw new Error(r)}function ap(e,t){return e!==void 0&&t!==void 0&&e!==t}function cp(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}/`)}var ce=wr(or(),1);import{spawnSync as lp}from"node:child_process";async function ys(e,t){let r=await R(t),o=j(e,t);if(!o)throw console.log(`Configuration file ${M(e)} not found`),X(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await up(r,o),a=await gs(i);for(;a;){if(t.toVersion&&ce.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,pp(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await gs(a)}}async function up(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function gs(e,t){let r=await st(e),o=r[0];return r.filter(n=>n===o||n===t||ce.gte(n,ce.inc(e,"minor"))).pop()}function pp(e,t){let r=M(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=lp(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function ws(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(cs),e.command("list").description("List Medplum AWS CloudFormation stacks").action(ls),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(os),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=>{Qe.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function tt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await N(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function se(e,t,r){return Number.parseInt(await tt(e,t.map(o=>o.toString()),r.toString()),10)}async function J(e){return(await tt(e,["y","n"])).toLowerCase()==="y"}async function ve(e){if(!await J(e))throw c("Exiting..."),new Error("User cancelled")}var rt=new ts({}),wu=new su({region:"us-east-1"}),lh=new au({}),be=new cu({}),Eu="medplum:environment";async function nr(){let e=[],t=nu({client:rt},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)for(let o of r.StackSummaries??fu)e.push(o);return e}async function ie(e){let t=await nr();for(let r of t){let o=r.StackName,n=await sr(o);if(n?.tag===e)return n}}async function sr(e){let t={};if(await es(rt,e,t),await rt.config.region()!=="us-east-1")try{await es(new ts({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function es(e,t,r){let o=new ou({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===Eu);if(!i)return;let a=await e.send(new ru({StackName:t}));if(a.StackResources){e===rt&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)Su(l,r)}}function Su(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: ${Ru(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 Ru(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function nt(e){let t=await wu.send(new iu({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function st(e){let o=(await(await gu("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(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>rs.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function it(e,t,r){let o=new pu({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await Au(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await ve(`Do you want to overwrite "${i}"?`)),await Pu(o,i,a)}}async function Au(e,t){let r=new lu({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Pu(e,t,r){let o=new uu({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function X(e,t){if(console.log(`Config not found: ${e} (${D(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=yu(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function ae(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new mu,r=new du({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",hu(t))}}async function os(e){let t=await ie(e);if(!t)throw await ae(e),new Error(`Stack not found: ${e}`);ot(t)}import{ACMClient as is,ListCertificatesCommand as Iu,RequestCertificateCommand as vu}from"@aws-sdk/client-acm";import{CloudFrontClient as bu,CreatePublicKeyCommand as Cu}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as Tu,STSClient as Ou}from"@aws-sdk/client-sts";import{normalizeErrorString as xu}from"@medplum/core";import{generateKeyPairSync as $u,randomUUID as ns}from"node:crypto";import{existsSync as Nu}from"node:fs";var Lu=e=>`${e}DomainName`,as=e=>`${e}SslCertArn`;async function cs(){let e={apiPort:8103,region:"us-east-1"};Ze(),v("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 ku(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 ve("Do you want to continue without AWS credentials?")),v("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+'"...'),v("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`);Nu(r)&&(c("Config file already exists."),await ve("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),v("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"),C(r,e),v("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),C(r,e),v("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",o),C(r,e),v("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:");C(r,e),v("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 n=await N("Enter your support email address:");v("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}/`,C(r,e),v("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),C(r,e),v("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),C(r,e),v("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),C(r,e),v("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 se("Enter the maximum number of availability zones:",[2,3,99],2),v("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 J("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 se("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"),C(r,e),v("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 se("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),v("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 se("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),v("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 se("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),v("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 s=(await st())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${s}`),C(r,e),v("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await Uu(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,C(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.')),v("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Mu(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:h}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await Du(e,a,u,h);e[as(h)]=m,C(r,e)}v("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:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await J("Do you want to store these values in AWS Parameter Store?"))await it(e.region,`/medplum/${e.name}/`,l);else{let u=D(e.name,{server:!0});C(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.")}v("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(""),et()}async function ku(e){try{let t=new Ou({region:e}),r=new Tu({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Mu(e){let t=await ss(e);if(e!=="us-east-1"){let r=await ss("us-east-1");t.push(...r)}return t}async function ss(e){try{let t=new is({region:e}),r=new Iu({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Du(e,t,r,o){let n=e[Lu(o)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===n);if(s)return c(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await J("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${as(o)}" setting.`),"TODO";let i=await _u(r,n);return c("Certificate ARN: "+i),i}async function _u(e,t){try{let r=await tt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new is({region:e}),n=new vu({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Uu(e,t){let r=ns(),o=$u("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new bu({region:e}).send(new Cu({PublicKeyConfig:{Name:t,CallerReference:ns(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",xu(n));return}}async function ls(){let e=await nr();for(let t of e){let r=t.StackName,o=await sr(r);o&&(ot(o),console.log(""))}}import{PutObjectCommand as ju}from"@aws-sdk/client-s3";import{ContentType as B}from"@medplum/core";import Fu from"fast-glob";import us from"node-fetch";import{createReadStream as Bu,mkdtempSync as Wu,readdirSync as Ku,readFileSync as qu,rmSync as Hu,writeFileSync as Gu}from"node:fs";import{tmpdir as Vu}from"node:os";import{join as at,sep as Ju}from"node:path";import{pipeline as Xu}from"node:stream/promises";async function ps(e,t){let r=j(e,t);if(!r)throw X(e,t),new Error(`Config not found: ${e}`);let o=await ie(e);if(!o)throw await ae(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let s;if(t.tarPath)s=t.tarPath;else{let i=t?.toVersion??"latest";s=await Yu("@medplum/app",i)}ds(s,{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 Zu(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await nt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function zu(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await us(r)).json()}async function Yu(e,t){let o=(await zu(e,t)).dist.tarball,n=Wu(at(Vu(),"tarball-"));try{let s=await us(o),i=zr(n);return await Xu(s.body,i),at(n,"package","dist")}catch(s){throw Hu(n,{recursive:!0,force:!0}),s}}function ds(e,t){for(let r of Ku(e,{withFileTypes:!0})){let o=at(e,r.name);r.isDirectory()?ds(o,t):r.isFile()&&o.endsWith(".js")&&Qu(o,t)}}function Qu(e,t){let r=qu(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Gu(e,r)}async function Zu(e,t,r){let o=[["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 n of o)await ep({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function ep(e){let t=Fu.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await tp(at(e.rootDir,r),e)}async function tp(e,t){let r=Bu(e),o=e.substring(t.rootDir.length+1).split(Ju).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await be.send(new ju(n))}import{GetBucketPolicyCommand as rp,PutBucketPolicyCommand as op}from"@aws-sdk/client-s3";async function fs(e,t){if(!j(e,t))throw X(e,t),new Error(`Config not found: ${e}`);let o=await ie(e);if(!o)throw await ae(e),new Error(`Stack not found: ${e}`);await ms("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await ms("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function ms(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=o.PhysicalResourceId,a=await np(s);if(ip(a,s,i))throw new Error(`${e} bucket already has policy statement`);ap(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await sp(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await nt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function np(e){let t=await be.send(new rp({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function sp(e,t){await be.send(new op({Bucket:e,Policy:JSON.stringify(t)}))}function ip(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function ap(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}/*`]})}async function hs(e,t){try{Ze();let r=j(e,t);if(!r)throw X(e,t),new Error(`Config not found: ${e}`);let o=Xr(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=D(e,{server:!0});if(console.log(ee.yellow(`Config file ${n} not found!`)),!await J("Do you want to proceed?")){console.log(ee.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}cp(r,o),up(r,o),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({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(ee.yellow("Dry run - skipping updates!")):(t.yes||await J("Do you want to store these values in AWS Parameter Store?"))&&await it(r.region,`/medplum/${r.name}/`,o)}finally{et()}}function cp(e,t){ct(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),ct(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),ct(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),ct(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function ct(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 up(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}/`)}var ce=wr(or(),1);import{spawnSync as pp}from"node:child_process";async function ys(e,t){let r=await R(t),o=j(e,t);if(!o)throw console.log(`Configuration file ${D(e)} not found`),X(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await dp(r,o),a=await gs(i);for(;a;){if(t.toVersion&&ce.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,mp(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await gs(a)}}async function dp(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function gs(e,t){let r=await st(e),o=r[0];return r.filter(n=>n===o||n===t||ce.gte(n,ce.inc(e,"minor"))).pop()}function mp(e,t){let r=D(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=pp(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function ws(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(cs),e.command("list").description("List Medplum AWS CloudFormation stacks").action(ls),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(os),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
  `+ee.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(hs),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(ys)),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(ps),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("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(fs),e}var Es=new g("save"),Ss=new g("deploy"),Rs=new g("create"),Ce=new g("bot");y(Ce,Es);y(Ce,Ss);y(Ce,Rs);var ir=new g("save-bot"),ar=new g("deploy-bot"),cr=new g("create-bot");Es.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await lt(r,e)});Ss.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await lt(r,e,!0)});Rs.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,n)=>{let s=await R(n);await xt(s,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function lt(e,t,r=!1){let o=Jr(t),n=[],s=[],i=0,a=0;for(let l of o)try{let u=await e.readResource("Bot",l.id);await Tt(e,l,u),i++,r&&(await Ot(e,l,u),a++)}catch(u){n.push(u),s.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: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
12
12
 
13
13
  ${s.join(`
14
- `)}`,{cause:n})}ir.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await lt(r,e)});ar.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await lt(r,e,!0)});cr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let s=await R(n);await xt(s,e,t,r,o)});import{createReadStream as dp,writeFile as mp}from"node:fs";import{resolve as Ps}from"node:path";import{createInterface as fp}from"node:readline";var Is=new g("export"),vs=new g("import"),ut=new g("bulk");y(ut,Is);y(ut,vs);Is.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,s=await R(e);(await s.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:a,url:l})=>{let u=new URL(l),h=await s.download(l),m=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",S=Ps(n??"",m);mp(`${S}`,await h.text(),()=>{console.log(`${S} is created`)})})});vs.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,s=Ps(n??process.cwd(),e),i=await R(t);await hp(s,Number.parseInt(r,10),i,o)});async function hp(e,t,r,o){let n=[],s=dp(e),i=fp({input:s});for await(let a of i){let l=gp(a,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await As(n,r),n=[])}n.length>0&&await As(n,r)}async function As(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{H(o.response)})}function gp(e,t){let r=JSON.parse(e);return t?yp(r):r}function yp(e){return e.resourceType==="ExplanationOfBenefit"?wp(e):e}function wp(e){return e.provider||(e.provider=$t()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=$t())}),e}import{formatHl7DateTime as xp,Hl7Message as $p}from"@medplum/core";import pt from"node:assert";import{connect as Rp}from"node:net";import{Hl7Message as Ap,OperationOutcomeError as Te,sleep as Pp,validationError as Ip}from"@medplum/core";import bs from"iconv-lite";import{sleep as Cp}from"@medplum/core";import Tp from"node:net";var Ep=Object.defineProperty,Sp=(e,t,r)=>t in e?Ep(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t,r)=>Sp(e,typeof t!="symbol"?t+"":t,r),Os=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var vp=class extends Event{constructor(e,t){super("message"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},le=class extends Event{constructor(e){super("error"),A(this,"error"),this.error=e}},lr=class extends Event{constructor(){super("close")}},Cs={FIRST:"first",APPLICATION:"application"},Ts="utf-8",bp=60*1e3,xs=class extends Os{constructor(e,t=Ts,r=!1,o={}){super(),A(this,"socket"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"chunks",[]),A(this,"pendingMessages",new Map),A(this,"responseQueue",[]),A(this,"lastMessageDispatchedTime",0),A(this,"responseQueueProcessing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,e.on("data",n=>{try{this.appendData(n);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new vp(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new le(i))})}catch(s){this.dispatchEvent(new le(s))}}),e.on("error",n=>{this.resetBuffer(),this.dispatchEvent(new le(n))}),e.on("close",()=>{this.dispatchEvent(new lr)}),this.addEventListener("message",n=>{this.enhancedMode&&this.send(n.message.buildAck({ackCode:"CA"}));let s=n.message.getSegment("MSA")?.getField(2)?.toString();if(!s)return;let i=this.pendingMessages.get(s);if(!i){this.dispatchEvent(new le(new Te({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${s}' but there was no pending message with this control ID`}]})));return}let a=n.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();a&&(i.returnAck===Cs.APPLICATION&&a==="CA"||(i.resolve(n.message),this.pendingMessages.delete(s)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=bs.encode(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=bp/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await Pp(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let o=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){o=a+1;break}if(o===-1)break;let n=t.subarray(r,o+1).subarray(1,-2),s=bs.decode(n,this.encoding),i=Ap.parse(s);e.push(i),r=o+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,o)=>{let n=e.getSegment("MSH")?.getField(10)?.toString();if(!n){o(new Te(Ip("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.pendingMessages.delete(n),o(new Te({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.pendingMessages.set(n,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??Cs.APPLICATION,timer:s}),this.sendImpl(e)})}async close(){if(!this.isClosed()){if(this.socket.end(),this.socket.destroy(),this.pendingMessages.size){for(let e of this.pendingMessages.values())e.timer&&clearTimeout(e.timer),e.reject(new Te({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new le(new Te({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${this.pendingMessages.size} messages were pending`}]}))),this.pendingMessages.clear()}await new Promise(e=>{this.socket.once("close",e)})}}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??Ts}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}},$s=class extends Os{constructor(e){super(),A(this,"options"),A(this,"host"),A(this,"port"),A(this,"encoding"),A(this,"connection"),A(this,"keepAlive"),A(this,"socket"),A(this,"connectTimeout"),A(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=Rp({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){pt(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let o=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,o)};t.on("timeout",r)}registerSocketConnectListener(e){pt(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=new xs(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){pt(this.socket);let t=this.socket,r=o=>{this.cleanupSocket(t),o.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,o.errors[0]):this.rejectDeferredPromise(e,o)};t.on("error",r)}registerSocketCloseListener(e){pt(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 lr)}),e.addEventListener("error",t=>{this.dispatchEvent(new le(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}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 lr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Op=1e4,Ns=class{constructor(e){A(this,"handler"),A(this,"server"),A(this,"encoding"),A(this,"enhancedMode",!1),A(this,"messagesPerMin"),A(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let n=Tp.createServer(s=>{let i=new xs(s,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});await new Promise(s=>{let i=l=>{n.listen(l,s)},a=async l=>{l?.code==="EADDRINUSE"&&(await Cp(50),n.close(),i(e))};n.on("error",a),n.once("listening",()=>{n.off("error",a)}),i(e),this.server=n})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let n of this.connections)n.close().catch(console.error)},e?.forceDrainTimeoutMs??Op)),this.server.close(n=>{if(n){r(n);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}};import{readFileSync as Np}from"node:fs";var Lp=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,o)=>{if(o.generateExample?r=Dp():o.file&&(r=Np(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new $s({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let s=await n.sendAndWait($p.parse(r));console.log(s.toString().replaceAll("\r",`
15
- `))}finally{await n.close()}}),kp=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 Ns(o=>{o.addEventListener("message",({message:n})=>{console.log(n.toString().replaceAll("\r",`
16
- `)),o.send(n.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),dt=new g("hl7");y(dt,Lp);y(dt,kp);function Dp(){let e=xp(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
14
+ `)}`,{cause:n})}ir.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await lt(r,e)});ar.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await lt(r,e,!0)});cr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let s=await R(n);await xt(s,e,t,r,o)});import{EMPTY as fp}from"@medplum/core";import{createReadStream as hp,writeFile as gp}from"node:fs";import{resolve as Ps}from"node:path";import{createInterface as yp}from"node:readline";var Is=new g("export"),vs=new g("import"),ut=new g("bulk");y(ut,Is);y(ut,vs);Is.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,s=await R(e);(await s.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:a,url:l})=>{let u=new URL(l),h=await s.download(l),m=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",S=Ps(n??"",m);gp(`${S}`,await h.text(),()=>{console.log(`${S} is created`)})})});vs.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,s=Ps(n??process.cwd(),e),i=await R(t);await wp(s,Number.parseInt(r,10),i,o)});async function wp(e,t,r,o){let n=[],s=hp(e),i=yp({input:s});for await(let a of i){let l=Ep(a,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await As(n,r),n=[])}n.length>0&&await As(n,r)}async function As(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??fp)H(o.response)}function Ep(e,t){let r=JSON.parse(e);return t?Sp(r):r}function Sp(e){return e.resourceType==="ExplanationOfBenefit"?Rp(e):e}function Rp(e){return e.provider||(e.provider=$t()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=$t())}),e}import{formatHl7DateTime as kp,Hl7Message as Mp}from"@medplum/core";import pt from"node:assert";import{connect as Ip}from"node:net";import{Hl7Message as vp,OperationOutcomeError as Te,sleep as bp,validationError as Cp}from"@medplum/core";import bs from"iconv-lite";import{sleep as $p}from"@medplum/core";import Np from"node:net";var Ap=Object.defineProperty,Pp=(e,t,r)=>t in e?Ap(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t,r)=>Pp(e,typeof t!="symbol"?t+"":t,r),Os=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Tp=class extends Event{constructor(e,t){super("message"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},Op=class extends Event{constructor(e,t){super("enhancedAckSent"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},le=class extends Event{constructor(e){super("error"),A(this,"error"),this.error=e}},lr=class extends Event{constructor(){super("close")}},Cs={FIRST:"first",APPLICATION:"application"},Ts="utf-8",xp=60*1e3,xs=class extends Os{constructor(e,t=Ts,r,o={}){super(),A(this,"socket"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"chunks",[]),A(this,"pendingMessages",new Map),A(this,"responseQueue",[]),A(this,"lastMessageDispatchedTime",0),A(this,"responseQueueProcessing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,e.on("data",n=>{try{this.appendData(n);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new Tp(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new le(i))})}catch(s){this.dispatchEvent(new le(s))}}),e.on("error",n=>{this.resetBuffer(),this.dispatchEvent(new le(n))}),e.on("close",()=>{this.dispatchEvent(new lr)}),this.addEventListener("message",n=>{let s;this.enhancedMode==="standard"?s=n.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(s=n.message.buildAck({ackCode:"AA"})),s&&(this.send(s),this.dispatchEvent(new Op(this,s)));let i=n.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.pendingMessages.get(i);if(!a){this.dispatchEvent(new le(new Te({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=n.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===Cs.APPLICATION&&l==="CA"||(a.resolve(n.message),this.pendingMessages.delete(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=bs.encode(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=xp/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await bp(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let o=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){o=a+1;break}if(o===-1)break;let n=t.subarray(r,o+1).subarray(1,-2),s=bs.decode(n,this.encoding),i=vp.parse(s);e.push(i),r=o+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,o)=>{let n=e.getSegment("MSH")?.getField(10)?.toString();if(!n){o(new Te(Cp("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.pendingMessages.delete(n),o(new Te({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.pendingMessages.set(n,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??Cs.APPLICATION,timer:s}),this.sendImpl(e)})}async close(){if(!this.isClosed()){if(this.socket.end(),this.socket.destroy(),this.pendingMessages.size){for(let e of this.pendingMessages.values())e.timer&&clearTimeout(e.timer),e.reject(new Te({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new le(new Te({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${this.pendingMessages.size} messages were pending`}]}))),this.pendingMessages.clear()}await new Promise(e=>{this.socket.once("close",e)})}}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??Ts}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}},$s=class extends Os{constructor(e){super(),A(this,"options"),A(this,"host"),A(this,"port"),A(this,"encoding"),A(this,"connection"),A(this,"keepAlive"),A(this,"socket"),A(this,"connectTimeout"),A(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=Ip({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){pt(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let o=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,o)};t.on("timeout",r)}registerSocketConnectListener(e){pt(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=new xs(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){pt(this.socket);let t=this.socket,r=o=>{this.cleanupSocket(t),o.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,o.errors[0]):this.rejectDeferredPromise(e,o)};t.on("error",r)}registerSocketCloseListener(e){pt(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 lr)}),e.addEventListener("error",t=>{this.dispatchEvent(new le(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}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 lr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Lp=1e4,Ns=class{constructor(e){A(this,"handler"),A(this,"server"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let n=Np.createServer(s=>{let i=new xs(s,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});await new Promise(s=>{let i=l=>{n.listen(l,s)},a=async l=>{l?.code==="EADDRINUSE"&&(await $p(50),n.close(),i(e))};n.on("error",a),n.once("listening",()=>{n.off("error",a)}),i(e),this.server=n})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let n of this.connections)n.close().catch(console.error)},e?.forceDrainTimeoutMs??Lp)),this.server.close(n=>{if(n){r(n);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}};import{readFileSync as Dp}from"node:fs";var _p=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,o)=>{if(o.generateExample?r=jp():o.file&&(r=Dp(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new $s({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let s=await n.sendAndWait(Mp.parse(r));console.log(s.toString().replaceAll("\r",`
15
+ `))}finally{await n.close()}}),Up=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 Ns(o=>{o.addEventListener("message",({message:n})=>{console.log(n.toString().replaceAll("\r",`
16
+ `)),o.send(n.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),dt=new g("hl7");y(dt,_p);y(dt,Up);function jp(){let e=kp(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 Mp}from"node:fs";import{homedir as _p}from"node:os";import{resolve as Up}from"node:path";var Ls=new g("set"),ks=new g("remove"),Ds=new g("list"),Ms=new g("describe"),ue=new g("profile");y(ue,Ls);y(ue,ks);y(ue,Ds);y(ue,Ms);Ls.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)});ks.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`)});Ds.description("List all profiles saved").action(async()=>{let e=Up(_p(),".medplum"),t=Mp(e),r=[];t.forEach(o=>{let n=o.split(".")[0],i=new _(n).getObject("options");i&&r.push({profileName:n,profile:i})}),console.log(r)});Ms.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Yr(e);console.log(t)});import{Option as jp}from"commander";var _s=new g("list"),Us=new g("current"),js=new g("switch"),Fs=new g("invite"),pe=new g("project");y(pe,_s);y(pe,Us);y(pe,js);y(pe,Fs);_s.description("List of current projects").action(async e=>{let t=await R(e);Fp(t)});function Fp(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
19
+ PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}import{readdirSync as Fp}from"node:fs";import{homedir as Bp}from"node:os";import{resolve as Wp}from"node:path";var Ls=new g("set"),ks=new g("remove"),Ms=new g("list"),Ds=new g("describe"),ue=new g("profile");y(ue,Ls);y(ue,ks);y(ue,Ms);y(ue,Ds);Ls.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)});ks.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`)});Ms.description("List all profiles saved").action(async()=>{let e=Wp(Bp(),".medplum"),t=Fp(e),r=[];t.forEach(o=>{let n=o.split(".")[0],i=new _(n).getObject("options");i&&r.push({profileName:n,profile:i})}),console.log(r)});Ds.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Yr(e);console.log(t)});import{Option as Kp}from"commander";var _s=new g("list"),Us=new g("current"),js=new g("switch"),Fs=new g("invite"),pe=new g("project");y(pe,_s);y(pe,Us);y(pe,js);y(pe,Fs);_s.description("List of current projects").action(async e=>{let t=await R(e);qp(t)});function qp(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
20
20
 
21
- `);console.log(r)}Us.description("Project you are currently on").action(async e=>{let r=(await R(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});js.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await R(t);await Bp(r,e)});Fs.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 jp("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await R(o),s=n.getActiveLogin();if(!s)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!s?.project?.reference)throw new Error("No current project to invite user to");let i=s.project.reference.split("/")[1],a={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await Wp(i,a,n)});async function Bp(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));if(!o)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(o),console.log(`Switched to project ${t}
22
- `)}async function Wp(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 Kp}from"@medplum/core";var ur=new g("delete"),pr=new g("get"),dr=new g("patch"),mr=new g("post"),fr=new g("put");ur.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await R(t);H(await r.delete(Oe(r,e)))});pr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await R(t),o=await r.get(Oe(r,e));t.asTransaction?H(Kp(o)):H(o)});dr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await R(r);H(await o.patch(Oe(o,e),hr(t)))});mr.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let o=await R(r),n=r.preferAsync?{Prefer:"respond-async"}:void 0;H(await o.post(Oe(o,e),hr(t),void 0,{headers:n}))});fr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await R(r);H(await o.put(Oe(o,e),hr(t)))});function hr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Oe(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function Vp(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 Hp("--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(qp),t.configureHelp({showGlobalOptions:!0}),y(t,kt),y(t,Dt),y(t,Mt),y(t,pr),y(t,mr),y(t,dr),y(t,fr),y(t,ur),y(t,pe),y(t,ut),y(t,Ce),y(t,Z),y(t,ir),y(t,ar),y(t,cr),y(t,ue),y(t,ws()),y(t,dt);try{await t.parseAsync(e)}catch(r){Jp(r)}}function Jp(e){let t=1,r=!0;if(e instanceof Bs&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){gr(e,!!process.env.VERBOSE);let o=e.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let n of o)gr(n,!0);else o instanceof Error&&gr(o,!0)}process.exit(t)}function gr(e,t=!1){if(t){console.error(e);return}e instanceof Bs?process.stderr.write(`${yr(e)}
21
+ `);console.log(r)}Us.description("Project you are currently on").action(async e=>{let r=(await R(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});js.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await R(t);await Hp(r,e)});Fs.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 Kp("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await R(o),s=n.getActiveLogin();if(!s)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!s?.project?.reference)throw new Error("No current project to invite user to");let i=s.project.reference.split("/")[1],a={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await Gp(i,a,n)});async function Hp(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));if(!o)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(o),console.log(`Switched to project ${t}
22
+ `)}async function Gp(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 Vp}from"@medplum/core";var ur=new g("delete"),pr=new g("get"),dr=new g("patch"),mr=new g("post"),fr=new g("put");ur.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await R(t);H(await r.delete(Oe(r,e)))});pr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await R(t),o=await r.get(Oe(r,e));t.asTransaction?H(Vp(o)):H(o)});dr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await R(r);H(await o.patch(Oe(o,e),hr(t)))});mr.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let o=await R(r),n=r.preferAsync?{Prefer:"respond-async"}:void 0;H(await o.post(Oe(o,e),hr(t),void 0,{headers:n}))});fr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await R(r);H(await o.put(Oe(o,e),hr(t)))});function hr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Oe(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function Yp(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 Xp("--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(Jp),t.configureHelp({showGlobalOptions:!0}),y(t,kt),y(t,Mt),y(t,Dt),y(t,pr),y(t,mr),y(t,dr),y(t,fr),y(t,ur),y(t,pe),y(t,ut),y(t,Ce),y(t,Z),y(t,ir),y(t,ar),y(t,cr),y(t,ue),y(t,ws()),y(t,dt);try{await t.parseAsync(e)}catch(r){Qp(r)}}function Qp(e){let t=1,r=!0;if(e instanceof Bs&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){gr(e,!!process.env.VERBOSE);let o=e.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let n of o)gr(n,!0);else o instanceof Error&&gr(o,!0)}process.exit(t)}function gr(e,t=!1){if(t){console.error(e);return}e instanceof Bs?process.stderr.write(`${yr(e)}
23
23
  `):process.stderr.write(`Error: ${yr(e)}
24
- `)}async function Xp(){Gp.config({quiet:!0}),await Vp(process.argv)}import.meta.main&&Xp().catch(e=>{console.error("Unhandled error:",yr(e)),process.exit(1)});export{Jp as handleError,Vp as main,Xp as run};
24
+ `)}async function Zp(){zp.config({quiet:!0}),await Yp(process.argv)}import.meta.main&&Zp().catch(e=>{console.error("Unhandled error:",yr(e)),process.exit(1)});export{Qp as handleError,Yp as main,Zp as run};
25
25
  //# sourceMappingURL=index.mjs.map