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