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