@medplum/cli 5.1.22 → 5.1.23

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Gi=Object.create;var Oe=Object.defineProperty;var Vi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Xi=Object.getPrototypeOf,zi=Object.prototype.hasOwnProperty;var Yi=(e,t,r)=>t in e?Oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Qi=(e,t)=>{for(var r in t)Oe(e,r,{get:t[r],enumerable:!0})},Hr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ji(t))!zi.call(e,s)&&s!==r&&Oe(e,s,{get:()=>t[s],enumerable:!(n=Vi(t,s))||n.enumerable});return e};var L=(e,t,r)=>(r=e!=null?Gi(Xi(e)):{},Hr(t||!e||!e.__esModule?Oe(r,"default",{value:e,enumerable:!0}):r,e)),Zi=e=>Hr(Oe({},"__esModule",{value:!0}),e);var b=(e,t,r)=>Yi(e,typeof t!="symbol"?t+"":t,r);var Ee=w((wm,Hn)=>{"use strict";var _a="2.0.0",Ua=Number.MAX_SAFE_INTEGER||9007199254740991,ja=16,Fa=250,Ba=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Hn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ja,MAX_SAFE_BUILD_LENGTH:Fa,MAX_SAFE_INTEGER:Ua,RELEASE_TYPES:Ba,SEMVER_SPEC_VERSION:_a,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ue=w((Em,Gn)=>{"use strict";var Wa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Gn.exports=Wa});var Se=w((V,Vn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ar,MAX_SAFE_BUILD_LENGTH:Ka,MAX_LENGTH:qa}=Ee(),Ha=Ue();V=Vn.exports={};var Ga=V.re=[],Va=V.safeRe=[],p=V.src=[],Ja=V.safeSrc=[],d=V.t={},Xa=0,cr="[a-zA-Z0-9-]",za=[["\\s",1],["\\d",qa],[cr,Ka]],Ya=e=>{for(let[t,r]of za)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=Ya(t),s=Xa++;Ha(e,s,t),d[e]=s,p[s]=t,Ja[s]=n,Ga[s]=new RegExp(t,r?"g":void 0),Va[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${cr}*`);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",`${cr}+`);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,${ar}})(?:\\.(\\d{1,${ar}}))?(?:\\.(\\d{1,${ar}}))?`);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);V.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);V.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);V.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 at=w((Sm,Jn)=>{"use strict";var Qa=Object.freeze({loose:!0}),Za=Object.freeze({}),ec=e=>e?typeof e!="object"?Qa:e:Za;Jn.exports=ec});var lr=w((Rm,Yn)=>{"use strict";var Xn=/^[0-9]+$/,zn=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Xn.test(e),n=Xn.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},tc=(e,t)=>zn(t,e);Yn.exports={compareIdentifiers:zn,rcompareIdentifiers:tc}});var O=w((Am,Zn)=>{"use strict";var ct=Ue(),{MAX_LENGTH:Qn,MAX_SAFE_INTEGER:lt}=Ee(),{safeRe:ut,t:pt}=Se(),rc=at(),{compareIdentifiers:ur}=lr(),nc=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(ur(e[n],r[n])!==0)return!1;return!0},pr=class e{constructor(t,r){if(r=rc(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>Qn)throw new TypeError(`version is longer than ${Qn} characters`);ct("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?ut[pt.LOOSE]:ut[pt.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>lt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>lt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>lt||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&o<lt)return o}return s}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(ct("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(ct("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return ur(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(ct("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return ur(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?ut[pt.PRERELEASELOOSE]:ut[pt.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];if(n===!1&&(o=[r]),nc(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Zn.exports=pr});var oe=w((bm,ts)=>{"use strict";var es=O(),sc=(e,t,r=!1)=>{if(e instanceof es)return e;try{return new es(e,t)}catch(n){if(!r)return null;throw n}};ts.exports=sc});var ns=w((Pm,rs)=>{"use strict";var oc=oe(),ic=(e,t)=>{let r=oc(e,t);return r?r.version:null};rs.exports=ic});var os=w((Im,ss)=>{"use strict";var ac=oe(),cc=(e,t)=>{let r=ac(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};ss.exports=cc});var cs=w((vm,as)=>{"use strict";var is=O(),lc=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new is(e instanceof is?e.version:e,r).inc(t,n,s).version}catch{return null}};as.exports=lc});var ps=w((Cm,us)=>{"use strict";var ls=oe(),uc=(e,t)=>{let r=ls(e,null,!0),n=ls(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,a=o?n:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let f=l?"pre":"";return r.major!==n.major?f+"major":r.minor!==n.minor?f+"minor":r.patch!==n.patch?f+"patch":"prerelease"};us.exports=uc});var ms=w((Tm,ds)=>{"use strict";var pc=O(),dc=(e,t)=>new pc(e,t).major;ds.exports=dc});var hs=w((Om,fs)=>{"use strict";var mc=O(),fc=(e,t)=>new mc(e,t).minor;fs.exports=fc});var ys=w((xm,gs)=>{"use strict";var hc=O(),gc=(e,t)=>new hc(e,t).patch;gs.exports=gc});var Es=w(($m,ws)=>{"use strict";var yc=oe(),wc=(e,t)=>{let r=yc(e,t);return r&&r.prerelease.length?r.prerelease:null};ws.exports=wc});var D=w((Nm,Rs)=>{"use strict";var Ss=O(),Ec=(e,t,r)=>new Ss(e,r).compare(new Ss(t,r));Rs.exports=Ec});var bs=w((km,As)=>{"use strict";var Sc=D(),Rc=(e,t,r)=>Sc(t,e,r);As.exports=Rc});var Is=w((Lm,Ps)=>{"use strict";var Ac=D(),bc=(e,t)=>Ac(e,t,!0);Ps.exports=bc});var dt=w((Mm,Cs)=>{"use strict";var vs=O(),Pc=(e,t,r)=>{let n=new vs(e,r),s=new vs(t,r);return n.compare(s)||n.compareBuild(s)};Cs.exports=Pc});var Os=w((Dm,Ts)=>{"use strict";var Ic=dt(),vc=(e,t)=>e.sort((r,n)=>Ic(r,n,t));Ts.exports=vc});var $s=w((_m,xs)=>{"use strict";var Cc=dt(),Tc=(e,t)=>e.sort((r,n)=>Cc(n,r,t));xs.exports=Tc});var je=w((Um,Ns)=>{"use strict";var Oc=D(),xc=(e,t,r)=>Oc(e,t,r)>0;Ns.exports=xc});var mt=w((jm,ks)=>{"use strict";var $c=D(),Nc=(e,t,r)=>$c(e,t,r)<0;ks.exports=Nc});var dr=w((Fm,Ls)=>{"use strict";var kc=D(),Lc=(e,t,r)=>kc(e,t,r)===0;Ls.exports=Lc});var mr=w((Bm,Ms)=>{"use strict";var Mc=D(),Dc=(e,t,r)=>Mc(e,t,r)!==0;Ms.exports=Dc});var ft=w((Wm,Ds)=>{"use strict";var _c=D(),Uc=(e,t,r)=>_c(e,t,r)>=0;Ds.exports=Uc});var ht=w((Km,_s)=>{"use strict";var jc=D(),Fc=(e,t,r)=>jc(e,t,r)<=0;_s.exports=Fc});var fr=w((qm,Us)=>{"use strict";var Bc=dr(),Wc=mr(),Kc=je(),qc=ft(),Hc=mt(),Gc=ht(),Vc=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return Bc(e,r,n);case"!=":return Wc(e,r,n);case">":return Kc(e,r,n);case">=":return qc(e,r,n);case"<":return Hc(e,r,n);case"<=":return Gc(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Us.exports=Vc});var Fs=w((Hm,js)=>{"use strict";var Jc=O(),Xc=oe(),{safeRe:gt,t:yt}=Se(),zc=(e,t)=>{if(e instanceof Jc)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?gt[yt.COERCEFULL]:gt[yt.COERCE]);else{let l=t.includePrerelease?gt[yt.COERCERTLFULL]:gt[yt.COERCERTL],u;for(;(u=l.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Xc(`${n}.${s}.${o}${i}${a}`,t)};js.exports=zc});var Ws=w((Gm,Bs)=>{"use strict";var Yc=oe(),Qc=Ee(),Zc=O(),el=(e,t,r)=>{if(!Qc.RELEASE_TYPES.includes(t))return null;let n=tl(e,r);return n&&rl(n,t)},tl=(e,t)=>{let r=e instanceof Zc?e.version:e;return Yc(r,t)},rl=(e,t)=>{if(nl(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},nl=e=>e.startsWith("pre");Bs.exports=el});var qs=w((Vm,Ks)=>{"use strict";var hr=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};Ks.exports=hr});var _=w((Jm,Js)=>{"use strict";var sl=/\s+/g,gr=class e{constructor(t,r){if(r=il(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof yr)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(sl," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Gs(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&hl(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(fl,"");let n=((this.options.includePrerelease&&dl)|(this.options.loose&&ml))+":"+t,s=Hs.get(n);if(s)return s;let o=this.options.loose,i=o?N[x.HYPHENRANGELOOSE]:N[x.HYPHENRANGE];t=t.replace(i,vl(this.options.includePrerelease)),P("hyphen replace",t),t=t.replace(N[x.COMPARATORTRIM],ll),P("comparator trim",t),t=t.replace(N[x.TILDETRIM],ul),P("tilde trim",t),t=t.replace(N[x.CARETTRIM],pl),P("caret trim",t);let a=t.split(" ").map(m=>gl(m,this.options)).join(" ").split(/\s+/).map(m=>Il(m,this.options));o&&(a=a.filter(m=>(P("loose invalid filter",m,this.options),!!m.match(N[x.COMPARATORLOOSE])))),P("range list",a);let l=new Map,u=a.map(m=>new yr(m,this.options));for(let m of u){if(Gs(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return Hs.set(n,f),f}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Vs(n,r)&&t.set.some(s=>Vs(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new al(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Cl(this.set[r],t,this.options))return!0;return!1}};Js.exports=gr;var ol=qs(),Hs=new ol,il=at(),yr=Fe(),P=Ue(),al=O(),{safeRe:N,src:cl,t:x,comparatorTrimReplace:ll,tildeTrimReplace:ul,caretTrimReplace:pl}=Se(),{FLAG_INCLUDE_PRERELEASE:dl,FLAG_LOOSE:ml}=Ee(),fl=new RegExp(cl[x.BUILD],"g"),Gs=e=>e.value==="<0.0.0-0",hl=e=>e.value==="",Vs=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},gl=(e,t)=>(e=e.replace(N[x.BUILD],""),P("comp",e,t),e=Sl(e,t),P("caret",e),e=wl(e,t),P("tildes",e),e=Al(e,t),P("xrange",e),e=Pl(e,t),P("stars",e),e),C=e=>!e||e.toLowerCase()==="x"||e==="*",yl=(e,t,r)=>C(e)&&!C(t)||C(t)&&r&&!C(r),wl=(e,t)=>e.trim().split(/\s+/).map(r=>El(r,t)).join(" "),El=(e,t)=>{let r=t.loose?N[x.TILDELOOSE]:N[x.TILDE];return e.replace(r,(n,s,o,i,a)=>{P("tilde",e,n,s,o,i,a);let l;return C(s)?l="":C(o)?l=`>=${s}.0.0 <${+s+1}.0.0-0`:C(i)?l=`>=${s}.${o}.0 <${s}.${+o+1}.0-0`:a?(P("replaceTilde pr",a),l=`>=${s}.${o}.${i}-${a} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${i} <${s}.${+o+1}.0-0`,P("tilde return",l),l})},Sl=(e,t)=>e.trim().split(/\s+/).map(r=>Rl(r,t)).join(" "),Rl=(e,t)=>{P("caret",e,t);let r=t.loose?N[x.CARETLOOSE]:N[x.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{P("caret",e,s,o,i,a,l);let u;return C(o)?u="":C(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:C(a)?o==="0"?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:l?(P("replaceCaret pr",l),o==="0"?i==="0"?u=`>=${o}.${i}.${a}-${l} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a}-${l} <${+o+1}.0.0-0`):(P("no pr"),o==="0"?i==="0"?u=`>=${o}.${i}.${a} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a} <${+o+1}.0.0-0`),P("caret return",u),u})},Al=(e,t)=>(P("replaceXRanges",e,t),e.split(/\s+/).map(r=>bl(r,t)).join(" ")),bl=(e,t)=>{e=e.trim();let r=t.loose?N[x.XRANGELOOSE]:N[x.XRANGE];return e.replace(r,(n,s,o,i,a,l)=>{if(P("xRange",e,n,s,o,i,a,l),yl(o,i,a))return e;let u=C(o),f=u||C(i),m=f||C(a),S=m;return s==="="&&S&&(s=""),l=t.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&S?(f&&(i=0),a=0,s===">"?(s=">=",f?(o=+o+1,i=0,a=0):(i=+i+1,a=0)):s==="<="&&(s="<",f?o=+o+1:i=+i+1),s==="<"&&(l="-0"),n=`${s+o}.${i}.${a}${l}`):f?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${i}.0${l} <${o}.${+i+1}.0-0`),P("xRange return",n),n})},Pl=(e,t)=>(P("replaceStars",e,t),e.trim().replace(N[x.STAR],"")),Il=(e,t)=>(P("replaceGTE0",e,t),e.trim().replace(N[t.includePrerelease?x.GTE0PRE:x.GTE0],"")),vl=e=>(t,r,n,s,o,i,a,l,u,f,m,S)=>(C(n)?r="":C(s)?r=`>=${n}.0.0${e?"-0":""}`:C(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,C(u)?l="":C(f)?l=`<${+u+1}.0.0-0`:C(m)?l=`<${u}.${+f+1}.0-0`:S?l=`<=${u}.${f}.${m}-${S}`:e?l=`<${u}.${f}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),Cl=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(P(e[n].semver),e[n].semver!==yr.ANY&&e[n].semver.prerelease.length>0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var Fe=w((Xm,eo)=>{"use strict";var Be=Symbol("SemVer ANY"),Sr=class e{static get ANY(){return Be}constructor(t,r){if(r=Xs(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Er("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Be?this.value="":this.value=this.operator+this.semver.version,Er("comp",this)}parse(t){let r=this.options.loose?zs[Ys.COMPARATORLOOSE]:zs[Ys.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Qs(n[2],this.options.loose):this.semver=Be}toString(){return this.value}test(t){if(Er("Comparator.test",t,this.options.loose),this.semver===Be||t===Be)return!0;if(typeof t=="string")try{t=new Qs(t,this.options)}catch{return!1}return wr(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 Zs(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Zs(this.value,r).test(t.semver):(r=Xs(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("=")||wr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||wr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};eo.exports=Sr;var Xs=at(),{safeRe:zs,t:Ys}=Se(),wr=fr(),Er=Ue(),Qs=O(),Zs=_()});var We=w((zm,to)=>{"use strict";var Tl=_(),Ol=(e,t,r)=>{try{t=new Tl(t,r)}catch{return!1}return t.test(e)};to.exports=Ol});var no=w((Ym,ro)=>{"use strict";var xl=_(),$l=(e,t)=>new xl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));ro.exports=$l});var oo=w((Qm,so)=>{"use strict";var Nl=O(),kl=_(),Ll=(e,t,r)=>{let n=null,s=null,o=null;try{o=new kl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new Nl(n,r))}),n};so.exports=Ll});var ao=w((Zm,io)=>{"use strict";var Ml=O(),Dl=_(),_l=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Dl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new Ml(n,r))}),n};io.exports=_l});var uo=w((ef,lo)=>{"use strict";var Rr=O(),Ul=_(),co=je(),jl=(e,t)=>{e=new Ul(e,t);let r=new Rr("0.0.0");if(e.test(r)||(r=new Rr("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let s=e.set[n],o=null;s.forEach(i=>{let a=new Rr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||co(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||co(r,o))&&(r=o)}return r&&e.test(r)?r:null};lo.exports=jl});var mo=w((tf,po)=>{"use strict";var Fl=_(),Bl=(e,t)=>{try{return new Fl(e,t).range||"*"}catch{return null}};po.exports=Bl});var wt=w((rf,yo)=>{"use strict";var Wl=O(),go=Fe(),{ANY:Kl}=go,ql=_(),Hl=We(),fo=je(),ho=mt(),Gl=ht(),Vl=ft(),Jl=(e,t,r,n)=>{e=new Wl(e,n),t=new ql(t,n);let s,o,i,a,l;switch(r){case">":s=fo,o=Gl,i=ho,a=">",l=">=";break;case"<":s=ho,o=Vl,i=fo,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Hl(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let f=t.set[u],m=null,S=null;if(f.forEach(h=>{h.semver===Kl&&(h=new go(">=0.0.0")),m=m||h,S=S||h,s(h.semver,m.semver,n)?m=h:i(h.semver,S.semver,n)&&(S=h)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&o(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};yo.exports=Jl});var Eo=w((nf,wo)=>{"use strict";var Xl=wt(),zl=(e,t,r)=>Xl(e,t,">",r);wo.exports=zl});var Ro=w((sf,So)=>{"use strict";var Yl=wt(),Ql=(e,t,r)=>Yl(e,t,"<",r);So.exports=Ql});var Po=w((of,bo)=>{"use strict";var Ao=_(),Zl=(e,t,r)=>(e=new Ao(e,r),t=new Ao(t,r),e.intersects(t,r));bo.exports=Zl});var vo=w((af,Io)=>{"use strict";var eu=We(),tu=D();Io.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((f,m)=>tu(f,m,r));for(let f of i)eu(f,t,r)?(o=f,s||(s=f)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let a=[];for(let[f,m]of n)f===m?a.push(f):!m&&f===i[0]?a.push("*"):m?f===i[0]?a.push(`<=${m}`):a.push(`${f} - ${m}`):a.push(`>=${f}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var No=w((cf,$o)=>{"use strict";var Co=_(),Pr=Fe(),{ANY:Ar}=Pr,br=We(),Ir=D(),ru=(e,t,r={})=>{if(e===t)return!0;e=new Co(e,r),t=new Co(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=su(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},nu=[new Pr(">=0.0.0-0")],To=[new Pr(">=0.0.0")],su=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Ar){if(t.length===1&&t[0].semver===Ar)return!0;r.includePrerelease?e=nu:e=To}if(t.length===1&&t[0].semver===Ar){if(r.includePrerelease)return!0;t=To}let n=new Set,s,o;for(let h of e)h.operator===">"||h.operator===">="?s=Oo(s,h,r):h.operator==="<"||h.operator==="<="?o=xo(o,h,r):n.add(h.semver);if(n.size>1)return null;let i;if(s&&o){if(i=Ir(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let h of n){if(s&&!br(h,String(s),r)||o&&!br(h,String(o),r))return null;for(let fe of t)if(!br(h,String(fe),r))return!1;return!0}let a,l,u,f,m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,S=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;m&&m.prerelease.length===1&&o.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let h of t){if(f=f||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",s){if(S&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===S.major&&h.semver.minor===S.minor&&h.semver.patch===S.patch&&(S=!1),h.operator===">"||h.operator===">="){if(a=Oo(s,h,r),a===h&&a!==s)return!1}else if(s.operator===">="&&!h.test(s.semver))return!1}if(o){if(m&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===m.major&&h.semver.minor===m.minor&&h.semver.patch===m.patch&&(m=!1),h.operator==="<"||h.operator==="<="){if(l=xo(o,h,r),l===h&&l!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||s)&&i!==0)return!1}return!(s&&u&&!o&&i!==0||o&&f&&!s&&i!==0||S||m)},Oo=(e,t,r)=>{if(!e)return t;let n=Ir(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},xo=(e,t,r)=>{if(!e)return t;let n=Ir(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};$o.exports=ru});var Cr=w((lf,Mo)=>{"use strict";var vr=Se(),ko=Ee(),ou=O(),Lo=lr(),iu=oe(),au=ns(),cu=os(),lu=cs(),uu=ps(),pu=ms(),du=hs(),mu=ys(),fu=Es(),hu=D(),gu=bs(),yu=Is(),wu=dt(),Eu=Os(),Su=$s(),Ru=je(),Au=mt(),bu=dr(),Pu=mr(),Iu=ft(),vu=ht(),Cu=fr(),Tu=Fs(),Ou=Ws(),xu=Fe(),$u=_(),Nu=We(),ku=no(),Lu=oo(),Mu=ao(),Du=uo(),_u=mo(),Uu=wt(),ju=Eo(),Fu=Ro(),Bu=Po(),Wu=vo(),Ku=No();Mo.exports={parse:iu,valid:au,clean:cu,inc:lu,diff:uu,major:pu,minor:du,patch:mu,prerelease:fu,compare:hu,rcompare:gu,compareLoose:yu,compareBuild:wu,sort:Eu,rsort:Su,gt:Ru,lt:Au,eq:bu,neq:Pu,gte:Iu,lte:vu,cmp:Cu,coerce:Tu,truncate:Ou,Comparator:xu,Range:$u,satisfies:Nu,toComparators:ku,maxSatisfying:Lu,minSatisfying:Mu,minVersion:Du,validRange:_u,outside:Uu,gtr:ju,ltr:Fu,intersects:Bu,simplifyRange:Wu,subset:Ku,SemVer:ou,re:vr.re,src:vr.src,tokens:vr.t,SEMVER_SPEC_VERSION:ko.SEMVER_SPEC_VERSION,RELEASE_TYPES:ko.RELEASE_TYPES,compareIdentifiers:Lo.compareIdentifiers,rcompareIdentifiers:Lo.rcompareIdentifiers}});var Dp={};Qi(Dp,{handleError:()=>Ki,main:()=>Wi,run:()=>qi});module.exports=Zi(Dp);var Te=require("@medplum/core"),ze=require("commander"),Bi=L(require("dotenv"),1);var F=require("@medplum/core"),De=require("commander");var Jr=require("@medplum/core");var Gr=require("@medplum/core"),X=require("node:fs"),Vr=require("node:os"),Bt=require("node:path");var K=class extends Gr.ClientStorage{constructor(r){super();b(this,"dirName");b(this,"fileName");this.dirName=(0,Bt.resolve)((0,Vr.homedir)(),".medplum"),this.fileName=(0,Bt.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let s=this.readFile()??{};n?s[r]=n:delete s[r],this.writeFile(s)}getObject(r){let n=this.getString(r);return n?JSON.parse(n):void 0}setObject(r,n){this.setString(r,n?JSON.stringify(n):void 0)}readFile(){if((0,X.existsSync)(this.fileName))return JSON.parse((0,X.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,X.existsSync)(this.dirName)||(0,X.mkdirSync)(this.dirName),(0,X.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function A(e,t=!0){let r=e.profile??"default",n=new K(r),s=n.getObject("options");if(r!=="default"&&!s)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:o,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:f,clientSecret:m}=ea(e,n),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await ta(e.baseUrl,S);let h=new Jr.MedplumClient({fetch:S,baseUrl:o,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:ra,verbose:e.verbose});return t&&(a?h.setAccessToken(a):f&&m&&(h.setBasicAuth(f,m),s?.authType!=="basic"&&await h.startClientLogin(f,m))),h}function ea(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",s=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,o=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,a=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:n,fhirUrlPath:s,accessToken:o,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function ta(e,t){try{let r=new URL("healthcheck",e).toString(),n=await t(r);if(!n.ok)throw new Error(`Healthcheck returned status ${n.status}`);if((await n.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${n}`)}}function ra(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var H=require("@medplum/core"),En=require("commander");var zr=require("node:buffer");var ce=new TextEncoder,Wt=new TextDecoder,Wp=2**32;function Xr(...e){let t=e.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}var Ye=e=>zr.Buffer.from(e).toString("base64url");var le=class extends Error{constructor(r,n){super(r,n);b(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};b(le,"code","ERR_JOSE_GENERIC");var M=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JOSE_NOT_SUPPORTED")}};b(M,"code","ERR_JOSE_NOT_SUPPORTED");var z=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JWS_INVALID")}};b(z,"code","ERR_JWS_INVALID");var xe=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JWT_INVALID")}};b(xe,"code","ERR_JWT_INVALID");var Yr,Qr,Kt=class extends(Qr=le,Yr=Symbol.asyncIterator,Qr){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);b(this,Yr);b(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};b(Kt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Zr=L(require("node:util"),1),Qe=e=>Zr.types.isKeyObject(e);var en=L(require("node:crypto"),1),tn=L(require("node:util"),1),sa=en.webcrypto,rn=sa,he=e=>tn.types.isCryptoKey(e);function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function $e(e,t){return e.name===t}function qt(e){return parseInt(e.name.slice(4),10)}function oa(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ia(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function nn(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!$e(e.algorithm,"HMAC"))throw q("HMAC");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!$e(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!$e(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw q("Ed25519 or Ed448");break}case"Ed25519":{if(!$e(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!$e(e.algorithm,"ECDSA"))throw q("ECDSA");let n=oa(t);if(e.algorithm.namedCurve!==n)throw q(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ia(e,r)}function sn(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Ne=(e,...t)=>sn("Key must be ",e,...t);function Ht(e,t,...r){return sn(`Key for the ${e} algorithm must be `,t,...r)}var Gt=e=>Qe(e)||he(e),Y=["KeyObject"];(globalThis.CryptoKey||rn?.CryptoKey)&&Y.push("CryptoKey");var aa=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0},on=aa;function ca(e){return typeof e=="object"&&e!==null}function ke(e){if(!ca(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}var pn=require("node:crypto");function te(e){return ke(e)&&typeof e.kty=="string"}function an(e){return e.kty!=="oct"&&typeof e.d=="string"}function cn(e){return e.kty!=="oct"&&typeof e.d>"u"}function ln(e){return te(e)&&e.kty==="oct"&&typeof e.k=="string"}var la=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 M("Unsupported key curve for this operation")}},ua=(e,t)=>{let r;if(he(e))r=pn.KeyObject.from(e);else if(Qe(e))r=e;else{if(te(e))return e.crv;throw new TypeError(Ne(e,...Y))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let n=r.asymmetricKeyDetails.namedCurve;return t?n:la(n)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},dn=ua;var mn=require("node:crypto"),Vt=(e,t)=>{let r;try{e instanceof mn.KeyObject?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 ge=e=>e?.[Symbol.toStringTag],Jt=(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},pa=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&te(t)){if(ln(t)&&Jt(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(!Gt(t))throw new TypeError(Ht(e,t,...Y,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${ge(t)} instances for symmetric algorithms must be of type "secret"`)}},da=(e,t,r,n)=>{if(n&&te(t))switch(r){case"sign":if(an(t)&&Jt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(cn(t)&&Jt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Gt(t))throw new TypeError(Ht(e,t,...Y,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${ge(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ge(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ge(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ge(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ge(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function fn(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?pa(t,r,n,e):da(t,r,n,e)}var dd=fn.bind(void 0,!1),hn=fn.bind(void 0,!0);function ma(e,t,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let i of n.crit){if(!o.has(i))throw new M(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var gn=ma;function Xt(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 M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Le=require("node:crypto");var fa=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function zt(e,t){let r,n,s;if(t instanceof Le.KeyObject)r=t.asymmetricKeyType,n=t.asymmetricKeyDetails;else switch(s=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let o;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Vt(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=n,u=parseInt(e.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||a!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Vt(t,e),o={padding:Le.constants.RSA_PKCS1_PSS_PADDING,saltLength:Le.constants.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=dn(t),a=fa.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);o={dsaEncoding:"ieee-p1363"};break}default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...o}:o?{...o,key:t}:t}var Ze=L(require("node:crypto"),1),yn=require("node:util");function Yt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ye=require("node:crypto");function Qt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ne(t,...Y));return(0,ye.createSecretKey)(t)}if(t instanceof ye.KeyObject)return t;if(he(t))return nn(t,e,r),ye.KeyObject.from(t);if(te(t))return e.startsWith("HS")?(0,ye.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(Ne(t,...Y,"Uint8Array","JSON Web Key"))}var ha=(0,yn.promisify)(Ze.sign),ga=async(e,t,r)=>{let n=Qt(e,t,"sign");if(e.startsWith("HS")){let s=Ze.createHmac(Yt(e),n);return s.update(r),s.digest()}return ha(Xt(e),r,zt(e,n))},wn=ga;var re=e=>Math.floor(e.getTime()/1e3);var ya=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,et=e=>{let t=ya.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-s:s};var tt=class{constructor(t){b(this,"_payload");b(this,"_protectedHeader");b(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 z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!on(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},s=gn(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');hn(i,t,"sign");let a=this._payload;o&&(a=ce.encode(Ye(a)));let l;this._protectedHeader?l=ce.encode(Ye(JSON.stringify(this._protectedHeader))):l=ce.encode("");let u=Xr(l,ce.encode("."),a),f=await wn(i,t,u),m={signature:Ye(f),payload:""};return o&&(m.payload=Wt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Wt.decode(l)),m}};var rt=class{constructor(t){b(this,"_flattened");this._flattened=new tt(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function ue(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var nt=class{constructor(t={}){b(this,"_payload");if(!ke(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:ue("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ue("setNotBefore",re(t))}:this._payload={...this._payload,nbf:re(new Date)+et(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ue("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ue("setExpirationTime",re(t))}:this._payload={...this._payload,exp:re(new Date)+et(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:re(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ue("setIssuedAt",re(t))}:typeof t=="string"?this._payload={...this._payload,iat:ue("setIssuedAt",re(new Date)+et(t))}:this._payload={...this._payload,iat:ue("setIssuedAt",t)},this}};var Me=class extends nt{constructor(){super(...arguments);b(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,n){let s=new rt(ce.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");return s.sign(r,n)}};var we=require("node:crypto"),ne=require("node:fs"),Q=require("node:path"),Sn=require("node:util/types"),Rn=require("tar");function Z(e){console.log(JSON.stringify(e,null,2))}async function Zt(e,t,r){let n=t.source,s=st(n);if(!s)return;console.log("Saving source code...");let o=await e.createAttachment({data:s,filename:(0,Q.basename)(n),contentType:Sa(n)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:o});console.log("Success! New bot version: "+i.meta?.versionId)}async function er(e,t,r){let n=t.dist??t.source,s=st(n);if(!s)return;console.log("Deploying bot...");let o=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:(0,Q.basename)(n)});console.log("Deploy result: "+o.issue?.[0]?.details?.text)}async function tr(e,t,r,n,s,o,i){let a={name:t,description:"",runtimeVersion:o},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),f={name:t,id:l.id,source:n,dist:s};await Zt(e,f,u),await er(e,f,u),console.log(`Success! Bot created: ${u.id}`),i&&wa(f)}function An(e){let t=new RegExp("^"+Ea(e).replaceAll(String.raw`\*`,".*")+"$"),r=G()?.bots?.filter(n=>t.test(n.name));return r||[]}function j(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function v(e,t){(0,ne.writeFileSync)((0,Q.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function G(e,t){let r=j(e,t),n=st(r);if(n)return JSON.parse(n)}function bn(e){let t=st(j(e,{server:!0}));if(t)return JSON.parse(t)}function st(e){let t=(0,Q.resolve)(e);return(0,ne.existsSync)(t)?(0,ne.readFileSync)(t,"utf8"):""}function wa(e){let t=G()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ne.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Ea(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Pn(e){let n=0,s=0;return(0,Rn.extract)({cwd:e,filter:(o,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(s+=i.size,s>10485760)throw new Error("Tar extractor reached max size");return!0}})}function rr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Sa(e){let t=(0,Q.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?H.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?H.ContentType.TYPESCRIPT:H.ContentType.TEXT}function ot(e,t){let r=new K(e),n={name:e,...t};return r.setObject("options",n),n}function In(e){return new K(e).getObject("options")}async function vn(e,t){let r={typ:"JWT",alg:H.OAuthSigningAlgorithm.HS256},n=Math.floor(Date.now()/1e3),s={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},o=(0,H.encodeBase64)(JSON.stringify(r)),i=(0,H.encodeBase64)(JSON.stringify(s)),a=`${o}.${i}`,l=(0,we.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Cn(e,t){let r=(0,we.createPrivateKey)((0,ne.readFileSync)((0,Q.resolve)(t.privateKeyPath))),n=await new Me({}).setProtectedHeader({typ:"JWT",alg:H.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,we.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends En.Command{action(t){let r=Ra(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 Ra(e,t){return async r=>{let n=e.registeredArguments.length,s=r.slice(0,n);s[n]=e.optsWithGlobals();try{let o=t(...s);(0,Sn.isPromise)(o)&&await o}finally{e.resetOptionDefaults()}}}var $n=new g("status").aliases(["info","list","ls"]),Nn=new g("ping"),kn=new g("push"),Ln=new g("reload-config"),Mn=new g("upgrade"),Dn=new g("stats"),se=new g("agent");y(se,$n);y(se,Nn);y(se,kn);y(se,Ln);y(se,Mn);y(se,Dn);$n.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=Un(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:n.version,connectionStatus:n.status,statusLastUpdated:n.lastUpdated??"N/A"}}})});Nn.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let n=await A(r),s=await _n(n,t,r),o=Number.parseInt(r.count,10);if(Number.isNaN(o))throw new Error("--count <count> must be an integer if specified");try{let i=await n.pushToAgent(s,e,`PING ${o}`,F.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});kn.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",F.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,n)=>{let s=await A(n),o=await _n(s,r,n),i;try{i=await s.pushToAgent(o,{reference:`Device/${e}`},t,n.contentType,n.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});Ln.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Mn.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await it({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});Dn.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=Un(r.result,{required:["stats"]}),s;try{s=JSON.parse(n)}catch(o){console.error(`Failed to parse stats for agent ${r.agent.id}: ${(0,F.normalizeErrorString)(o)}`)}return{id:r.agent.id,name:r.agent.name,stats:s}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),Aa(r[n])}})});var Tn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function On(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function xn(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function Aa(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let i of Tn)r[i]=On(e.stats[i]);let n=new Set([...Tn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=On(a));console.table(r);let s=xn(e.stats.channelStats);s.length&&(console.info("Channel Stats:"),console.table(s));let o=xn(e.stats.clientStats);o.length&&(console.info("Client Stats:"),console.table(o))}async function it({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:s,renderSuccessfulRows:o}){let i=va(t,r),a=await A(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[T,J]of Object.entries(n))u.append(T,J.toString());let f;try{let T=a.fhirUrl("Agent",e);T.search=u.toString(),f=await a.get(T,{cache:"reload"})}catch(T){throw new Error(`Operation '${e}' failed`,{cause:T})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let m=[],S=[];switch(f.resourceType){case"Bundle":{let T=ba(f);for(let J of T)J.result.resourceType==="Parameters"||(0,F.isOk)(J.result)?m.push(J):S.push(J);break}case"Parameters":case"OperationOutcome":{let T=await a.searchOne("Agent",u,{cache:"reload"});if(!T)throw new Error("Agent not found");f.resourceType==="Parameters"?m.push({agent:T,result:f}):S.push({agent:T,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let h=[];for(let T of m){let J=s(T);h.push(J)}let fe=[];for(let T of S){let Ft=T.result.issue?.[0],Hi={id:T.agent.id,name:T.agent.name,severity:Ft.severity,code:Ft.code,details:Ft.details?.text??"No details to show"};fe.push(Hi)}console.info(`
2
+ "use strict";var Gi=Object.create;var Oe=Object.defineProperty;var Vi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Xi=Object.getPrototypeOf,zi=Object.prototype.hasOwnProperty;var Yi=(e,t,r)=>t in e?Oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Qi=(e,t)=>{for(var r in t)Oe(e,r,{get:t[r],enumerable:!0})},Hr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ji(t))!zi.call(e,s)&&s!==r&&Oe(e,s,{get:()=>t[s],enumerable:!(n=Vi(t,s))||n.enumerable});return e};var L=(e,t,r)=>(r=e!=null?Gi(Xi(e)):{},Hr(t||!e||!e.__esModule?Oe(r,"default",{value:e,enumerable:!0}):r,e)),Zi=e=>Hr(Oe({},"__esModule",{value:!0}),e);var b=(e,t,r)=>Yi(e,typeof t!="symbol"?t+"":t,r);var Ee=w((wm,Hn)=>{"use strict";var _a="2.0.0",Ua=Number.MAX_SAFE_INTEGER||9007199254740991,ja=16,Fa=250,Ba=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Hn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ja,MAX_SAFE_BUILD_LENGTH:Fa,MAX_SAFE_INTEGER:Ua,RELEASE_TYPES:Ba,SEMVER_SPEC_VERSION:_a,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ue=w((Em,Gn)=>{"use strict";var Wa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Gn.exports=Wa});var Se=w((V,Vn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ar,MAX_SAFE_BUILD_LENGTH:Ka,MAX_LENGTH:qa}=Ee(),Ha=Ue();V=Vn.exports={};var Ga=V.re=[],Va=V.safeRe=[],p=V.src=[],Ja=V.safeSrc=[],d=V.t={},Xa=0,cr="[a-zA-Z0-9-]",za=[["\\s",1],["\\d",qa],[cr,Ka]],Ya=e=>{for(let[t,r]of za)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=Ya(t),s=Xa++;Ha(e,s,t),d[e]=s,p[s]=t,Ja[s]=n,Ga[s]=new RegExp(t,r?"g":void 0),Va[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${cr}*`);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",`${cr}+`);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,${ar}})(?:\\.(\\d{1,${ar}}))?(?:\\.(\\d{1,${ar}}))?`);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);V.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);V.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);V.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 at=w((Sm,Jn)=>{"use strict";var Qa=Object.freeze({loose:!0}),Za=Object.freeze({}),ec=e=>e?typeof e!="object"?Qa:e:Za;Jn.exports=ec});var lr=w((Rm,Yn)=>{"use strict";var Xn=/^[0-9]+$/,zn=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Xn.test(e),n=Xn.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},tc=(e,t)=>zn(t,e);Yn.exports={compareIdentifiers:zn,rcompareIdentifiers:tc}});var O=w((Am,Zn)=>{"use strict";var ct=Ue(),{MAX_LENGTH:Qn,MAX_SAFE_INTEGER:lt}=Ee(),{safeRe:ut,t:pt}=Se(),rc=at(),{compareIdentifiers:ur}=lr(),nc=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(ur(e[n],r[n])!==0)return!1;return!0},pr=class e{constructor(t,r){if(r=rc(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>Qn)throw new TypeError(`version is longer than ${Qn} characters`);ct("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?ut[pt.LOOSE]:ut[pt.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>lt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>lt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>lt||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&o<lt)return o}return s}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(ct("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(ct("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return ur(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(ct("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return ur(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?ut[pt.PRERELEASELOOSE]:ut[pt.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];if(n===!1&&(o=[r]),nc(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Zn.exports=pr});var oe=w((bm,ts)=>{"use strict";var es=O(),sc=(e,t,r=!1)=>{if(e instanceof es)return e;try{return new es(e,t)}catch(n){if(!r)return null;throw n}};ts.exports=sc});var ns=w((Pm,rs)=>{"use strict";var oc=oe(),ic=(e,t)=>{let r=oc(e,t);return r?r.version:null};rs.exports=ic});var os=w((Im,ss)=>{"use strict";var ac=oe(),cc=(e,t)=>{let r=ac(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};ss.exports=cc});var cs=w((vm,as)=>{"use strict";var is=O(),lc=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new is(e instanceof is?e.version:e,r).inc(t,n,s).version}catch{return null}};as.exports=lc});var ps=w((Cm,us)=>{"use strict";var ls=oe(),uc=(e,t)=>{let r=ls(e,null,!0),n=ls(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,a=o?n:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let f=l?"pre":"";return r.major!==n.major?f+"major":r.minor!==n.minor?f+"minor":r.patch!==n.patch?f+"patch":"prerelease"};us.exports=uc});var ms=w((Tm,ds)=>{"use strict";var pc=O(),dc=(e,t)=>new pc(e,t).major;ds.exports=dc});var hs=w((Om,fs)=>{"use strict";var mc=O(),fc=(e,t)=>new mc(e,t).minor;fs.exports=fc});var ys=w((xm,gs)=>{"use strict";var hc=O(),gc=(e,t)=>new hc(e,t).patch;gs.exports=gc});var Es=w(($m,ws)=>{"use strict";var yc=oe(),wc=(e,t)=>{let r=yc(e,t);return r&&r.prerelease.length?r.prerelease:null};ws.exports=wc});var D=w((Nm,Rs)=>{"use strict";var Ss=O(),Ec=(e,t,r)=>new Ss(e,r).compare(new Ss(t,r));Rs.exports=Ec});var bs=w((km,As)=>{"use strict";var Sc=D(),Rc=(e,t,r)=>Sc(t,e,r);As.exports=Rc});var Is=w((Lm,Ps)=>{"use strict";var Ac=D(),bc=(e,t)=>Ac(e,t,!0);Ps.exports=bc});var dt=w((Mm,Cs)=>{"use strict";var vs=O(),Pc=(e,t,r)=>{let n=new vs(e,r),s=new vs(t,r);return n.compare(s)||n.compareBuild(s)};Cs.exports=Pc});var Os=w((Dm,Ts)=>{"use strict";var Ic=dt(),vc=(e,t)=>e.sort((r,n)=>Ic(r,n,t));Ts.exports=vc});var $s=w((_m,xs)=>{"use strict";var Cc=dt(),Tc=(e,t)=>e.sort((r,n)=>Cc(n,r,t));xs.exports=Tc});var je=w((Um,Ns)=>{"use strict";var Oc=D(),xc=(e,t,r)=>Oc(e,t,r)>0;Ns.exports=xc});var mt=w((jm,ks)=>{"use strict";var $c=D(),Nc=(e,t,r)=>$c(e,t,r)<0;ks.exports=Nc});var dr=w((Fm,Ls)=>{"use strict";var kc=D(),Lc=(e,t,r)=>kc(e,t,r)===0;Ls.exports=Lc});var mr=w((Bm,Ms)=>{"use strict";var Mc=D(),Dc=(e,t,r)=>Mc(e,t,r)!==0;Ms.exports=Dc});var ft=w((Wm,Ds)=>{"use strict";var _c=D(),Uc=(e,t,r)=>_c(e,t,r)>=0;Ds.exports=Uc});var ht=w((Km,_s)=>{"use strict";var jc=D(),Fc=(e,t,r)=>jc(e,t,r)<=0;_s.exports=Fc});var fr=w((qm,Us)=>{"use strict";var Bc=dr(),Wc=mr(),Kc=je(),qc=ft(),Hc=mt(),Gc=ht(),Vc=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return Bc(e,r,n);case"!=":return Wc(e,r,n);case">":return Kc(e,r,n);case">=":return qc(e,r,n);case"<":return Hc(e,r,n);case"<=":return Gc(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Us.exports=Vc});var Fs=w((Hm,js)=>{"use strict";var Jc=O(),Xc=oe(),{safeRe:gt,t:yt}=Se(),zc=(e,t)=>{if(e instanceof Jc)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?gt[yt.COERCEFULL]:gt[yt.COERCE]);else{let l=t.includePrerelease?gt[yt.COERCERTLFULL]:gt[yt.COERCERTL],u;for(;(u=l.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Xc(`${n}.${s}.${o}${i}${a}`,t)};js.exports=zc});var Ws=w((Gm,Bs)=>{"use strict";var Yc=oe(),Qc=Ee(),Zc=O(),el=(e,t,r)=>{if(!Qc.RELEASE_TYPES.includes(t))return null;let n=tl(e,r);return n&&rl(n,t)},tl=(e,t)=>{let r=e instanceof Zc?e.version:e;return Yc(r,t)},rl=(e,t)=>{if(nl(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},nl=e=>e.startsWith("pre");Bs.exports=el});var qs=w((Vm,Ks)=>{"use strict";var hr=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};Ks.exports=hr});var _=w((Jm,Js)=>{"use strict";var sl=/\s+/g,gr=class e{constructor(t,r){if(r=il(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof yr)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(sl," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Gs(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&hl(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(fl,"");let n=((this.options.includePrerelease&&dl)|(this.options.loose&&ml))+":"+t,s=Hs.get(n);if(s)return s;let o=this.options.loose,i=o?N[x.HYPHENRANGELOOSE]:N[x.HYPHENRANGE];t=t.replace(i,vl(this.options.includePrerelease)),P("hyphen replace",t),t=t.replace(N[x.COMPARATORTRIM],ll),P("comparator trim",t),t=t.replace(N[x.TILDETRIM],ul),P("tilde trim",t),t=t.replace(N[x.CARETTRIM],pl),P("caret trim",t);let a=t.split(" ").map(m=>gl(m,this.options)).join(" ").split(/\s+/).map(m=>Il(m,this.options));o&&(a=a.filter(m=>(P("loose invalid filter",m,this.options),!!m.match(N[x.COMPARATORLOOSE])))),P("range list",a);let l=new Map,u=a.map(m=>new yr(m,this.options));for(let m of u){if(Gs(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return Hs.set(n,f),f}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Vs(n,r)&&t.set.some(s=>Vs(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new al(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Cl(this.set[r],t,this.options))return!0;return!1}};Js.exports=gr;var ol=qs(),Hs=new ol,il=at(),yr=Fe(),P=Ue(),al=O(),{safeRe:N,src:cl,t:x,comparatorTrimReplace:ll,tildeTrimReplace:ul,caretTrimReplace:pl}=Se(),{FLAG_INCLUDE_PRERELEASE:dl,FLAG_LOOSE:ml}=Ee(),fl=new RegExp(cl[x.BUILD],"g"),Gs=e=>e.value==="<0.0.0-0",hl=e=>e.value==="",Vs=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},gl=(e,t)=>(e=e.replace(N[x.BUILD],""),P("comp",e,t),e=Sl(e,t),P("caret",e),e=wl(e,t),P("tildes",e),e=Al(e,t),P("xrange",e),e=Pl(e,t),P("stars",e),e),C=e=>!e||e.toLowerCase()==="x"||e==="*",yl=(e,t,r)=>C(e)&&!C(t)||C(t)&&r&&!C(r),wl=(e,t)=>e.trim().split(/\s+/).map(r=>El(r,t)).join(" "),El=(e,t)=>{let r=t.loose?N[x.TILDELOOSE]:N[x.TILDE],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{P("tilde",e,s,o,i,a,l);let u;return C(o)?u="":C(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:C(a)?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:l?(P("replaceTilde pr",l),u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`):u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`,P("tilde return",u),u})},Sl=(e,t)=>e.trim().split(/\s+/).map(r=>Rl(r,t)).join(" "),Rl=(e,t)=>{P("caret",e,t);let r=t.loose?N[x.CARETLOOSE]:N[x.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{P("caret",e,s,o,i,a,l);let u;return C(o)?u="":C(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:C(a)?o==="0"?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:l?(P("replaceCaret pr",l),o==="0"?i==="0"?u=`>=${o}.${i}.${a}-${l} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a}-${l} <${+o+1}.0.0-0`):(P("no pr"),o==="0"?i==="0"?u=`>=${o}.${i}.${a} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a} <${+o+1}.0.0-0`),P("caret return",u),u})},Al=(e,t)=>(P("replaceXRanges",e,t),e.split(/\s+/).map(r=>bl(r,t)).join(" ")),bl=(e,t)=>{e=e.trim();let r=t.loose?N[x.XRANGELOOSE]:N[x.XRANGE];return e.replace(r,(n,s,o,i,a,l)=>{if(P("xRange",e,n,s,o,i,a,l),yl(o,i,a))return e;let u=C(o),f=u||C(i),m=f||C(a),S=m;return s==="="&&S&&(s=""),l=t.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&S?(f&&(i=0),a=0,s===">"?(s=">=",f?(o=+o+1,i=0,a=0):(i=+i+1,a=0)):s==="<="&&(s="<",f?o=+o+1:i=+i+1),s==="<"&&(l="-0"),n=`${s+o}.${i}.${a}${l}`):f?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${i}.0${l} <${o}.${+i+1}.0-0`),P("xRange return",n),n})},Pl=(e,t)=>(P("replaceStars",e,t),e.trim().replace(N[x.STAR],"")),Il=(e,t)=>(P("replaceGTE0",e,t),e.trim().replace(N[t.includePrerelease?x.GTE0PRE:x.GTE0],"")),vl=e=>(t,r,n,s,o,i,a,l,u,f,m,S)=>(C(n)?r="":C(s)?r=`>=${n}.0.0${e?"-0":""}`:C(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,C(u)?l="":C(f)?l=`<${+u+1}.0.0-0`:C(m)?l=`<${u}.${+f+1}.0-0`:S?l=`<=${u}.${f}.${m}-${S}`:e?l=`<${u}.${f}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),Cl=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(P(e[n].semver),e[n].semver!==yr.ANY&&e[n].semver.prerelease.length>0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var Fe=w((Xm,eo)=>{"use strict";var Be=Symbol("SemVer ANY"),Sr=class e{static get ANY(){return Be}constructor(t,r){if(r=Xs(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Er("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Be?this.value="":this.value=this.operator+this.semver.version,Er("comp",this)}parse(t){let r=this.options.loose?zs[Ys.COMPARATORLOOSE]:zs[Ys.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Qs(n[2],this.options.loose):this.semver=Be}toString(){return this.value}test(t){if(Er("Comparator.test",t,this.options.loose),this.semver===Be||t===Be)return!0;if(typeof t=="string")try{t=new Qs(t,this.options)}catch{return!1}return wr(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 Zs(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Zs(this.value,r).test(t.semver):(r=Xs(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("=")||wr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||wr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};eo.exports=Sr;var Xs=at(),{safeRe:zs,t:Ys}=Se(),wr=fr(),Er=Ue(),Qs=O(),Zs=_()});var We=w((zm,to)=>{"use strict";var Tl=_(),Ol=(e,t,r)=>{try{t=new Tl(t,r)}catch{return!1}return t.test(e)};to.exports=Ol});var no=w((Ym,ro)=>{"use strict";var xl=_(),$l=(e,t)=>new xl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));ro.exports=$l});var oo=w((Qm,so)=>{"use strict";var Nl=O(),kl=_(),Ll=(e,t,r)=>{let n=null,s=null,o=null;try{o=new kl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new Nl(n,r))}),n};so.exports=Ll});var ao=w((Zm,io)=>{"use strict";var Ml=O(),Dl=_(),_l=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Dl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new Ml(n,r))}),n};io.exports=_l});var uo=w((ef,lo)=>{"use strict";var Rr=O(),Ul=_(),co=je(),jl=(e,t)=>{e=new Ul(e,t);let r=new Rr("0.0.0");if(e.test(r)||(r=new Rr("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let s=e.set[n],o=null;s.forEach(i=>{let a=new Rr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||co(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||co(r,o))&&(r=o)}return r&&e.test(r)?r:null};lo.exports=jl});var mo=w((tf,po)=>{"use strict";var Fl=_(),Bl=(e,t)=>{try{return new Fl(e,t).range||"*"}catch{return null}};po.exports=Bl});var wt=w((rf,yo)=>{"use strict";var Wl=O(),go=Fe(),{ANY:Kl}=go,ql=_(),Hl=We(),fo=je(),ho=mt(),Gl=ht(),Vl=ft(),Jl=(e,t,r,n)=>{e=new Wl(e,n),t=new ql(t,n);let s,o,i,a,l;switch(r){case">":s=fo,o=Gl,i=ho,a=">",l=">=";break;case"<":s=ho,o=Vl,i=fo,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Hl(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let f=t.set[u],m=null,S=null;if(f.forEach(h=>{h.semver===Kl&&(h=new go(">=0.0.0")),m=m||h,S=S||h,s(h.semver,m.semver,n)?m=h:i(h.semver,S.semver,n)&&(S=h)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&o(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};yo.exports=Jl});var Eo=w((nf,wo)=>{"use strict";var Xl=wt(),zl=(e,t,r)=>Xl(e,t,">",r);wo.exports=zl});var Ro=w((sf,So)=>{"use strict";var Yl=wt(),Ql=(e,t,r)=>Yl(e,t,"<",r);So.exports=Ql});var Po=w((of,bo)=>{"use strict";var Ao=_(),Zl=(e,t,r)=>(e=new Ao(e,r),t=new Ao(t,r),e.intersects(t,r));bo.exports=Zl});var vo=w((af,Io)=>{"use strict";var eu=We(),tu=D();Io.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((f,m)=>tu(f,m,r));for(let f of i)eu(f,t,r)?(o=f,s||(s=f)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let a=[];for(let[f,m]of n)f===m?a.push(f):!m&&f===i[0]?a.push("*"):m?f===i[0]?a.push(`<=${m}`):a.push(`${f} - ${m}`):a.push(`>=${f}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var No=w((cf,$o)=>{"use strict";var Co=_(),Pr=Fe(),{ANY:Ar}=Pr,br=We(),Ir=D(),ru=(e,t,r={})=>{if(e===t)return!0;e=new Co(e,r),t=new Co(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=su(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},nu=[new Pr(">=0.0.0-0")],To=[new Pr(">=0.0.0")],su=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Ar){if(t.length===1&&t[0].semver===Ar)return!0;r.includePrerelease?e=nu:e=To}if(t.length===1&&t[0].semver===Ar){if(r.includePrerelease)return!0;t=To}let n=new Set,s,o;for(let h of e)h.operator===">"||h.operator===">="?s=Oo(s,h,r):h.operator==="<"||h.operator==="<="?o=xo(o,h,r):n.add(h.semver);if(n.size>1)return null;let i;if(s&&o){if(i=Ir(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let h of n){if(s&&!br(h,String(s),r)||o&&!br(h,String(o),r))return null;for(let fe of t)if(!br(h,String(fe),r))return!1;return!0}let a,l,u,f,m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,S=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;m&&m.prerelease.length===1&&o.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let h of t){if(f=f||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",s){if(S&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===S.major&&h.semver.minor===S.minor&&h.semver.patch===S.patch&&(S=!1),h.operator===">"||h.operator===">="){if(a=Oo(s,h,r),a===h&&a!==s)return!1}else if(s.operator===">="&&!h.test(s.semver))return!1}if(o){if(m&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===m.major&&h.semver.minor===m.minor&&h.semver.patch===m.patch&&(m=!1),h.operator==="<"||h.operator==="<="){if(l=xo(o,h,r),l===h&&l!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||s)&&i!==0)return!1}return!(s&&u&&!o&&i!==0||o&&f&&!s&&i!==0||S||m)},Oo=(e,t,r)=>{if(!e)return t;let n=Ir(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},xo=(e,t,r)=>{if(!e)return t;let n=Ir(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};$o.exports=ru});var Cr=w((lf,Mo)=>{"use strict";var vr=Se(),ko=Ee(),ou=O(),Lo=lr(),iu=oe(),au=ns(),cu=os(),lu=cs(),uu=ps(),pu=ms(),du=hs(),mu=ys(),fu=Es(),hu=D(),gu=bs(),yu=Is(),wu=dt(),Eu=Os(),Su=$s(),Ru=je(),Au=mt(),bu=dr(),Pu=mr(),Iu=ft(),vu=ht(),Cu=fr(),Tu=Fs(),Ou=Ws(),xu=Fe(),$u=_(),Nu=We(),ku=no(),Lu=oo(),Mu=ao(),Du=uo(),_u=mo(),Uu=wt(),ju=Eo(),Fu=Ro(),Bu=Po(),Wu=vo(),Ku=No();Mo.exports={parse:iu,valid:au,clean:cu,inc:lu,diff:uu,major:pu,minor:du,patch:mu,prerelease:fu,compare:hu,rcompare:gu,compareLoose:yu,compareBuild:wu,sort:Eu,rsort:Su,gt:Ru,lt:Au,eq:bu,neq:Pu,gte:Iu,lte:vu,cmp:Cu,coerce:Tu,truncate:Ou,Comparator:xu,Range:$u,satisfies:Nu,toComparators:ku,maxSatisfying:Lu,minSatisfying:Mu,minVersion:Du,validRange:_u,outside:Uu,gtr:ju,ltr:Fu,intersects:Bu,simplifyRange:Wu,subset:Ku,SemVer:ou,re:vr.re,src:vr.src,tokens:vr.t,SEMVER_SPEC_VERSION:ko.SEMVER_SPEC_VERSION,RELEASE_TYPES:ko.RELEASE_TYPES,compareIdentifiers:Lo.compareIdentifiers,rcompareIdentifiers:Lo.rcompareIdentifiers}});var Dp={};Qi(Dp,{handleError:()=>Ki,main:()=>Wi,run:()=>qi});module.exports=Zi(Dp);var Te=require("@medplum/core"),ze=require("commander"),Bi=L(require("dotenv"),1);var F=require("@medplum/core"),De=require("commander");var Jr=require("@medplum/core");var Gr=require("@medplum/core"),X=require("node:fs"),Vr=require("node:os"),Bt=require("node:path");var K=class extends Gr.ClientStorage{constructor(r){super();b(this,"dirName");b(this,"fileName");this.dirName=(0,Bt.resolve)((0,Vr.homedir)(),".medplum"),this.fileName=(0,Bt.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let s=this.readFile()??{};n?s[r]=n:delete s[r],this.writeFile(s)}getObject(r){let n=this.getString(r);return n?JSON.parse(n):void 0}setObject(r,n){this.setString(r,n?JSON.stringify(n):void 0)}readFile(){if((0,X.existsSync)(this.fileName))return JSON.parse((0,X.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,X.existsSync)(this.dirName)||(0,X.mkdirSync)(this.dirName),(0,X.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function A(e,t=!0){let r=e.profile??"default",n=new K(r),s=n.getObject("options");if(r!=="default"&&!s)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:o,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:f,clientSecret:m}=ea(e,n),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await ta(e.baseUrl,S);let h=new Jr.MedplumClient({fetch:S,baseUrl:o,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:ra,verbose:e.verbose});return t&&(a?h.setAccessToken(a):f&&m&&(h.setBasicAuth(f,m),s?.authType!=="basic"&&await h.startClientLogin(f,m))),h}function ea(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",s=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,o=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,a=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:n,fhirUrlPath:s,accessToken:o,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function ta(e,t){try{let r=new URL("healthcheck",e).toString(),n=await t(r);if(!n.ok)throw new Error(`Healthcheck returned status ${n.status}`);if((await n.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${n}`)}}function ra(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var H=require("@medplum/core"),En=require("commander");var zr=require("node:buffer");var ce=new TextEncoder,Wt=new TextDecoder,Wp=2**32;function Xr(...e){let t=e.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}var Ye=e=>zr.Buffer.from(e).toString("base64url");var le=class extends Error{constructor(r,n){super(r,n);b(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};b(le,"code","ERR_JOSE_GENERIC");var M=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JOSE_NOT_SUPPORTED")}};b(M,"code","ERR_JOSE_NOT_SUPPORTED");var z=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JWS_INVALID")}};b(z,"code","ERR_JWS_INVALID");var xe=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JWT_INVALID")}};b(xe,"code","ERR_JWT_INVALID");var Yr,Qr,Kt=class extends(Qr=le,Yr=Symbol.asyncIterator,Qr){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);b(this,Yr);b(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};b(Kt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Zr=L(require("node:util"),1),Qe=e=>Zr.types.isKeyObject(e);var en=L(require("node:crypto"),1),tn=L(require("node:util"),1),sa=en.webcrypto,rn=sa,he=e=>tn.types.isCryptoKey(e);function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function $e(e,t){return e.name===t}function qt(e){return parseInt(e.name.slice(4),10)}function oa(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ia(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function nn(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!$e(e.algorithm,"HMAC"))throw q("HMAC");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!$e(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!$e(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw q("Ed25519 or Ed448");break}case"Ed25519":{if(!$e(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!$e(e.algorithm,"ECDSA"))throw q("ECDSA");let n=oa(t);if(e.algorithm.namedCurve!==n)throw q(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ia(e,r)}function sn(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Ne=(e,...t)=>sn("Key must be ",e,...t);function Ht(e,t,...r){return sn(`Key for the ${e} algorithm must be `,t,...r)}var Gt=e=>Qe(e)||he(e),Y=["KeyObject"];(globalThis.CryptoKey||rn?.CryptoKey)&&Y.push("CryptoKey");var aa=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0},on=aa;function ca(e){return typeof e=="object"&&e!==null}function ke(e){if(!ca(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}var pn=require("node:crypto");function te(e){return ke(e)&&typeof e.kty=="string"}function an(e){return e.kty!=="oct"&&typeof e.d=="string"}function cn(e){return e.kty!=="oct"&&typeof e.d>"u"}function ln(e){return te(e)&&e.kty==="oct"&&typeof e.k=="string"}var la=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 M("Unsupported key curve for this operation")}},ua=(e,t)=>{let r;if(he(e))r=pn.KeyObject.from(e);else if(Qe(e))r=e;else{if(te(e))return e.crv;throw new TypeError(Ne(e,...Y))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let n=r.asymmetricKeyDetails.namedCurve;return t?n:la(n)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},dn=ua;var mn=require("node:crypto"),Vt=(e,t)=>{let r;try{e instanceof mn.KeyObject?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 ge=e=>e?.[Symbol.toStringTag],Jt=(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},pa=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&te(t)){if(ln(t)&&Jt(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(!Gt(t))throw new TypeError(Ht(e,t,...Y,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${ge(t)} instances for symmetric algorithms must be of type "secret"`)}},da=(e,t,r,n)=>{if(n&&te(t))switch(r){case"sign":if(an(t)&&Jt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(cn(t)&&Jt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Gt(t))throw new TypeError(Ht(e,t,...Y,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${ge(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ge(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ge(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ge(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ge(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function fn(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?pa(t,r,n,e):da(t,r,n,e)}var dd=fn.bind(void 0,!1),hn=fn.bind(void 0,!0);function ma(e,t,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let i of n.crit){if(!o.has(i))throw new M(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var gn=ma;function Xt(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 M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Le=require("node:crypto");var fa=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function zt(e,t){let r,n,s;if(t instanceof Le.KeyObject)r=t.asymmetricKeyType,n=t.asymmetricKeyDetails;else switch(s=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let o;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Vt(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=n,u=parseInt(e.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||a!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Vt(t,e),o={padding:Le.constants.RSA_PKCS1_PSS_PADDING,saltLength:Le.constants.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=dn(t),a=fa.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);o={dsaEncoding:"ieee-p1363"};break}default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...o}:o?{...o,key:t}:t}var Ze=L(require("node:crypto"),1),yn=require("node:util");function Yt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ye=require("node:crypto");function Qt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ne(t,...Y));return(0,ye.createSecretKey)(t)}if(t instanceof ye.KeyObject)return t;if(he(t))return nn(t,e,r),ye.KeyObject.from(t);if(te(t))return e.startsWith("HS")?(0,ye.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(Ne(t,...Y,"Uint8Array","JSON Web Key"))}var ha=(0,yn.promisify)(Ze.sign),ga=async(e,t,r)=>{let n=Qt(e,t,"sign");if(e.startsWith("HS")){let s=Ze.createHmac(Yt(e),n);return s.update(r),s.digest()}return ha(Xt(e),r,zt(e,n))},wn=ga;var re=e=>Math.floor(e.getTime()/1e3);var ya=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,et=e=>{let t=ya.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-s:s};var tt=class{constructor(t){b(this,"_payload");b(this,"_protectedHeader");b(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 z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!on(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},s=gn(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');hn(i,t,"sign");let a=this._payload;o&&(a=ce.encode(Ye(a)));let l;this._protectedHeader?l=ce.encode(Ye(JSON.stringify(this._protectedHeader))):l=ce.encode("");let u=Xr(l,ce.encode("."),a),f=await wn(i,t,u),m={signature:Ye(f),payload:""};return o&&(m.payload=Wt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Wt.decode(l)),m}};var rt=class{constructor(t){b(this,"_flattened");this._flattened=new tt(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function ue(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var nt=class{constructor(t={}){b(this,"_payload");if(!ke(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:ue("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ue("setNotBefore",re(t))}:this._payload={...this._payload,nbf:re(new Date)+et(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ue("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ue("setExpirationTime",re(t))}:this._payload={...this._payload,exp:re(new Date)+et(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:re(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ue("setIssuedAt",re(t))}:typeof t=="string"?this._payload={...this._payload,iat:ue("setIssuedAt",re(new Date)+et(t))}:this._payload={...this._payload,iat:ue("setIssuedAt",t)},this}};var Me=class extends nt{constructor(){super(...arguments);b(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,n){let s=new rt(ce.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");return s.sign(r,n)}};var we=require("node:crypto"),ne=require("node:fs"),Q=require("node:path"),Sn=require("node:util/types"),Rn=require("tar");function Z(e){console.log(JSON.stringify(e,null,2))}async function Zt(e,t,r){let n=t.source,s=st(n);if(!s)return;console.log("Saving source code...");let o=await e.createAttachment({data:s,filename:(0,Q.basename)(n),contentType:Sa(n)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:o});console.log("Success! New bot version: "+i.meta?.versionId)}async function er(e,t,r){let n=t.dist??t.source,s=st(n);if(!s)return;console.log("Deploying bot...");let o=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:(0,Q.basename)(n)});console.log("Deploy result: "+o.issue?.[0]?.details?.text)}async function tr(e,t,r,n,s,o,i){let a={name:t,description:"",runtimeVersion:o},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),f={name:t,id:l.id,source:n,dist:s};await Zt(e,f,u),await er(e,f,u),console.log(`Success! Bot created: ${u.id}`),i&&wa(f)}function An(e){let t=new RegExp("^"+Ea(e).replaceAll(String.raw`\*`,".*")+"$"),r=G()?.bots?.filter(n=>t.test(n.name));return r||[]}function j(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function v(e,t){(0,ne.writeFileSync)((0,Q.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function G(e,t){let r=j(e,t),n=st(r);if(n)return JSON.parse(n)}function bn(e){let t=st(j(e,{server:!0}));if(t)return JSON.parse(t)}function st(e){let t=(0,Q.resolve)(e);return(0,ne.existsSync)(t)?(0,ne.readFileSync)(t,"utf8"):""}function wa(e){let t=G()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ne.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Ea(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Pn(e){let n=0,s=0;return(0,Rn.extract)({cwd:e,filter:(o,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(s+=i.size,s>10485760)throw new Error("Tar extractor reached max size");return!0}})}function rr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Sa(e){let t=(0,Q.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?H.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?H.ContentType.TYPESCRIPT:H.ContentType.TEXT}function ot(e,t){let r=new K(e),n={name:e,...t};return r.setObject("options",n),n}function In(e){return new K(e).getObject("options")}async function vn(e,t){let r={typ:"JWT",alg:H.OAuthSigningAlgorithm.HS256},n=Math.floor(Date.now()/1e3),s={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},o=(0,H.encodeBase64)(JSON.stringify(r)),i=(0,H.encodeBase64)(JSON.stringify(s)),a=`${o}.${i}`,l=(0,we.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Cn(e,t){let r=(0,we.createPrivateKey)((0,ne.readFileSync)((0,Q.resolve)(t.privateKeyPath))),n=await new Me({}).setProtectedHeader({typ:"JWT",alg:H.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,we.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends En.Command{action(t){let r=Ra(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 Ra(e,t){return async r=>{let n=e.registeredArguments.length,s=r.slice(0,n);s[n]=e.optsWithGlobals();try{let o=t(...s);(0,Sn.isPromise)(o)&&await o}finally{e.resetOptionDefaults()}}}var $n=new g("status").aliases(["info","list","ls"]),Nn=new g("ping"),kn=new g("push"),Ln=new g("reload-config"),Mn=new g("upgrade"),Dn=new g("stats"),se=new g("agent");y(se,$n);y(se,Nn);y(se,kn);y(se,Ln);y(se,Mn);y(se,Dn);$n.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=Un(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:n.version,connectionStatus:n.status,statusLastUpdated:n.lastUpdated??"N/A"}}})});Nn.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let n=await A(r),s=await _n(n,t,r),o=Number.parseInt(r.count,10);if(Number.isNaN(o))throw new Error("--count <count> must be an integer if specified");try{let i=await n.pushToAgent(s,e,`PING ${o}`,F.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});kn.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",F.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,n)=>{let s=await A(n),o=await _n(s,r,n),i;try{i=await s.pushToAgent(o,{reference:`Device/${e}`},t,n.contentType,n.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});Ln.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Mn.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await it({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});Dn.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=Un(r.result,{required:["stats"]}),s;try{s=JSON.parse(n)}catch(o){console.error(`Failed to parse stats for agent ${r.agent.id}: ${(0,F.normalizeErrorString)(o)}`)}return{id:r.agent.id,name:r.agent.name,stats:s}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),Aa(r[n])}})});var Tn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function On(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function xn(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function Aa(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let i of Tn)r[i]=On(e.stats[i]);let n=new Set([...Tn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=On(a));console.table(r);let s=xn(e.stats.channelStats);s.length&&(console.info("Channel Stats:"),console.table(s));let o=xn(e.stats.clientStats);o.length&&(console.info("Client Stats:"),console.table(o))}async function it({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:s,renderSuccessfulRows:o}){let i=va(t,r),a=await A(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[T,J]of Object.entries(n))u.append(T,J.toString());let f;try{let T=a.fhirUrl("Agent",e);T.search=u.toString(),f=await a.get(T,{cache:"reload"})}catch(T){throw new Error(`Operation '${e}' failed`,{cause:T})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let m=[],S=[];switch(f.resourceType){case"Bundle":{let T=ba(f);for(let J of T)J.result.resourceType==="Parameters"||(0,F.isOk)(J.result)?m.push(J):S.push(J);break}case"Parameters":case"OperationOutcome":{let T=await a.searchOne("Agent",u,{cache:"reload"});if(!T)throw new Error("Agent not found");f.resourceType==="Parameters"?m.push({agent:T,result:f}):S.push({agent:T,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let h=[];for(let T of m){let J=s(T);h.push(J)}let fe=[];for(let T of S){let Ft=T.result.issue?.[0],Hi={id:T.agent.id,name:T.agent.name,severity:Ft.severity,code:Ft.code,details:Ft.details?.text??"No details to show"};fe.push(Hi)}console.info(`
3
3
  ${h.length} successful response(s):
4
4
  `),o?h.length?o(h):console.info("No successful responses received"):console.table(h.length?h:"No successful responses received"),console.info(),fe.length&&(console.info(`${fe.length} failed response(s):`),console.info(),console.table(fe))}async function _n(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let n;if(t)n=t;else{jn(r.criteria);let s=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!s?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(s.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");n=s.entry[0].resource?.id}return{reference:`Agent/${n}`}}function ba(e){let t=[];for(let r of e.entry??F.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(Pa(r.resource))}return t}function Pa(e){let t=e.parameter?.find(n=>n.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(n=>n.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function Un(e,t){let r={},n=t.required,s=t.optional;for(let o of n){let i=e.parameter?.find(l=>l.name===o);if(!i)throw new Error(`Failed to find parameter '${o}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${o}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${o}'`);r[o]=i[a]}if(s?.length)for(let o of s){let i=e.parameter?.find(l=>l.name===o);if(!i)continue;let a=Ia(o,i);r[o]=a}return r}function Ia(e,t){let r;for(let n in t)if(n.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=n}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function va(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!(0,F.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return jn(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function jn(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,n]=e.split("?");if(r!=="Agent"||!n)throw new Error(t);try{new URLSearchParams(n)}catch(s){throw new Error(t,{cause:s})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var B=require("@medplum/core"),Fn=require("node:child_process"),Bn=require("node:http"),Wn=require("node:os");var Kn=B.MEDPLUM_CLI_CLIENT_ID,qn="http://localhost:9615",nr=new g("login"),sr=new g("whoami"),or=new g("token");nr.action(async e=>{let t=e.profile??"default",r=ot(t,e),n=await A(e,!1);await Ca(n,r)});sr.action(async e=>{let t=await A(e);xa(t)});or.action(async e=>{let t=await A(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function Ca(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await $a(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 vn(e,t);break;case"jwt-assertion":await Cn(e,t);break}}async function Ta(e){let t=(0,Bn.createServer)(async(r,n)=>{let s=new URL(r.url,"http://localhost:9615"),o=s.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":B.ContentType.TEXT}),n.end("OK");return}if(s.pathname==="/"&&o)try{let i=await e.processCode(o,{clientId:Kn,redirectUri:qn});n.writeHead(200,{"Content-Type":B.ContentType.TEXT}),n.end(`Signed in as ${(0,B.getDisplayString)(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":B.ContentType.TEXT}),n.end(`Error: ${(0,B.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":B.ContentType.TEXT}),n.end("Not found")}).listen(9615)}async function Oa(e){let t=(0,Wn.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}return new Promise((n,s)=>{(0,Fn.exec)(r,(o,i,a)=>{if(o){s(o);return}if(a){s(new Error("Could not open browser: "+a));return}n()})})}function xa(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 $a(e){await Ta(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Kn),t.searchParams.set("redirect_uri",qn),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Oa(t.toString())}var _e="\x1B[0m",Na="\x1B[1m",ka="\x1B[31m",La="\x1B[32m",Ma="\x1B[33m",Da="\x1B[34m",pe={red:e=>`${ka}${e}${_e}`,green:e=>`${La}${e}${_e}`,yellow:e=>`${Ma}${e}${_e}`,blue:e=>`${Da}${e}${_e}`,bold:e=>`${Na}${e}${_e}`},ir=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>pe.bold(r));var ee=require("@aws-sdk/client-cloudformation"),Pt=require("@aws-sdk/client-cloudfront"),Uo=require("@aws-sdk/client-ecs"),jo=require("@aws-sdk/client-s3"),Ae=require("@aws-sdk/client-ssm"),It=require("@aws-sdk/client-sts"),vt=require("@medplum/core"),Fo=require("node:fs"),Bo=L(Cr(),1);var Do=L(require("node:readline"),1),Et;function St(){Et=Do.default.createInterface({input:process.stdin,output:process.stdout})}function Rt(){Et.close()}function c(e){Et.write(e+`
5
5
  `)}function I(e){c(`