@medplum/cli 4.3.6 → 4.3.8

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