@medplum/cli 5.1.3 → 5.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +12 -12
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/esm/index.mjs +11 -11
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +14 -14
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Mi=Object.create;var Te=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var Ui=Object.getPrototypeOf,ji=Object.prototype.hasOwnProperty;var Fi=(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),Bi=(e,t)=>{for(var r in t)Te(e,r,{get:t[r],enumerable:!0})},Kr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of _i(t))!ji.call(e,n)&&n!==r&&Te(e,n,{get:()=>t[n],enumerable:!(o=Di(t,n))||o.enumerable});return e};var L=(e,t,r)=>(r=e!=null?Mi(Ui(e)):{},Kr(t||!e||!e.__esModule?Te(r,"default",{value:e,enumerable:!0}):r,e)),Wi=e=>Kr(Te({},"__esModule",{value:!0}),e);var P=(e,t,r)=>Fi(e,typeof t!="symbol"?t+"":t,r);var De=w((Gd,Uo)=>{"use strict";var va="2.0.0",ba=Number.MAX_SAFE_INTEGER||9007199254740991,Ca=16,Ta=250,Oa=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Uo.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Ca,MAX_SAFE_BUILD_LENGTH:Ta,MAX_SAFE_INTEGER:ba,RELEASE_TYPES:Oa,SEMVER_SPEC_VERSION:va,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var _e=w((Vd,jo)=>{"use strict";var xa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};jo.exports=xa});var we=w((G,Fo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ar,MAX_SAFE_BUILD_LENGTH:$a,MAX_LENGTH:Na}=De(),La=_e();G=Fo.exports={};var ka=G.re=[],Ma=G.safeRe=[],p=G.src=[],Da=G.safeSrc=[],d=G.t={},_a=0,cr="[a-zA-Z0-9-]",Ua=[["\\s",1],["\\d",Na],[cr,$a]],ja=e=>{for(let[t,r]of Ua)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let o=ja(t),n=_a++;La(e,n,t),d[e]=n,p[n]=t,Da[n]=o,ka[n]=new RegExp(t,r?"g":void 0),Ma[n]=new RegExp(o,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${cr}*`);E("MAINVERSION",`(${p[d.NUMERICIDENTIFIER]})\\.(${p[d.NUMERICIDENTIFIER]})\\.(${p[d.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${p[d.NUMERICIDENTIFIERLOOSE]})\\.(${p[d.NUMERICIDENTIFIERLOOSE]})\\.(${p[d.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${p[d.NONNUMERICIDENTIFIER]}|${p[d.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${p[d.NONNUMERICIDENTIFIER]}|${p[d.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${p[d.PRERELEASEIDENTIFIER]}(?:\\.${p[d.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${p[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${p[d.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${cr}+`);E("BUILD",`(?:\\+(${p[d.BUILDIDENTIFIER]}(?:\\.${p[d.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${p[d.MAINVERSION]}${p[d.PRERELEASE]}?${p[d.BUILD]}?`);E("FULL",`^${p[d.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${p[d.MAINVERSIONLOOSE]}${p[d.PRERELEASELOOSE]}?${p[d.BUILD]}?`);E("LOOSE",`^${p[d.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${p[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${p[d.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${p[d.XRANGEIDENTIFIER]})(?:\\.(${p[d.XRANGEIDENTIFIER]})(?:\\.(${p[d.XRANGEIDENTIFIER]})(?:${p[d.PRERELEASE]})?${p[d.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${p[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[d.XRANGEIDENTIFIERLOOSE]})(?:${p[d.PRERELEASELOOSE]})?${p[d.BUILD]}?)?)?`);E("XRANGE",`^${p[d.GTLT]}\\s*${p[d.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${p[d.GTLT]}\\s*${p[d.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${ar}})(?:\\.(\\d{1,${ar}}))?(?:\\.(\\d{1,${ar}}))?`);E("COERCE",`${p[d.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",p[d.COERCEPLAIN]+`(?:${p[d.PRERELEASE]})?(?:${p[d.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",p[d.COERCE],!0);E("COERCERTLFULL",p[d.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${p[d.LONETILDE]}\\s+`,!0);G.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);G.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);G.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((Jd,Bo)=>{"use strict";var Fa=Object.freeze({loose:!0}),Ba=Object.freeze({}),Wa=e=>e?typeof e!="object"?Fa:e:Ba;Bo.exports=Wa});var lr=w((Xd,qo)=>{"use strict";var Wo=/^[0-9]+$/,Ko=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Wo.test(e),o=Wo.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1},Ka=(e,t)=>Ko(t,e);qo.exports={compareIdentifiers:Ko,rcompareIdentifiers:Ka}});var T=w((zd,Go)=>{"use strict";var at=_e(),{MAX_LENGTH:Ho,MAX_SAFE_INTEGER:ct}=De(),{safeRe:lt,t:ut}=we(),qa=it(),{compareIdentifiers:ur}=lr(),pr=class e{constructor(t,r){if(r=qa(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>Ho)throw new TypeError(`version is longer than ${Ho} 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)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let 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 ur(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 ur(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]),ur(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}};Go.exports=pr});var pe=w((Yd,Jo)=>{"use strict";var Vo=T(),Ha=(e,t,r=!1)=>{if(e instanceof Vo)return e;try{return new Vo(e,t)}catch(o){if(!r)return null;throw o}};Jo.exports=Ha});var zo=w((Qd,Xo)=>{"use strict";var Ga=pe(),Va=(e,t)=>{let r=Ga(e,t);return r?r.version:null};Xo.exports=Va});var Qo=w((Zd,Yo)=>{"use strict";var Ja=pe(),Xa=(e,t)=>{let r=Ja(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Yo.exports=Xa});var tn=w((em,en)=>{"use strict";var Zo=T(),za=(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}};en.exports=za});var nn=w((tm,on)=>{"use strict";var rn=pe(),Ya=(e,t)=>{let r=rn(e,null,!0),o=rn(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"};on.exports=Ya});var an=w((rm,sn)=>{"use strict";var Qa=T(),Za=(e,t)=>new Qa(e,t).major;sn.exports=Za});var ln=w((om,cn)=>{"use strict";var ec=T(),tc=(e,t)=>new ec(e,t).minor;cn.exports=tc});var pn=w((nm,un)=>{"use strict";var rc=T(),oc=(e,t)=>new rc(e,t).patch;un.exports=oc});var mn=w((sm,dn)=>{"use strict";var nc=pe(),sc=(e,t)=>{let r=nc(e,t);return r&&r.prerelease.length?r.prerelease:null};dn.exports=sc});var D=w((im,hn)=>{"use strict";var fn=T(),ic=(e,t,r)=>new fn(e,r).compare(new fn(t,r));hn.exports=ic});var yn=w((am,gn)=>{"use strict";var ac=D(),cc=(e,t,r)=>ac(t,e,r);gn.exports=cc});var En=w((cm,wn)=>{"use strict";var lc=D(),uc=(e,t)=>lc(e,t,!0);wn.exports=uc});var pt=w((lm,Rn)=>{"use strict";var Sn=T(),pc=(e,t,r)=>{let o=new Sn(e,r),n=new Sn(t,r);return o.compare(n)||o.compareBuild(n)};Rn.exports=pc});var Pn=w((um,An)=>{"use strict";var dc=pt(),mc=(e,t)=>e.sort((r,o)=>dc(r,o,t));An.exports=mc});var vn=w((pm,In)=>{"use strict";var fc=pt(),hc=(e,t)=>e.sort((r,o)=>fc(o,r,t));In.exports=hc});var Ue=w((dm,bn)=>{"use strict";var gc=D(),yc=(e,t,r)=>gc(e,t,r)>0;bn.exports=yc});var dt=w((mm,Cn)=>{"use strict";var wc=D(),Ec=(e,t,r)=>wc(e,t,r)<0;Cn.exports=Ec});var dr=w((fm,Tn)=>{"use strict";var Sc=D(),Rc=(e,t,r)=>Sc(e,t,r)===0;Tn.exports=Rc});var mr=w((hm,On)=>{"use strict";var Ac=D(),Pc=(e,t,r)=>Ac(e,t,r)!==0;On.exports=Pc});var mt=w((gm,xn)=>{"use strict";var Ic=D(),vc=(e,t,r)=>Ic(e,t,r)>=0;xn.exports=vc});var ft=w((ym,$n)=>{"use strict";var bc=D(),Cc=(e,t,r)=>bc(e,t,r)<=0;$n.exports=Cc});var fr=w((wm,Nn)=>{"use strict";var Tc=dr(),Oc=mr(),xc=Ue(),$c=mt(),Nc=dt(),Lc=ft(),kc=(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 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);case"<=":return Lc(e,r,o);default:throw new TypeError(`Invalid operator: ${t}`)}};Nn.exports=kc});var kn=w((Em,Ln)=>{"use strict";var Mc=T(),Dc=pe(),{safeRe:ht,t:gt}=we(),_c=(e,t)=>{if(e instanceof Mc)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)};Ln.exports=_c});var Dn=w((Sm,Mn)=>{"use strict";var hr=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};Mn.exports=hr});var _=w((Rm,Fn)=>{"use strict";var Uc=/\s+/g,gr=class e{constructor(t,r){if(r=Fc(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof yr)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(Uc," "),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=>!Un(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&&Vc(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&&Hc)|(this.options.loose&&Gc))+":"+t,n=_n.get(o);if(n)return n;let s=this.options.loose,i=s?x[O.HYPHENRANGELOOSE]:x[O.HYPHENRANGE];t=t.replace(i,ol(this.options.includePrerelease)),I("hyphen replace",t),t=t.replace(x[O.COMPARATORTRIM],Wc),I("comparator trim",t),t=t.replace(x[O.TILDETRIM],Kc),I("tilde trim",t),t=t.replace(x[O.CARETTRIM],qc),I("caret trim",t);let a=t.split(" ").map(m=>Jc(m,this.options)).join(" ").split(/\s+/).map(m=>rl(m,this.options));s&&(a=a.filter(m=>(I("loose invalid filter",m,this.options),!!m.match(x[O.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(m=>new yr(m,this.options));for(let m of u){if(Un(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let h=[...l.values()];return _n.set(o,h),h}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(o=>jn(o,r)&&t.set.some(n=>jn(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 Bc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(nl(this.set[r],t,this.options))return!0;return!1}};Fn.exports=gr;var jc=Dn(),_n=new jc,Fc=it(),yr=je(),I=_e(),Bc=T(),{safeRe:x,t:O,comparatorTrimReplace:Wc,tildeTrimReplace:Kc,caretTrimReplace:qc}=we(),{FLAG_INCLUDE_PRERELEASE:Hc,FLAG_LOOSE:Gc}=De(),Un=e=>e.value==="<0.0.0-0",Vc=e=>e.value==="",jn=(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},Jc=(e,t)=>(e=e.replace(x[O.BUILD],""),I("comp",e,t),e=Yc(e,t),I("caret",e),e=Xc(e,t),I("tildes",e),e=Zc(e,t),I("xrange",e),e=tl(e,t),I("stars",e),e),$=e=>!e||e.toLowerCase()==="x"||e==="*",Xc=(e,t)=>e.trim().split(/\s+/).map(r=>zc(r,t)).join(" "),zc=(e,t)=>{let r=t.loose?x[O.TILDELOOSE]:x[O.TILDE];return e.replace(r,(o,n,s,i,a)=>{I("tilde",e,o,n,s,i,a);let l;return $(n)?l="":$(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:$(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${n}.${s}.${i}-${a} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,I("tilde return",l),l})},Yc=(e,t)=>e.trim().split(/\s+/).map(r=>Qc(r,t)).join(" "),Qc=(e,t)=>{I("caret",e,t);let r=t.loose?x[O.CARETLOOSE]:x[O.CARET],o=t.includePrerelease?"-0":"";return e.replace(r,(n,s,i,a,l)=>{I("caret",e,n,s,i,a,l);let u;return $(s)?u="":$(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:$(a)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(I("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`):(I("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`),I("caret return",u),u})},Zc=(e,t)=>(I("replaceXRanges",e,t),e.split(/\s+/).map(r=>el(r,t)).join(" ")),el=(e,t)=>{e=e.trim();let r=t.loose?x[O.XRANGELOOSE]:x[O.XRANGE];return e.replace(r,(o,n,s,i,a,l)=>{I("xRange",e,o,n,s,i,a,l);let u=$(s),h=u||$(i),m=h||$(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`),I("xRange return",o),o})},tl=(e,t)=>(I("replaceStars",e,t),e.trim().replace(x[O.STAR],"")),rl=(e,t)=>(I("replaceGTE0",e,t),e.trim().replace(x[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),ol=e=>(t,r,o,n,s,i,a,l,u,h,m,S)=>($(o)?r="":$(n)?r=`>=${o}.0.0${e?"-0":""}`:$(s)?r=`>=${o}.${n}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,$(u)?l="":$(h)?l=`<${+u+1}.0.0-0`:$(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()),nl=(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(I(e[o].semver),e[o].semver!==yr.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((Am,Gn)=>{"use strict";var Fe=Symbol("SemVer ANY"),Sr=class e{static get ANY(){return Fe}constructor(t,r){if(r=Bn(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Er("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Fe?this.value="":this.value=this.operator+this.semver.version,Er("comp",this)}parse(t){let r=this.options.loose?Wn[Kn.COMPARATORLOOSE]:Wn[Kn.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 qn(o[2],this.options.loose):this.semver=Fe}toString(){return this.value}test(t){if(Er("Comparator.test",t,this.options.loose),this.semver===Fe||t===Fe)return!0;if(typeof t=="string")try{t=new qn(t,this.options)}catch{return!1}return wr(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Hn(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Hn(this.value,r).test(t.semver):(r=Bn(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||wr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||wr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Gn.exports=Sr;var Bn=it(),{safeRe:Wn,t:Kn}=we(),wr=fr(),Er=_e(),qn=T(),Hn=_()});var Be=w((Pm,Vn)=>{"use strict";var sl=_(),il=(e,t,r)=>{try{t=new sl(t,r)}catch{return!1}return t.test(e)};Vn.exports=il});var Xn=w((Im,Jn)=>{"use strict";var al=_(),cl=(e,t)=>new al(e,t).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Jn.exports=cl});var Yn=w((vm,zn)=>{"use strict";var ll=T(),ul=_(),pl=(e,t,r)=>{let o=null,n=null,s=null;try{s=new ul(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new ll(o,r))}),o};zn.exports=pl});var Zn=w((bm,Qn)=>{"use strict";var dl=T(),ml=_(),fl=(e,t,r)=>{let o=null,n=null,s=null;try{s=new ml(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new dl(o,r))}),o};Qn.exports=fl});var rs=w((Cm,ts)=>{"use strict";var Rr=T(),hl=_(),es=Ue(),gl=(e,t)=>{e=new hl(e,t);let r=new Rr("0.0.0");if(e.test(r)||(r=new Rr("0.0.0-0"),e.test(r)))return r;r=null;for(let o=0;o<e.set.length;++o){let n=e.set[o],s=null;n.forEach(i=>{let a=new Rr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||es(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||es(r,s))&&(r=s)}return r&&e.test(r)?r:null};ts.exports=gl});var ns=w((Tm,os)=>{"use strict";var yl=_(),wl=(e,t)=>{try{return new yl(e,t).range||"*"}catch{return null}};os.exports=wl});var yt=w((Om,cs)=>{"use strict";var El=T(),as=je(),{ANY:Sl}=as,Rl=_(),Al=Be(),ss=Ue(),is=dt(),Pl=ft(),Il=mt(),vl=(e,t,r,o)=>{e=new El(e,o),t=new Rl(t,o);let n,s,i,a,l;switch(r){case">":n=ss,s=Pl,i=is,a=">",l=">=";break;case"<":n=is,s=Il,i=ss,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Al(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===Sl&&(f=new as(">=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};cs.exports=vl});var us=w((xm,ls)=>{"use strict";var bl=yt(),Cl=(e,t,r)=>bl(e,t,">",r);ls.exports=Cl});var ds=w(($m,ps)=>{"use strict";var Tl=yt(),Ol=(e,t,r)=>Tl(e,t,"<",r);ps.exports=Ol});var hs=w((Nm,fs)=>{"use strict";var ms=_(),xl=(e,t,r)=>(e=new ms(e,r),t=new ms(t,r),e.intersects(t,r));fs.exports=xl});var ys=w((Lm,gs)=>{"use strict";var $l=Be(),Nl=D();gs.exports=(e,t,r)=>{let o=[],n=null,s=null,i=e.sort((h,m)=>Nl(h,m,r));for(let h of i)$l(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 Ps=w((km,As)=>{"use strict";var ws=_(),Pr=je(),{ANY:Ar}=Pr,We=Be(),Ir=D(),Ll=(e,t,r={})=>{if(e===t)return!0;e=new ws(e,r),t=new ws(t,r);let o=!1;e:for(let n of e.set){for(let s of t.set){let i=Ml(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},kl=[new Pr(">=0.0.0-0")],Es=[new Pr(">=0.0.0")],Ml=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Ar){if(t.length===1&&t[0].semver===Ar)return!0;r.includePrerelease?e=kl:e=Es}if(t.length===1&&t[0].semver===Ar){if(r.includePrerelease)return!0;t=Es}let o=new Set,n,s;for(let f of e)f.operator===">"||f.operator===">="?n=Ss(n,f,r):f.operator==="<"||f.operator==="<="?s=Rs(s,f,r):o.add(f.semver);if(o.size>1)return null;let i;if(n&&s){if(i=Ir(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 b of t)if(!We(f,String(b),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=Ss(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=Rs(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)},Ss=(e,t,r)=>{if(!e)return t;let o=Ir(e.semver,t.semver,r);return o>0?e:o<0||t.operator===">"&&e.operator===">="?t:e},Rs=(e,t,r)=>{if(!e)return t;let o=Ir(e.semver,t.semver,r);return o<0?e:o>0||t.operator==="<"&&e.operator==="<="?t:e};As.exports=Ll});var br=w((Mm,bs)=>{"use strict";var vr=we(),Is=De(),Dl=T(),vs=lr(),_l=pe(),Ul=zo(),jl=Qo(),Fl=tn(),Bl=nn(),Wl=an(),Kl=ln(),ql=pn(),Hl=mn(),Gl=D(),Vl=yn(),Jl=En(),Xl=pt(),zl=Pn(),Yl=vn(),Ql=Ue(),Zl=dt(),eu=dr(),tu=mr(),ru=mt(),ou=ft(),nu=fr(),su=kn(),iu=je(),au=_(),cu=Be(),lu=Xn(),uu=Yn(),pu=Zn(),du=rs(),mu=ns(),fu=yt(),hu=us(),gu=ds(),yu=hs(),wu=ys(),Eu=Ps();bs.exports={parse:_l,valid:Ul,clean:jl,inc:Fl,diff:Bl,major:Wl,minor:Kl,patch:ql,prerelease:Hl,compare:Gl,rcompare:Vl,compareLoose:Jl,compareBuild:Xl,sort:zl,rsort:Yl,gt:Ql,lt:Zl,eq:eu,neq:tu,gte:ru,lte:ou,cmp:nu,coerce:su,Comparator:iu,Range:au,satisfies:cu,toComparators:lu,maxSatisfying:uu,minSatisfying:pu,minVersion:du,validRange:mu,outside:fu,gtr:hu,ltr:gu,intersects:yu,simplifyRange:wu,subset:Eu,SemVer:Dl,re:vr.re,src:vr.src,tokens:vr.t,SEMVER_SPEC_VERSION:Is.SEMVER_SPEC_VERSION,RELEASE_TYPES:Is.RELEASE_TYPES,compareIdentifiers:vs.compareIdentifiers,rcompareIdentifiers:vs.rcompareIdentifiers}});var up={};Bi(up,{handleError:()=>Ni,main:()=>$i,run:()=>Li});module.exports=Wi(up);var Ce=require("@medplum/core"),Xe=require("commander"),xi=L(require("dotenv"),1);var Z=require("@medplum/core"),st=require("commander");var Gr=require("@medplum/core");var qr=require("@medplum/core"),J=require("node:fs"),Hr=require("node:os"),Ft=require("node:path");var W=class extends qr.ClientStorage{constructor(r){super();P(this,"dirName");P(this,"fileName");this.dirName=(0,Ft.resolve)((0,Hr.homedir)(),".medplum"),this.fileName=(0,Ft.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if((0,J.existsSync)(this.fileName))return JSON.parse((0,J.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,J.existsSync)(this.dirName)||(0,J.mkdirSync)(this.dirName),(0,J.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",o=new W(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}=Ki(e,o),S=e.fetch??fetch,f=new Gr.MedplumClient({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:qi,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 Ki(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 qi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var q=require("@medplum/core"),yo=require("commander");var Jr=require("node:buffer");var ie=new TextEncoder,Bt=new TextDecoder,gp=2**32;function Vr(...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=>Jr.Buffer.from(e).toString("base64url");var ae=class extends Error{constructor(r,o){super(r,o);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};P(ae,"code","ERR_JOSE_GENERIC");var M=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}};P(M,"code","ERR_JOSE_NOT_SUPPORTED");var X=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}};P(X,"code","ERR_JWS_INVALID");var Oe=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}};P(Oe,"code","ERR_JWT_INVALID");var Xr,zr,Wt=class extends(zr=ae,Xr=Symbol.asyncIterator,zr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);P(this,Xr);P(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};P(Wt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Yr=L(require("node:util"),1),Ye=e=>Yr.types.isKeyObject(e);var Qr=L(require("node:crypto"),1),Zr=L(require("node:util"),1),Gi=Qr.webcrypto,eo=Gi,fe=e=>Zr.types.isCryptoKey(e);function K(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 Kt(e){return parseInt(e.name.slice(4),10)}function Vi(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Ji(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 to(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!xe(e.algorithm,"HMAC"))throw K("HMAC");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!xe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw K("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!xe(e.algorithm,"RSA-PSS"))throw K("RSA-PSS");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw K("Ed25519 or Ed448");break}case"Ed25519":{if(!xe(e.algorithm,"Ed25519"))throw K("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!xe(e.algorithm,"ECDSA"))throw K("ECDSA");let o=Vi(t);if(e.algorithm.namedCurve!==o)throw K(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Ji(e,r)}function ro(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)=>ro("Key must be ",e,...t);function qt(e,t,...r){return ro(`Key for the ${e} algorithm must be `,t,...r)}var Ht=e=>Ye(e)||fe(e),z=["KeyObject"];(globalThis.CryptoKey||eo?.CryptoKey)&&z.push("CryptoKey");var Xi=(...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},oo=Xi;function zi(e){return typeof e=="object"&&e!==null}function Ne(e){if(!zi(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 co=require("node:crypto");function te(e){return Ne(e)&&typeof e.kty=="string"}function no(e){return e.kty!=="oct"&&typeof e.d=="string"}function so(e){return e.kty!=="oct"&&typeof e.d>"u"}function io(e){return te(e)&&e.kty==="oct"&&typeof e.k=="string"}var Yi=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new M("Unsupported key curve for this operation")}},Qi=(e,t)=>{let r;if(fe(e))r=co.KeyObject.from(e);else if(Ye(e))r=e;else{if(te(e))return e.crv;throw new TypeError($e(e,...z))}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:Yi(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},lo=Qi;var uo=require("node:crypto"),Gt=(e,t)=>{let r;try{e instanceof uo.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 he=e=>e?.[Symbol.toStringTag],Vt=(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},Zi=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&te(t)){if(io(t)&&Vt(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(!Ht(t))throw new TypeError(qt(e,t,...z,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${he(t)} instances for symmetric algorithms must be of type "secret"`)}},ea=(e,t,r,o)=>{if(o&&te(t))switch(r){case"sign":if(no(t)&&Vt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(so(t)&&Vt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ht(t))throw new TypeError(qt(e,t,...z,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${he(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function po(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Zi(t,r,o,e):ea(t,r,o,e)}var Fp=po.bind(void 0,!1),mo=po.bind(void 0,!0);function ta(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 M(`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 fo=ta;function Jt(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Le=require("node:crypto");var ra=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Xt(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");Gt(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");Gt(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=lo(t),a=ra.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 M(`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=L(require("node:crypto"),1),ho=require("node:util");function zt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ge=require("node:crypto");function Yt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError($e(t,...z));return(0,ge.createSecretKey)(t)}if(t instanceof ge.KeyObject)return t;if(fe(t))return to(t,e,r),ge.KeyObject.from(t);if(te(t))return e.startsWith("HS")?(0,ge.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError($e(t,...z,"Uint8Array","JSON Web Key"))}var oa=(0,ho.promisify)(Qe.sign),na=async(e,t,r)=>{let o=Yt(e,t,"sign");if(e.startsWith("HS")){let n=Qe.createHmac(zt(e),o);return n.update(r),n.digest()}return oa(Jt(e),r,Xt(e,o))},go=na;var re=e=>Math.floor(e.getTime()/1e3);var sa=/^(\+|\-)? ?(\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=sa.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){P(this,"_payload");P(this,"_protectedHeader");P(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 X("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!oo(this._protectedHeader,this._unprotectedHeader))throw new X("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=fo(X,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new X('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new X('JWS "alg" (Algorithm) Header Parameter missing or invalid');mo(i,t,"sign");let a=this._payload;s&&(a=ie.encode(ze(a)));let l;this._protectedHeader?l=ie.encode(ze(JSON.stringify(this._protectedHeader))):l=ie.encode("");let u=Vr(l,ie.encode("."),a),h=await go(i,t,u),m={signature:ze(h),payload:""};return s&&(m.payload=Bt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Bt.decode(l)),m}};var tt=class{constructor(t){P(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 ce(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var rt=class{constructor(t={}){P(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:ce("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ce("setNotBefore",re(t))}:this._payload={...this._payload,nbf:re(new Date)+Ze(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ce("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ce("setExpirationTime",re(t))}:this._payload={...this._payload,exp:re(new Date)+Ze(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:re(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ce("setIssuedAt",re(t))}:typeof t=="string"?this._payload={...this._payload,iat:ce("setIssuedAt",re(new Date)+Ze(t))}:this._payload={...this._payload,iat:ce("setIssuedAt",t)},this}};var ke=class extends rt{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new tt(ie.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 ye=require("node:crypto"),oe=require("node:fs"),Y=require("node:path"),wo=require("node:util/types"),Eo=require("tar");function Q(e){console.log(JSON.stringify(e,null,2))}async function Qt(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,Y.basename)(o),contentType:ca(o)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Zt(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,Y.basename)(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function er(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 Qt(e,h,u),await Zt(e,h,u),console.log(`Success! Bot created: ${u.id}`),i&&ia(h)}function So(e){let t=new RegExp("^"+aa(e).replaceAll(String.raw`\*`,".*")+"$"),r=H()?.bots?.filter(o=>t.test(o.name));return r||[]}function j(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function C(e,t){(0,oe.writeFileSync)((0,Y.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function H(e,t){let r=j(e,t),o=ot(r);if(o)return JSON.parse(o)}function Ro(e){let t=ot(j(e,{server:!0}));if(t)return JSON.parse(t)}function ot(e){let t=(0,Y.resolve)(e);return(0,oe.existsSync)(t)?(0,oe.readFileSync)(t,"utf8"):""}function ia(e){let t=H()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,oe.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function aa(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Ao(e){let o=0,n=0;return(0,Eo.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 tr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ca(e){let t=(0,Y.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?q.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?q.ContentType.TYPESCRIPT:q.ContentType.TEXT}function nt(e,t){let r=new W(e),o={name:e,...t};return r.setObject("options",o),o}function Po(e){return new W(e).getObject("options")}async function Io(e,t){let r={typ:"JWT",alg:q.OAuthSigningAlgorithm.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,q.encodeBase64)(JSON.stringify(r)),i=(0,q.encodeBase64)(JSON.stringify(n)),a=`${s}.${i}`,l=(0,ye.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function vo(e,t){let r=(0,ye.createPrivateKey)((0,oe.readFileSync)((0,Y.resolve)(t.privateKeyPath))),o=await new ke({}).setProtectedHeader({typ:"JWT",alg:q.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ye.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 yo.Command{action(t){let r=la(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 la(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,wo.isPromise)(s)&&await s}finally{e.resetOptionDefaults()}}}var bo=new g("status").aliases(["info","list","ls"]),Co=new g("ping"),To=new g("push"),Oo=new g("reload-config"),xo=new g("upgrade"),le=new g("agent");y(le,bo);y(le,Co);y(le,To);y(le,Oo);y(le,xo);bo.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 rr({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=da(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"}}})});Co.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 $o(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}`,Z.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});To.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",Z.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 $o(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)});Oo.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 rr({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});xo.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 rr({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function rr({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n}){let s=fa(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[b,V]of Object.entries(o))l.append(b,V.toString());let u;try{let b=i.fhirUrl("Agent",e);b.search=l.toString(),u=await i.get(b,{cache:"reload"})}catch(b){throw new Error(`Operation '${e}' failed`,{cause:b})}if(r.output==="json"){console.info(JSON.stringify(u,null,2));return}let h=[],m=[];switch(u.resourceType){case"Bundle":{let b=ua(u);for(let V of b)V.result.resourceType==="Parameters"||(0,Z.isOk)(V.result)?h.push(V):m.push(V);break}case"Parameters":case"OperationOutcome":{let b=await i.searchOne("Agent",l,{cache:"reload"});if(!b)throw new Error("Agent not found");u.resourceType==="Parameters"?h.push({agent:b,result:u}):m.push({agent:b,result:u});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(u)}`)}let S=[];for(let b of h){let V=n(b);S.push(V)}let f=[];for(let b of m){let jt=b.result.issue?.[0],ki={id:b.agent.id,name:b.agent.name,severity:jt.severity,code:jt.code,details:jt.details?.text??"No details to show"};f.push(ki)}console.info(`
|
|
2
|
+
"use strict";var Mi=Object.create;var Te=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var Ui=Object.getPrototypeOf,ji=Object.prototype.hasOwnProperty;var Fi=(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),Bi=(e,t)=>{for(var r in t)Te(e,r,{get:t[r],enumerable:!0})},Kr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of _i(t))!ji.call(e,n)&&n!==r&&Te(e,n,{get:()=>t[n],enumerable:!(o=Di(t,n))||o.enumerable});return e};var k=(e,t,r)=>(r=e!=null?Mi(Ui(e)):{},Kr(t||!e||!e.__esModule?Te(r,"default",{value:e,enumerable:!0}):r,e)),Wi=e=>Kr(Te({},"__esModule",{value:!0}),e);var P=(e,t,r)=>Fi(e,typeof t!="symbol"?t+"":t,r);var De=w((Vd,Uo)=>{"use strict";var ba="2.0.0",Ca=Number.MAX_SAFE_INTEGER||9007199254740991,Ta=16,Oa=250,xa=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Uo.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Ta,MAX_SAFE_BUILD_LENGTH:Oa,MAX_SAFE_INTEGER:Ca,RELEASE_TYPES:xa,SEMVER_SPEC_VERSION:ba,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var _e=w((Jd,jo)=>{"use strict";var $a=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};jo.exports=$a});var we=w((G,Fo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ar,MAX_SAFE_BUILD_LENGTH:Na,MAX_LENGTH:ka}=De(),La=_e();G=Fo.exports={};var Ma=G.re=[],Da=G.safeRe=[],p=G.src=[],_a=G.safeSrc=[],d=G.t={},Ua=0,cr="[a-zA-Z0-9-]",ja=[["\\s",1],["\\d",ka],[cr,Na]],Fa=e=>{for(let[t,r]of ja)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let o=Fa(t),n=Ua++;La(e,n,t),d[e]=n,p[n]=t,_a[n]=o,Ma[n]=new RegExp(t,r?"g":void 0),Da[n]=new RegExp(o,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${cr}*`);E("MAINVERSION",`(${p[d.NUMERICIDENTIFIER]})\\.(${p[d.NUMERICIDENTIFIER]})\\.(${p[d.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${p[d.NUMERICIDENTIFIERLOOSE]})\\.(${p[d.NUMERICIDENTIFIERLOOSE]})\\.(${p[d.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${p[d.NONNUMERICIDENTIFIER]}|${p[d.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${p[d.NONNUMERICIDENTIFIER]}|${p[d.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${p[d.PRERELEASEIDENTIFIER]}(?:\\.${p[d.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${p[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${p[d.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${cr}+`);E("BUILD",`(?:\\+(${p[d.BUILDIDENTIFIER]}(?:\\.${p[d.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${p[d.MAINVERSION]}${p[d.PRERELEASE]}?${p[d.BUILD]}?`);E("FULL",`^${p[d.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${p[d.MAINVERSIONLOOSE]}${p[d.PRERELEASELOOSE]}?${p[d.BUILD]}?`);E("LOOSE",`^${p[d.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${p[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${p[d.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${p[d.XRANGEIDENTIFIER]})(?:\\.(${p[d.XRANGEIDENTIFIER]})(?:\\.(${p[d.XRANGEIDENTIFIER]})(?:${p[d.PRERELEASE]})?${p[d.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${p[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[d.XRANGEIDENTIFIERLOOSE]})(?:${p[d.PRERELEASELOOSE]})?${p[d.BUILD]}?)?)?`);E("XRANGE",`^${p[d.GTLT]}\\s*${p[d.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${p[d.GTLT]}\\s*${p[d.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${ar}})(?:\\.(\\d{1,${ar}}))?(?:\\.(\\d{1,${ar}}))?`);E("COERCE",`${p[d.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",p[d.COERCEPLAIN]+`(?:${p[d.PRERELEASE]})?(?:${p[d.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",p[d.COERCE],!0);E("COERCERTLFULL",p[d.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${p[d.LONETILDE]}\\s+`,!0);G.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);G.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);G.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((Xd,Bo)=>{"use strict";var Ba=Object.freeze({loose:!0}),Wa=Object.freeze({}),Ka=e=>e?typeof e!="object"?Ba:e:Wa;Bo.exports=Ka});var lr=w((zd,qo)=>{"use strict";var Wo=/^[0-9]+$/,Ko=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Wo.test(e),o=Wo.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1},qa=(e,t)=>Ko(t,e);qo.exports={compareIdentifiers:Ko,rcompareIdentifiers:qa}});var T=w((Yd,Go)=>{"use strict";var at=_e(),{MAX_LENGTH:Ho,MAX_SAFE_INTEGER:ct}=De(),{safeRe:lt,t:ut}=we(),Ha=it(),{compareIdentifiers:ur}=lr(),pr=class e{constructor(t,r){if(r=Ha(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>Ho)throw new TypeError(`version is longer than ${Ho} 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)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let 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 ur(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 ur(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]),ur(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}};Go.exports=pr});var pe=w((Qd,Jo)=>{"use strict";var Vo=T(),Ga=(e,t,r=!1)=>{if(e instanceof Vo)return e;try{return new Vo(e,t)}catch(o){if(!r)return null;throw o}};Jo.exports=Ga});var zo=w((Zd,Xo)=>{"use strict";var Va=pe(),Ja=(e,t)=>{let r=Va(e,t);return r?r.version:null};Xo.exports=Ja});var Qo=w((em,Yo)=>{"use strict";var Xa=pe(),za=(e,t)=>{let r=Xa(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Yo.exports=za});var tn=w((tm,en)=>{"use strict";var Zo=T(),Ya=(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}};en.exports=Ya});var nn=w((rm,on)=>{"use strict";var rn=pe(),Qa=(e,t)=>{let r=rn(e,null,!0),o=rn(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"};on.exports=Qa});var an=w((om,sn)=>{"use strict";var Za=T(),ec=(e,t)=>new Za(e,t).major;sn.exports=ec});var ln=w((nm,cn)=>{"use strict";var tc=T(),rc=(e,t)=>new tc(e,t).minor;cn.exports=rc});var pn=w((sm,un)=>{"use strict";var oc=T(),nc=(e,t)=>new oc(e,t).patch;un.exports=nc});var mn=w((im,dn)=>{"use strict";var sc=pe(),ic=(e,t)=>{let r=sc(e,t);return r&&r.prerelease.length?r.prerelease:null};dn.exports=ic});var D=w((am,hn)=>{"use strict";var fn=T(),ac=(e,t,r)=>new fn(e,r).compare(new fn(t,r));hn.exports=ac});var yn=w((cm,gn)=>{"use strict";var cc=D(),lc=(e,t,r)=>cc(t,e,r);gn.exports=lc});var En=w((lm,wn)=>{"use strict";var uc=D(),pc=(e,t)=>uc(e,t,!0);wn.exports=pc});var pt=w((um,Rn)=>{"use strict";var Sn=T(),dc=(e,t,r)=>{let o=new Sn(e,r),n=new Sn(t,r);return o.compare(n)||o.compareBuild(n)};Rn.exports=dc});var Pn=w((pm,An)=>{"use strict";var mc=pt(),fc=(e,t)=>e.sort((r,o)=>mc(r,o,t));An.exports=fc});var In=w((dm,vn)=>{"use strict";var hc=pt(),gc=(e,t)=>e.sort((r,o)=>hc(o,r,t));vn.exports=gc});var Ue=w((mm,bn)=>{"use strict";var yc=D(),wc=(e,t,r)=>yc(e,t,r)>0;bn.exports=wc});var dt=w((fm,Cn)=>{"use strict";var Ec=D(),Sc=(e,t,r)=>Ec(e,t,r)<0;Cn.exports=Sc});var dr=w((hm,Tn)=>{"use strict";var Rc=D(),Ac=(e,t,r)=>Rc(e,t,r)===0;Tn.exports=Ac});var mr=w((gm,On)=>{"use strict";var Pc=D(),vc=(e,t,r)=>Pc(e,t,r)!==0;On.exports=vc});var mt=w((ym,xn)=>{"use strict";var Ic=D(),bc=(e,t,r)=>Ic(e,t,r)>=0;xn.exports=bc});var ft=w((wm,$n)=>{"use strict";var Cc=D(),Tc=(e,t,r)=>Cc(e,t,r)<=0;$n.exports=Tc});var fr=w((Em,Nn)=>{"use strict";var Oc=dr(),xc=mr(),$c=Ue(),Nc=mt(),kc=dt(),Lc=ft(),Mc=(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 Oc(e,r,o);case"!=":return xc(e,r,o);case">":return $c(e,r,o);case">=":return Nc(e,r,o);case"<":return kc(e,r,o);case"<=":return Lc(e,r,o);default:throw new TypeError(`Invalid operator: ${t}`)}};Nn.exports=Mc});var Ln=w((Sm,kn)=>{"use strict";var Dc=T(),_c=pe(),{safeRe:ht,t:gt}=we(),Uc=(e,t)=>{if(e instanceof Dc)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?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 _c(`${o}.${n}.${s}${i}${a}`,t)};kn.exports=Uc});var Dn=w((Rm,Mn)=>{"use strict";var hr=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};Mn.exports=hr});var _=w((Am,Fn)=>{"use strict";var jc=/\s+/g,gr=class e{constructor(t,r){if(r=Bc(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof yr)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(jc," "),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=>!Un(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&&Jc(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&&Gc)|(this.options.loose&&Vc))+":"+t,n=_n.get(o);if(n)return n;let s=this.options.loose,i=s?x[O.HYPHENRANGELOOSE]:x[O.HYPHENRANGE];t=t.replace(i,nl(this.options.includePrerelease)),v("hyphen replace",t),t=t.replace(x[O.COMPARATORTRIM],Kc),v("comparator trim",t),t=t.replace(x[O.TILDETRIM],qc),v("tilde trim",t),t=t.replace(x[O.CARETTRIM],Hc),v("caret trim",t);let a=t.split(" ").map(m=>Xc(m,this.options)).join(" ").split(/\s+/).map(m=>ol(m,this.options));s&&(a=a.filter(m=>(v("loose invalid filter",m,this.options),!!m.match(x[O.COMPARATORLOOSE])))),v("range list",a);let l=new Map,u=a.map(m=>new yr(m,this.options));for(let m of u){if(Un(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let h=[...l.values()];return _n.set(o,h),h}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(o=>jn(o,r)&&t.set.some(n=>jn(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 Wc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(sl(this.set[r],t,this.options))return!0;return!1}};Fn.exports=gr;var Fc=Dn(),_n=new Fc,Bc=it(),yr=je(),v=_e(),Wc=T(),{safeRe:x,t:O,comparatorTrimReplace:Kc,tildeTrimReplace:qc,caretTrimReplace:Hc}=we(),{FLAG_INCLUDE_PRERELEASE:Gc,FLAG_LOOSE:Vc}=De(),Un=e=>e.value==="<0.0.0-0",Jc=e=>e.value==="",jn=(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},Xc=(e,t)=>(e=e.replace(x[O.BUILD],""),v("comp",e,t),e=Qc(e,t),v("caret",e),e=zc(e,t),v("tildes",e),e=el(e,t),v("xrange",e),e=rl(e,t),v("stars",e),e),$=e=>!e||e.toLowerCase()==="x"||e==="*",zc=(e,t)=>e.trim().split(/\s+/).map(r=>Yc(r,t)).join(" "),Yc=(e,t)=>{let r=t.loose?x[O.TILDELOOSE]:x[O.TILDE];return e.replace(r,(o,n,s,i,a)=>{v("tilde",e,o,n,s,i,a);let l;return $(n)?l="":$(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:$(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(v("replaceTilde pr",a),l=`>=${n}.${s}.${i}-${a} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,v("tilde return",l),l})},Qc=(e,t)=>e.trim().split(/\s+/).map(r=>Zc(r,t)).join(" "),Zc=(e,t)=>{v("caret",e,t);let r=t.loose?x[O.CARETLOOSE]:x[O.CARET],o=t.includePrerelease?"-0":"";return e.replace(r,(n,s,i,a,l)=>{v("caret",e,n,s,i,a,l);let u;return $(s)?u="":$(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:$(a)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(v("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`):(v("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`),v("caret return",u),u})},el=(e,t)=>(v("replaceXRanges",e,t),e.split(/\s+/).map(r=>tl(r,t)).join(" ")),tl=(e,t)=>{e=e.trim();let r=t.loose?x[O.XRANGELOOSE]:x[O.XRANGE];return e.replace(r,(o,n,s,i,a,l)=>{v("xRange",e,o,n,s,i,a,l);let u=$(s),h=u||$(i),m=h||$(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`),v("xRange return",o),o})},rl=(e,t)=>(v("replaceStars",e,t),e.trim().replace(x[O.STAR],"")),ol=(e,t)=>(v("replaceGTE0",e,t),e.trim().replace(x[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),nl=e=>(t,r,o,n,s,i,a,l,u,h,m,S)=>($(o)?r="":$(n)?r=`>=${o}.0.0${e?"-0":""}`:$(s)?r=`>=${o}.${n}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,$(u)?l="":$(h)?l=`<${+u+1}.0.0-0`:$(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()),sl=(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(v(e[o].semver),e[o].semver!==yr.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((Pm,Gn)=>{"use strict";var Fe=Symbol("SemVer ANY"),Sr=class e{static get ANY(){return Fe}constructor(t,r){if(r=Bn(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Er("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Fe?this.value="":this.value=this.operator+this.semver.version,Er("comp",this)}parse(t){let r=this.options.loose?Wn[Kn.COMPARATORLOOSE]:Wn[Kn.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 qn(o[2],this.options.loose):this.semver=Fe}toString(){return this.value}test(t){if(Er("Comparator.test",t,this.options.loose),this.semver===Fe||t===Fe)return!0;if(typeof t=="string")try{t=new qn(t,this.options)}catch{return!1}return wr(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Hn(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Hn(this.value,r).test(t.semver):(r=Bn(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||wr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||wr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Gn.exports=Sr;var Bn=it(),{safeRe:Wn,t:Kn}=we(),wr=fr(),Er=_e(),qn=T(),Hn=_()});var Be=w((vm,Vn)=>{"use strict";var il=_(),al=(e,t,r)=>{try{t=new il(t,r)}catch{return!1}return t.test(e)};Vn.exports=al});var Xn=w((Im,Jn)=>{"use strict";var cl=_(),ll=(e,t)=>new cl(e,t).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Jn.exports=ll});var Yn=w((bm,zn)=>{"use strict";var ul=T(),pl=_(),dl=(e,t,r)=>{let o=null,n=null,s=null;try{s=new pl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new ul(o,r))}),o};zn.exports=dl});var Zn=w((Cm,Qn)=>{"use strict";var ml=T(),fl=_(),hl=(e,t,r)=>{let o=null,n=null,s=null;try{s=new fl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new ml(o,r))}),o};Qn.exports=hl});var rs=w((Tm,ts)=>{"use strict";var Rr=T(),gl=_(),es=Ue(),yl=(e,t)=>{e=new gl(e,t);let r=new Rr("0.0.0");if(e.test(r)||(r=new Rr("0.0.0-0"),e.test(r)))return r;r=null;for(let o=0;o<e.set.length;++o){let n=e.set[o],s=null;n.forEach(i=>{let a=new Rr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||es(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||es(r,s))&&(r=s)}return r&&e.test(r)?r:null};ts.exports=yl});var ns=w((Om,os)=>{"use strict";var wl=_(),El=(e,t)=>{try{return new wl(e,t).range||"*"}catch{return null}};os.exports=El});var yt=w((xm,cs)=>{"use strict";var Sl=T(),as=je(),{ANY:Rl}=as,Al=_(),Pl=Be(),ss=Ue(),is=dt(),vl=ft(),Il=mt(),bl=(e,t,r,o)=>{e=new Sl(e,o),t=new Al(t,o);let n,s,i,a,l;switch(r){case">":n=ss,s=vl,i=is,a=">",l=">=";break;case"<":n=is,s=Il,i=ss,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Pl(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===Rl&&(f=new as(">=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};cs.exports=bl});var us=w(($m,ls)=>{"use strict";var Cl=yt(),Tl=(e,t,r)=>Cl(e,t,">",r);ls.exports=Tl});var ds=w((Nm,ps)=>{"use strict";var Ol=yt(),xl=(e,t,r)=>Ol(e,t,"<",r);ps.exports=xl});var hs=w((km,fs)=>{"use strict";var ms=_(),$l=(e,t,r)=>(e=new ms(e,r),t=new ms(t,r),e.intersects(t,r));fs.exports=$l});var ys=w((Lm,gs)=>{"use strict";var Nl=Be(),kl=D();gs.exports=(e,t,r)=>{let o=[],n=null,s=null,i=e.sort((h,m)=>kl(h,m,r));for(let h of i)Nl(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 Ps=w((Mm,As)=>{"use strict";var ws=_(),Pr=je(),{ANY:Ar}=Pr,We=Be(),vr=D(),Ll=(e,t,r={})=>{if(e===t)return!0;e=new ws(e,r),t=new ws(t,r);let o=!1;e:for(let n of e.set){for(let s of t.set){let i=Dl(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},Ml=[new Pr(">=0.0.0-0")],Es=[new Pr(">=0.0.0")],Dl=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Ar){if(t.length===1&&t[0].semver===Ar)return!0;r.includePrerelease?e=Ml:e=Es}if(t.length===1&&t[0].semver===Ar){if(r.includePrerelease)return!0;t=Es}let o=new Set,n,s;for(let f of e)f.operator===">"||f.operator===">="?n=Ss(n,f,r):f.operator==="<"||f.operator==="<="?s=Rs(s,f,r):o.add(f.semver);if(o.size>1)return null;let i;if(n&&s){if(i=vr(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 b of t)if(!We(f,String(b),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=Ss(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=Rs(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)},Ss=(e,t,r)=>{if(!e)return t;let o=vr(e.semver,t.semver,r);return o>0?e:o<0||t.operator===">"&&e.operator===">="?t:e},Rs=(e,t,r)=>{if(!e)return t;let o=vr(e.semver,t.semver,r);return o<0?e:o>0||t.operator==="<"&&e.operator==="<="?t:e};As.exports=Ll});var br=w((Dm,bs)=>{"use strict";var Ir=we(),vs=De(),_l=T(),Is=lr(),Ul=pe(),jl=zo(),Fl=Qo(),Bl=tn(),Wl=nn(),Kl=an(),ql=ln(),Hl=pn(),Gl=mn(),Vl=D(),Jl=yn(),Xl=En(),zl=pt(),Yl=Pn(),Ql=In(),Zl=Ue(),eu=dt(),tu=dr(),ru=mr(),ou=mt(),nu=ft(),su=fr(),iu=Ln(),au=je(),cu=_(),lu=Be(),uu=Xn(),pu=Yn(),du=Zn(),mu=rs(),fu=ns(),hu=yt(),gu=us(),yu=ds(),wu=hs(),Eu=ys(),Su=Ps();bs.exports={parse:Ul,valid:jl,clean:Fl,inc:Bl,diff:Wl,major:Kl,minor:ql,patch:Hl,prerelease:Gl,compare:Vl,rcompare:Jl,compareLoose:Xl,compareBuild:zl,sort:Yl,rsort:Ql,gt:Zl,lt:eu,eq:tu,neq:ru,gte:ou,lte:nu,cmp:su,coerce:iu,Comparator:au,Range:cu,satisfies:lu,toComparators:uu,maxSatisfying:pu,minSatisfying:du,minVersion:mu,validRange:fu,outside:hu,gtr:gu,ltr:yu,intersects:wu,simplifyRange:Eu,subset:Su,SemVer:_l,re:Ir.re,src:Ir.src,tokens:Ir.t,SEMVER_SPEC_VERSION:vs.SEMVER_SPEC_VERSION,RELEASE_TYPES:vs.RELEASE_TYPES,compareIdentifiers:Is.compareIdentifiers,rcompareIdentifiers:Is.rcompareIdentifiers}});var pp={};Bi(pp,{handleError:()=>Ni,main:()=>$i,run:()=>ki});module.exports=Wi(pp);var Ce=require("@medplum/core"),Xe=require("commander"),xi=k(require("dotenv"),1);var Z=require("@medplum/core"),st=require("commander");var Gr=require("@medplum/core");var qr=require("@medplum/core"),J=require("node:fs"),Hr=require("node:os"),Ft=require("node:path");var W=class extends qr.ClientStorage{constructor(r){super();P(this,"dirName");P(this,"fileName");this.dirName=(0,Ft.resolve)((0,Hr.homedir)(),".medplum"),this.fileName=(0,Ft.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if((0,J.existsSync)(this.fileName))return JSON.parse((0,J.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,J.existsSync)(this.dirName)||(0,J.mkdirSync)(this.dirName),(0,J.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",o=new W(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}=Ki(e,o),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await qi(e.baseUrl,S);let f=new Gr.MedplumClient({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:Hi,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 Ki(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}}async function qi(e,t){try{let r=new URL("healthcheck",e).toString(),o=await t(r);if(!o.ok)throw new Error(`Healthcheck returned status ${o.status}`);if((await o.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${o}`)}}function Hi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var q=require("@medplum/core"),yo=require("commander");var Jr=require("node:buffer");var ie=new TextEncoder,Bt=new TextDecoder,yp=2**32;function Vr(...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=>Jr.Buffer.from(e).toString("base64url");var ae=class extends Error{constructor(r,o){super(r,o);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};P(ae,"code","ERR_JOSE_GENERIC");var M=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}};P(M,"code","ERR_JOSE_NOT_SUPPORTED");var X=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}};P(X,"code","ERR_JWS_INVALID");var Oe=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}};P(Oe,"code","ERR_JWT_INVALID");var Xr,zr,Wt=class extends(zr=ae,Xr=Symbol.asyncIterator,zr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);P(this,Xr);P(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};P(Wt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Yr=k(require("node:util"),1),Ye=e=>Yr.types.isKeyObject(e);var Qr=k(require("node:crypto"),1),Zr=k(require("node:util"),1),Vi=Qr.webcrypto,eo=Vi,fe=e=>Zr.types.isCryptoKey(e);function K(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 Kt(e){return parseInt(e.name.slice(4),10)}function Ji(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Xi(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 to(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!xe(e.algorithm,"HMAC"))throw K("HMAC");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!xe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw K("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!xe(e.algorithm,"RSA-PSS"))throw K("RSA-PSS");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw K("Ed25519 or Ed448");break}case"Ed25519":{if(!xe(e.algorithm,"Ed25519"))throw K("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!xe(e.algorithm,"ECDSA"))throw K("ECDSA");let o=Ji(t);if(e.algorithm.namedCurve!==o)throw K(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Xi(e,r)}function ro(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)=>ro("Key must be ",e,...t);function qt(e,t,...r){return ro(`Key for the ${e} algorithm must be `,t,...r)}var Ht=e=>Ye(e)||fe(e),z=["KeyObject"];(globalThis.CryptoKey||eo?.CryptoKey)&&z.push("CryptoKey");var zi=(...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},oo=zi;function Yi(e){return typeof e=="object"&&e!==null}function Ne(e){if(!Yi(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 co=require("node:crypto");function te(e){return Ne(e)&&typeof e.kty=="string"}function no(e){return e.kty!=="oct"&&typeof e.d=="string"}function so(e){return e.kty!=="oct"&&typeof e.d>"u"}function io(e){return te(e)&&e.kty==="oct"&&typeof e.k=="string"}var Qi=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new M("Unsupported key curve for this operation")}},Zi=(e,t)=>{let r;if(fe(e))r=co.KeyObject.from(e);else if(Ye(e))r=e;else{if(te(e))return e.crv;throw new TypeError($e(e,...z))}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:Qi(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},lo=Zi;var uo=require("node:crypto"),Gt=(e,t)=>{let r;try{e instanceof uo.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 he=e=>e?.[Symbol.toStringTag],Vt=(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},ea=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&te(t)){if(io(t)&&Vt(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(!Ht(t))throw new TypeError(qt(e,t,...z,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${he(t)} instances for symmetric algorithms must be of type "secret"`)}},ta=(e,t,r,o)=>{if(o&&te(t))switch(r){case"sign":if(no(t)&&Vt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(so(t)&&Vt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ht(t))throw new TypeError(qt(e,t,...z,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${he(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function po(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?ea(t,r,o,e):ta(t,r,o,e)}var Bp=po.bind(void 0,!1),mo=po.bind(void 0,!0);function ra(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 M(`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 fo=ra;function Jt(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ke=require("node:crypto");var oa=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Xt(e,t){let r,o,n;if(t instanceof ke.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");Gt(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");Gt(t,e),s={padding:ke.constants.RSA_PKCS1_PSS_PADDING,saltLength:ke.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=lo(t),a=oa.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 M(`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=k(require("node:crypto"),1),ho=require("node:util");function zt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ge=require("node:crypto");function Yt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError($e(t,...z));return(0,ge.createSecretKey)(t)}if(t instanceof ge.KeyObject)return t;if(fe(t))return to(t,e,r),ge.KeyObject.from(t);if(te(t))return e.startsWith("HS")?(0,ge.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError($e(t,...z,"Uint8Array","JSON Web Key"))}var na=(0,ho.promisify)(Qe.sign),sa=async(e,t,r)=>{let o=Yt(e,t,"sign");if(e.startsWith("HS")){let n=Qe.createHmac(zt(e),o);return n.update(r),n.digest()}return na(Jt(e),r,Xt(e,o))},go=sa;var re=e=>Math.floor(e.getTime()/1e3);var ia=/^(\+|\-)? ?(\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=ia.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){P(this,"_payload");P(this,"_protectedHeader");P(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 X("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!oo(this._protectedHeader,this._unprotectedHeader))throw new X("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=fo(X,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new X('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new X('JWS "alg" (Algorithm) Header Parameter missing or invalid');mo(i,t,"sign");let a=this._payload;s&&(a=ie.encode(ze(a)));let l;this._protectedHeader?l=ie.encode(ze(JSON.stringify(this._protectedHeader))):l=ie.encode("");let u=Vr(l,ie.encode("."),a),h=await go(i,t,u),m={signature:ze(h),payload:""};return s&&(m.payload=Bt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Bt.decode(l)),m}};var tt=class{constructor(t){P(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 ce(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var rt=class{constructor(t={}){P(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:ce("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ce("setNotBefore",re(t))}:this._payload={...this._payload,nbf:re(new Date)+Ze(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ce("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ce("setExpirationTime",re(t))}:this._payload={...this._payload,exp:re(new Date)+Ze(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:re(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ce("setIssuedAt",re(t))}:typeof t=="string"?this._payload={...this._payload,iat:ce("setIssuedAt",re(new Date)+Ze(t))}:this._payload={...this._payload,iat:ce("setIssuedAt",t)},this}};var Le=class extends rt{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new tt(ie.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 ye=require("node:crypto"),oe=require("node:fs"),Y=require("node:path"),wo=require("node:util/types"),Eo=require("tar");function Q(e){console.log(JSON.stringify(e,null,2))}async function Qt(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,Y.basename)(o),contentType:la(o)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Zt(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,Y.basename)(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function er(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 Qt(e,h,u),await Zt(e,h,u),console.log(`Success! Bot created: ${u.id}`),i&&aa(h)}function So(e){let t=new RegExp("^"+ca(e).replaceAll(String.raw`\*`,".*")+"$"),r=H()?.bots?.filter(o=>t.test(o.name));return r||[]}function j(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function C(e,t){(0,oe.writeFileSync)((0,Y.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function H(e,t){let r=j(e,t),o=ot(r);if(o)return JSON.parse(o)}function Ro(e){let t=ot(j(e,{server:!0}));if(t)return JSON.parse(t)}function ot(e){let t=(0,Y.resolve)(e);return(0,oe.existsSync)(t)?(0,oe.readFileSync)(t,"utf8"):""}function aa(e){let t=H()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,oe.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ca(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Ao(e){let o=0,n=0;return(0,Eo.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 tr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function la(e){let t=(0,Y.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?q.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?q.ContentType.TYPESCRIPT:q.ContentType.TEXT}function nt(e,t){let r=new W(e),o={name:e,...t};return r.setObject("options",o),o}function Po(e){return new W(e).getObject("options")}async function vo(e,t){let r={typ:"JWT",alg:q.OAuthSigningAlgorithm.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,q.encodeBase64)(JSON.stringify(r)),i=(0,q.encodeBase64)(JSON.stringify(n)),a=`${s}.${i}`,l=(0,ye.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Io(e,t){let r=(0,ye.createPrivateKey)((0,oe.readFileSync)((0,Y.resolve)(t.privateKeyPath))),o=await new Le({}).setProtectedHeader({typ:"JWT",alg:q.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ye.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 yo.Command{action(t){let r=ua(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 ua(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,wo.isPromise)(s)&&await s}finally{e.resetOptionDefaults()}}}var bo=new g("status").aliases(["info","list","ls"]),Co=new g("ping"),To=new g("push"),Oo=new g("reload-config"),xo=new g("upgrade"),le=new g("agent");y(le,bo);y(le,Co);y(le,To);y(le,Oo);y(le,xo);bo.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 rr({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=ma(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"}}})});Co.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 $o(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}`,Z.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});To.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",Z.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 $o(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)});Oo.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 rr({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});xo.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 rr({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function rr({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n}){let s=ha(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[b,V]of Object.entries(o))l.append(b,V.toString());let u;try{let b=i.fhirUrl("Agent",e);b.search=l.toString(),u=await i.get(b,{cache:"reload"})}catch(b){throw new Error(`Operation '${e}' failed`,{cause:b})}if(r.output==="json"){console.info(JSON.stringify(u,null,2));return}let h=[],m=[];switch(u.resourceType){case"Bundle":{let b=pa(u);for(let V of b)V.result.resourceType==="Parameters"||(0,Z.isOk)(V.result)?h.push(V):m.push(V);break}case"Parameters":case"OperationOutcome":{let b=await i.searchOne("Agent",l,{cache:"reload"});if(!b)throw new Error("Agent not found");u.resourceType==="Parameters"?h.push({agent:b,result:u}):m.push({agent:b,result:u});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(u)}`)}let S=[];for(let b of h){let V=n(b);S.push(V)}let f=[];for(let b of m){let jt=b.result.issue?.[0],Li={id:b.agent.id,name:b.agent.name,severity:jt.severity,code:jt.code,details:jt.details?.text??"No details to show"};f.push(Li)}console.info(`
|
|
3
3
|
${S.length} successful response(s):
|
|
4
|
-
`),console.table(S.length?S:"No successful responses received"),console.info(),f.length&&(console.info(`${f.length} failed response(s):`),console.info(),console.table(f))}async function $o(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{No(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
|
|
5
|
-
`)}function
|
|
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 $o(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{No(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 pa(e){let t=[];for(let r of e.entry??Z.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(da(r.resource))}return t}function da(e){let t=e.parameter?.find(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 ma(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=fa(s,i);r[s]=a}return r}function fa(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 ha(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,Z.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return No(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function No(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 F=require("@medplum/core"),ko=require("node:child_process"),Lo=require("node:http"),Mo=require("node:os");var Do=F.MEDPLUM_CLI_CLIENT_ID,_o="http://localhost:9615",or=new g("login"),nr=new g("whoami"),sr=new g("token");or.action(async e=>{let t=e.profile??"default",r=nt(t,e),o=await R(e,!1);await ga(o,r)});nr.action(async e=>{let t=await R(e);Ea(t)});sr.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 ga(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Sa(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 vo(e,t);break;case"jwt-assertion":await Io(e,t);break}}async function ya(e){let t=(0,Lo.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":F.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:Do,redirectUri:_o});o.writeHead(200,{"Content-Type":F.ContentType.TEXT}),o.end(`Signed in as ${(0,F.getDisplayString)(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":F.ContentType.TEXT}),o.end(`Error: ${(0,F.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":F.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function wa(e){let t=(0,Mo.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,ko.exec)(r,(s,i,a)=>{if(s){n(s);return}if(a){n(new Error("Could not open browser: "+a));return}o()})})}function Ea(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 Sa(e){await ya(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Do),t.searchParams.set("redirect_uri",_o),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await wa(t.toString())}var Me="\x1B[0m",Ra="\x1B[1m",Aa="\x1B[31m",Pa="\x1B[32m",va="\x1B[33m",Ia="\x1B[34m",ue={red:e=>`${Aa}${e}${Me}`,green:e=>`${Pa}${e}${Me}`,yellow:e=>`${va}${e}${Me}`,blue:e=>`${Ia}${e}${Me}`,bold:e=>`${Ra}${e}${Me}`},ir=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>ue.bold(r));var ee=require("@aws-sdk/client-cloudformation"),Pt=require("@aws-sdk/client-cloudfront"),Os=require("@aws-sdk/client-ecs"),xs=require("@aws-sdk/client-s3"),Se=require("@aws-sdk/client-ssm"),vt=require("@aws-sdk/client-sts"),It=require("@medplum/core"),$s=k(require("node-fetch"),1),Ns=require("node:fs"),ks=k(br(),1);var Cs=k(require("node:readline"),1),wt;function Et(){wt=Cs.default.createInterface({input:process.stdin,output:process.stdout})}function St(){wt.close()}function c(e){wt.write(e+`
|
|
5
|
+
`)}function I(e){c(`
|
|
6
6
|
`+e+`
|
|
7
|
-
`)}function k(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 k(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 Number.parseInt(await Rt(e,t.map(o=>o.toString()),r.toString()),10)}async function ne(e){return(await Rt(e,["y","n"])).toLowerCase()==="y"}async function Ke(e){if(!await ne(e))throw c("Exiting..."),new Error("User cancelled")}var At=new ee.CloudFormationClient({}),Su=new Pt.CloudFrontClient({region:"us-east-1"}),jm=new Os.ECSClient({}),qe=new xs.S3Client({}),Ru="medplum:environment";async function Cr(){let e=[],t=(0,ee.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)for(let o of r.StackSummaries??vt.EMPTY)e.push(o);return e}async function Re(e){let t=await Cr();for(let r of t){let o=r.StackName,n=await Tr(o);if(n?.tag===e)return n}}async function Tr(e){let t={};if(await Ts(At,e,t),await At.config.region()!=="us-east-1")try{await Ts(new ee.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Ts(e,t,r){let o=new ee.DescribeStacksCommand({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===Ru);if(!i)return;let a=await e.send(new ee.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===At&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)Au(l,r)}}function Au(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 bt(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: ${Pu(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 Pu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Ct(e){let t=await Su.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 Tt(e){let o=(await(await(0,$s.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)=>Ls.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function Ot(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 Iu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ke(`Do you want to overwrite "${i}"?`)),await vu(o,i,a)}}async function Iu(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 vu(e,t,r){let o=new Se.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function se(e,t){if(console.log(`Config not found: ${e} (${j(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,Ns.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,vt.normalizeErrorString)(t))}}async function ks(e){let t=await Re(e);if(!t)throw await Ae(e),new Error(`Stack not found: ${e}`);bt(t)}var de=require("@aws-sdk/client-acm"),xt=require("@aws-sdk/client-cloudfront"),$t=require("@aws-sdk/client-sts"),Ds=require("@medplum/core"),He=require("node:crypto"),_s=require("node:fs");var bu=e=>`${e}DomainName`,Us=e=>`${e}SslCertArn`;async function js(){let e={apiPort:8103,region:"us-east-1"};Et(),v("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await Cu(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?")),v("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await k("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),v("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await k("What is the config file name?",`medplum.${e.name}.config.json`);(0,_s.existsSync)(r)&&(c("Config file already exists."),await Ke("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),v("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await k("Enter your AWS region:","us-east-1"),C(r,e),v("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await k("What is your AWS account number?",t),C(r,e),v("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await k("Enter your CloudFormation stack name?",o),C(r,e),v("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await k("Enter your base domain name:");C(r,e),v("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await k("Enter your support email address:");v("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await k("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,C(r,e),v("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await k("Enter your web application domain name:","app."+e.domainName),C(r,e),v("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await k("Enter your storage domain name:","storage."+e.domainName),C(r,e),v("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await k("Enter your storage bucket name:",e.storageDomainName),C(r,e),v("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await Ee("Enter the maximum number of availability zones:",[2,3,99],2),v("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await ne("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"),C(r,e),v("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await Ee("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),v("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await Ee("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),v("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await Ee("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),v("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let s=(await Tt())[0]??"latest";e.serverImage=await k("Enter the server image:",`medplum/medplum-server:${s}`),C(r,e),v("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await $u(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,C(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),v("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Tu(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 Ou(e,a,u,h);e[Us(h)]=m,C(r,e)}v("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ne("Do you want to store these values in AWS Parameter Store?"))await Ot(e.region,`/medplum/${e.name}/`,l);else{let u=j(e.name,{server:!0});C(u,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${u}`),c("Please add these values to AWS Parameter Store manually.")}v("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),St()}async function Cu(e){try{let t=new $t.STSClient({region:e}),r=new $t.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Tu(e){let t=await Ms(e);if(e!=="us-east-1"){let r=await Ms("us-east-1");t.push(...r)}return t}async function Ms(e){try{let t=new de.ACMClient({region:e}),r=new de.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ou(e,t,r,o){let n=e[bu(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 ne("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Us(o)}" setting.`),"TODO";let i=await xu(r,n);return c("Certificate ARN: "+i),i}async function xu(e,t){try{let r=await Rt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new de.ACMClient({region:e}),n=new de.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 $u(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 xt.CloudFrontClient({region:e}).send(new xt.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,Ds.normalizeErrorString)(n));return}}async function Fs(){let e=await Cr();for(let t of e){let r=t.StackName,o=await Tr(r);o&&(bt(o),console.log(""))}}var Bs=require("@aws-sdk/client-s3"),B=require("@medplum/core"),Ws=L(require("fast-glob"),1),Or=L(require("node-fetch"),1),U=require("node:fs"),Ks=require("node:os"),me=require("node:path"),qs=require("node:stream/promises");async function Hs(e,t){let r=H(e,t);if(!r)throw se(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 Lu("@medplum/app",i)}Gs(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 Mu(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Ct(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Nu(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Or.default)(r)).json()}async function Lu(e,t){let o=(await Nu(e,t)).dist.tarball,n=(0,U.mkdtempSync)((0,me.join)((0,Ks.tmpdir)(),"tarball-"));try{let s=await(0,Or.default)(o),i=Ao(n);return await(0,qs.pipeline)(s.body,i),(0,me.join)(n,"package","dist")}catch(s){throw(0,U.rmSync)(n,{recursive:!0,force:!0}),s}}function Gs(e,t){for(let r of(0,U.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Gs(o,t):r.isFile()&&o.endsWith(".js")&&ku(o,t)}}function ku(e,t){let r=(0,U.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,U.writeFileSync)(e,r)}async function Mu(e,t,r){let o=[["assets/**/*.css",B.ContentType.CSS,!0],["assets/**/*.css.map",B.ContentType.JSON,!0],["assets/**/*.js",B.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",B.ContentType.JSON,!0],["assets/**/*.txt",B.ContentType.TEXT,!0],["assets/**/*.ico",B.ContentType.FAVICON,!0],["img/**/*.png",B.ContentType.PNG,!0],["img/**/*.svg",B.ContentType.SVG,!0],["robots.txt",B.ContentType.TEXT,!0],["index.html",B.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=Ws.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await _u((0,me.join)(e.rootDir,r),e)}async function _u(e,t){let r=(0,U.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.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 Bs.PutObjectCommand(n))}var Nt=require("@aws-sdk/client-s3");async function Js(e,t){if(!H(e,t))throw se(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 Vs("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Vs("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Vs(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 Uu(s);if(Fu(a,s,i))throw new Error(`${e} bucket already has policy statement`);Bu(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 ju(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Ct(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Uu(e){let t=await qe.send(new Nt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ju(e,t){await qe.send(new Nt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Fu(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 Bu(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 Xs(e,t){try{Et();let r=H(e,t);if(!r)throw se(e,t),new Error(`Config not found: ${e}`);let o=Ro(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=j(e,{server:!0});if(console.log(ue.yellow(`Config file ${n} not found!`)),!await ne("Do you want to proceed?")){console.log(ue.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}Wu(r,o),qu(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(ue.yellow("Dry run - skipping updates!")):(t.yes||await ne("Do you want to store these values in AWS Parameter Store?"))&&await Ot(r.region,`/medplum/${r.name}/`,o)}finally{St()}}function Wu(e,t){Lt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Lt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Lt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Lt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Lt(e,t,r){if(Ku(e,t))throw new Error(r)}function Ku(e,t){return e!==void 0&&t!==void 0&&e!==t}function qu(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/binary/`)}var Ys=require("node:child_process"),Pe=L(br(),1);async function Qs(e,t){let r=await R(t),o=H(e,t);if(!o)throw console.log(`Configuration file ${j(e)} not found`),se(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await Hu(r,o),a=await zs(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}`,Gu(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await zs(a)}}async function Hu(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 zs(e,t){let r=await Tt(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function Gu(e,t){let r=j(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Ys.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 Zs(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(js),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Fs),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(ks),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(ir(`Update the AWS Parameter Store config values.
|
|
7
|
+
`)}function L(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 L(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 Number.parseInt(await Rt(e,t.map(o=>o.toString()),r.toString()),10)}async function ne(e){return(await Rt(e,["y","n"])).toLowerCase()==="y"}async function Ke(e){if(!await ne(e))throw c("Exiting..."),new Error("User cancelled")}var At=new ee.CloudFormationClient({}),Ru=new Pt.CloudFrontClient({region:"us-east-1"}),Fm=new Os.ECSClient({}),qe=new xs.S3Client({}),Au="medplum:environment";async function Cr(){let e=[],t=(0,ee.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)for(let o of r.StackSummaries??It.EMPTY)e.push(o);return e}async function Re(e){let t=await Cr();for(let r of t){let o=r.StackName,n=await Tr(o);if(n?.tag===e)return n}}async function Tr(e){let t={};if(await Ts(At,e,t),await At.config.region()!=="us-east-1")try{await Ts(new ee.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Ts(e,t,r){let o=new ee.DescribeStacksCommand({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===Au);if(!i)return;let a=await e.send(new ee.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===At&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)Pu(l,r)}}function Pu(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 bt(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: ${vu(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 vu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Ct(e){let t=await Ru.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 Tt(e){let o=(await(await(0,$s.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)=>ks.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function Ot(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 Iu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ke(`Do you want to overwrite "${i}"?`)),await bu(o,i,a)}}async function Iu(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 bu(e,t,r){let o=new Se.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function se(e,t){if(console.log(`Config not found: ${e} (${j(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,Ns.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 vt.STSClient,r=new vt.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,It.normalizeErrorString)(t))}}async function Ls(e){let t=await Re(e);if(!t)throw await Ae(e),new Error(`Stack not found: ${e}`);bt(t)}var de=require("@aws-sdk/client-acm"),xt=require("@aws-sdk/client-cloudfront"),$t=require("@aws-sdk/client-sts"),Ds=require("@medplum/core"),He=require("node:crypto"),_s=require("node:fs");var Cu=e=>`${e}DomainName`,Us=e=>`${e}SslCertArn`;async function js(){let e={apiPort:8103,region:"us-east-1"};Et(),I("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await Tu(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?")),I("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await L("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),I("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await L("What is the config file name?",`medplum.${e.name}.config.json`);(0,_s.existsSync)(r)&&(c("Config file already exists."),await Ke("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),I("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await L("Enter your AWS region:","us-east-1"),C(r,e),I("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await L("What is your AWS account number?",t),C(r,e),I("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await L("Enter your CloudFormation stack name?",o),C(r,e),I("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await L("Enter your base domain name:");C(r,e),I("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await L("Enter your support email address:");I("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await L("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,C(r,e),I("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await L("Enter your web application domain name:","app."+e.domainName),C(r,e),I("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await L("Enter your storage domain name:","storage."+e.domainName),C(r,e),I("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await L("Enter your storage bucket name:",e.storageDomainName),C(r,e),I("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await Ee("Enter the maximum number of availability zones:",[2,3,99],2),I("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await ne("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"),C(r,e),I("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await Ee("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),I("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await Ee("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),I("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await Ee("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),I("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let s=(await Tt())[0]??"latest";e.serverImage=await L("Enter the server image:",`medplum/medplum-server:${s}`),C(r,e),I("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await Nu(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,C(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),I("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Ou(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 xu(e,a,u,h);e[Us(h)]=m,C(r,e)}I("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ne("Do you want to store these values in AWS Parameter Store?"))await Ot(e.region,`/medplum/${e.name}/`,l);else{let u=j(e.name,{server:!0});C(u,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${u}`),c("Please add these values to AWS Parameter Store manually.")}I("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),St()}async function Tu(e){try{let t=new $t.STSClient({region:e}),r=new $t.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Ou(e){let t=await Ms(e);if(e!=="us-east-1"){let r=await Ms("us-east-1");t.push(...r)}return t}async function Ms(e){try{let t=new de.ACMClient({region:e}),r=new de.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function xu(e,t,r,o){let n=e[Cu(o)],s=t.find(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 ne("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Us(o)}" setting.`),"TODO";let i=await $u(r,n);return c("Certificate ARN: "+i),i}async function $u(e,t){try{let r=await Rt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new de.ACMClient({region:e}),n=new de.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 Nu(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 xt.CloudFrontClient({region:e}).send(new xt.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,Ds.normalizeErrorString)(n));return}}async function Fs(){let e=await Cr();for(let t of e){let r=t.StackName,o=await Tr(r);o&&(bt(o),console.log(""))}}var Bs=require("@aws-sdk/client-s3"),B=require("@medplum/core"),Ws=k(require("fast-glob"),1),Or=k(require("node-fetch"),1),U=require("node:fs"),Ks=require("node:os"),me=require("node:path"),qs=require("node:stream/promises");async function Hs(e,t){let r=H(e,t);if(!r)throw se(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 Lu("@medplum/app",i)}Gs(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 Du(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Ct(o.appDistribution.PhysicalResourceId),console.log("Done")}async function ku(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Or.default)(r)).json()}async function Lu(e,t){let o=(await ku(e,t)).dist.tarball,n=(0,U.mkdtempSync)((0,me.join)((0,Ks.tmpdir)(),"tarball-"));try{let s=await(0,Or.default)(o),i=Ao(n);return await(0,qs.pipeline)(s.body,i),(0,me.join)(n,"package","dist")}catch(s){throw(0,U.rmSync)(n,{recursive:!0,force:!0}),s}}function Gs(e,t){for(let r of(0,U.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Gs(o,t):r.isFile()&&o.endsWith(".js")&&Mu(o,t)}}function Mu(e,t){let r=(0,U.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,U.writeFileSync)(e,r)}async function Du(e,t,r){let o=[["assets/**/*.css",B.ContentType.CSS,!0],["assets/**/*.css.map",B.ContentType.JSON,!0],["assets/**/*.js",B.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",B.ContentType.JSON,!0],["assets/**/*.txt",B.ContentType.TEXT,!0],["assets/**/*.ico",B.ContentType.FAVICON,!0],["img/**/*.png",B.ContentType.PNG,!0],["img/**/*.svg",B.ContentType.SVG,!0],["robots.txt",B.ContentType.TEXT,!0],["index.html",B.ContentType.HTML,!1]];for(let n of o)await _u({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function _u(e){let t=Ws.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Uu((0,me.join)(e.rootDir,r),e)}async function Uu(e,t){let r=(0,U.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.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 Bs.PutObjectCommand(n))}var Nt=require("@aws-sdk/client-s3");async function Js(e,t){if(!H(e,t))throw se(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 Vs("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Vs("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Vs(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 ju(s);if(Bu(a,s,i))throw new Error(`${e} bucket already has policy statement`);Wu(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 Fu(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Ct(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function ju(e){let t=await qe.send(new Nt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Fu(e,t){await qe.send(new Nt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Bu(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 Wu(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 Xs(e,t){try{Et();let r=H(e,t);if(!r)throw se(e,t),new Error(`Config not found: ${e}`);let o=Ro(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=j(e,{server:!0});if(console.log(ue.yellow(`Config file ${n} not found!`)),!await ne("Do you want to proceed?")){console.log(ue.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}Ku(r,o),Hu(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(ue.yellow("Dry run - skipping updates!")):(t.yes||await ne("Do you want to store these values in AWS Parameter Store?"))&&await Ot(r.region,`/medplum/${r.name}/`,o)}finally{St()}}function Ku(e,t){kt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),kt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),kt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),kt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function kt(e,t,r){if(qu(e,t))throw new Error(r)}function qu(e,t){return e!==void 0&&t!==void 0&&e!==t}function Hu(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/binary/`)}var Ys=require("node:child_process"),Pe=k(br(),1);async function Qs(e,t){let r=await R(t),o=H(e,t);if(!o)throw console.log(`Configuration file ${j(e)} not found`),se(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await Gu(r,o),a=await zs(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}`,Vu(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await zs(a)}}async function Gu(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 zs(e,t){let r=await Tt(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function Vu(e,t){let r=j(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Ys.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 Zs(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(js),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Fs),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Ls),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(ir(`Update the AWS Parameter Store config values.
|
|
8
8
|
|
|
9
9
|
Configuration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.
|
|
10
10
|
|
|
11
|
-
`+ue.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",ir("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(Xs),y(e,new g("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(Qs)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(Hs),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Js),e}var ei=new g("save"),ti=new g("deploy"),ri=new g("create"),Ge=new g("bot");y(Ge,ei);y(Ge,ti);y(Ge,ri);var xr=new g("save-bot"),$r=new g("deploy-bot"),Nr=new g("create-bot");ei.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await
|
|
11
|
+
`+ue.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",ir("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(Xs),y(e,new g("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(Qs)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(Hs),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Js),e}var ei=new g("save"),ti=new g("deploy"),ri=new g("create"),Ge=new g("bot");y(Ge,ei);y(Ge,ti);y(Ge,ri);var xr=new g("save-bot"),$r=new g("deploy-bot"),Nr=new g("create-bot");ei.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await Lt(r,e)});ti.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await Lt(r,e,!0)});ri.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,n)=>{let s=await R(n);await er(s,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function Lt(e,t,r=!1){let o=So(t),n=[],s=[],i=0,a=0;for(let l of o)try{let u=await e.readResource("Bot",l.id);await Qt(e,l,u),i++,r&&(await Zt(e,l,u),a++)}catch(u){n.push(u),s.push(`${l.name} [${l.id}]`)}if(console.log(`Number of bots saved: ${i}`),console.log(`Number of bots deployed: ${a}`),console.log(`Number of errors: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
|
|
12
12
|
|
|
13
13
|
${s.join(`
|
|
14
|
-
`)}`,{cause:n})}xr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await kt(r,e)});$r.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await kt(r,e,!0)});Nr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let s=await R(n);await er(s,e,t,r,o)});var ni=require("@medplum/core"),Mt=require("node:fs"),Lr=require("node:path"),si=require("node:readline");var ii=new g("export"),ai=new g("import"),Dt=new g("bulk");y(Dt,ii);y(Dt,ai);ii.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,s=await R(e);(await s.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:a,url:l})=>{let u=new URL(l),h=await s.download(l),m=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",S=(0,Lr.resolve)(n??"",m);(0,Mt.writeFile)(`${S}`,await h.text(),()=>{console.log(`${S} is created`)})})});ai.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,s=(0,Lr.resolve)(n??process.cwd(),e),i=await R(t);await Vu(s,Number.parseInt(r,10),i,o)});async function Vu(e,t,r,o){let n=[],s=(0,Mt.createReadStream)(e),i=(0,si.createInterface)({input:s});for await(let a of i){let l=Ju(a,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await oi(n,r),n=[])}n.length>0&&await oi(n,r)}async function oi(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??ni.EMPTY)Q(o.response)}function Ju(e,t){let r=JSON.parse(e);return t?Xu(r):r}function Xu(e){return e.resourceType==="ExplanationOfBenefit"?zu(e):e}function zu(e){return e.provider||(e.provider=tr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=tr())}),e}var _t=require("@medplum/core");var Ve=L(require("node:assert"),1),ui=require("node:net"),N=require("@medplum/core"),kr=L(require("iconv-lite"),1),tp=require("@medplum/core"),mi=require("@medplum/core"),fi=L(require("node:net"),1),Yu=Object.defineProperty,Qu=(e,t,r)=>t in e?Yu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t,r)=>Qu(e,typeof t!="symbol"?t+"":t,r),li=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Zu=class extends Event{constructor(e,t){super("message"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},ep=class extends Event{constructor(e,t){super("enhancedAckSent"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},Ie=class extends Event{constructor(e){super("error"),A(this,"error"),this.error=e}},Mr=class extends Event{constructor(){super("close")}},ci="utf-8",rp=60*1e3,pi=class extends li{constructor(e,t=ci,r,o={}){super(),A(this,"socket"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"chunks",[]),A(this,"pendingMessages",new Map),A(this,"responseQueue",[]),A(this,"lastMessageDispatchedTime",0),A(this,"responseQueueProcessing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,e.on("data",n=>{try{this.appendData(n);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new Zu(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Ie(i))})}catch(s){this.dispatchEvent(new Ie(s))}}),e.on("error",n=>{this.resetBuffer(),this.dispatchEvent(new Ie(n))}),e.on("close",()=>{this.dispatchEvent(new Mr)}),this.addEventListener("message",n=>{let s;this.enhancedMode==="standard"?s=n.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(s=n.message.buildAck({ackCode:"AA"})),s&&(this.send(s),this.dispatchEvent(new ep(this,s)));let i=n.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.pendingMessages.get(i);if(!a){this.dispatchEvent(new Ie(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${i}' but there was no pending message with this control ID`}]})));return}let l=n.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===N.ReturnAckCategory.APPLICATION&&l==="CA"||(a.resolve(n.message),this.pendingMessages.delete(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=kr.default.encode(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=rp/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,N.sleep)(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let o=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){o=a+1;break}if(o===-1)break;let n=t.subarray(r,o+1).subarray(1,-2),s=kr.default.decode(n,this.encoding),i=N.Hl7Message.parse(s);e.push(i),r=o+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,o)=>{let n=e.getSegment("MSH")?.getField(10)?.toString();if(!n){o(new N.OperationOutcomeError((0,N.validationError)("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.pendingMessages.delete(n),o(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.pendingMessages.set(n,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??N.ReturnAckCategory.APPLICATION,timer:s}),this.sendImpl(e)})}async close(){if(!this.isClosed()){if(this.socket.end(),this.socket.destroy(),this.pendingMessages.size){for(let e of this.pendingMessages.values())e.timer&&clearTimeout(e.timer),e.reject(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Ie(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${this.pendingMessages.size} messages were pending`}]}))),this.pendingMessages.clear()}await new Promise(e=>{this.socket.once("close",e)})}}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??ci}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}},di=class extends li{constructor(e){super(),A(this,"options"),A(this,"host"),A(this,"port"),A(this,"encoding"),A(this,"connection"),A(this,"keepAlive"),A(this,"socket"),A(this,"connectTimeout"),A(this,"deferredConnectionPromise"),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1,this.connectTimeout=this.options.connectTimeout??3e4}connect(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=(0,ui.connect)({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){(0,Ve.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let o=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,o)};t.on("timeout",r)}registerSocketConnectListener(e){(0,Ve.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=new pi(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){(0,Ve.default)(this.socket);let t=this.socket,r=o=>{this.cleanupSocket(t),o.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,o.errors[0]):this.rejectDeferredPromise(e,o)};t.on("error",r)}registerSocketCloseListener(e){(0,Ve.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new Mr)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ie(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new Mr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},op=1e4,hi=class{constructor(e){A(this,"handler"),A(this,"server"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let n=fi.default.createServer(s=>{let i=new pi(s,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});await new Promise(s=>{let i=l=>{n.listen(l,s)},a=async l=>{l?.code==="EADDRINUSE"&&(await(0,mi.sleep)(50),n.close(),i(e))};n.on("error",a),n.once("listening",()=>{n.off("error",a)}),i(e),this.server=n})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let n of this.connections)n.close().catch(console.error)},e?.forceDrainTimeoutMs??op)),this.server.close(n=>{if(n){r(n);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}};var gi=require("node:fs");var np=new g("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=ip():o.file&&(r=(0,gi.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new di({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let s=await n.sendAndWait(_t.Hl7Message.parse(r));console.log(s.toString().replaceAll("\r",`
|
|
15
|
-
`))}finally{await n.close()}}),
|
|
16
|
-
`)),o.send(n.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),Ut=new g("hl7");y(Ut,
|
|
14
|
+
`)}`,{cause:n})}xr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await Lt(r,e)});$r.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await Lt(r,e,!0)});Nr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let s=await R(n);await er(s,e,t,r,o)});var ni=require("@medplum/core"),Mt=require("node:fs"),kr=require("node:path"),si=require("node:readline");var ii=new g("export"),ai=new g("import"),Dt=new g("bulk");y(Dt,ii);y(Dt,ai);ii.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,s=await R(e);(await s.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:a,url:l})=>{let u=new URL(l),h=await s.download(l),m=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",S=(0,kr.resolve)(n??"",m);(0,Mt.writeFile)(`${S}`,await h.text(),()=>{console.log(`${S} is created`)})})});ai.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,s=(0,kr.resolve)(n??process.cwd(),e),i=await R(t);await Ju(s,Number.parseInt(r,10),i,o)});async function Ju(e,t,r,o){let n=[],s=(0,Mt.createReadStream)(e),i=(0,si.createInterface)({input:s});for await(let a of i){let l=Xu(a,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await oi(n,r),n=[])}n.length>0&&await oi(n,r)}async function oi(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??ni.EMPTY)Q(o.response)}function Xu(e,t){let r=JSON.parse(e);return t?zu(r):r}function zu(e){return e.resourceType==="ExplanationOfBenefit"?Yu(e):e}function Yu(e){return e.provider||(e.provider=tr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=tr())}),e}var _t=require("@medplum/core");var Ve=k(require("node:assert"),1),ui=require("node:net"),N=require("@medplum/core"),Lr=k(require("iconv-lite"),1),rp=require("@medplum/core"),mi=require("@medplum/core"),fi=k(require("node:net"),1),Qu=Object.defineProperty,Zu=(e,t,r)=>t in e?Qu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t,r)=>Zu(e,typeof t!="symbol"?t+"":t,r),li=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var ep=class extends Event{constructor(e,t){super("message"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},tp=class extends Event{constructor(e,t){super("enhancedAckSent"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},ve=class extends Event{constructor(e){super("error"),A(this,"error"),this.error=e}},Mr=class extends Event{constructor(){super("close")}},ci="utf-8",op=60*1e3,pi=class extends li{constructor(e,t=ci,r,o={}){super(),A(this,"socket"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"chunks",[]),A(this,"pendingMessages",new Map),A(this,"responseQueue",[]),A(this,"lastMessageDispatchedTime",0),A(this,"responseQueueProcessing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,e.on("data",n=>{try{this.appendData(n);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new ep(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new ve(i))})}catch(s){this.dispatchEvent(new ve(s))}}),e.on("error",n=>{this.resetBuffer(),this.dispatchEvent(new ve(n))}),e.on("close",()=>{this.dispatchEvent(new Mr)}),this.addEventListener("message",n=>{let s;this.enhancedMode==="standard"?s=n.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(s=n.message.buildAck({ackCode:"AA"})),s&&(this.send(s),this.dispatchEvent(new tp(this,s)));let i=n.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.pendingMessages.get(i);if(!a){this.dispatchEvent(new ve(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${i}' but there was no pending message with this control ID`}]})));return}let l=n.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===N.ReturnAckCategory.APPLICATION&&l==="CA"||(a.resolve(n.message),this.pendingMessages.delete(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Lr.default.encode(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=op/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,N.sleep)(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let o=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){o=a+1;break}if(o===-1)break;let n=t.subarray(r,o+1).subarray(1,-2),s=Lr.default.decode(n,this.encoding),i=N.Hl7Message.parse(s);e.push(i),r=o+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,o)=>{let n=e.getSegment("MSH")?.getField(10)?.toString();if(!n){o(new N.OperationOutcomeError((0,N.validationError)("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.pendingMessages.delete(n),o(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.pendingMessages.set(n,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??N.ReturnAckCategory.APPLICATION,timer:s}),this.sendImpl(e)})}async close(){if(!this.isClosed()){if(this.socket.end(),this.socket.destroy(),this.pendingMessages.size){for(let e of this.pendingMessages.values())e.timer&&clearTimeout(e.timer),e.reject(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new ve(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${this.pendingMessages.size} messages were pending`}]}))),this.pendingMessages.clear()}await new Promise(e=>{this.socket.once("close",e)})}}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??ci}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}},di=class extends li{constructor(e){super(),A(this,"options"),A(this,"host"),A(this,"port"),A(this,"encoding"),A(this,"connection"),A(this,"keepAlive"),A(this,"socket"),A(this,"connectTimeout"),A(this,"deferredConnectionPromise"),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1,this.connectTimeout=this.options.connectTimeout??3e4}connect(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=(0,ui.connect)({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){(0,Ve.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let o=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,o)};t.on("timeout",r)}registerSocketConnectListener(e){(0,Ve.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=new pi(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){(0,Ve.default)(this.socket);let t=this.socket,r=o=>{this.cleanupSocket(t),o.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,o.errors[0]):this.rejectDeferredPromise(e,o)};t.on("error",r)}registerSocketCloseListener(e){(0,Ve.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new Mr)}),e.addEventListener("error",t=>{this.dispatchEvent(new ve(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new Mr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},np=1e4,hi=class{constructor(e){A(this,"handler"),A(this,"server"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let n=fi.default.createServer(s=>{let i=new pi(s,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});await new Promise(s=>{let i=l=>{n.listen(l,s)},a=async l=>{l?.code==="EADDRINUSE"&&(await(0,mi.sleep)(50),n.close(),i(e))};n.on("error",a),n.once("listening",()=>{n.off("error",a)}),i(e),this.server=n})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let n of this.connections)n.close().catch(console.error)},e?.forceDrainTimeoutMs??np)),this.server.close(n=>{if(n){r(n);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}};var gi=require("node:fs");var sp=new g("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=ap():o.file&&(r=(0,gi.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new di({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let s=await n.sendAndWait(_t.Hl7Message.parse(r));console.log(s.toString().replaceAll("\r",`
|
|
15
|
+
`))}finally{await n.close()}}),ip=new g("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new hi(o=>{o.addEventListener("message",({message:n})=>{console.log(n.toString().replaceAll("\r",`
|
|
16
|
+
`)),o.send(n.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),Ut=new g("hl7");y(Ut,sp);y(Ut,ip);function ap(){let e=(0,_t.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
|
|
17
17
|
EVN|A01|${e}||
|
|
18
18
|
PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|
|
|
19
|
-
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var yi=require("node:fs"),wi=require("node:os"),Ei=require("node:path");var Si=new g("set"),Ri=new g("remove"),Ai=new g("list"),Pi=new g("describe"),
|
|
19
|
+
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var yi=require("node:fs"),wi=require("node:os"),Ei=require("node:path");var Si=new g("set"),Ri=new g("remove"),Ai=new g("list"),Pi=new g("describe"),Ie=new g("profile");y(Ie,Si);y(Ie,Ri);y(Ie,Ai);y(Ie,Pi);Si.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{nt(e,t)});Ri.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new W(e).setObject("options",void 0),console.log(`${e} profile removed`)});Ai.description("List all profiles saved").action(async()=>{let e=(0,Ei.resolve)((0,wi.homedir)(),".medplum"),t=(0,yi.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],i=new W(n).getObject("options");i&&r.push({profileName:n,profile:i})}),console.log(r)});Pi.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Po(e);console.log(t)});var vi=require("commander");var Ii=new g("list"),bi=new g("current"),Ci=new g("switch"),Ti=new g("invite"),be=new g("project");y(be,Ii);y(be,bi);y(be,Ci);y(be,Ti);Ii.description("List of current projects").action(async e=>{let t=await R(e);cp(t)});function cp(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
|
|
20
20
|
|
|
21
|
-
`);console.log(r)}bi.description("Project you are currently on").action(async e=>{let r=(await R(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});Ci.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await R(t);await
|
|
22
|
-
`)}async function
|
|
21
|
+
`);console.log(r)}bi.description("Project you are currently on").action(async e=>{let r=(await R(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});Ci.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await R(t);await lp(r,e)});Ti.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new vi.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await R(o),s=n.getActiveLogin();if(!s)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!s?.project?.reference)throw new Error("No current project to invite user to");let i=s.project.reference.split("/")[1],a={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await up(i,a,n)});async function lp(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));if(!o)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(o),console.log(`Switched to project ${t}
|
|
22
|
+
`)}async function up(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var Oi=require("@medplum/core");var Dr=new g("delete"),_r=new g("get"),Ur=new g("patch"),jr=new g("post"),Fr=new g("put");Dr.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await R(t);Q(await r.delete(Je(r,e)))});_r.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await R(t),o=await r.get(Je(r,e));t.asTransaction?Q((0,Oi.convertToTransactionBundle)(o)):Q(o)});Ur.arguments("<url> <body>").action(async(e,t,r)=>{let o=await R(r);Q(await o.patch(Je(o,e),Br(t)))});jr.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let o=await R(r),n=r.preferAsync?{Prefer:"respond-async"}:void 0;Q(await o.post(Je(o,e),Br(t),void 0,{headers:n}))});Fr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await R(r);Q(await o.put(Je(o,e),Br(t)))});function Br(e){if(e)try{return JSON.parse(e)}catch{return e}}function Je(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function $i(e){let t=new g("medplum").description("Command to access Medplum CLI").option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new Xe.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});t.exitOverride(),t.version(Ce.MEDPLUM_VERSION),t.configureHelp({showGlobalOptions:!0}),y(t,or),y(t,nr),y(t,sr),y(t,_r),y(t,jr),y(t,Ur),y(t,Fr),y(t,Dr),y(t,be),y(t,Dt),y(t,Ge),y(t,le),y(t,xr),y(t,$r),y(t,Nr),y(t,Ie),y(t,Zs()),y(t,Ut);try{await t.parseAsync(e)}catch(r){Ni(r)}}function Ni(e){let t=1,r=!0;if(e instanceof Xe.CommanderError&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){Wr(e,!!process.env.VERBOSE);let o=e.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let n of o)Wr(n,!0);else o instanceof Error&&Wr(o,!0)}process.exit(t)}function Wr(e,t=!1){if(t){console.error(e);return}e instanceof Xe.CommanderError?process.stderr.write(`${(0,Ce.normalizeErrorString)(e)}
|
|
23
23
|
`):process.stderr.write(`Error: ${(0,Ce.normalizeErrorString)(e)}
|
|
24
|
-
`)}async function
|
|
24
|
+
`)}async function ki(){xi.default.config({quiet:!0}),await $i(process.argv)}ki().catch(e=>{console.error("Unhandled error:",(0,Ce.normalizeErrorString)(e)),process.exit(1)});0&&(module.exports={handleError,main,run});
|
|
25
25
|
//# sourceMappingURL=index.cjs.map
|