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