@medplum/cli 5.1.27 → 5.1.29

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