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