@medplum/cli 4.4.0 → 4.4.2
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/LICENSE.txt +176 -0
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/index.mjs.map +2 -2
- package/package.json +15 -15
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var ki=Object.create;var Te=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var Mi=Object.getOwnPropertyNames;var _i=Object.getPrototypeOf,Ui=Object.prototype.hasOwnProperty;var ji=(e,t,r)=>t in e?Te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fi=(e,t)=>{for(var r in t)Te(e,r,{get:t[r],enumerable:!0})},Fr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Mi(t))!Ui.call(e,n)&&n!==r&&Te(e,n,{get:()=>t[n],enumerable:!(o=Di(t,n))||o.enumerable});return e};var x=(e,t,r)=>(r=e!=null?ki(_i(e)):{},Fr(t||!e||!e.__esModule?Te(r,"default",{value:e,enumerable:!0}):r,e)),Bi=e=>Fr(Te({},"__esModule",{value:!0}),e);var I=(e,t,r)=>ji(e,typeof t!="symbol"?t+"":t,r);var Me=w((Jd,Do)=>{"use strict";var Ia="2.0.0",va=Number.MAX_SAFE_INTEGER||9007199254740991,ba=16,Ca=250,Ta=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Do.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ba,MAX_SAFE_BUILD_LENGTH:Ca,MAX_SAFE_INTEGER:va,RELEASE_TYPES:Ta,SEMVER_SPEC_VERSION:Ia,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var _e=w((Xd,Mo)=>{"use strict";var Oa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Mo.exports=Oa});var ye=w((q,_o)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ir,MAX_SAFE_BUILD_LENGTH:xa,MAX_LENGTH:$a}=Me(),Na=_e();q=_o.exports={};var La=q.re=[],ka=q.safeRe=[],p=q.src=[],Da=q.safeSrc=[],d=q.t={},Ma=0,ar="[a-zA-Z0-9-]",_a=[["\\s",1],["\\d",$a],[ar,xa]],Ua=e=>{for(let[t,r]of _a)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let o=Ua(t),n=Ma++;Na(e,n,t),d[e]=n,p[n]=t,Da[n]=o,La[n]=new RegExp(t,r?"g":void 0),ka[n]=new RegExp(o,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ar}*`);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",`${ar}+`);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,${ir}})(?:\\.(\\d{1,${ir}}))?(?:\\.(\\d{1,${ir}}))?`);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);q.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);q.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);q.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 it=w((zd,Uo)=>{"use strict";var ja=Object.freeze({loose:!0}),Fa=Object.freeze({}),Ba=e=>e?typeof e!="object"?ja:e:Fa;Uo.exports=Ba});var cr=w((Yd,Bo)=>{"use strict";var jo=/^[0-9]+$/,Fo=(e,t)=>{let r=jo.test(e),o=jo.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1},Wa=(e,t)=>Fo(t,e);Bo.exports={compareIdentifiers:Fo,rcompareIdentifiers:Wa}});var C=w((Qd,Ko)=>{"use strict";var at=_e(),{MAX_LENGTH:Wo,MAX_SAFE_INTEGER:ct}=Me(),{safeRe:lt,t:ut}=ye(),Ka=it(),{compareIdentifiers:we}=cr(),lr=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>Wo)throw new TypeError(`version is longer than ${Wo} characters`);at("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=t.trim().match(r.loose?lt[ut.LOOSE]:lt[ut.FULL]);if(!o)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>ct||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ct||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ct||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<ct)return s}return n}):this.prerelease=[],this.build=o[5]?o[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(at("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)),we(this.major,t.major)||we(this.minor,t.minor)||we(this.patch,t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let o=this.prerelease[r],n=t.prerelease[r];if(at("prerelease compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return we(o,n)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let o=this.build[r],n=t.build[r];if(at("build compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return we(o,n)}while(++r)}inc(t,r,o){if(t.startsWith("pre")){if(!r&&o===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=`-${r}`.match(this.options.loose?lt[ut.PRERELEASELOOSE]:lt[ut.PRERELEASE]);if(!n||n[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,o);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,o);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,o),this.inc("pre",r,o);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,o),this.inc("pre",r,o);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(o)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&o===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];o===!1&&(s=[r]),we(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Ko.exports=lr});var ue=w((Zd,Ho)=>{"use strict";var qo=C(),qa=(e,t,r=!1)=>{if(e instanceof qo)return e;try{return new qo(e,t)}catch(o){if(!r)return null;throw o}};Ho.exports=qa});var Vo=w((em,Go)=>{"use strict";var Ha=ue(),Ga=(e,t)=>{let r=Ha(e,t);return r?r.version:null};Go.exports=Ga});var Xo=w((tm,Jo)=>{"use strict";var Va=ue(),Ja=(e,t)=>{let r=Va(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Jo.exports=Ja});var Qo=w((rm,Yo)=>{"use strict";var zo=C(),Xa=(e,t,r,o,n)=>{typeof r=="string"&&(n=o,o=r,r=void 0);try{return new zo(e instanceof zo?e.version:e,r).inc(t,o,n).version}catch{return null}};Yo.exports=Xa});var tn=w((om,en)=>{"use strict";var Zo=ue(),za=(e,t)=>{let r=Zo(e,null,!0),o=Zo(t,null,!0),n=r.compare(o);if(n===0)return null;let s=n>0,i=s?r:o,a=s?o:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let h=l?"pre":"";return r.major!==o.major?h+"major":r.minor!==o.minor?h+"minor":r.patch!==o.patch?h+"patch":"prerelease"};en.exports=za});var on=w((nm,rn)=>{"use strict";var Ya=C(),Qa=(e,t)=>new Ya(e,t).major;rn.exports=Qa});var sn=w((sm,nn)=>{"use strict";var Za=C(),ec=(e,t)=>new Za(e,t).minor;nn.exports=ec});var cn=w((im,an)=>{"use strict";var tc=C(),rc=(e,t)=>new tc(e,t).patch;an.exports=rc});var un=w((am,ln)=>{"use strict";var oc=ue(),nc=(e,t)=>{let r=oc(e,t);return r&&r.prerelease.length?r.prerelease:null};ln.exports=nc});var k=w((cm,dn)=>{"use strict";var pn=C(),sc=(e,t,r)=>new pn(e,r).compare(new pn(t,r));dn.exports=sc});var fn=w((lm,mn)=>{"use strict";var ic=k(),ac=(e,t,r)=>ic(t,e,r);mn.exports=ac});var gn=w((um,hn)=>{"use strict";var cc=k(),lc=(e,t)=>cc(e,t,!0);hn.exports=lc});var pt=w((pm,wn)=>{"use strict";var yn=C(),uc=(e,t,r)=>{let o=new yn(e,r),n=new yn(t,r);return o.compare(n)||o.compareBuild(n)};wn.exports=uc});var Sn=w((dm,En)=>{"use strict";var pc=pt(),dc=(e,t)=>e.sort((r,o)=>pc(r,o,t));En.exports=dc});var An=w((mm,Rn)=>{"use strict";var mc=pt(),fc=(e,t)=>e.sort((r,o)=>mc(o,r,t));Rn.exports=fc});var Ue=w((fm,Pn)=>{"use strict";var hc=k(),gc=(e,t,r)=>hc(e,t,r)>0;Pn.exports=gc});var dt=w((hm,In)=>{"use strict";var yc=k(),wc=(e,t,r)=>yc(e,t,r)<0;In.exports=wc});var ur=w((gm,vn)=>{"use strict";var Ec=k(),Sc=(e,t,r)=>Ec(e,t,r)===0;vn.exports=Sc});var pr=w((ym,bn)=>{"use strict";var Rc=k(),Ac=(e,t,r)=>Rc(e,t,r)!==0;bn.exports=Ac});var mt=w((wm,Cn)=>{"use strict";var Pc=k(),Ic=(e,t,r)=>Pc(e,t,r)>=0;Cn.exports=Ic});var ft=w((Em,Tn)=>{"use strict";var vc=k(),bc=(e,t,r)=>vc(e,t,r)<=0;Tn.exports=bc});var dr=w((Sm,On)=>{"use strict";var Cc=ur(),Tc=pr(),Oc=Ue(),xc=mt(),$c=dt(),Nc=ft(),Lc=(e,t,r,o)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return Cc(e,r,o);case"!=":return Tc(e,r,o);case">":return Oc(e,r,o);case">=":return xc(e,r,o);case"<":return $c(e,r,o);case"<=":return Nc(e,r,o);default:throw new TypeError(`Invalid operator: ${t}`)}};On.exports=Lc});var $n=w((Rm,xn)=>{"use strict";var kc=C(),Dc=ue(),{safeRe:ht,t:gt}=ye(),Mc=(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?ht[gt.COERCEFULL]:ht[gt.COERCE]);else{let l=t.includePrerelease?ht[gt.COERCERTLFULL]:ht[gt.COERCERTL],u;for(;(u=l.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let o=r[2],n=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Dc(`${o}.${n}.${s}${i}${a}`,t)};xn.exports=Mc});var Ln=w((Am,Nn)=>{"use strict";var mr=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};Nn.exports=mr});var D=w((Pm,_n)=>{"use strict";var _c=/\s+/g,fr=class e{constructor(t,r){if(r=jc(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof hr)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(_c," "),this.set=this.raw.split("||").map(o=>this.parseRange(o.trim())).filter(o=>o.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let o=this.set[0];if(this.set=this.set.filter(n=>!Dn(n[0])),this.set.length===0)this.set=[o];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&Gc(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let o=0;o<r.length;o++)o>0&&(this.formatted+=" "),this.formatted+=r[o].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let o=((this.options.includePrerelease&&qc)|(this.options.loose&&Hc))+":"+t,n=kn.get(o);if(n)return n;let s=this.options.loose,i=s?$[T.HYPHENRANGELOOSE]:$[T.HYPHENRANGE];t=t.replace(i,rl(this.options.includePrerelease)),A("hyphen replace",t),t=t.replace($[T.COMPARATORTRIM],Bc),A("comparator trim",t),t=t.replace($[T.TILDETRIM],Wc),A("tilde trim",t),t=t.replace($[T.CARETTRIM],Kc),A("caret trim",t);let a=t.split(" ").map(m=>Vc(m,this.options)).join(" ").split(/\s+/).map(m=>tl(m,this.options));s&&(a=a.filter(m=>(A("loose invalid filter",m,this.options),!!m.match($[T.COMPARATORLOOSE])))),A("range list",a);let l=new Map,u=a.map(m=>new hr(m,this.options));for(let m of u){if(Dn(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let h=[...l.values()];return kn.set(o,h),h}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(o=>Mn(o,r)&&t.set.some(n=>Mn(n,r)&&o.every(s=>n.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Fc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(ol(this.set[r],t,this.options))return!0;return!1}};_n.exports=fr;var Uc=Ln(),kn=new Uc,jc=it(),hr=je(),A=_e(),Fc=C(),{safeRe:$,t:T,comparatorTrimReplace:Bc,tildeTrimReplace:Wc,caretTrimReplace:Kc}=ye(),{FLAG_INCLUDE_PRERELEASE:qc,FLAG_LOOSE:Hc}=Me(),Dn=e=>e.value==="<0.0.0-0",Gc=e=>e.value==="",Mn=(e,t)=>{let r=!0,o=e.slice(),n=o.pop();for(;r&&o.length;)r=o.every(s=>n.intersects(s,t)),n=o.pop();return r},Vc=(e,t)=>(A("comp",e,t),e=zc(e,t),A("caret",e),e=Jc(e,t),A("tildes",e),e=Qc(e,t),A("xrange",e),e=el(e,t),A("stars",e),e),O=e=>!e||e.toLowerCase()==="x"||e==="*",Jc=(e,t)=>e.trim().split(/\s+/).map(r=>Xc(r,t)).join(" "),Xc=(e,t)=>{let r=t.loose?$[T.TILDELOOSE]:$[T.TILDE];return e.replace(r,(o,n,s,i,a)=>{A("tilde",e,o,n,s,i,a);let l;return O(n)?l="":O(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:O(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(A("replaceTilde pr",a),l=`>=${n}.${s}.${i}-${a} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,A("tilde return",l),l})},zc=(e,t)=>e.trim().split(/\s+/).map(r=>Yc(r,t)).join(" "),Yc=(e,t)=>{A("caret",e,t);let r=t.loose?$[T.CARETLOOSE]:$[T.CARET],o=t.includePrerelease?"-0":"";return e.replace(r,(n,s,i,a,l)=>{A("caret",e,n,s,i,a,l);let u;return O(s)?u="":O(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:O(a)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(A("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(A("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a}${o} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),A("caret return",u),u})},Qc=(e,t)=>(A("replaceXRanges",e,t),e.split(/\s+/).map(r=>Zc(r,t)).join(" ")),Zc=(e,t)=>{e=e.trim();let r=t.loose?$[T.XRANGELOOSE]:$[T.XRANGE];return e.replace(r,(o,n,s,i,a,l)=>{A("xRange",e,o,n,s,i,a,l);let u=O(s),h=u||O(i),m=h||O(a),S=m;return n==="="&&S&&(n=""),l=t.includePrerelease?"-0":"",u?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&S?(h&&(i=0),a=0,n===">"?(n=">=",h?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):n==="<="&&(n="<",h?s=+s+1:i=+i+1),n==="<"&&(l="-0"),o=`${n+s}.${i}.${a}${l}`):h?o=`>=${s}.0.0${l} <${+s+1}.0.0-0`:m&&(o=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),A("xRange return",o),o})},el=(e,t)=>(A("replaceStars",e,t),e.trim().replace($[T.STAR],"")),tl=(e,t)=>(A("replaceGTE0",e,t),e.trim().replace($[t.includePrerelease?T.GTE0PRE:T.GTE0],"")),rl=e=>(t,r,o,n,s,i,a,l,u,h,m,S)=>(O(o)?r="":O(n)?r=`>=${o}.0.0${e?"-0":""}`:O(s)?r=`>=${o}.${n}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,O(u)?l="":O(h)?l=`<${+u+1}.0.0-0`:O(m)?l=`<${u}.${+h+1}.0-0`:S?l=`<=${u}.${h}.${m}-${S}`:e?l=`<${u}.${h}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),ol=(e,t,r)=>{for(let o=0;o<e.length;o++)if(!e[o].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let o=0;o<e.length;o++)if(A(e[o].semver),e[o].semver!==hr.ANY&&e[o].semver.prerelease.length>0){let n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}});var je=w((Im,Kn)=>{"use strict";var Fe=Symbol("SemVer ANY"),wr=class e{static get ANY(){return Fe}constructor(t,r){if(r=Un(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),yr("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Fe?this.value="":this.value=this.operator+this.semver.version,yr("comp",this)}parse(t){let r=this.options.loose?jn[Fn.COMPARATORLOOSE]:jn[Fn.COMPARATOR],o=t.match(r);if(!o)throw new TypeError(`Invalid comparator: ${t}`);this.operator=o[1]!==void 0?o[1]:"",this.operator==="="&&(this.operator=""),o[2]?this.semver=new Bn(o[2],this.options.loose):this.semver=Fe}toString(){return this.value}test(t){if(yr("Comparator.test",t,this.options.loose),this.semver===Fe||t===Fe)return!0;if(typeof t=="string")try{t=new Bn(t,this.options)}catch{return!1}return gr(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Wn(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Wn(this.value,r).test(t.semver):(r=Un(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||gr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||gr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Kn.exports=wr;var Un=it(),{safeRe:jn,t:Fn}=ye(),gr=dr(),yr=_e(),Bn=C(),Wn=D()});var Be=w((vm,qn)=>{"use strict";var nl=D(),sl=(e,t,r)=>{try{t=new nl(t,r)}catch{return!1}return t.test(e)};qn.exports=sl});var Gn=w((bm,Hn)=>{"use strict";var il=D(),al=(e,t)=>new il(e,t).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Hn.exports=al});var Jn=w((Cm,Vn)=>{"use strict";var cl=C(),ll=D(),ul=(e,t,r)=>{let o=null,n=null,s=null;try{s=new ll(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new cl(o,r))}),o};Vn.exports=ul});var zn=w((Tm,Xn)=>{"use strict";var pl=C(),dl=D(),ml=(e,t,r)=>{let o=null,n=null,s=null;try{s=new dl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new pl(o,r))}),o};Xn.exports=ml});var Zn=w((Om,Qn)=>{"use strict";var Er=C(),fl=D(),Yn=Ue(),hl=(e,t)=>{e=new fl(e,t);let r=new Er("0.0.0");if(e.test(r)||(r=new Er("0.0.0-0"),e.test(r)))return r;r=null;for(let o=0;o<e.set.length;++o){let n=e.set[o],s=null;n.forEach(i=>{let a=new Er(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||Yn(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||Yn(r,s))&&(r=s)}return r&&e.test(r)?r:null};Qn.exports=hl});var ts=w((xm,es)=>{"use strict";var gl=D(),yl=(e,t)=>{try{return new gl(e,t).range||"*"}catch{return null}};es.exports=yl});var yt=w(($m,ss)=>{"use strict";var wl=C(),ns=je(),{ANY:El}=ns,Sl=D(),Rl=Be(),rs=Ue(),os=dt(),Al=ft(),Pl=mt(),Il=(e,t,r,o)=>{e=new wl(e,o),t=new Sl(t,o);let n,s,i,a,l;switch(r){case">":n=rs,s=Al,i=os,a=">",l=">=";break;case"<":n=os,s=Pl,i=rs,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Rl(e,t,o))return!1;for(let u=0;u<t.set.length;++u){let h=t.set[u],m=null,S=null;if(h.forEach(f=>{f.semver===El&&(f=new ns(">=0.0.0")),m=m||f,S=S||f,n(f.semver,m.semver,o)?m=f:i(f.semver,S.semver,o)&&(S=f)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&s(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};ss.exports=Il});var as=w((Nm,is)=>{"use strict";var vl=yt(),bl=(e,t,r)=>vl(e,t,">",r);is.exports=bl});var ls=w((Lm,cs)=>{"use strict";var Cl=yt(),Tl=(e,t,r)=>Cl(e,t,"<",r);cs.exports=Tl});var ds=w((km,ps)=>{"use strict";var us=D(),Ol=(e,t,r)=>(e=new us(e,r),t=new us(t,r),e.intersects(t,r));ps.exports=Ol});var fs=w((Dm,ms)=>{"use strict";var xl=Be(),$l=k();ms.exports=(e,t,r)=>{let o=[],n=null,s=null,i=e.sort((h,m)=>$l(h,m,r));for(let h of i)xl(h,t,r)?(s=h,n||(n=h)):(s&&o.push([n,s]),s=null,n=null);n&&o.push([n,null]);let a=[];for(let[h,m]of o)h===m?a.push(h):!m&&h===i[0]?a.push("*"):m?h===i[0]?a.push(`<=${m}`):a.push(`${h} - ${m}`):a.push(`>=${h}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var Ss=w((Mm,Es)=>{"use strict";var hs=D(),Rr=je(),{ANY:Sr}=Rr,We=Be(),Ar=k(),Nl=(e,t,r={})=>{if(e===t)return!0;e=new hs(e,r),t=new hs(t,r);let o=!1;e:for(let n of e.set){for(let s of t.set){let i=kl(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},Ll=[new Rr(">=0.0.0-0")],gs=[new Rr(">=0.0.0")],kl=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Sr){if(t.length===1&&t[0].semver===Sr)return!0;r.includePrerelease?e=Ll:e=gs}if(t.length===1&&t[0].semver===Sr){if(r.includePrerelease)return!0;t=gs}let o=new Set,n,s;for(let f of e)f.operator===">"||f.operator===">="?n=ys(n,f,r):f.operator==="<"||f.operator==="<="?s=ws(s,f,r):o.add(f.semver);if(o.size>1)return null;let i;if(n&&s){if(i=Ar(n.semver,s.semver,r),i>0)return null;if(i===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let f of o){if(n&&!We(f,String(n),r)||s&&!We(f,String(s),r))return null;for(let v of t)if(!We(f,String(v),r))return!1;return!0}let a,l,u,h,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1;m&&m.prerelease.length===1&&s.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let f of t){if(h=h||f.operator===">"||f.operator===">=",u=u||f.operator==="<"||f.operator==="<=",n){if(S&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===S.major&&f.semver.minor===S.minor&&f.semver.patch===S.patch&&(S=!1),f.operator===">"||f.operator===">="){if(a=ys(n,f,r),a===f&&a!==n)return!1}else if(n.operator===">="&&!We(n.semver,String(f),r))return!1}if(s){if(m&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===m.major&&f.semver.minor===m.minor&&f.semver.patch===m.patch&&(m=!1),f.operator==="<"||f.operator==="<="){if(l=ws(s,f,r),l===f&&l!==s)return!1}else if(s.operator==="<="&&!We(s.semver,String(f),r))return!1}if(!f.operator&&(s||n)&&i!==0)return!1}return!(n&&u&&!s&&i!==0||s&&h&&!n&&i!==0||S||m)},ys=(e,t,r)=>{if(!e)return t;let o=Ar(e.semver,t.semver,r);return o>0?e:o<0||t.operator===">"&&e.operator===">="?t:e},ws=(e,t,r)=>{if(!e)return t;let o=Ar(e.semver,t.semver,r);return o<0?e:o>0||t.operator==="<"&&e.operator==="<="?t:e};Es.exports=Nl});var Ir=w((_m,Ps)=>{"use strict";var Pr=ye(),Rs=Me(),Dl=C(),As=cr(),Ml=ue(),_l=Vo(),Ul=Xo(),jl=Qo(),Fl=tn(),Bl=on(),Wl=sn(),Kl=cn(),ql=un(),Hl=k(),Gl=fn(),Vl=gn(),Jl=pt(),Xl=Sn(),zl=An(),Yl=Ue(),Ql=dt(),Zl=ur(),eu=pr(),tu=mt(),ru=ft(),ou=dr(),nu=$n(),su=je(),iu=D(),au=Be(),cu=Gn(),lu=Jn(),uu=zn(),pu=Zn(),du=ts(),mu=yt(),fu=as(),hu=ls(),gu=ds(),yu=fs(),wu=Ss();Ps.exports={parse:Ml,valid:_l,clean:Ul,inc:jl,diff:Fl,major:Bl,minor:Wl,patch:Kl,prerelease:ql,compare:Hl,rcompare:Gl,compareLoose:Vl,compareBuild:Jl,sort:Xl,rsort:zl,gt:Yl,lt:Ql,eq:Zl,neq:eu,gte:tu,lte:ru,cmp:ou,coerce:nu,Comparator:su,Range:iu,satisfies:au,toComparators:cu,maxSatisfying:lu,minSatisfying:uu,minVersion:pu,validRange:du,outside:mu,gtr:fu,ltr:hu,intersects:gu,simplifyRange:yu,subset:wu,SemVer:Dl,re:Pr.re,src:Pr.src,tokens:Pr.t,SEMVER_SPEC_VERSION:Rs.SEMVER_SPEC_VERSION,RELEASE_TYPES:Rs.RELEASE_TYPES,compareIdentifiers:As.compareIdentifiers,rcompareIdentifiers:As.rcompareIdentifiers}});var np={};Fi(np,{handleError:()=>$i,main:()=>xi,run:()=>Ni});module.exports=Bi(np);var Ce=require("@medplum/core"),Xe=require("commander"),Oi=x(require("dotenv"));var ae=require("@medplum/core"),st=require("commander");var Kr=require("@medplum/core");var Br=require("@medplum/core"),G=require("node:fs"),Wr=require("node:os"),jt=require("node:path"),B=class extends Br.ClientStorage{constructor(t){super(),this.dirName=(0,jt.resolve)((0,Wr.homedir)(),".medplum"),this.fileName=(0,jt.resolve)(this.dirName,t+".json")}clear(){this.writeFile({})}getString(t){return this.readFile()?.[t]}setString(t,r){let o=this.readFile()??{};r?o[t]=r:delete o[t],this.writeFile(o)}getObject(t){let r=this.getString(t);return r?JSON.parse(r):void 0}setObject(t,r){this.setString(t,r?JSON.stringify(r):void 0)}readFile(){if((0,G.existsSync)(this.fileName))return JSON.parse((0,G.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,G.existsSync)(this.dirName)||(0,G.mkdirSync)(this.dirName),(0,G.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",o=new B(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:h,clientSecret:m}=Wi(e,o),S=e.fetch??fetch,f=new Kr.MedplumClient({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:Ki,verbose:e.verbose});return t&&(a?f.setAccessToken(a):h&&m&&(f.setBasicAuth(h,m),n?.authType!=="basic"&&await f.startClientLogin(h,m))),f}function Wi(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,s=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,a=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}function Ki(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ie=require("@medplum/core"),fo=require("commander");var Hr=require("node:buffer");var oe=new TextEncoder,Ft=new TextDecoder,up=2**32;function qr(...e){let t=e.reduce((n,{length:s})=>n+s,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var ze=e=>Hr.Buffer.from(e).toString("base64url");var ne=class extends Error{constructor(r,o){super(r,o);I(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};I(ne,"code","ERR_JOSE_GENERIC");var L=class extends ne{constructor(){super(...arguments);I(this,"code","ERR_JOSE_NOT_SUPPORTED")}};I(L,"code","ERR_JOSE_NOT_SUPPORTED");var V=class extends ne{constructor(){super(...arguments);I(this,"code","ERR_JWS_INVALID")}};I(V,"code","ERR_JWS_INVALID");var Oe=class extends ne{constructor(){super(...arguments);I(this,"code","ERR_JWT_INVALID")}};I(Oe,"code","ERR_JWT_INVALID");var Gr,Vr,Bt=class extends(Vr=ne,Gr=Symbol.asyncIterator,Vr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);I(this,Gr);I(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};I(Bt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Jr=x(require("node:util"),1),Ye=e=>Jr.types.isKeyObject(e);var Xr=x(require("node:crypto"),1),zr=x(require("node:util"),1),Hi=Xr.webcrypto,Yr=Hi,me=e=>zr.types.isCryptoKey(e);function W(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function xe(e,t){return e.name===t}function Wt(e){return parseInt(e.name.slice(4),10)}function Gi(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.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Qr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!xe(e.algorithm,"HMAC"))throw W("HMAC");let o=parseInt(t.slice(2),10);if(Wt(e.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!xe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw W("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Wt(e.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!xe(e.algorithm,"RSA-PSS"))throw W("RSA-PSS");let o=parseInt(t.slice(2),10);if(Wt(e.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw W("Ed25519 or Ed448");break}case"Ed25519":{if(!xe(e.algorithm,"Ed25519"))throw W("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!xe(e.algorithm,"ECDSA"))throw W("ECDSA");let o=Gi(t);if(e.algorithm.namedCurve!==o)throw W(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vi(e,r)}function Zr(e,t,...r){if(r=r.filter(Boolean),r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var $e=(e,...t)=>Zr("Key must be ",e,...t);function Kt(e,t,...r){return Zr(`Key for the ${e} algorithm must be `,t,...r)}var qt=e=>Ye(e)||me(e),J=["KeyObject"];(globalThis.CryptoKey||Yr?.CryptoKey)&&J.push("CryptoKey");var Ji=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let s of n){if(r.has(s))return!1;r.add(s)}}return!0},eo=Ji;function Xi(e){return typeof e=="object"&&e!==null}function Ne(e){if(!Xi(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var so=require("node:crypto");function Q(e){return Ne(e)&&typeof e.kty=="string"}function to(e){return e.kty!=="oct"&&typeof e.d=="string"}function ro(e){return e.kty!=="oct"&&typeof e.d>"u"}function oo(e){return Q(e)&&e.kty==="oct"&&typeof e.k=="string"}var zi=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new L("Unsupported key curve for this operation")}},Yi=(e,t)=>{let r;if(me(e))r=so.KeyObject.from(e);else if(Ye(e))r=e;else{if(Q(e))return e.crv;throw new TypeError($e(e,...J))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return t?o:zi(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},io=Yi;var ao=require("node:crypto"),Ht=(e,t)=>{let r;try{e instanceof ao.KeyObject?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var fe=e=>e?.[Symbol.toStringTag],Gt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Qi=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&Q(t)){if(oo(t)&&Gt(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(!qt(t))throw new TypeError(Kt(e,t,...J,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${fe(t)} instances for symmetric algorithms must be of type "secret"`)}},Zi=(e,t,r,o)=>{if(o&&Q(t))switch(r){case"sign":if(to(t)&&Gt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(ro(t)&&Gt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!qt(t))throw new TypeError(Kt(e,t,...J,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${fe(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${fe(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${fe(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${fe(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${fe(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function co(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Qi(t,r,o,e):Zi(t,r,o,e)}var kp=co.bind(void 0,!1),lo=co.bind(void 0,!0);function ea(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let i of o.crit){if(!s.has(i))throw new L(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&o[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}var uo=ea;function Vt(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Le=require("node:crypto");var ta=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Jt(e,t){let r,o,n;if(t instanceof Le.KeyObject)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(n=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let s;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Ht(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=o,u=parseInt(e.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||a!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Ht(t,e),s={padding:Le.constants.RSA_PKCS1_PSS_PADDING,saltLength:Le.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let i=io(t),a=ta.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);s={dsaEncoding:"ieee-p1363"};break}default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return n?{format:"jwk",key:t,...s}:s?{...s,key:t}:t}var Qe=x(require("node:crypto"),1),po=require("node:util");function Xt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var he=require("node:crypto");function zt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError($e(t,...J));return(0,he.createSecretKey)(t)}if(t instanceof he.KeyObject)return t;if(me(t))return Qr(t,e,r),he.KeyObject.from(t);if(Q(t))return e.startsWith("HS")?(0,he.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError($e(t,...J,"Uint8Array","JSON Web Key"))}var ra=(0,po.promisify)(Qe.sign),oa=async(e,t,r)=>{let o=zt(e,t,"sign");if(e.startsWith("HS")){let n=Qe.createHmac(Xt(e),o);return n.update(r),n.digest()}return ra(Vt(e),r,Jt(e,o))},mo=oa;var Z=e=>Math.floor(e.getTime()/1e3);var na=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ze=e=>{let t=na.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-n:n};var et=class{constructor(t){I(this,"_payload");I(this,"_protectedHeader");I(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new V("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!eo(this._protectedHeader,this._unprotectedHeader))throw new V("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=uo(V,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new V('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new V('JWS "alg" (Algorithm) Header Parameter missing or invalid');lo(i,t,"sign");let a=this._payload;s&&(a=oe.encode(ze(a)));let l;this._protectedHeader?l=oe.encode(ze(JSON.stringify(this._protectedHeader))):l=oe.encode("");let u=qr(l,oe.encode("."),a),h=await mo(i,t,u),m={signature:ze(h),payload:""};return s&&(m.payload=Ft.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Ft.decode(l)),m}};var tt=class{constructor(t){I(this,"_flattened");this._flattened=new et(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function se(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var rt=class{constructor(t={}){I(this,"_payload");if(!Ne(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:se("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:se("setNotBefore",Z(t))}:this._payload={...this._payload,nbf:Z(new Date)+Ze(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:se("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:se("setExpirationTime",Z(t))}:this._payload={...this._payload,exp:Z(new Date)+Ze(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:t instanceof Date?this._payload={...this._payload,iat:se("setIssuedAt",Z(t))}:typeof t=="string"?this._payload={...this._payload,iat:se("setIssuedAt",Z(new Date)+Ze(t))}:this._payload={...this._payload,iat:se("setIssuedAt",t)},this}};var ke=class extends rt{constructor(){super(...arguments);I(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new tt(oe.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Oe("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var ge=require("node:crypto"),ee=require("node:fs"),X=require("node:path"),ho=require("node:util/types"),go=require("tar");function z(e){console.log(JSON.stringify(e,null,2))}async function Yt(e,t,r){let o=t.source,n=ot(o);if(!n)return;console.log("Saving source code...");let s=await e.createAttachment({data:n,filename:(0,X.basename)(o),contentType:aa(o)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Qt(e,t,r){let o=t.dist??t.source,n=ot(o);if(!n)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,X.basename)(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function Zt(e,t,r,o,n,s,i){let a={name:t,description:"",runtimeVersion:s},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),h={name:t,id:l.id,source:o,dist:n};await Yt(e,h,u),await Qt(e,h,u),console.log(`Success! Bot created: ${u.id}`),i&&sa(h)}function yo(e){let t=new RegExp("^"+ia(e).replace(/\\\*/g,".*")+"$"),r=K()?.bots?.filter(o=>t.test(o.name));return r||[]}function U(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 b(e,t){(0,ee.writeFileSync)((0,X.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function K(e,t){let r=U(e,t),o=ot(r);if(o)return JSON.parse(o)}function wo(e){let t=ot(U(e,{server:!0}));if(t)return JSON.parse(t)}function ot(e){let t=(0,X.resolve)(e);return(0,ee.existsSync)(t)?(0,ee.readFileSync)(t,"utf8"):""}function sa(e){let t=K()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ee.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ia(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Eo(e){let o=0,n=0;return(0,go.extract)({cwd:e,filter:(s,i)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=i.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function er(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function aa(e){let t=(0,X.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?ie.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?ie.ContentType.TYPESCRIPT:ie.ContentType.TEXT}function nt(e,t){let r=new B(e),o={name:e,...t};return r.setObject("options",o),o}function So(e){return new B(e).getObject("options")}async function Ro(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},s=(0,ie.encodeBase64)(JSON.stringify(r)),i=(0,ie.encodeBase64)(JSON.stringify(n)),a=`${s}.${i}`,l=(0,ge.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Ao(e,t){let r=(0,ge.createPrivateKey)((0,ee.readFileSync)((0,X.resolve)(t.privateKeyPath))),o=await new ke({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ge.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends fo.Command{action(t){let r=ca(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 ca(e,t){return async r=>{let o=e.registeredArguments.length,n=r.slice(0,o);n[o]=e.optsWithGlobals();try{let s=t(...n);(0,ho.isPromise)(s)&&await s}finally{e.resetOptionDefaults()}}}var Po=new g("status").aliases(["info","list","ls"]),Io=new g("ping"),vo=new g("push"),bo=new g("reload-config"),Co=new g("upgrade"),ce=new g("agent");y(ce,Po);y(ce,Io);y(ce,vo);y(ce,bo);y(ce,Co);Po.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 st.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tr({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=pa(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});Io.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await R(r),n=await To(o,t,r),s=Number.parseInt(r.count,10);if(Number.isNaN(s))throw new Error("--count <count> must be an integer if specified");try{let i=await o.pushToAgent(n,e,`PING ${s}`,ae.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});vo.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",ae.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let n=await R(o),s=await To(n,r,o),i;try{i=await n.pushToAgent(s,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});bo.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 st.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tr({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Co.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 st.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await tr({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function tr({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n}){let s=ma(t,r),i=await R(r),a=s.type==="criteria"?s.criteria:`Agent?_id=${s.ids.join(",")}`,l=new URLSearchParams(a.split("?")[1]);for(let[v,H]of Object.entries(o))l.append(v,H.toString());let u;try{let v=i.fhirUrl("Agent",e);v.search=l.toString(),u=await i.get(v,{cache:"reload"})}catch(v){throw new Error(`Operation '${e}' failed`,{cause:v})}if(r.output==="json"){console.info(JSON.stringify(u,null,2));return}let h=[],m=[];switch(u.resourceType){case"Bundle":{let v=la(u);for(let H of v)H.result.resourceType==="Parameters"||(0,ae.isOk)(H.result)?h.push(H):m.push(H);break}case"Parameters":case"OperationOutcome":{let v=await i.searchOne("Agent",l,{cache:"reload"});if(!v)throw new Error("Agent not found");u.resourceType==="Parameters"?h.push({agent:v,result:u}):m.push({agent:v,result:u});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(u)}`)}let S=[];for(let v of h){let H=n(v);S.push(H)}let f=[];for(let v of m){let Ut=v.result.issue?.[0],Li={id:v.agent.id,name:v.agent.name,severity:Ut.severity,code:Ut.code,details:Ut.details?.text??"No details to show"};f.push(Li)}console.info(`
|
|
2
|
+
"use strict";var ki=Object.create;var Te=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var Mi=Object.getOwnPropertyNames;var _i=Object.getPrototypeOf,Ui=Object.prototype.hasOwnProperty;var ji=(e,t,r)=>t in e?Te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fi=(e,t)=>{for(var r in t)Te(e,r,{get:t[r],enumerable:!0})},Fr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Mi(t))!Ui.call(e,n)&&n!==r&&Te(e,n,{get:()=>t[n],enumerable:!(o=Di(t,n))||o.enumerable});return e};var x=(e,t,r)=>(r=e!=null?ki(_i(e)):{},Fr(t||!e||!e.__esModule?Te(r,"default",{value:e,enumerable:!0}):r,e)),Bi=e=>Fr(Te({},"__esModule",{value:!0}),e);var I=(e,t,r)=>ji(e,typeof t!="symbol"?t+"":t,r);var Me=w((jd,Do)=>{"use strict";var Ia="2.0.0",va=Number.MAX_SAFE_INTEGER||9007199254740991,ba=16,Ca=250,Ta=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Do.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ba,MAX_SAFE_BUILD_LENGTH:Ca,MAX_SAFE_INTEGER:va,RELEASE_TYPES:Ta,SEMVER_SPEC_VERSION:Ia,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var _e=w((Fd,Mo)=>{"use strict";var Oa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Mo.exports=Oa});var ye=w((q,_o)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ir,MAX_SAFE_BUILD_LENGTH:xa,MAX_LENGTH:$a}=Me(),Na=_e();q=_o.exports={};var La=q.re=[],ka=q.safeRe=[],p=q.src=[],Da=q.safeSrc=[],d=q.t={},Ma=0,ar="[a-zA-Z0-9-]",_a=[["\\s",1],["\\d",$a],[ar,xa]],Ua=e=>{for(let[t,r]of _a)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let o=Ua(t),n=Ma++;Na(e,n,t),d[e]=n,p[n]=t,Da[n]=o,La[n]=new RegExp(t,r?"g":void 0),ka[n]=new RegExp(o,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ar}*`);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",`${ar}+`);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,${ir}})(?:\\.(\\d{1,${ir}}))?(?:\\.(\\d{1,${ir}}))?`);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);q.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);q.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);q.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 it=w((Bd,Uo)=>{"use strict";var ja=Object.freeze({loose:!0}),Fa=Object.freeze({}),Ba=e=>e?typeof e!="object"?ja:e:Fa;Uo.exports=Ba});var cr=w((Wd,Bo)=>{"use strict";var jo=/^[0-9]+$/,Fo=(e,t)=>{let r=jo.test(e),o=jo.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1},Wa=(e,t)=>Fo(t,e);Bo.exports={compareIdentifiers:Fo,rcompareIdentifiers:Wa}});var C=w((Kd,Ko)=>{"use strict";var at=_e(),{MAX_LENGTH:Wo,MAX_SAFE_INTEGER:ct}=Me(),{safeRe:lt,t:ut}=ye(),Ka=it(),{compareIdentifiers:we}=cr(),lr=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>Wo)throw new TypeError(`version is longer than ${Wo} characters`);at("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=t.trim().match(r.loose?lt[ut.LOOSE]:lt[ut.FULL]);if(!o)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>ct||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ct||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ct||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<ct)return s}return n}):this.prerelease=[],this.build=o[5]?o[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(at("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)),we(this.major,t.major)||we(this.minor,t.minor)||we(this.patch,t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let o=this.prerelease[r],n=t.prerelease[r];if(at("prerelease compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return we(o,n)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let o=this.build[r],n=t.build[r];if(at("build compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return we(o,n)}while(++r)}inc(t,r,o){if(t.startsWith("pre")){if(!r&&o===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=`-${r}`.match(this.options.loose?lt[ut.PRERELEASELOOSE]:lt[ut.PRERELEASE]);if(!n||n[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,o);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,o);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,o),this.inc("pre",r,o);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,o),this.inc("pre",r,o);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(o)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&o===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];o===!1&&(s=[r]),we(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Ko.exports=lr});var ue=w((qd,Ho)=>{"use strict";var qo=C(),qa=(e,t,r=!1)=>{if(e instanceof qo)return e;try{return new qo(e,t)}catch(o){if(!r)return null;throw o}};Ho.exports=qa});var Vo=w((Hd,Go)=>{"use strict";var Ha=ue(),Ga=(e,t)=>{let r=Ha(e,t);return r?r.version:null};Go.exports=Ga});var Xo=w((Gd,Jo)=>{"use strict";var Va=ue(),Ja=(e,t)=>{let r=Va(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Jo.exports=Ja});var Qo=w((Vd,Yo)=>{"use strict";var zo=C(),Xa=(e,t,r,o,n)=>{typeof r=="string"&&(n=o,o=r,r=void 0);try{return new zo(e instanceof zo?e.version:e,r).inc(t,o,n).version}catch{return null}};Yo.exports=Xa});var tn=w((Jd,en)=>{"use strict";var Zo=ue(),za=(e,t)=>{let r=Zo(e,null,!0),o=Zo(t,null,!0),n=r.compare(o);if(n===0)return null;let s=n>0,i=s?r:o,a=s?o:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let h=l?"pre":"";return r.major!==o.major?h+"major":r.minor!==o.minor?h+"minor":r.patch!==o.patch?h+"patch":"prerelease"};en.exports=za});var on=w((Xd,rn)=>{"use strict";var Ya=C(),Qa=(e,t)=>new Ya(e,t).major;rn.exports=Qa});var sn=w((zd,nn)=>{"use strict";var Za=C(),ec=(e,t)=>new Za(e,t).minor;nn.exports=ec});var cn=w((Yd,an)=>{"use strict";var tc=C(),rc=(e,t)=>new tc(e,t).patch;an.exports=rc});var un=w((Qd,ln)=>{"use strict";var oc=ue(),nc=(e,t)=>{let r=oc(e,t);return r&&r.prerelease.length?r.prerelease:null};ln.exports=nc});var k=w((Zd,dn)=>{"use strict";var pn=C(),sc=(e,t,r)=>new pn(e,r).compare(new pn(t,r));dn.exports=sc});var fn=w((em,mn)=>{"use strict";var ic=k(),ac=(e,t,r)=>ic(t,e,r);mn.exports=ac});var gn=w((tm,hn)=>{"use strict";var cc=k(),lc=(e,t)=>cc(e,t,!0);hn.exports=lc});var pt=w((rm,wn)=>{"use strict";var yn=C(),uc=(e,t,r)=>{let o=new yn(e,r),n=new yn(t,r);return o.compare(n)||o.compareBuild(n)};wn.exports=uc});var Sn=w((om,En)=>{"use strict";var pc=pt(),dc=(e,t)=>e.sort((r,o)=>pc(r,o,t));En.exports=dc});var An=w((nm,Rn)=>{"use strict";var mc=pt(),fc=(e,t)=>e.sort((r,o)=>mc(o,r,t));Rn.exports=fc});var Ue=w((sm,Pn)=>{"use strict";var hc=k(),gc=(e,t,r)=>hc(e,t,r)>0;Pn.exports=gc});var dt=w((im,In)=>{"use strict";var yc=k(),wc=(e,t,r)=>yc(e,t,r)<0;In.exports=wc});var ur=w((am,vn)=>{"use strict";var Ec=k(),Sc=(e,t,r)=>Ec(e,t,r)===0;vn.exports=Sc});var pr=w((cm,bn)=>{"use strict";var Rc=k(),Ac=(e,t,r)=>Rc(e,t,r)!==0;bn.exports=Ac});var mt=w((lm,Cn)=>{"use strict";var Pc=k(),Ic=(e,t,r)=>Pc(e,t,r)>=0;Cn.exports=Ic});var ft=w((um,Tn)=>{"use strict";var vc=k(),bc=(e,t,r)=>vc(e,t,r)<=0;Tn.exports=bc});var dr=w((pm,On)=>{"use strict";var Cc=ur(),Tc=pr(),Oc=Ue(),xc=mt(),$c=dt(),Nc=ft(),Lc=(e,t,r,o)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return Cc(e,r,o);case"!=":return Tc(e,r,o);case">":return Oc(e,r,o);case">=":return xc(e,r,o);case"<":return $c(e,r,o);case"<=":return Nc(e,r,o);default:throw new TypeError(`Invalid operator: ${t}`)}};On.exports=Lc});var $n=w((dm,xn)=>{"use strict";var kc=C(),Dc=ue(),{safeRe:ht,t:gt}=ye(),Mc=(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?ht[gt.COERCEFULL]:ht[gt.COERCE]);else{let l=t.includePrerelease?ht[gt.COERCERTLFULL]:ht[gt.COERCERTL],u;for(;(u=l.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let o=r[2],n=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Dc(`${o}.${n}.${s}${i}${a}`,t)};xn.exports=Mc});var Ln=w((mm,Nn)=>{"use strict";var mr=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};Nn.exports=mr});var D=w((fm,_n)=>{"use strict";var _c=/\s+/g,fr=class e{constructor(t,r){if(r=jc(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof hr)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(_c," "),this.set=this.raw.split("||").map(o=>this.parseRange(o.trim())).filter(o=>o.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let o=this.set[0];if(this.set=this.set.filter(n=>!Dn(n[0])),this.set.length===0)this.set=[o];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&Gc(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let o=0;o<r.length;o++)o>0&&(this.formatted+=" "),this.formatted+=r[o].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let o=((this.options.includePrerelease&&qc)|(this.options.loose&&Hc))+":"+t,n=kn.get(o);if(n)return n;let s=this.options.loose,i=s?$[T.HYPHENRANGELOOSE]:$[T.HYPHENRANGE];t=t.replace(i,rl(this.options.includePrerelease)),A("hyphen replace",t),t=t.replace($[T.COMPARATORTRIM],Bc),A("comparator trim",t),t=t.replace($[T.TILDETRIM],Wc),A("tilde trim",t),t=t.replace($[T.CARETTRIM],Kc),A("caret trim",t);let a=t.split(" ").map(m=>Vc(m,this.options)).join(" ").split(/\s+/).map(m=>tl(m,this.options));s&&(a=a.filter(m=>(A("loose invalid filter",m,this.options),!!m.match($[T.COMPARATORLOOSE])))),A("range list",a);let l=new Map,u=a.map(m=>new hr(m,this.options));for(let m of u){if(Dn(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let h=[...l.values()];return kn.set(o,h),h}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(o=>Mn(o,r)&&t.set.some(n=>Mn(n,r)&&o.every(s=>n.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Fc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(ol(this.set[r],t,this.options))return!0;return!1}};_n.exports=fr;var Uc=Ln(),kn=new Uc,jc=it(),hr=je(),A=_e(),Fc=C(),{safeRe:$,t:T,comparatorTrimReplace:Bc,tildeTrimReplace:Wc,caretTrimReplace:Kc}=ye(),{FLAG_INCLUDE_PRERELEASE:qc,FLAG_LOOSE:Hc}=Me(),Dn=e=>e.value==="<0.0.0-0",Gc=e=>e.value==="",Mn=(e,t)=>{let r=!0,o=e.slice(),n=o.pop();for(;r&&o.length;)r=o.every(s=>n.intersects(s,t)),n=o.pop();return r},Vc=(e,t)=>(A("comp",e,t),e=zc(e,t),A("caret",e),e=Jc(e,t),A("tildes",e),e=Qc(e,t),A("xrange",e),e=el(e,t),A("stars",e),e),O=e=>!e||e.toLowerCase()==="x"||e==="*",Jc=(e,t)=>e.trim().split(/\s+/).map(r=>Xc(r,t)).join(" "),Xc=(e,t)=>{let r=t.loose?$[T.TILDELOOSE]:$[T.TILDE];return e.replace(r,(o,n,s,i,a)=>{A("tilde",e,o,n,s,i,a);let l;return O(n)?l="":O(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:O(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(A("replaceTilde pr",a),l=`>=${n}.${s}.${i}-${a} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,A("tilde return",l),l})},zc=(e,t)=>e.trim().split(/\s+/).map(r=>Yc(r,t)).join(" "),Yc=(e,t)=>{A("caret",e,t);let r=t.loose?$[T.CARETLOOSE]:$[T.CARET],o=t.includePrerelease?"-0":"";return e.replace(r,(n,s,i,a,l)=>{A("caret",e,n,s,i,a,l);let u;return O(s)?u="":O(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:O(a)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(A("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(A("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a}${o} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),A("caret return",u),u})},Qc=(e,t)=>(A("replaceXRanges",e,t),e.split(/\s+/).map(r=>Zc(r,t)).join(" ")),Zc=(e,t)=>{e=e.trim();let r=t.loose?$[T.XRANGELOOSE]:$[T.XRANGE];return e.replace(r,(o,n,s,i,a,l)=>{A("xRange",e,o,n,s,i,a,l);let u=O(s),h=u||O(i),m=h||O(a),S=m;return n==="="&&S&&(n=""),l=t.includePrerelease?"-0":"",u?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&S?(h&&(i=0),a=0,n===">"?(n=">=",h?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):n==="<="&&(n="<",h?s=+s+1:i=+i+1),n==="<"&&(l="-0"),o=`${n+s}.${i}.${a}${l}`):h?o=`>=${s}.0.0${l} <${+s+1}.0.0-0`:m&&(o=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),A("xRange return",o),o})},el=(e,t)=>(A("replaceStars",e,t),e.trim().replace($[T.STAR],"")),tl=(e,t)=>(A("replaceGTE0",e,t),e.trim().replace($[t.includePrerelease?T.GTE0PRE:T.GTE0],"")),rl=e=>(t,r,o,n,s,i,a,l,u,h,m,S)=>(O(o)?r="":O(n)?r=`>=${o}.0.0${e?"-0":""}`:O(s)?r=`>=${o}.${n}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,O(u)?l="":O(h)?l=`<${+u+1}.0.0-0`:O(m)?l=`<${u}.${+h+1}.0-0`:S?l=`<=${u}.${h}.${m}-${S}`:e?l=`<${u}.${h}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),ol=(e,t,r)=>{for(let o=0;o<e.length;o++)if(!e[o].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let o=0;o<e.length;o++)if(A(e[o].semver),e[o].semver!==hr.ANY&&e[o].semver.prerelease.length>0){let n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}});var je=w((hm,Kn)=>{"use strict";var Fe=Symbol("SemVer ANY"),wr=class e{static get ANY(){return Fe}constructor(t,r){if(r=Un(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),yr("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Fe?this.value="":this.value=this.operator+this.semver.version,yr("comp",this)}parse(t){let r=this.options.loose?jn[Fn.COMPARATORLOOSE]:jn[Fn.COMPARATOR],o=t.match(r);if(!o)throw new TypeError(`Invalid comparator: ${t}`);this.operator=o[1]!==void 0?o[1]:"",this.operator==="="&&(this.operator=""),o[2]?this.semver=new Bn(o[2],this.options.loose):this.semver=Fe}toString(){return this.value}test(t){if(yr("Comparator.test",t,this.options.loose),this.semver===Fe||t===Fe)return!0;if(typeof t=="string")try{t=new Bn(t,this.options)}catch{return!1}return gr(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Wn(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Wn(this.value,r).test(t.semver):(r=Un(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||gr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||gr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Kn.exports=wr;var Un=it(),{safeRe:jn,t:Fn}=ye(),gr=dr(),yr=_e(),Bn=C(),Wn=D()});var Be=w((gm,qn)=>{"use strict";var nl=D(),sl=(e,t,r)=>{try{t=new nl(t,r)}catch{return!1}return t.test(e)};qn.exports=sl});var Gn=w((ym,Hn)=>{"use strict";var il=D(),al=(e,t)=>new il(e,t).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Hn.exports=al});var Jn=w((wm,Vn)=>{"use strict";var cl=C(),ll=D(),ul=(e,t,r)=>{let o=null,n=null,s=null;try{s=new ll(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new cl(o,r))}),o};Vn.exports=ul});var zn=w((Em,Xn)=>{"use strict";var pl=C(),dl=D(),ml=(e,t,r)=>{let o=null,n=null,s=null;try{s=new dl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new pl(o,r))}),o};Xn.exports=ml});var Zn=w((Sm,Qn)=>{"use strict";var Er=C(),fl=D(),Yn=Ue(),hl=(e,t)=>{e=new fl(e,t);let r=new Er("0.0.0");if(e.test(r)||(r=new Er("0.0.0-0"),e.test(r)))return r;r=null;for(let o=0;o<e.set.length;++o){let n=e.set[o],s=null;n.forEach(i=>{let a=new Er(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||Yn(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||Yn(r,s))&&(r=s)}return r&&e.test(r)?r:null};Qn.exports=hl});var ts=w((Rm,es)=>{"use strict";var gl=D(),yl=(e,t)=>{try{return new gl(e,t).range||"*"}catch{return null}};es.exports=yl});var yt=w((Am,ss)=>{"use strict";var wl=C(),ns=je(),{ANY:El}=ns,Sl=D(),Rl=Be(),rs=Ue(),os=dt(),Al=ft(),Pl=mt(),Il=(e,t,r,o)=>{e=new wl(e,o),t=new Sl(t,o);let n,s,i,a,l;switch(r){case">":n=rs,s=Al,i=os,a=">",l=">=";break;case"<":n=os,s=Pl,i=rs,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Rl(e,t,o))return!1;for(let u=0;u<t.set.length;++u){let h=t.set[u],m=null,S=null;if(h.forEach(f=>{f.semver===El&&(f=new ns(">=0.0.0")),m=m||f,S=S||f,n(f.semver,m.semver,o)?m=f:i(f.semver,S.semver,o)&&(S=f)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&s(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};ss.exports=Il});var as=w((Pm,is)=>{"use strict";var vl=yt(),bl=(e,t,r)=>vl(e,t,">",r);is.exports=bl});var ls=w((Im,cs)=>{"use strict";var Cl=yt(),Tl=(e,t,r)=>Cl(e,t,"<",r);cs.exports=Tl});var ds=w((vm,ps)=>{"use strict";var us=D(),Ol=(e,t,r)=>(e=new us(e,r),t=new us(t,r),e.intersects(t,r));ps.exports=Ol});var fs=w((bm,ms)=>{"use strict";var xl=Be(),$l=k();ms.exports=(e,t,r)=>{let o=[],n=null,s=null,i=e.sort((h,m)=>$l(h,m,r));for(let h of i)xl(h,t,r)?(s=h,n||(n=h)):(s&&o.push([n,s]),s=null,n=null);n&&o.push([n,null]);let a=[];for(let[h,m]of o)h===m?a.push(h):!m&&h===i[0]?a.push("*"):m?h===i[0]?a.push(`<=${m}`):a.push(`${h} - ${m}`):a.push(`>=${h}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var Ss=w((Cm,Es)=>{"use strict";var hs=D(),Rr=je(),{ANY:Sr}=Rr,We=Be(),Ar=k(),Nl=(e,t,r={})=>{if(e===t)return!0;e=new hs(e,r),t=new hs(t,r);let o=!1;e:for(let n of e.set){for(let s of t.set){let i=kl(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},Ll=[new Rr(">=0.0.0-0")],gs=[new Rr(">=0.0.0")],kl=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Sr){if(t.length===1&&t[0].semver===Sr)return!0;r.includePrerelease?e=Ll:e=gs}if(t.length===1&&t[0].semver===Sr){if(r.includePrerelease)return!0;t=gs}let o=new Set,n,s;for(let f of e)f.operator===">"||f.operator===">="?n=ys(n,f,r):f.operator==="<"||f.operator==="<="?s=ws(s,f,r):o.add(f.semver);if(o.size>1)return null;let i;if(n&&s){if(i=Ar(n.semver,s.semver,r),i>0)return null;if(i===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let f of o){if(n&&!We(f,String(n),r)||s&&!We(f,String(s),r))return null;for(let v of t)if(!We(f,String(v),r))return!1;return!0}let a,l,u,h,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1;m&&m.prerelease.length===1&&s.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let f of t){if(h=h||f.operator===">"||f.operator===">=",u=u||f.operator==="<"||f.operator==="<=",n){if(S&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===S.major&&f.semver.minor===S.minor&&f.semver.patch===S.patch&&(S=!1),f.operator===">"||f.operator===">="){if(a=ys(n,f,r),a===f&&a!==n)return!1}else if(n.operator===">="&&!We(n.semver,String(f),r))return!1}if(s){if(m&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===m.major&&f.semver.minor===m.minor&&f.semver.patch===m.patch&&(m=!1),f.operator==="<"||f.operator==="<="){if(l=ws(s,f,r),l===f&&l!==s)return!1}else if(s.operator==="<="&&!We(s.semver,String(f),r))return!1}if(!f.operator&&(s||n)&&i!==0)return!1}return!(n&&u&&!s&&i!==0||s&&h&&!n&&i!==0||S||m)},ys=(e,t,r)=>{if(!e)return t;let o=Ar(e.semver,t.semver,r);return o>0?e:o<0||t.operator===">"&&e.operator===">="?t:e},ws=(e,t,r)=>{if(!e)return t;let o=Ar(e.semver,t.semver,r);return o<0?e:o>0||t.operator==="<"&&e.operator==="<="?t:e};Es.exports=Nl});var Ir=w((Tm,Ps)=>{"use strict";var Pr=ye(),Rs=Me(),Dl=C(),As=cr(),Ml=ue(),_l=Vo(),Ul=Xo(),jl=Qo(),Fl=tn(),Bl=on(),Wl=sn(),Kl=cn(),ql=un(),Hl=k(),Gl=fn(),Vl=gn(),Jl=pt(),Xl=Sn(),zl=An(),Yl=Ue(),Ql=dt(),Zl=ur(),eu=pr(),tu=mt(),ru=ft(),ou=dr(),nu=$n(),su=je(),iu=D(),au=Be(),cu=Gn(),lu=Jn(),uu=zn(),pu=Zn(),du=ts(),mu=yt(),fu=as(),hu=ls(),gu=ds(),yu=fs(),wu=Ss();Ps.exports={parse:Ml,valid:_l,clean:Ul,inc:jl,diff:Fl,major:Bl,minor:Wl,patch:Kl,prerelease:ql,compare:Hl,rcompare:Gl,compareLoose:Vl,compareBuild:Jl,sort:Xl,rsort:zl,gt:Yl,lt:Ql,eq:Zl,neq:eu,gte:tu,lte:ru,cmp:ou,coerce:nu,Comparator:su,Range:iu,satisfies:au,toComparators:cu,maxSatisfying:lu,minSatisfying:uu,minVersion:pu,validRange:du,outside:mu,gtr:fu,ltr:hu,intersects:gu,simplifyRange:yu,subset:wu,SemVer:Dl,re:Pr.re,src:Pr.src,tokens:Pr.t,SEMVER_SPEC_VERSION:Rs.SEMVER_SPEC_VERSION,RELEASE_TYPES:Rs.RELEASE_TYPES,compareIdentifiers:As.compareIdentifiers,rcompareIdentifiers:As.rcompareIdentifiers}});var np={};Fi(np,{handleError:()=>$i,main:()=>xi,run:()=>Ni});module.exports=Bi(np);var Ce=require("@medplum/core"),Xe=require("commander"),Oi=x(require("dotenv"));var ae=require("@medplum/core"),st=require("commander");var Kr=require("@medplum/core");var Br=require("@medplum/core"),G=require("node:fs"),Wr=require("node:os"),jt=require("node:path"),B=class extends Br.ClientStorage{constructor(t){super(),this.dirName=(0,jt.resolve)((0,Wr.homedir)(),".medplum"),this.fileName=(0,jt.resolve)(this.dirName,t+".json")}clear(){this.writeFile({})}getString(t){return this.readFile()?.[t]}setString(t,r){let o=this.readFile()??{};r?o[t]=r:delete o[t],this.writeFile(o)}getObject(t){let r=this.getString(t);return r?JSON.parse(r):void 0}setObject(t,r){this.setString(t,r?JSON.stringify(r):void 0)}readFile(){if((0,G.existsSync)(this.fileName))return JSON.parse((0,G.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,G.existsSync)(this.dirName)||(0,G.mkdirSync)(this.dirName),(0,G.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",o=new B(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:h,clientSecret:m}=Wi(e,o),S=e.fetch??fetch,f=new Kr.MedplumClient({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:Ki,verbose:e.verbose});return t&&(a?f.setAccessToken(a):h&&m&&(f.setBasicAuth(h,m),n?.authType!=="basic"&&await f.startClientLogin(h,m))),f}function Wi(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,s=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,a=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}function Ki(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ie=require("@medplum/core"),fo=require("commander");var Hr=require("node:buffer");var oe=new TextEncoder,Ft=new TextDecoder,lp=2**32;function qr(...e){let t=e.reduce((n,{length:s})=>n+s,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var ze=e=>Hr.Buffer.from(e).toString("base64url");var ne=class extends Error{constructor(r,o){super(r,o);I(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};I(ne,"code","ERR_JOSE_GENERIC");var L=class extends ne{constructor(){super(...arguments);I(this,"code","ERR_JOSE_NOT_SUPPORTED")}};I(L,"code","ERR_JOSE_NOT_SUPPORTED");var V=class extends ne{constructor(){super(...arguments);I(this,"code","ERR_JWS_INVALID")}};I(V,"code","ERR_JWS_INVALID");var Oe=class extends ne{constructor(){super(...arguments);I(this,"code","ERR_JWT_INVALID")}};I(Oe,"code","ERR_JWT_INVALID");var Gr,Vr,Bt=class extends(Vr=ne,Gr=Symbol.asyncIterator,Vr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);I(this,Gr);I(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};I(Bt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Jr=x(require("node:util"),1),Ye=e=>Jr.types.isKeyObject(e);var Xr=x(require("node:crypto"),1),zr=x(require("node:util"),1),Hi=Xr.webcrypto,Yr=Hi,me=e=>zr.types.isCryptoKey(e);function W(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function xe(e,t){return e.name===t}function Wt(e){return parseInt(e.name.slice(4),10)}function Gi(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.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Qr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!xe(e.algorithm,"HMAC"))throw W("HMAC");let o=parseInt(t.slice(2),10);if(Wt(e.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!xe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw W("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Wt(e.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!xe(e.algorithm,"RSA-PSS"))throw W("RSA-PSS");let o=parseInt(t.slice(2),10);if(Wt(e.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw W("Ed25519 or Ed448");break}case"Ed25519":{if(!xe(e.algorithm,"Ed25519"))throw W("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!xe(e.algorithm,"ECDSA"))throw W("ECDSA");let o=Gi(t);if(e.algorithm.namedCurve!==o)throw W(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vi(e,r)}function Zr(e,t,...r){if(r=r.filter(Boolean),r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var $e=(e,...t)=>Zr("Key must be ",e,...t);function Kt(e,t,...r){return Zr(`Key for the ${e} algorithm must be `,t,...r)}var qt=e=>Ye(e)||me(e),J=["KeyObject"];(globalThis.CryptoKey||Yr?.CryptoKey)&&J.push("CryptoKey");var Ji=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let s of n){if(r.has(s))return!1;r.add(s)}}return!0},eo=Ji;function Xi(e){return typeof e=="object"&&e!==null}function Ne(e){if(!Xi(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var so=require("node:crypto");function Q(e){return Ne(e)&&typeof e.kty=="string"}function to(e){return e.kty!=="oct"&&typeof e.d=="string"}function ro(e){return e.kty!=="oct"&&typeof e.d>"u"}function oo(e){return Q(e)&&e.kty==="oct"&&typeof e.k=="string"}var zi=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new L("Unsupported key curve for this operation")}},Yi=(e,t)=>{let r;if(me(e))r=so.KeyObject.from(e);else if(Ye(e))r=e;else{if(Q(e))return e.crv;throw new TypeError($e(e,...J))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return t?o:zi(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},io=Yi;var ao=require("node:crypto"),Ht=(e,t)=>{let r;try{e instanceof ao.KeyObject?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var fe=e=>e?.[Symbol.toStringTag],Gt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Qi=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&Q(t)){if(oo(t)&&Gt(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(!qt(t))throw new TypeError(Kt(e,t,...J,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${fe(t)} instances for symmetric algorithms must be of type "secret"`)}},Zi=(e,t,r,o)=>{if(o&&Q(t))switch(r){case"sign":if(to(t)&&Gt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(ro(t)&&Gt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!qt(t))throw new TypeError(Kt(e,t,...J,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${fe(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${fe(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${fe(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${fe(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${fe(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function co(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Qi(t,r,o,e):Zi(t,r,o,e)}var Lp=co.bind(void 0,!1),lo=co.bind(void 0,!0);function ea(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let i of o.crit){if(!s.has(i))throw new L(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&o[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}var uo=ea;function Vt(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Le=require("node:crypto");var ta=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Jt(e,t){let r,o,n;if(t instanceof Le.KeyObject)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(n=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let s;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Ht(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=o,u=parseInt(e.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||a!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Ht(t,e),s={padding:Le.constants.RSA_PKCS1_PSS_PADDING,saltLength:Le.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let i=io(t),a=ta.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);s={dsaEncoding:"ieee-p1363"};break}default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return n?{format:"jwk",key:t,...s}:s?{...s,key:t}:t}var Qe=x(require("node:crypto"),1),po=require("node:util");function Xt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var he=require("node:crypto");function zt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError($e(t,...J));return(0,he.createSecretKey)(t)}if(t instanceof he.KeyObject)return t;if(me(t))return Qr(t,e,r),he.KeyObject.from(t);if(Q(t))return e.startsWith("HS")?(0,he.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError($e(t,...J,"Uint8Array","JSON Web Key"))}var ra=(0,po.promisify)(Qe.sign),oa=async(e,t,r)=>{let o=zt(e,t,"sign");if(e.startsWith("HS")){let n=Qe.createHmac(Xt(e),o);return n.update(r),n.digest()}return ra(Vt(e),r,Jt(e,o))},mo=oa;var Z=e=>Math.floor(e.getTime()/1e3);var na=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ze=e=>{let t=na.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-n:n};var et=class{constructor(t){I(this,"_payload");I(this,"_protectedHeader");I(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new V("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!eo(this._protectedHeader,this._unprotectedHeader))throw new V("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=uo(V,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new V('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new V('JWS "alg" (Algorithm) Header Parameter missing or invalid');lo(i,t,"sign");let a=this._payload;s&&(a=oe.encode(ze(a)));let l;this._protectedHeader?l=oe.encode(ze(JSON.stringify(this._protectedHeader))):l=oe.encode("");let u=qr(l,oe.encode("."),a),h=await mo(i,t,u),m={signature:ze(h),payload:""};return s&&(m.payload=Ft.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Ft.decode(l)),m}};var tt=class{constructor(t){I(this,"_flattened");this._flattened=new et(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function se(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var rt=class{constructor(t={}){I(this,"_payload");if(!Ne(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:se("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:se("setNotBefore",Z(t))}:this._payload={...this._payload,nbf:Z(new Date)+Ze(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:se("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:se("setExpirationTime",Z(t))}:this._payload={...this._payload,exp:Z(new Date)+Ze(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:t instanceof Date?this._payload={...this._payload,iat:se("setIssuedAt",Z(t))}:typeof t=="string"?this._payload={...this._payload,iat:se("setIssuedAt",Z(new Date)+Ze(t))}:this._payload={...this._payload,iat:se("setIssuedAt",t)},this}};var ke=class extends rt{constructor(){super(...arguments);I(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new tt(oe.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Oe("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var ge=require("node:crypto"),ee=require("node:fs"),X=require("node:path"),ho=require("node:util/types"),go=require("tar");function z(e){console.log(JSON.stringify(e,null,2))}async function Yt(e,t,r){let o=t.source,n=ot(o);if(!n)return;console.log("Saving source code...");let s=await e.createAttachment({data:n,filename:(0,X.basename)(o),contentType:aa(o)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Qt(e,t,r){let o=t.dist??t.source,n=ot(o);if(!n)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,X.basename)(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function Zt(e,t,r,o,n,s,i){let a={name:t,description:"",runtimeVersion:s},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),h={name:t,id:l.id,source:o,dist:n};await Yt(e,h,u),await Qt(e,h,u),console.log(`Success! Bot created: ${u.id}`),i&&sa(h)}function yo(e){let t=new RegExp("^"+ia(e).replace(/\\\*/g,".*")+"$"),r=K()?.bots?.filter(o=>t.test(o.name));return r||[]}function U(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 b(e,t){(0,ee.writeFileSync)((0,X.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function K(e,t){let r=U(e,t),o=ot(r);if(o)return JSON.parse(o)}function wo(e){let t=ot(U(e,{server:!0}));if(t)return JSON.parse(t)}function ot(e){let t=(0,X.resolve)(e);return(0,ee.existsSync)(t)?(0,ee.readFileSync)(t,"utf8"):""}function sa(e){let t=K()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ee.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ia(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Eo(e){let o=0,n=0;return(0,go.extract)({cwd:e,filter:(s,i)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=i.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function er(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function aa(e){let t=(0,X.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?ie.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?ie.ContentType.TYPESCRIPT:ie.ContentType.TEXT}function nt(e,t){let r=new B(e),o={name:e,...t};return r.setObject("options",o),o}function So(e){return new B(e).getObject("options")}async function Ro(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},s=(0,ie.encodeBase64)(JSON.stringify(r)),i=(0,ie.encodeBase64)(JSON.stringify(n)),a=`${s}.${i}`,l=(0,ge.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Ao(e,t){let r=(0,ge.createPrivateKey)((0,ee.readFileSync)((0,X.resolve)(t.privateKeyPath))),o=await new ke({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ge.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends fo.Command{action(t){let r=ca(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 ca(e,t){return async r=>{let o=e.registeredArguments.length,n=r.slice(0,o);n[o]=e.optsWithGlobals();try{let s=t(...n);(0,ho.isPromise)(s)&&await s}finally{e.resetOptionDefaults()}}}var Po=new g("status").aliases(["info","list","ls"]),Io=new g("ping"),vo=new g("push"),bo=new g("reload-config"),Co=new g("upgrade"),ce=new g("agent");y(ce,Po);y(ce,Io);y(ce,vo);y(ce,bo);y(ce,Co);Po.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 st.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tr({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=pa(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});Io.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await R(r),n=await To(o,t,r),s=Number.parseInt(r.count,10);if(Number.isNaN(s))throw new Error("--count <count> must be an integer if specified");try{let i=await o.pushToAgent(n,e,`PING ${s}`,ae.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});vo.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",ae.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let n=await R(o),s=await To(n,r,o),i;try{i=await n.pushToAgent(s,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});bo.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 st.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tr({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Co.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 st.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await tr({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function tr({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n}){let s=ma(t,r),i=await R(r),a=s.type==="criteria"?s.criteria:`Agent?_id=${s.ids.join(",")}`,l=new URLSearchParams(a.split("?")[1]);for(let[v,H]of Object.entries(o))l.append(v,H.toString());let u;try{let v=i.fhirUrl("Agent",e);v.search=l.toString(),u=await i.get(v,{cache:"reload"})}catch(v){throw new Error(`Operation '${e}' failed`,{cause:v})}if(r.output==="json"){console.info(JSON.stringify(u,null,2));return}let h=[],m=[];switch(u.resourceType){case"Bundle":{let v=la(u);for(let H of v)H.result.resourceType==="Parameters"||(0,ae.isOk)(H.result)?h.push(H):m.push(H);break}case"Parameters":case"OperationOutcome":{let v=await i.searchOne("Agent",l,{cache:"reload"});if(!v)throw new Error("Agent not found");u.resourceType==="Parameters"?h.push({agent:v,result:u}):m.push({agent:v,result:u});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(u)}`)}let S=[];for(let v of h){let H=n(v);S.push(H)}let f=[];for(let v of m){let Ut=v.result.issue?.[0],Li={id:v.agent.id,name:v.agent.name,severity:Ut.severity,code:Ut.code,details:Ut.details?.text??"No details to show"};f.push(Li)}console.info(`
|
|
3
3
|
${S.length} successful response(s):
|
|
4
4
|
`),console.table(S.length?S:"No successful responses received"),console.info(),f.length&&(console.info(`${f.length} failed response(s):`),console.info(),console.table(f))}async function To(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(t)o=t;else{Oo(r.criteria);let n=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!n?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(n.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=n.entry[0].resource?.id}return{reference:`Agent/${o}`}}function la(e){let t=[];for(let r of e.entry??[]){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ua(r.resource))}return t}function ua(e){let t=e.parameter?.find(o=>o.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function pa(e,t){let r={},o=t.required,n=t.optional;for(let s of o){let i=e.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${s}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[a]}if(n?.length)for(let s of n){let i=e.parameter?.find(l=>l.name===s);if(!i)continue;let a=da(s,i);r[s]=a}return r}function da(e,t){let r;for(let o in t)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function ma(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!(0,ae.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return Oo(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function Oo(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,o]=e.split("?");if(r!=="Agent"||!o)throw new Error(t);try{new URLSearchParams(o)}catch(n){throw new Error(t,{cause:n})}if(!o.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var j=require("@medplum/core"),xo=require("node:child_process"),$o=require("node:http"),No=require("node:os");var Lo=j.MEDPLUM_CLI_CLIENT_ID,ko="http://localhost:9615",rr=new g("login"),or=new g("whoami"),nr=new g("token");rr.action(async e=>{let t=e.profile??"default",r=nt(t,e),o=await R(e,!1);await fa(o,r)});or.action(async e=>{let t=await R(e);ya(t)});nr.action(async e=>{let t=await R(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function fa(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await wa(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 Ro(e,t);break;case"jwt-assertion":await Ao(e,t);break}}async function ha(e){let t=(0,$o.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),s=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":j.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:Lo,redirectUri:ko});o.writeHead(200,{"Content-Type":j.ContentType.TEXT}),o.end(`Signed in as ${(0,j.getDisplayString)(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":j.ContentType.TEXT}),o.end(`Error: ${(0,j.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":j.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function ga(e){let t=(0,No.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}return new Promise((o,n)=>{(0,xo.exec)(r,(s,i,a)=>{if(s){n(s);return}if(a){n(new Error("Could not open browser: "+a));return}o()})})}function ya(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 wa(e){await ha(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Lo),t.searchParams.set("redirect_uri",ko),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await ga(t.toString())}var De="\x1B[0m",Ea="\x1B[1m",Sa="\x1B[31m",Ra="\x1B[32m",Aa="\x1B[33m",Pa="\x1B[34m",le={red:e=>`${Sa}${e}${De}`,green:e=>`${Ra}${e}${De}`,yellow:e=>`${Aa}${e}${De}`,blue:e=>`${Pa}${e}${De}`,bold:e=>`${Ea}${e}${De}`},sr=e=>e.replace(/\*\*(.*?)\*\*/g,(t,r)=>le.bold(r));var Y=require("@aws-sdk/client-cloudformation"),Pt=require("@aws-sdk/client-cloudfront"),bs=require("@aws-sdk/client-ecs"),Cs=require("@aws-sdk/client-s3"),Se=require("@aws-sdk/client-ssm"),It=require("@aws-sdk/client-sts"),Ts=require("@medplum/core"),Os=x(require("node-fetch")),xs=require("node:fs"),$s=x(Ir());var Is=x(require("node:readline")),wt;function Et(){wt=Is.default.createInterface({input:process.stdin,output:process.stdout})}function St(){wt.close()}function c(e){wt.write(e+`
|
|
5
5
|
`)}function P(e){c(`
|
|
6
6
|
`+e+`
|
|
7
|
-
`)}function N(e,t=""){return new Promise(r=>{wt.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Rt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await N(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function Ee(e,t,r){return parseInt(await Rt(e,t.map(o=>o.toString()),r.toString()),10)}async function te(e){return(await Rt(e,["y","n"])).toLowerCase()==="y"}async function Ke(e){if(!await te(e))throw c("Exiting..."),new Error("User cancelled")}var At=new Y.CloudFormationClient({}),Eu=new Pt.CloudFrontClient({region:"us-east-1"}),qm=new bs.ECSClient({}),qe=new Cs.S3Client({}),Su="medplum:environment";async function vr(){let e=[],t=(0,Y.paginateListStacks)({client:At},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)if(r.StackSummaries)for(let o of r.StackSummaries)e.push(o);return e}async function Re(e){let t=await vr();for(let r of t){let o=r.StackName,n=await br(o);if(n?.tag===e)return n}}async function br(e){let t={};if(await vs(At,e,t),await At.config.region()!=="us-east-1")try{await vs(new Y.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function vs(e,t,r){let o=new Y.DescribeStacksCommand({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===Su);if(!i)return;let a=await e.send(new Y.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===At&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)Ru(l,r)}}function Ru(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 vt(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: ${Au(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 Au(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function bt(e){let t=await Eu.send(new Pt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Ct(e){let o=(await(await(0,Os.default)("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>$s.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function Tt(e,t,r){let o=new Se.SSMClient({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await Pu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ke(`Do you want to overwrite "${i}"?`)),await Iu(o,i,a)}}async function Pu(e,t){let r=new Se.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Iu(e,t,r){let o=new Se.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function re(e,t){if(console.log(`Config not found: ${e} (${U(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=(0,xs.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function Ae(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new It.STSClient,r=new It.GetCallerIdentityCommand({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,Ts.normalizeErrorString)(t))}}async function Ns(e){let t=await Re(e);if(!t)throw await Ae(e),new Error(`Stack not found: ${e}`);vt(t)}var pe=require("@aws-sdk/client-acm"),Ot=require("@aws-sdk/client-cloudfront"),xt=require("@aws-sdk/client-sts"),ks=require("@medplum/core"),He=require("node:crypto"),Ds=require("node:fs");var vu=e=>`${e}DomainName`,Ms=e=>`${e}SslCertArn`;async function _s(){let e={apiPort:8103,region:"us-east-1"};Et(),P("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 bu(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 Ke("Do you want to continue without AWS credentials?")),P("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await N("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),P("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await N("What is the config file name?",`medplum.${e.name}.config.json`);(0,Ds.existsSync)(r)&&(c("Config file already exists."),await Ke("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),b(r,e),P("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await N("Enter your AWS region:","us-east-1"),b(r,e),P("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await N("What is your AWS account number?",t),b(r,e),P("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",o),b(r,e),P("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await N("Enter your base domain name:");b(r,e),P("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await N("Enter your support email address:");P("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await N("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,b(r,e),P("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await N("Enter your web application domain name:","app."+e.domainName),b(r,e),P("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),b(r,e),P("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await N("Enter your storage bucket name:",e.storageDomainName),b(r,e),P("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 Ee("Enter the maximum number of availability zones:",[2,3,99],2),P("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 te("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 Ee("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"),b(r,e),P("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 Ee("Enter the number of server instances:",[1,2,3,4,6,8],1),b(r,e),P("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 Ee("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),b(r,e),P("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 Ee("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),b(r,e),P("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let s=(await Ct())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${s}`),b(r,e),P("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await xu(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,b(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.')),P("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Cu(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:h}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await Tu(e,a,u,h);e[Ms(h)]=m,b(r,e)}P("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await te("Do you want to store these values in AWS Parameter Store?"))await Tt(e.region,`/medplum/${e.name}/`,l);else{let u=U(e.name,{server:!0});b(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.")}P("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(""),St()}async function bu(e){try{let t=new xt.STSClient({region:e}),r=new xt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Cu(e){let t=await Ls(e);if(e!=="us-east-1"){let r=await Ls("us-east-1");t.push(...r)}return t}async function Ls(e){try{let t=new pe.ACMClient({region:e}),r=new pe.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Tu(e,t,r,o){let n=e[vu(o)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===n);if(s)return c(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await te("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Ms(o)}" setting.`),"TODO";let i=await Ou(r,n);return c("Certificate ARN: "+i),i}async function Ou(e,t){try{let r=await Rt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new pe.ACMClient({region:e}),n=new pe.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function xu(e,t){let r=(0,He.randomUUID)(),o=(0,He.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Ot.CloudFrontClient({region:e}).send(new Ot.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,He.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,ks.normalizeErrorString)(n));return}}async function Us(){let e=await vr();for(let t of e){let r=t.StackName,o=await br(r);o&&(vt(o),console.log(""))}}var js=require("@aws-sdk/client-s3"),F=require("@medplum/core"),Fs=x(require("fast-glob")),Cr=x(require("node-fetch")),M=require("node:fs"),Bs=require("node:os"),de=require("node:path"),Ws=require("node:stream/promises");async function Ks(e,t){let r=K(e,t);if(!r)throw re(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let s;if(t.tarPath)s=t.tarPath;else{let i=t?.toVersion??"latest";s=await Nu("@medplum/app",i)}qs(s,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await ku(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await bt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function $u(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Cr.default)(r)).json()}async function Nu(e,t){let o=(await $u(e,t)).dist.tarball,n=(0,M.mkdtempSync)((0,de.join)((0,Bs.tmpdir)(),"tarball-"));try{let s=await(0,Cr.default)(o),i=Eo(n);return await(0,Ws.pipeline)(s.body,i),(0,de.join)(n,"package","dist")}catch(s){throw(0,M.rmSync)(n,{recursive:!0,force:!0}),s}}function qs(e,t){for(let r of(0,M.readdirSync)(e,{withFileTypes:!0})){let o=(0,de.join)(e,r.name);r.isDirectory()?qs(o,t):r.isFile()&&o.endsWith(".js")&&Lu(o,t)}}function Lu(e,t){let r=(0,M.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,M.writeFileSync)(e,r)}async function ku(e,t,r){let o=[["assets/**/*.css",F.ContentType.CSS,!0],["assets/**/*.css.map",F.ContentType.JSON,!0],["assets/**/*.js",F.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",F.ContentType.JSON,!0],["assets/**/*.txt",F.ContentType.TEXT,!0],["assets/**/*.ico",F.ContentType.FAVICON,!0],["img/**/*.png",F.ContentType.PNG,!0],["img/**/*.svg",F.ContentType.SVG,!0],["robots.txt",F.ContentType.TEXT,!0],["index.html",F.ContentType.HTML,!1]];for(let n of o)await Du({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Du(e){let t=Fs.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Mu((0,de.join)(e.rootDir,r),e)}async function Mu(e,t){let r=(0,M.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(de.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await qe.send(new js.PutObjectCommand(n))}var $t=require("@aws-sdk/client-s3");async function Gs(e,t){if(!K(e,t))throw re(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);await Hs("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Hs("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Hs(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=o.PhysicalResourceId,a=await _u(s);if(ju(a,s,i))throw new Error(`${e} bucket already has policy statement`);Fu(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Uu(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await bt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function _u(e){let t=await qe.send(new $t.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Uu(e,t){await qe.send(new $t.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function ju(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Fu(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}async function Vs(e,t){try{Et();let r=K(e,t);if(!r)throw re(e,t),new Error(`Config not found: ${e}`);let o=wo(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=U(e,{server:!0});if(console.log(le.yellow(`Config file ${n} not found!`)),!await te("Do you want to proceed?")){console.log(le.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}Bu(r,o),Ku(r,o),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(le.yellow("Dry run - skipping updates!")):(t.yes||await te("Do you want to store these values in AWS Parameter Store?"))&&await Tt(r.region,`/medplum/${r.name}/`,o)}finally{St()}}function Bu(e,t){Nt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Nt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Nt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Nt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Nt(e,t,r){if(Wu(e,t))throw new Error(r)}function Wu(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ku(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/`)}var Xs=require("node:child_process"),Pe=x(Ir());async function zs(e,t){let r=await R(t),o=K(e,t);if(!o)throw console.log(`Configuration file ${U(e)} not found`),re(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await qu(r,o),a=await Js(i);for(;a;){if(t.toVersion&&Pe.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,Hu(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await Js(a)}}async function qu(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function Js(e,t){let r=await Ct(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function Hu(e,t){let r=U(e);b(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Xs.spawnSync)(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function Ys(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(_s),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Us),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Ns),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(sr(`Update the AWS Parameter Store config values.
|
|
7
|
+
`)}function N(e,t=""){return new Promise(r=>{wt.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Rt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await N(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function Ee(e,t,r){return parseInt(await Rt(e,t.map(o=>o.toString()),r.toString()),10)}async function te(e){return(await Rt(e,["y","n"])).toLowerCase()==="y"}async function Ke(e){if(!await te(e))throw c("Exiting..."),new Error("User cancelled")}var At=new Y.CloudFormationClient({}),Eu=new Pt.CloudFrontClient({region:"us-east-1"}),Nm=new bs.ECSClient({}),qe=new Cs.S3Client({}),Su="medplum:environment";async function vr(){let e=[],t=(0,Y.paginateListStacks)({client:At},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)if(r.StackSummaries)for(let o of r.StackSummaries)e.push(o);return e}async function Re(e){let t=await vr();for(let r of t){let o=r.StackName,n=await br(o);if(n?.tag===e)return n}}async function br(e){let t={};if(await vs(At,e,t),await At.config.region()!=="us-east-1")try{await vs(new Y.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function vs(e,t,r){let o=new Y.DescribeStacksCommand({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===Su);if(!i)return;let a=await e.send(new Y.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===At&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)Ru(l,r)}}function Ru(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 vt(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: ${Au(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 Au(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function bt(e){let t=await Eu.send(new Pt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Ct(e){let o=(await(await(0,Os.default)("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>$s.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function Tt(e,t,r){let o=new Se.SSMClient({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await Pu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ke(`Do you want to overwrite "${i}"?`)),await Iu(o,i,a)}}async function Pu(e,t){let r=new Se.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Iu(e,t,r){let o=new Se.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function re(e,t){if(console.log(`Config not found: ${e} (${U(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=(0,xs.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function Ae(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new It.STSClient,r=new It.GetCallerIdentityCommand({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,Ts.normalizeErrorString)(t))}}async function Ns(e){let t=await Re(e);if(!t)throw await Ae(e),new Error(`Stack not found: ${e}`);vt(t)}var pe=require("@aws-sdk/client-acm"),Ot=require("@aws-sdk/client-cloudfront"),xt=require("@aws-sdk/client-sts"),ks=require("@medplum/core"),He=require("node:crypto"),Ds=require("node:fs");var vu=e=>`${e}DomainName`,Ms=e=>`${e}SslCertArn`;async function _s(){let e={apiPort:8103,region:"us-east-1"};Et(),P("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 bu(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 Ke("Do you want to continue without AWS credentials?")),P("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await N("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),P("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await N("What is the config file name?",`medplum.${e.name}.config.json`);(0,Ds.existsSync)(r)&&(c("Config file already exists."),await Ke("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),b(r,e),P("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await N("Enter your AWS region:","us-east-1"),b(r,e),P("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await N("What is your AWS account number?",t),b(r,e),P("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",o),b(r,e),P("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await N("Enter your base domain name:");b(r,e),P("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await N("Enter your support email address:");P("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await N("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,b(r,e),P("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await N("Enter your web application domain name:","app."+e.domainName),b(r,e),P("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),b(r,e),P("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await N("Enter your storage bucket name:",e.storageDomainName),b(r,e),P("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 Ee("Enter the maximum number of availability zones:",[2,3,99],2),P("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 te("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 Ee("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"),b(r,e),P("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 Ee("Enter the number of server instances:",[1,2,3,4,6,8],1),b(r,e),P("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 Ee("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),b(r,e),P("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 Ee("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),b(r,e),P("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let s=(await Ct())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${s}`),b(r,e),P("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await xu(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,b(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.')),P("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Cu(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:h}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await Tu(e,a,u,h);e[Ms(h)]=m,b(r,e)}P("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await te("Do you want to store these values in AWS Parameter Store?"))await Tt(e.region,`/medplum/${e.name}/`,l);else{let u=U(e.name,{server:!0});b(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.")}P("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(""),St()}async function bu(e){try{let t=new xt.STSClient({region:e}),r=new xt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Cu(e){let t=await Ls(e);if(e!=="us-east-1"){let r=await Ls("us-east-1");t.push(...r)}return t}async function Ls(e){try{let t=new pe.ACMClient({region:e}),r=new pe.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Tu(e,t,r,o){let n=e[vu(o)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===n);if(s)return c(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await te("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Ms(o)}" setting.`),"TODO";let i=await Ou(r,n);return c("Certificate ARN: "+i),i}async function Ou(e,t){try{let r=await Rt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new pe.ACMClient({region:e}),n=new pe.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function xu(e,t){let r=(0,He.randomUUID)(),o=(0,He.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Ot.CloudFrontClient({region:e}).send(new Ot.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,He.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,ks.normalizeErrorString)(n));return}}async function Us(){let e=await vr();for(let t of e){let r=t.StackName,o=await br(r);o&&(vt(o),console.log(""))}}var js=require("@aws-sdk/client-s3"),F=require("@medplum/core"),Fs=x(require("fast-glob")),Cr=x(require("node-fetch")),M=require("node:fs"),Bs=require("node:os"),de=require("node:path"),Ws=require("node:stream/promises");async function Ks(e,t){let r=K(e,t);if(!r)throw re(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let s;if(t.tarPath)s=t.tarPath;else{let i=t?.toVersion??"latest";s=await Nu("@medplum/app",i)}qs(s,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await ku(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await bt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function $u(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Cr.default)(r)).json()}async function Nu(e,t){let o=(await $u(e,t)).dist.tarball,n=(0,M.mkdtempSync)((0,de.join)((0,Bs.tmpdir)(),"tarball-"));try{let s=await(0,Cr.default)(o),i=Eo(n);return await(0,Ws.pipeline)(s.body,i),(0,de.join)(n,"package","dist")}catch(s){throw(0,M.rmSync)(n,{recursive:!0,force:!0}),s}}function qs(e,t){for(let r of(0,M.readdirSync)(e,{withFileTypes:!0})){let o=(0,de.join)(e,r.name);r.isDirectory()?qs(o,t):r.isFile()&&o.endsWith(".js")&&Lu(o,t)}}function Lu(e,t){let r=(0,M.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,M.writeFileSync)(e,r)}async function ku(e,t,r){let o=[["assets/**/*.css",F.ContentType.CSS,!0],["assets/**/*.css.map",F.ContentType.JSON,!0],["assets/**/*.js",F.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",F.ContentType.JSON,!0],["assets/**/*.txt",F.ContentType.TEXT,!0],["assets/**/*.ico",F.ContentType.FAVICON,!0],["img/**/*.png",F.ContentType.PNG,!0],["img/**/*.svg",F.ContentType.SVG,!0],["robots.txt",F.ContentType.TEXT,!0],["index.html",F.ContentType.HTML,!1]];for(let n of o)await Du({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Du(e){let t=Fs.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Mu((0,de.join)(e.rootDir,r),e)}async function Mu(e,t){let r=(0,M.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(de.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await qe.send(new js.PutObjectCommand(n))}var $t=require("@aws-sdk/client-s3");async function Gs(e,t){if(!K(e,t))throw re(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);await Hs("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Hs("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Hs(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=o.PhysicalResourceId,a=await _u(s);if(ju(a,s,i))throw new Error(`${e} bucket already has policy statement`);Fu(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Uu(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await bt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function _u(e){let t=await qe.send(new $t.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Uu(e,t){await qe.send(new $t.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function ju(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Fu(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}async function Vs(e,t){try{Et();let r=K(e,t);if(!r)throw re(e,t),new Error(`Config not found: ${e}`);let o=wo(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=U(e,{server:!0});if(console.log(le.yellow(`Config file ${n} not found!`)),!await te("Do you want to proceed?")){console.log(le.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}Bu(r,o),Ku(r,o),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(le.yellow("Dry run - skipping updates!")):(t.yes||await te("Do you want to store these values in AWS Parameter Store?"))&&await Tt(r.region,`/medplum/${r.name}/`,o)}finally{St()}}function Bu(e,t){Nt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Nt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Nt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Nt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Nt(e,t,r){if(Wu(e,t))throw new Error(r)}function Wu(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ku(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/`)}var Xs=require("node:child_process"),Pe=x(Ir());async function zs(e,t){let r=await R(t),o=K(e,t);if(!o)throw console.log(`Configuration file ${U(e)} not found`),re(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await qu(r,o),a=await Js(i);for(;a;){if(t.toVersion&&Pe.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,Hu(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await Js(a)}}async function qu(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function Js(e,t){let r=await Ct(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function Hu(e,t){let r=U(e);b(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Xs.spawnSync)(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function Ys(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(_s),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Us),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Ns),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(sr(`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
|
|