@medplum/cli 3.1.4 → 3.1.5
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 +2 -2
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +12 -12
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var wn=Object.create;var Re=Object.defineProperty;var En=Object.getOwnPropertyDescriptor;var Sn=Object.getOwnPropertyNames;var An=Object.getPrototypeOf,bn=Object.prototype.hasOwnProperty;var vn=(e,t,r)=>t in e?Re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Cn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),In=(e,t)=>{for(var r in t)Re(e,r,{get:t[r],enumerable:!0})},pr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Sn(t))!bn.call(e,n)&&n!==r&&Re(e,n,{get:()=>t[n],enumerable:!(o=En(t,n))||o.enumerable});return e};var N=(e,t,r)=>(r=e!=null?wn(An(e)):{},pr(t||!e||!e.__esModule?Re(r,"default",{value:e,enumerable:!0}):r,e)),Pn=e=>pr(Re({},"__esModule",{value:!0}),e);var P=(e,t,r)=>(vn(e,typeof t!="symbol"?t+"":t,r),r);var zt=Cn((u,Yr)=>{"use strict";u=Yr.exports=m;var g;typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?g=function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:g=function(){};u.SEMVER_SPEC_VERSION="2.0.0";var ke=256,Qe=Number.MAX_SAFE_INTEGER||9007199254740991,$t=16,Ri=ke-6,Se=u.re=[],y=u.safeRe=[],p=u.src=[],a=u.tokens={},zr=0;function f(e){a[e]=zr++}var Bt="[a-zA-Z0-9-]",Ft=[["\\s",1],["\\d",ke],[Bt,Ri]];function Me(e){for(var t=0;t<Ft.length;t++){var r=Ft[t][0],o=Ft[t][1];e=e.split(r+"*").join(r+"{0,"+o+"}").split(r+"+").join(r+"{1,"+o+"}")}return e}f("NUMERICIDENTIFIER");p[a.NUMERICIDENTIFIER]="0|[1-9]\\d*";f("NUMERICIDENTIFIERLOOSE");p[a.NUMERICIDENTIFIERLOOSE]="\\d+";f("NONNUMERICIDENTIFIER");p[a.NONNUMERICIDENTIFIER]="\\d*[a-zA-Z-]"+Bt+"*";f("MAINVERSION");p[a.MAINVERSION]="("+p[a.NUMERICIDENTIFIER]+")\\.("+p[a.NUMERICIDENTIFIER]+")\\.("+p[a.NUMERICIDENTIFIER]+")";f("MAINVERSIONLOOSE");p[a.MAINVERSIONLOOSE]="("+p[a.NUMERICIDENTIFIERLOOSE]+")\\.("+p[a.NUMERICIDENTIFIERLOOSE]+")\\.("+p[a.NUMERICIDENTIFIERLOOSE]+")";f("PRERELEASEIDENTIFIER");p[a.PRERELEASEIDENTIFIER]="(?:"+p[a.NUMERICIDENTIFIER]+"|"+p[a.NONNUMERICIDENTIFIER]+")";f("PRERELEASEIDENTIFIERLOOSE");p[a.PRERELEASEIDENTIFIERLOOSE]="(?:"+p[a.NUMERICIDENTIFIERLOOSE]+"|"+p[a.NONNUMERICIDENTIFIER]+")";f("PRERELEASE");p[a.PRERELEASE]="(?:-("+p[a.PRERELEASEIDENTIFIER]+"(?:\\."+p[a.PRERELEASEIDENTIFIER]+")*))";f("PRERELEASELOOSE");p[a.PRERELEASELOOSE]="(?:-?("+p[a.PRERELEASEIDENTIFIERLOOSE]+"(?:\\."+p[a.PRERELEASEIDENTIFIERLOOSE]+")*))";f("BUILDIDENTIFIER");p[a.BUILDIDENTIFIER]=Bt+"+";f("BUILD");p[a.BUILD]="(?:\\+("+p[a.BUILDIDENTIFIER]+"(?:\\."+p[a.BUILDIDENTIFIER]+")*))";f("FULL");f("FULLPLAIN");p[a.FULLPLAIN]="v?"+p[a.MAINVERSION]+p[a.PRERELEASE]+"?"+p[a.BUILD]+"?";p[a.FULL]="^"+p[a.FULLPLAIN]+"$";f("LOOSEPLAIN");p[a.LOOSEPLAIN]="[v=\\s]*"+p[a.MAINVERSIONLOOSE]+p[a.PRERELEASELOOSE]+"?"+p[a.BUILD]+"?";f("LOOSE");p[a.LOOSE]="^"+p[a.LOOSEPLAIN]+"$";f("GTLT");p[a.GTLT]="((?:<|>)?=?)";f("XRANGEIDENTIFIERLOOSE");p[a.XRANGEIDENTIFIERLOOSE]=p[a.NUMERICIDENTIFIERLOOSE]+"|x|X|\\*";f("XRANGEIDENTIFIER");p[a.XRANGEIDENTIFIER]=p[a.NUMERICIDENTIFIER]+"|x|X|\\*";f("XRANGEPLAIN");p[a.XRANGEPLAIN]="[v=\\s]*("+p[a.XRANGEIDENTIFIER]+")(?:\\.("+p[a.XRANGEIDENTIFIER]+")(?:\\.("+p[a.XRANGEIDENTIFIER]+")(?:"+p[a.PRERELEASE]+")?"+p[a.BUILD]+"?)?)?";f("XRANGEPLAINLOOSE");p[a.XRANGEPLAINLOOSE]="[v=\\s]*("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:"+p[a.PRERELEASELOOSE]+")?"+p[a.BUILD]+"?)?)?";f("XRANGE");p[a.XRANGE]="^"+p[a.GTLT]+"\\s*"+p[a.XRANGEPLAIN]+"$";f("XRANGELOOSE");p[a.XRANGELOOSE]="^"+p[a.GTLT]+"\\s*"+p[a.XRANGEPLAINLOOSE]+"$";f("COERCE");p[a.COERCE]="(^|[^\\d])(\\d{1,"+$t+"})(?:\\.(\\d{1,"+$t+"}))?(?:\\.(\\d{1,"+$t+"}))?(?:$|[^\\d])";f("COERCERTL");Se[a.COERCERTL]=new RegExp(p[a.COERCE],"g");y[a.COERCERTL]=new RegExp(Me(p[a.COERCE]),"g");f("LONETILDE");p[a.LONETILDE]="(?:~>?)";f("TILDETRIM");p[a.TILDETRIM]="(\\s*)"+p[a.LONETILDE]+"\\s+";Se[a.TILDETRIM]=new RegExp(p[a.TILDETRIM],"g");y[a.TILDETRIM]=new RegExp(Me(p[a.TILDETRIM]),"g");var Ti="$1~";f("TILDE");p[a.TILDE]="^"+p[a.LONETILDE]+p[a.XRANGEPLAIN]+"$";f("TILDELOOSE");p[a.TILDELOOSE]="^"+p[a.LONETILDE]+p[a.XRANGEPLAINLOOSE]+"$";f("LONECARET");p[a.LONECARET]="(?:\\^)";f("CARETTRIM");p[a.CARETTRIM]="(\\s*)"+p[a.LONECARET]+"\\s+";Se[a.CARETTRIM]=new RegExp(p[a.CARETTRIM],"g");y[a.CARETTRIM]=new RegExp(Me(p[a.CARETTRIM]),"g");var xi="$1^";f("CARET");p[a.CARET]="^"+p[a.LONECARET]+p[a.XRANGEPLAIN]+"$";f("CARETLOOSE");p[a.CARETLOOSE]="^"+p[a.LONECARET]+p[a.XRANGEPLAINLOOSE]+"$";f("COMPARATORLOOSE");p[a.COMPARATORLOOSE]="^"+p[a.GTLT]+"\\s*("+p[a.LOOSEPLAIN]+")$|^$";f("COMPARATOR");p[a.COMPARATOR]="^"+p[a.GTLT]+"\\s*("+p[a.FULLPLAIN]+")$|^$";f("COMPARATORTRIM");p[a.COMPARATORTRIM]="(\\s*)"+p[a.GTLT]+"\\s*("+p[a.LOOSEPLAIN]+"|"+p[a.XRANGEPLAIN]+")";Se[a.COMPARATORTRIM]=new RegExp(p[a.COMPARATORTRIM],"g");y[a.COMPARATORTRIM]=new RegExp(Me(p[a.COMPARATORTRIM]),"g");var Oi="$1$2$3";f("HYPHENRANGE");p[a.HYPHENRANGE]="^\\s*("+p[a.XRANGEPLAIN]+")\\s+-\\s+("+p[a.XRANGEPLAIN]+")\\s*$";f("HYPHENRANGELOOSE");p[a.HYPHENRANGELOOSE]="^\\s*("+p[a.XRANGEPLAINLOOSE]+")\\s+-\\s+("+p[a.XRANGEPLAINLOOSE]+")\\s*$";f("STAR");p[a.STAR]="(<|>)?=?\\s*\\*";for(X=0;X<zr;X++)g(X,p[X]),Se[X]||(Se[X]=new RegExp(p[X]),y[X]=new RegExp(Me(p[X])));var X;u.parse=de;function de(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m)return e;if(typeof e!="string"||e.length>ke)return null;var r=t.loose?y[a.LOOSE]:y[a.FULL];if(!r.test(e))return null;try{return new m(e,t)}catch{return null}}u.valid=Ni;function Ni(e,t){var r=de(e,t);return r?r.version:null}u.clean=_i;function _i(e,t){var r=de(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}u.SemVer=m;function m(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m){if(e.loose===t.loose)return e;e=e.version}else if(typeof e!="string")throw new TypeError("Invalid Version: "+e);if(e.length>ke)throw new TypeError("version is longer than "+ke+" characters");if(!(this instanceof m))return new m(e,t);g("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?y[a.LOOSE]:y[a.FULL]);if(!r)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Qe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Qe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Qe||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(function(o){if(/^[0-9]+$/.test(o)){var n=+o;if(n>=0&&n<Qe)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}m.prototype.format=function(){return this.version=this.major+"."+this.minor+"."+this.patch,this.prerelease.length&&(this.version+="-"+this.prerelease.join(".")),this.version};m.prototype.toString=function(){return this.version};m.prototype.compare=function(e){return g("SemVer.compare",this.version,this.options,e),e instanceof m||(e=new m(e,this.options)),this.compareMain(e)||this.comparePre(e)};m.prototype.compareMain=function(e){return e instanceof m||(e=new m(e,this.options)),pe(this.major,e.major)||pe(this.minor,e.minor)||pe(this.patch,e.patch)};m.prototype.comparePre=function(e){if(e instanceof m||(e=new m(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;var t=0;do{var r=this.prerelease[t],o=e.prerelease[t];if(g("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return pe(r,o)}while(++t)};m.prototype.compareBuild=function(e){e instanceof m||(e=new m(e,this.options));var t=0;do{var r=this.build[t],o=e.build[t];if(g("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return pe(r,o)}while(++t)};m.prototype.inc=function(e,t){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t),this.inc("pre",t);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t),this.inc("pre",t);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":if(this.prerelease.length===0)this.prerelease=[0];else{for(var r=this.prerelease.length;--r>=0;)typeof this.prerelease[r]=="number"&&(this.prerelease[r]++,r=-2);r===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this};u.inc=Di;function Di(e,t,r,o){typeof r=="string"&&(o=r,r=void 0);try{return new m(e,r).inc(t,o).version}catch{return null}}u.diff=Hi;function Hi(e,t){if(Gt(e,t))return null;var r=de(e),o=de(t),n="";if(r.prerelease.length||o.prerelease.length){n="pre";var i="prerelease"}for(var c in r)if((c==="major"||c==="minor"||c==="patch")&&r[c]!==o[c])return n+c;return i}u.compareIdentifiers=pe;var Vr=/^[0-9]+$/;function pe(e,t){var r=Vr.test(e),o=Vr.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1}u.rcompareIdentifiers=Ki;function Ki(e,t){return pe(t,e)}u.major=ki;function ki(e,t){return new m(e,t).major}u.minor=Li;function Li(e,t){return new m(e,t).minor}u.patch=Mi;function Mi(e,t){return new m(e,t).patch}u.compare=re;function re(e,t,r){return new m(e,r).compare(new m(t,r))}u.compareLoose=Wi;function Wi(e,t){return re(e,t,!0)}u.compareBuild=Ui;function Ui(e,t,r){var o=new m(e,r),n=new m(t,r);return o.compare(n)||o.compareBuild(n)}u.rcompare=Ji;function Ji(e,t,r){return re(t,e,r)}u.sort=$i;function $i(e,t){return e.sort(function(r,o){return u.compareBuild(r,o,t)})}u.rsort=Fi;function Fi(e,t){return e.sort(function(r,o){return u.compareBuild(o,r,t)})}u.gt=Le;function Le(e,t,r){return re(e,t,r)>0}u.lt=et;function et(e,t,r){return re(e,t,r)<0}u.eq=Gt;function Gt(e,t,r){return re(e,t,r)===0}u.neq=qr;function qr(e,t,r){return re(e,t,r)!==0}u.gte=jt;function jt(e,t,r){return re(e,t,r)>=0}u.lte=Vt;function Vt(e,t,r){return re(e,t,r)<=0}u.cmp=tt;function tt(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 Gt(e,r,o);case"!=":return qr(e,r,o);case">":return Le(e,r,o);case">=":return jt(e,r,o);case"<":return et(e,r,o);case"<=":return Vt(e,r,o);default:throw new TypeError("Invalid operator: "+t)}}u.Comparator=J;function J(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof J){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof J))return new J(e,t);e=e.trim().split(/\s+/).join(" "),g("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ae?this.value="":this.value=this.operator+this.semver.version,g("comp",this)}var Ae={};J.prototype.parse=function(e){var t=this.options.loose?y[a.COMPARATORLOOSE]:y[a.COMPARATOR],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new m(r[2],this.options.loose):this.semver=Ae};J.prototype.toString=function(){return this.value};J.prototype.test=function(e){if(g("Comparator.test",e,this.options.loose),this.semver===Ae||e===Ae)return!0;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}return tt(e,this.operator,this.semver,this.options)};J.prototype.intersects=function(e,t){if(!(e instanceof J))throw new TypeError("a Comparator is required");(!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1});var r;if(this.operator==="")return this.value===""?!0:(r=new C(e.value,t),rt(this.value,r,t));if(e.operator==="")return e.value===""?!0:(r=new C(this.value,t),rt(e.semver,r,t));var o=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),n=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),i=this.semver.version===e.semver.version,c=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),d=tt(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=tt(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return o||n||i&&c||d||l};u.Range=C;function C(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof C)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new C(e.raw,t);if(e instanceof J)return new C(e.value,t);if(!(this instanceof C))return new C(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map(function(r){return this.parseRange(r.trim())},this).filter(function(r){return r.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+this.raw);this.format()}C.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range};C.prototype.toString=function(){return this.range};C.prototype.parseRange=function(e){var t=this.options.loose,r=t?y[a.HYPHENRANGELOOSE]:y[a.HYPHENRANGE];e=e.replace(r,Qi),g("hyphen replace",e),e=e.replace(y[a.COMPARATORTRIM],Oi),g("comparator trim",e,y[a.COMPARATORTRIM]),e=e.replace(y[a.TILDETRIM],Ti),e=e.replace(y[a.CARETTRIM],xi),e=e.split(/\s+/).join(" ");var o=t?y[a.COMPARATORLOOSE]:y[a.COMPARATOR],n=e.split(" ").map(function(i){return Gi(i,this.options)},this).join(" ").split(/\s+/);return this.options.loose&&(n=n.filter(function(i){return!!i.match(o)})),n=n.map(function(i){return new J(i,this.options)},this),n};C.prototype.intersects=function(e,t){if(!(e instanceof C))throw new TypeError("a Range is required");return this.set.some(function(r){return Xr(r,t)&&e.set.some(function(o){return Xr(o,t)&&r.every(function(n){return o.every(function(i){return n.intersects(i,t)})})})})};function Xr(e,t){for(var r=!0,o=e.slice(),n=o.pop();r&&o.length;)r=o.every(function(i){return n.intersects(i,t)}),n=o.pop();return r}u.toComparators=Bi;function Bi(e,t){return new C(e,t).set.map(function(r){return r.map(function(o){return o.value}).join(" ").trim().split(" ")})}function Gi(e,t){return g("comp",e,t),e=Xi(e,t),g("caret",e),e=ji(e,t),g("tildes",e),e=qi(e,t),g("xrange",e),e=Zi(e,t),g("stars",e),e}function O(e){return!e||e.toLowerCase()==="x"||e==="*"}function ji(e,t){return e.trim().split(/\s+/).map(function(r){return Vi(r,t)}).join(" ")}function Vi(e,t){var r=t.loose?y[a.TILDELOOSE]:y[a.TILDE];return e.replace(r,function(o,n,i,c,d){g("tilde",e,o,n,i,c,d);var l;return O(n)?l="":O(i)?l=">="+n+".0.0 <"+(+n+1)+".0.0":O(c)?l=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":d?(g("replaceTilde pr",d),l=">="+n+"."+i+"."+c+"-"+d+" <"+n+"."+(+i+1)+".0"):l=">="+n+"."+i+"."+c+" <"+n+"."+(+i+1)+".0",g("tilde return",l),l})}function Xi(e,t){return e.trim().split(/\s+/).map(function(r){return zi(r,t)}).join(" ")}function zi(e,t){g("caret",e,t);var r=t.loose?y[a.CARETLOOSE]:y[a.CARET];return e.replace(r,function(o,n,i,c,d){g("caret",e,o,n,i,c,d);var l;return O(n)?l="":O(i)?l=">="+n+".0.0 <"+(+n+1)+".0.0":O(c)?n==="0"?l=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+".0 <"+(+n+1)+".0.0":d?(g("replaceCaret pr",d),n==="0"?i==="0"?l=">="+n+"."+i+"."+c+"-"+d+" <"+n+"."+i+"."+(+c+1):l=">="+n+"."+i+"."+c+"-"+d+" <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+"."+c+"-"+d+" <"+(+n+1)+".0.0"):(g("no pr"),n==="0"?i==="0"?l=">="+n+"."+i+"."+c+" <"+n+"."+i+"."+(+c+1):l=">="+n+"."+i+"."+c+" <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+"."+c+" <"+(+n+1)+".0.0"),g("caret return",l),l})}function qi(e,t){return g("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return Yi(r,t)}).join(" ")}function Yi(e,t){e=e.trim();var r=t.loose?y[a.XRANGELOOSE]:y[a.XRANGE];return e.replace(r,function(o,n,i,c,d,l){g("xRange",e,o,n,i,c,d,l);var w=O(i),A=w||O(c),b=A||O(d),T=b;return n==="="&&T&&(n=""),l=t.includePrerelease?"-0":"",w?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&T?(A&&(c=0),d=0,n===">"?(n=">=",A?(i=+i+1,c=0,d=0):(c=+c+1,d=0)):n==="<="&&(n="<",A?i=+i+1:c=+c+1),o=n+i+"."+c+"."+d+l):A?o=">="+i+".0.0"+l+" <"+(+i+1)+".0.0"+l:b&&(o=">="+i+"."+c+".0"+l+" <"+i+"."+(+c+1)+".0"+l),g("xRange return",o),o})}function Zi(e,t){return g("replaceStars",e,t),e.trim().replace(y[a.STAR],"")}function Qi(e,t,r,o,n,i,c,d,l,w,A,b,T){return O(r)?t="":O(o)?t=">="+r+".0.0":O(n)?t=">="+r+"."+o+".0":t=">="+t,O(l)?d="":O(w)?d="<"+(+l+1)+".0.0":O(A)?d="<"+l+"."+(+w+1)+".0":b?d="<="+l+"."+w+"."+A+"-"+b:d="<="+d,(t+" "+d).trim()}C.prototype.test=function(e){if(!e)return!1;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}for(var t=0;t<this.set.length;t++)if(ea(this.set[t],e,this.options))return!0;return!1};function ea(e,t,r){for(var o=0;o<e.length;o++)if(!e[o].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(o=0;o<e.length;o++)if(g(e[o].semver),e[o].semver!==Ae&&e[o].semver.prerelease.length>0){var n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}u.satisfies=rt;function rt(e,t,r){try{t=new C(t,r)}catch{return!1}return t.test(e)}u.maxSatisfying=ta;function ta(e,t,r){var o=null,n=null;try{var i=new C(t,r)}catch{return null}return e.forEach(function(c){i.test(c)&&(!o||n.compare(c)===-1)&&(o=c,n=new m(o,r))}),o}u.minSatisfying=ra;function ra(e,t,r){var o=null,n=null;try{var i=new C(t,r)}catch{return null}return e.forEach(function(c){i.test(c)&&(!o||n.compare(c)===1)&&(o=c,n=new m(o,r))}),o}u.minVersion=oa;function oa(e,t){e=new C(e,t);var r=new m("0.0.0");if(e.test(r)||(r=new m("0.0.0-0"),e.test(r)))return r;r=null;for(var o=0;o<e.set.length;++o){var n=e.set[o];n.forEach(function(i){var c=new m(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!r||Le(r,c))&&(r=c);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+i.operator)}})}return r&&e.test(r)?r:null}u.validRange=na;function na(e,t){try{return new C(e,t).range||"*"}catch{return null}}u.ltr=ia;function ia(e,t,r){return Xt(e,t,"<",r)}u.gtr=aa;function aa(e,t,r){return Xt(e,t,">",r)}u.outside=Xt;function Xt(e,t,r,o){e=new m(e,o),t=new C(t,o);var n,i,c,d,l;switch(r){case">":n=Le,i=Vt,c=et,d=">",l=">=";break;case"<":n=et,i=jt,c=Le,d="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(rt(e,t,o))return!1;for(var w=0;w<t.set.length;++w){var A=t.set[w],b=null,T=null;if(A.forEach(function(K){K.semver===Ae&&(K=new J(">=0.0.0")),b=b||K,T=T||K,n(K.semver,b.semver,o)?b=K:c(K.semver,T.semver,o)&&(T=K)}),b.operator===d||b.operator===l||(!T.operator||T.operator===d)&&i(e,T.semver))return!1;if(T.operator===l&&c(e,T.semver))return!1}return!0}u.prerelease=sa;function sa(e,t){var r=de(e,t);return r&&r.prerelease.length?r.prerelease:null}u.intersects=ca;function ca(e,t,r){return e=new C(e,r),t=new C(t,r),e.intersects(t)}u.coerce=pa;function pa(e,t){if(e instanceof m)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};var r=null;if(!t.rtl)r=e.match(y[a.COERCE]);else{for(var o;(o=y[a.COERCERTL].exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||o.index+o[0].length!==r.index+r[0].length)&&(r=o),y[a.COERCERTL].lastIndex=o.index+o[1].length+o[2].length;y[a.COERCERTL].lastIndex=-1}return r===null?null:de(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}});var za={};In(za,{main:()=>yn,run:()=>gn});module.exports=Pn(za);var bt=require("@medplum/core"),fn=require("commander"),hn=N(require("dotenv"));var B=require("@medplum/core"),$r=require("child_process"),Fr=require("http"),Br=require("os");var ur=require("@medplum/core");var dr=require("@medplum/core"),z=require("fs"),lr=require("os"),vt=require("path"),j=class extends dr.ClientStorage{constructor(t){super(),this.dirName=(0,vt.resolve)((0,lr.homedir)(),".medplum"),this.fileName=(0,vt.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,z.existsSync)(this.fileName))return JSON.parse((0,z.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,z.existsSync)(this.dirName)||(0,z.mkdirSync)(this.dirName),(0,z.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function S(e,t=!0){let r=e.profile??"default",o=new j(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:c,accessToken:d,tokenUrl:l,authorizeUrl:w,clientId:A,clientSecret:b}=Rn(e,o),T=e.fetch??fetch,K=new ur.MedplumClient({fetch:T,baseUrl:i,tokenUrl:l,fhirUrlPath:c,authorizeUrl:w,storage:o,onUnauthenticated:Tn,verbose:e.verbose});return t&&(d?K.setAccessToken(d):A&&b&&(K.setBasicAuth(A,b),n?.authType!=="basic"&&await K.startClientLogin(A,b))),K}function Rn(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,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,c=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,d=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,w=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:i,tokenUrl:c,authorizeUrl:d,clientId:l,clientSecret:w}}function Tn(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Fe=require("commander");function h(e){return new Fe.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 Fe.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var ce=require("@medplum/core"),Ee=require("crypto"),ie=require("fs");var mr=require("buffer");var k=new TextEncoder,_=new TextDecoder,ns=2**32;function F(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var L=e=>mr.Buffer.from(e).toString("base64url");var fe=class extends Error{constructor(r){super(r);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}static get code(){return"ERR_JOSE_GENERIC"}};var E=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var M=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},ne=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var hr=N(require("util"),1),W=e=>hr.types.isKeyObject(e);var yr=N(require("crypto"),1),gr=N(require("util"),1),Nn=yr.webcrypto,wr=Nn,D=e=>gr.types.isCryptoKey(e);function Y(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Be(e,t){return e.name===t}function It(e){return parseInt(e.name.slice(4),10)}function _n(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Dn(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 Er(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Be(e.algorithm,"HMAC"))throw Y("HMAC");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Be(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Y("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Be(e.algorithm,"RSA-PSS"))throw Y("RSA-PSS");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw Y("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Be(e.algorithm,"ECDSA"))throw Y("ECDSA");let o=_n(t);if(e.algorithm.namedCurve!==o)throw Y(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Dn(e,r)}function Sr(e,t,...r){if(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 U=(e,...t)=>Sr("Key must be ",e,...t);function Pt(e,t,...r){return Sr(`Key for the ${e} algorithm must be `,t,...r)}var Rt=e=>W(e)||D(e),v=["KeyObject"];(globalThis.CryptoKey||wr?.CryptoKey)&&v.push("CryptoKey");var Mn=(...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 i of n){if(r.has(i))return!1;r.add(i)}}return!0},he=Mn;function Wn(e){return typeof e=="object"&&e!==null}function x(e){if(!Wn(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 Ge=require("crypto"),vr=require("util");var br=require("crypto");var Un=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 E("Unsupported key curve for this operation")}},Jn=(e,t)=>{let r;if(D(e))r=br.KeyObject.from(e);else if(W(e))r=e;else throw new TypeError(U(e,...v));if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return t?o:Un(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Tt=Jn;var Ec=(0,vr.promisify)(Ge.generateKeyPair);var Ir=require("util"),xt=require("crypto");var Hc=(0,Ir.promisify)(xt.pbkdf2);var xe=require("crypto"),Pr=require("util");var je=(e,t)=>{let{modulusLength:r}=e.asymmetricKeyDetails;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var Fc=(0,Pr.deprecate)(()=>xe.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var Bn=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Rt(t))throw new TypeError(Pt(e,t,...v,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${v.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Gn=(e,t,r)=>{if(!Rt(t))throw new TypeError(Pt(e,t,...v));if(t.type==="secret")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},jn=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Bn(e,t):Gn(e,t,r)},Ne=jn;function Zn(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(c=>typeof c!="string"||c.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let c of o.crit){if(!i.has(c))throw new E(`Extension Header Parameter "${c}" is not recognized`);if(n[c]===void 0)throw new e(`Extension Header Parameter "${c}" is missing`);if(i.get(c)&&o[c]===void 0)throw new e(`Extension Header Parameter "${c}" MUST be integrity protected`)}return new Set(o.crit)}var ye=Zn;var oi=Symbol();var Ht=N(require("crypto"),1),Nr=require("util");function Ve(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 E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Nt=require("crypto");var ni={padding:Nt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Nt.constants.RSA_PSS_SALTLEN_DIGEST},ii=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Xe(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return je(t,e),t;case"PS256":case"PS384":case"PS512":if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,i=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${i}`||o!==r))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>i>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return je(t,e),{key:t,...ni};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=Tt(t),o=ii.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var qe=N(require("crypto"),1),Or=require("util");function _t(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var _e=require("crypto");function ze(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(U(t,...v));return(0,_e.createSecretKey)(t)}if(t instanceof _e.KeyObject)return t;if(D(t))return Er(t,e,r),_e.KeyObject.from(t);throw new TypeError(U(t,...v,"Uint8Array"))}var ai=(0,Or.promisify)(qe.sign),si=async(e,t,r)=>{let o=ze(e,t,"sign");if(e.startsWith("HS")){let n=qe.createHmac(_t(e),o);return n.update(r),n.digest()}return ai(Ve(e),r,Xe(e,o))},Dt=si;var Tl=(0,Nr.promisify)(Ht.verify);var Z=e=>Math.floor(e.getTime()/1e3);var pi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,De=e=>{let t=pi.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 ge=class{constructor(t){P(this,"_payload");P(this,"_protectedHeader");P(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new M("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!he(this._protectedHeader,this._unprotectedHeader))throw new M("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=ye(M,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),i=!0;if(n.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new M('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:c}=o;if(typeof c!="string"||!c)throw new M('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ne(c,t,"sign");let d=this._payload;i&&(d=k.encode(L(d)));let l;this._protectedHeader?l=k.encode(L(JSON.stringify(this._protectedHeader))):l=k.encode("");let w=F(l,k.encode("."),d),A=await Dt(c,t,w),b={signature:L(A),payload:""};return i&&(b.payload=_.decode(d)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=_.decode(l)),b}};var He=class{constructor(t){P(this,"_flattened");this._flattened=new ge(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function se(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var we=class{constructor(t={}){P(this,"_payload");if(!x(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:se("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:se("setNotBefore",Z(t))}:this._payload={...this._payload,nbf:Z(new Date)+De(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:se("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:se("setExpirationTime",Z(t))}:this._payload={...this._payload,exp:Z(new Date)+De(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:t instanceof Date?this._payload={...this._payload,iat:se("setIssuedAt",Z(t))}:typeof t=="string"?this._payload={...this._payload,iat:se("setIssuedAt",Z(new Date)+De(t))}:this._payload={...this._payload,iat:se("setIssuedAt",t)},this}};var Ke=class extends we{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new He(k.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 ne("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var yi;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(yi="jose/v5.2.4");var Kt=require("crypto"),Hr=require("util");var Lm=(0,Hr.promisify)(Kt.generateKeyPair);var Q=require("path"),Kr=N(require("tar"));function ee(e){console.log(JSON.stringify(e,null,2))}async function kt(e,t,r){let o=t.source,n=Ye(o);if(n)try{console.log("Saving source code...");let i=await e.createAttachment(n,(0,Q.basename)(o),Ai(o));console.log("Updating bot.....");let c=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+c.meta?.versionId)}catch(i){console.log("Update error: ",i)}}async function Lt(e,t,r){let o=t.dist??t.source,n=Ye(o);if(n)try{console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,Q.basename)(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}catch(i){console.log("Deploy error: ",i)}}async function Mt(e,t,r,o,n,i,c){try{let d={name:t,description:"",runtimeVersion:i},l=await e.post("admin/projects/"+r+"/bot",d),w=await e.readResource("Bot",l.id),A={name:t,id:l.id,source:o,dist:n};await kt(e,A,w),await Lt(e,A,w),console.log(`Success! Bot created: ${w.id}`),c&&Ei(A)}catch(d){console.log("Error while creating new bot: "+d)}}function kr(e){let t=new RegExp("^"+Si(e).replace(/\\\*/g,".*")+"$"),r=V()?.bots?.filter(o=>t.test(o.name));return r||[]}function te(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 R(e,t){(0,ie.writeFileSync)((0,Q.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function V(e,t){let r=te(e,t),o=Ye(r);if(o)return JSON.parse(o)}function Lr(e){let t=Ye(te(e,{server:!0}));if(t)return JSON.parse(t)}function Ye(e){let t=(0,Q.resolve)(e);return(0,ie.existsSync)(t)?(0,ie.readFileSync)(t,"utf8"):""}function Ei(e){let t=V()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ie.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Si(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Mr(e){let o=0,n=0;return Kr.default.x({cwd:e,filter:(i,c)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=c.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Wt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Ai(e){let t=(0,Q.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?ce.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?ce.ContentType.TYPESCRIPT:ce.ContentType.TEXT}function Ze(e,t){let r=new j(e),o={name:e,...t};return r.setObject("options",o),o}function Wr(e){return new j(e).getObject("options")}async function Ur(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},i=(0,ce.encodeBase64)(JSON.stringify(r)),c=(0,ce.encodeBase64)(JSON.stringify(n)),d=`${i}.${c}`,l=(0,Ee.createHmac)("sha256",t.clientSecret).update(d).digest("base64url"),w=`${d}.${l}`;await e.startJwtBearerLogin(t.clientId,w,t.scope??"")}async function Jr(e,t){let r=(0,Ee.createPrivateKey)((0,ie.readFileSync)((0,Q.resolve)(t.privateKeyPath))),o=await new Ke({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,Ee.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Gr=B.MEDPLUM_CLI_CLIENT_ID,jr="http://localhost:9615",Ut=h("login"),Jt=h("whoami");Ut.action(async e=>{let t=e.profile??"default",r=Ze(t,e),o=await S(e,!1);await bi(o,r)});Jt.action(async e=>{let t=await S(e);Ii(t)});async function bi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Pi(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 Ur(e,t);break;case"jwt-assertion":await Jr(e,t);break}}async function vi(e){let t=(0,Fr.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),i=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":B.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let c=await e.processCode(i,{clientId:Gr,redirectUri:jr});o.writeHead(200,{"Content-Type":B.ContentType.TEXT}),o.end(`Signed in as ${(0,B.getDisplayString)(c)}. You may close this window.`)}catch(c){o.writeHead(400,{"Content-Type":B.ContentType.TEXT}),o.end(`Error: ${(0,B.normalizeErrorString)(c)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":B.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function Ci(e){let t=(0,Br.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,$r.exec)(r)}function Ii(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 Pi(e){await vi(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Gr),t.searchParams.set("redirect_uri",jr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Ci(t.toString())}var Po=require("commander");var oe=require("@aws-sdk/client-cloudformation"),ct=require("@aws-sdk/client-cloudfront"),eo=require("@aws-sdk/client-ecs"),to=require("@aws-sdk/client-s3"),ve=require("@aws-sdk/client-ssm"),pt=require("@aws-sdk/client-sts"),ro=require("@medplum/core"),oo=require("fs"),no=N(require("node-fetch")),io=N(zt());var Zr=N(require("readline")),ot;function nt(){ot=Zr.default.createInterface({input:process.stdin,output:process.stdout})}function it(){ot.close()}function s(e){ot.write(e+`
|
|
2
|
+
"use strict";var wn=Object.create;var Re=Object.defineProperty;var En=Object.getOwnPropertyDescriptor;var Sn=Object.getOwnPropertyNames;var An=Object.getPrototypeOf,bn=Object.prototype.hasOwnProperty;var vn=(e,t,r)=>t in e?Re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Cn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),In=(e,t)=>{for(var r in t)Re(e,r,{get:t[r],enumerable:!0})},pr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Sn(t))!bn.call(e,n)&&n!==r&&Re(e,n,{get:()=>t[n],enumerable:!(o=En(t,n))||o.enumerable});return e};var K=(e,t,r)=>(r=e!=null?wn(An(e)):{},pr(t||!e||!e.__esModule?Re(r,"default",{value:e,enumerable:!0}):r,e)),Pn=e=>pr(Re({},"__esModule",{value:!0}),e);var P=(e,t,r)=>(vn(e,typeof t!="symbol"?t+"":t,r),r);var zt=Cn((u,Yr)=>{"use strict";u=Yr.exports=m;var g;typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?g=function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:g=function(){};u.SEMVER_SPEC_VERSION="2.0.0";var ke=256,Qe=Number.MAX_SAFE_INTEGER||9007199254740991,$t=16,Ri=ke-6,Se=u.re=[],y=u.safeRe=[],p=u.src=[],a=u.tokens={},zr=0;function f(e){a[e]=zr++}var Bt="[a-zA-Z0-9-]",Ft=[["\\s",1],["\\d",ke],[Bt,Ri]];function Me(e){for(var t=0;t<Ft.length;t++){var r=Ft[t][0],o=Ft[t][1];e=e.split(r+"*").join(r+"{0,"+o+"}").split(r+"+").join(r+"{1,"+o+"}")}return e}f("NUMERICIDENTIFIER");p[a.NUMERICIDENTIFIER]="0|[1-9]\\d*";f("NUMERICIDENTIFIERLOOSE");p[a.NUMERICIDENTIFIERLOOSE]="\\d+";f("NONNUMERICIDENTIFIER");p[a.NONNUMERICIDENTIFIER]="\\d*[a-zA-Z-]"+Bt+"*";f("MAINVERSION");p[a.MAINVERSION]="("+p[a.NUMERICIDENTIFIER]+")\\.("+p[a.NUMERICIDENTIFIER]+")\\.("+p[a.NUMERICIDENTIFIER]+")";f("MAINVERSIONLOOSE");p[a.MAINVERSIONLOOSE]="("+p[a.NUMERICIDENTIFIERLOOSE]+")\\.("+p[a.NUMERICIDENTIFIERLOOSE]+")\\.("+p[a.NUMERICIDENTIFIERLOOSE]+")";f("PRERELEASEIDENTIFIER");p[a.PRERELEASEIDENTIFIER]="(?:"+p[a.NUMERICIDENTIFIER]+"|"+p[a.NONNUMERICIDENTIFIER]+")";f("PRERELEASEIDENTIFIERLOOSE");p[a.PRERELEASEIDENTIFIERLOOSE]="(?:"+p[a.NUMERICIDENTIFIERLOOSE]+"|"+p[a.NONNUMERICIDENTIFIER]+")";f("PRERELEASE");p[a.PRERELEASE]="(?:-("+p[a.PRERELEASEIDENTIFIER]+"(?:\\."+p[a.PRERELEASEIDENTIFIER]+")*))";f("PRERELEASELOOSE");p[a.PRERELEASELOOSE]="(?:-?("+p[a.PRERELEASEIDENTIFIERLOOSE]+"(?:\\."+p[a.PRERELEASEIDENTIFIERLOOSE]+")*))";f("BUILDIDENTIFIER");p[a.BUILDIDENTIFIER]=Bt+"+";f("BUILD");p[a.BUILD]="(?:\\+("+p[a.BUILDIDENTIFIER]+"(?:\\."+p[a.BUILDIDENTIFIER]+")*))";f("FULL");f("FULLPLAIN");p[a.FULLPLAIN]="v?"+p[a.MAINVERSION]+p[a.PRERELEASE]+"?"+p[a.BUILD]+"?";p[a.FULL]="^"+p[a.FULLPLAIN]+"$";f("LOOSEPLAIN");p[a.LOOSEPLAIN]="[v=\\s]*"+p[a.MAINVERSIONLOOSE]+p[a.PRERELEASELOOSE]+"?"+p[a.BUILD]+"?";f("LOOSE");p[a.LOOSE]="^"+p[a.LOOSEPLAIN]+"$";f("GTLT");p[a.GTLT]="((?:<|>)?=?)";f("XRANGEIDENTIFIERLOOSE");p[a.XRANGEIDENTIFIERLOOSE]=p[a.NUMERICIDENTIFIERLOOSE]+"|x|X|\\*";f("XRANGEIDENTIFIER");p[a.XRANGEIDENTIFIER]=p[a.NUMERICIDENTIFIER]+"|x|X|\\*";f("XRANGEPLAIN");p[a.XRANGEPLAIN]="[v=\\s]*("+p[a.XRANGEIDENTIFIER]+")(?:\\.("+p[a.XRANGEIDENTIFIER]+")(?:\\.("+p[a.XRANGEIDENTIFIER]+")(?:"+p[a.PRERELEASE]+")?"+p[a.BUILD]+"?)?)?";f("XRANGEPLAINLOOSE");p[a.XRANGEPLAINLOOSE]="[v=\\s]*("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:"+p[a.PRERELEASELOOSE]+")?"+p[a.BUILD]+"?)?)?";f("XRANGE");p[a.XRANGE]="^"+p[a.GTLT]+"\\s*"+p[a.XRANGEPLAIN]+"$";f("XRANGELOOSE");p[a.XRANGELOOSE]="^"+p[a.GTLT]+"\\s*"+p[a.XRANGEPLAINLOOSE]+"$";f("COERCE");p[a.COERCE]="(^|[^\\d])(\\d{1,"+$t+"})(?:\\.(\\d{1,"+$t+"}))?(?:\\.(\\d{1,"+$t+"}))?(?:$|[^\\d])";f("COERCERTL");Se[a.COERCERTL]=new RegExp(p[a.COERCE],"g");y[a.COERCERTL]=new RegExp(Me(p[a.COERCE]),"g");f("LONETILDE");p[a.LONETILDE]="(?:~>?)";f("TILDETRIM");p[a.TILDETRIM]="(\\s*)"+p[a.LONETILDE]+"\\s+";Se[a.TILDETRIM]=new RegExp(p[a.TILDETRIM],"g");y[a.TILDETRIM]=new RegExp(Me(p[a.TILDETRIM]),"g");var Ti="$1~";f("TILDE");p[a.TILDE]="^"+p[a.LONETILDE]+p[a.XRANGEPLAIN]+"$";f("TILDELOOSE");p[a.TILDELOOSE]="^"+p[a.LONETILDE]+p[a.XRANGEPLAINLOOSE]+"$";f("LONECARET");p[a.LONECARET]="(?:\\^)";f("CARETTRIM");p[a.CARETTRIM]="(\\s*)"+p[a.LONECARET]+"\\s+";Se[a.CARETTRIM]=new RegExp(p[a.CARETTRIM],"g");y[a.CARETTRIM]=new RegExp(Me(p[a.CARETTRIM]),"g");var xi="$1^";f("CARET");p[a.CARET]="^"+p[a.LONECARET]+p[a.XRANGEPLAIN]+"$";f("CARETLOOSE");p[a.CARETLOOSE]="^"+p[a.LONECARET]+p[a.XRANGEPLAINLOOSE]+"$";f("COMPARATORLOOSE");p[a.COMPARATORLOOSE]="^"+p[a.GTLT]+"\\s*("+p[a.LOOSEPLAIN]+")$|^$";f("COMPARATOR");p[a.COMPARATOR]="^"+p[a.GTLT]+"\\s*("+p[a.FULLPLAIN]+")$|^$";f("COMPARATORTRIM");p[a.COMPARATORTRIM]="(\\s*)"+p[a.GTLT]+"\\s*("+p[a.LOOSEPLAIN]+"|"+p[a.XRANGEPLAIN]+")";Se[a.COMPARATORTRIM]=new RegExp(p[a.COMPARATORTRIM],"g");y[a.COMPARATORTRIM]=new RegExp(Me(p[a.COMPARATORTRIM]),"g");var Oi="$1$2$3";f("HYPHENRANGE");p[a.HYPHENRANGE]="^\\s*("+p[a.XRANGEPLAIN]+")\\s+-\\s+("+p[a.XRANGEPLAIN]+")\\s*$";f("HYPHENRANGELOOSE");p[a.HYPHENRANGELOOSE]="^\\s*("+p[a.XRANGEPLAINLOOSE]+")\\s+-\\s+("+p[a.XRANGEPLAINLOOSE]+")\\s*$";f("STAR");p[a.STAR]="(<|>)?=?\\s*\\*";for(X=0;X<zr;X++)g(X,p[X]),Se[X]||(Se[X]=new RegExp(p[X]),y[X]=new RegExp(Me(p[X])));var X;u.parse=de;function de(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m)return e;if(typeof e!="string"||e.length>ke)return null;var r=t.loose?y[a.LOOSE]:y[a.FULL];if(!r.test(e))return null;try{return new m(e,t)}catch{return null}}u.valid=Ni;function Ni(e,t){var r=de(e,t);return r?r.version:null}u.clean=_i;function _i(e,t){var r=de(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}u.SemVer=m;function m(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m){if(e.loose===t.loose)return e;e=e.version}else if(typeof e!="string")throw new TypeError("Invalid Version: "+e);if(e.length>ke)throw new TypeError("version is longer than "+ke+" characters");if(!(this instanceof m))return new m(e,t);g("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?y[a.LOOSE]:y[a.FULL]);if(!r)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Qe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Qe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Qe||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(function(o){if(/^[0-9]+$/.test(o)){var n=+o;if(n>=0&&n<Qe)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}m.prototype.format=function(){return this.version=this.major+"."+this.minor+"."+this.patch,this.prerelease.length&&(this.version+="-"+this.prerelease.join(".")),this.version};m.prototype.toString=function(){return this.version};m.prototype.compare=function(e){return g("SemVer.compare",this.version,this.options,e),e instanceof m||(e=new m(e,this.options)),this.compareMain(e)||this.comparePre(e)};m.prototype.compareMain=function(e){return e instanceof m||(e=new m(e,this.options)),pe(this.major,e.major)||pe(this.minor,e.minor)||pe(this.patch,e.patch)};m.prototype.comparePre=function(e){if(e instanceof m||(e=new m(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;var t=0;do{var r=this.prerelease[t],o=e.prerelease[t];if(g("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return pe(r,o)}while(++t)};m.prototype.compareBuild=function(e){e instanceof m||(e=new m(e,this.options));var t=0;do{var r=this.build[t],o=e.build[t];if(g("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return pe(r,o)}while(++t)};m.prototype.inc=function(e,t){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t),this.inc("pre",t);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t),this.inc("pre",t);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":if(this.prerelease.length===0)this.prerelease=[0];else{for(var r=this.prerelease.length;--r>=0;)typeof this.prerelease[r]=="number"&&(this.prerelease[r]++,r=-2);r===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this};u.inc=Di;function Di(e,t,r,o){typeof r=="string"&&(o=r,r=void 0);try{return new m(e,r).inc(t,o).version}catch{return null}}u.diff=Hi;function Hi(e,t){if(Gt(e,t))return null;var r=de(e),o=de(t),n="";if(r.prerelease.length||o.prerelease.length){n="pre";var i="prerelease"}for(var c in r)if((c==="major"||c==="minor"||c==="patch")&&r[c]!==o[c])return n+c;return i}u.compareIdentifiers=pe;var Vr=/^[0-9]+$/;function pe(e,t){var r=Vr.test(e),o=Vr.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1}u.rcompareIdentifiers=Ki;function Ki(e,t){return pe(t,e)}u.major=ki;function ki(e,t){return new m(e,t).major}u.minor=Li;function Li(e,t){return new m(e,t).minor}u.patch=Mi;function Mi(e,t){return new m(e,t).patch}u.compare=re;function re(e,t,r){return new m(e,r).compare(new m(t,r))}u.compareLoose=Wi;function Wi(e,t){return re(e,t,!0)}u.compareBuild=Ui;function Ui(e,t,r){var o=new m(e,r),n=new m(t,r);return o.compare(n)||o.compareBuild(n)}u.rcompare=Ji;function Ji(e,t,r){return re(t,e,r)}u.sort=$i;function $i(e,t){return e.sort(function(r,o){return u.compareBuild(r,o,t)})}u.rsort=Fi;function Fi(e,t){return e.sort(function(r,o){return u.compareBuild(o,r,t)})}u.gt=Le;function Le(e,t,r){return re(e,t,r)>0}u.lt=et;function et(e,t,r){return re(e,t,r)<0}u.eq=Gt;function Gt(e,t,r){return re(e,t,r)===0}u.neq=qr;function qr(e,t,r){return re(e,t,r)!==0}u.gte=jt;function jt(e,t,r){return re(e,t,r)>=0}u.lte=Vt;function Vt(e,t,r){return re(e,t,r)<=0}u.cmp=tt;function tt(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 Gt(e,r,o);case"!=":return qr(e,r,o);case">":return Le(e,r,o);case">=":return jt(e,r,o);case"<":return et(e,r,o);case"<=":return Vt(e,r,o);default:throw new TypeError("Invalid operator: "+t)}}u.Comparator=J;function J(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof J){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof J))return new J(e,t);e=e.trim().split(/\s+/).join(" "),g("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ae?this.value="":this.value=this.operator+this.semver.version,g("comp",this)}var Ae={};J.prototype.parse=function(e){var t=this.options.loose?y[a.COMPARATORLOOSE]:y[a.COMPARATOR],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new m(r[2],this.options.loose):this.semver=Ae};J.prototype.toString=function(){return this.value};J.prototype.test=function(e){if(g("Comparator.test",e,this.options.loose),this.semver===Ae||e===Ae)return!0;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}return tt(e,this.operator,this.semver,this.options)};J.prototype.intersects=function(e,t){if(!(e instanceof J))throw new TypeError("a Comparator is required");(!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1});var r;if(this.operator==="")return this.value===""?!0:(r=new C(e.value,t),rt(this.value,r,t));if(e.operator==="")return e.value===""?!0:(r=new C(this.value,t),rt(e.semver,r,t));var o=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),n=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),i=this.semver.version===e.semver.version,c=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),d=tt(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=tt(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return o||n||i&&c||d||l};u.Range=C;function C(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof C)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new C(e.raw,t);if(e instanceof J)return new C(e.value,t);if(!(this instanceof C))return new C(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map(function(r){return this.parseRange(r.trim())},this).filter(function(r){return r.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+this.raw);this.format()}C.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range};C.prototype.toString=function(){return this.range};C.prototype.parseRange=function(e){var t=this.options.loose,r=t?y[a.HYPHENRANGELOOSE]:y[a.HYPHENRANGE];e=e.replace(r,Qi),g("hyphen replace",e),e=e.replace(y[a.COMPARATORTRIM],Oi),g("comparator trim",e,y[a.COMPARATORTRIM]),e=e.replace(y[a.TILDETRIM],Ti),e=e.replace(y[a.CARETTRIM],xi),e=e.split(/\s+/).join(" ");var o=t?y[a.COMPARATORLOOSE]:y[a.COMPARATOR],n=e.split(" ").map(function(i){return Gi(i,this.options)},this).join(" ").split(/\s+/);return this.options.loose&&(n=n.filter(function(i){return!!i.match(o)})),n=n.map(function(i){return new J(i,this.options)},this),n};C.prototype.intersects=function(e,t){if(!(e instanceof C))throw new TypeError("a Range is required");return this.set.some(function(r){return Xr(r,t)&&e.set.some(function(o){return Xr(o,t)&&r.every(function(n){return o.every(function(i){return n.intersects(i,t)})})})})};function Xr(e,t){for(var r=!0,o=e.slice(),n=o.pop();r&&o.length;)r=o.every(function(i){return n.intersects(i,t)}),n=o.pop();return r}u.toComparators=Bi;function Bi(e,t){return new C(e,t).set.map(function(r){return r.map(function(o){return o.value}).join(" ").trim().split(" ")})}function Gi(e,t){return g("comp",e,t),e=Xi(e,t),g("caret",e),e=ji(e,t),g("tildes",e),e=qi(e,t),g("xrange",e),e=Zi(e,t),g("stars",e),e}function O(e){return!e||e.toLowerCase()==="x"||e==="*"}function ji(e,t){return e.trim().split(/\s+/).map(function(r){return Vi(r,t)}).join(" ")}function Vi(e,t){var r=t.loose?y[a.TILDELOOSE]:y[a.TILDE];return e.replace(r,function(o,n,i,c,d){g("tilde",e,o,n,i,c,d);var l;return O(n)?l="":O(i)?l=">="+n+".0.0 <"+(+n+1)+".0.0":O(c)?l=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":d?(g("replaceTilde pr",d),l=">="+n+"."+i+"."+c+"-"+d+" <"+n+"."+(+i+1)+".0"):l=">="+n+"."+i+"."+c+" <"+n+"."+(+i+1)+".0",g("tilde return",l),l})}function Xi(e,t){return e.trim().split(/\s+/).map(function(r){return zi(r,t)}).join(" ")}function zi(e,t){g("caret",e,t);var r=t.loose?y[a.CARETLOOSE]:y[a.CARET];return e.replace(r,function(o,n,i,c,d){g("caret",e,o,n,i,c,d);var l;return O(n)?l="":O(i)?l=">="+n+".0.0 <"+(+n+1)+".0.0":O(c)?n==="0"?l=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+".0 <"+(+n+1)+".0.0":d?(g("replaceCaret pr",d),n==="0"?i==="0"?l=">="+n+"."+i+"."+c+"-"+d+" <"+n+"."+i+"."+(+c+1):l=">="+n+"."+i+"."+c+"-"+d+" <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+"."+c+"-"+d+" <"+(+n+1)+".0.0"):(g("no pr"),n==="0"?i==="0"?l=">="+n+"."+i+"."+c+" <"+n+"."+i+"."+(+c+1):l=">="+n+"."+i+"."+c+" <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+"."+c+" <"+(+n+1)+".0.0"),g("caret return",l),l})}function qi(e,t){return g("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return Yi(r,t)}).join(" ")}function Yi(e,t){e=e.trim();var r=t.loose?y[a.XRANGELOOSE]:y[a.XRANGE];return e.replace(r,function(o,n,i,c,d,l){g("xRange",e,o,n,i,c,d,l);var w=O(i),A=w||O(c),b=A||O(d),T=b;return n==="="&&T&&(n=""),l=t.includePrerelease?"-0":"",w?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&T?(A&&(c=0),d=0,n===">"?(n=">=",A?(i=+i+1,c=0,d=0):(c=+c+1,d=0)):n==="<="&&(n="<",A?i=+i+1:c=+c+1),o=n+i+"."+c+"."+d+l):A?o=">="+i+".0.0"+l+" <"+(+i+1)+".0.0"+l:b&&(o=">="+i+"."+c+".0"+l+" <"+i+"."+(+c+1)+".0"+l),g("xRange return",o),o})}function Zi(e,t){return g("replaceStars",e,t),e.trim().replace(y[a.STAR],"")}function Qi(e,t,r,o,n,i,c,d,l,w,A,b,T){return O(r)?t="":O(o)?t=">="+r+".0.0":O(n)?t=">="+r+"."+o+".0":t=">="+t,O(l)?d="":O(w)?d="<"+(+l+1)+".0.0":O(A)?d="<"+l+"."+(+w+1)+".0":b?d="<="+l+"."+w+"."+A+"-"+b:d="<="+d,(t+" "+d).trim()}C.prototype.test=function(e){if(!e)return!1;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}for(var t=0;t<this.set.length;t++)if(ea(this.set[t],e,this.options))return!0;return!1};function ea(e,t,r){for(var o=0;o<e.length;o++)if(!e[o].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(o=0;o<e.length;o++)if(g(e[o].semver),e[o].semver!==Ae&&e[o].semver.prerelease.length>0){var n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}u.satisfies=rt;function rt(e,t,r){try{t=new C(t,r)}catch{return!1}return t.test(e)}u.maxSatisfying=ta;function ta(e,t,r){var o=null,n=null;try{var i=new C(t,r)}catch{return null}return e.forEach(function(c){i.test(c)&&(!o||n.compare(c)===-1)&&(o=c,n=new m(o,r))}),o}u.minSatisfying=ra;function ra(e,t,r){var o=null,n=null;try{var i=new C(t,r)}catch{return null}return e.forEach(function(c){i.test(c)&&(!o||n.compare(c)===1)&&(o=c,n=new m(o,r))}),o}u.minVersion=oa;function oa(e,t){e=new C(e,t);var r=new m("0.0.0");if(e.test(r)||(r=new m("0.0.0-0"),e.test(r)))return r;r=null;for(var o=0;o<e.set.length;++o){var n=e.set[o];n.forEach(function(i){var c=new m(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!r||Le(r,c))&&(r=c);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+i.operator)}})}return r&&e.test(r)?r:null}u.validRange=na;function na(e,t){try{return new C(e,t).range||"*"}catch{return null}}u.ltr=ia;function ia(e,t,r){return Xt(e,t,"<",r)}u.gtr=aa;function aa(e,t,r){return Xt(e,t,">",r)}u.outside=Xt;function Xt(e,t,r,o){e=new m(e,o),t=new C(t,o);var n,i,c,d,l;switch(r){case">":n=Le,i=Vt,c=et,d=">",l=">=";break;case"<":n=et,i=jt,c=Le,d="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(rt(e,t,o))return!1;for(var w=0;w<t.set.length;++w){var A=t.set[w],b=null,T=null;if(A.forEach(function(H){H.semver===Ae&&(H=new J(">=0.0.0")),b=b||H,T=T||H,n(H.semver,b.semver,o)?b=H:c(H.semver,T.semver,o)&&(T=H)}),b.operator===d||b.operator===l||(!T.operator||T.operator===d)&&i(e,T.semver))return!1;if(T.operator===l&&c(e,T.semver))return!1}return!0}u.prerelease=sa;function sa(e,t){var r=de(e,t);return r&&r.prerelease.length?r.prerelease:null}u.intersects=ca;function ca(e,t,r){return e=new C(e,r),t=new C(t,r),e.intersects(t)}u.coerce=pa;function pa(e,t){if(e instanceof m)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};var r=null;if(!t.rtl)r=e.match(y[a.COERCE]);else{for(var o;(o=y[a.COERCERTL].exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||o.index+o[0].length!==r.index+r[0].length)&&(r=o),y[a.COERCERTL].lastIndex=o.index+o[1].length+o[2].length;y[a.COERCERTL].lastIndex=-1}return r===null?null:de(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}});var za={};In(za,{main:()=>yn,run:()=>gn});module.exports=Pn(za);var bt=require("@medplum/core"),fn=require("commander"),hn=K(require("dotenv"));var B=require("@medplum/core"),$r=require("child_process"),Fr=require("http"),Br=require("os");var ur=require("@medplum/core");var dr=require("@medplum/core"),z=require("fs"),lr=require("os"),vt=require("path"),j=class extends dr.ClientStorage{constructor(t){super(),this.dirName=(0,vt.resolve)((0,lr.homedir)(),".medplum"),this.fileName=(0,vt.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,z.existsSync)(this.fileName))return JSON.parse((0,z.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,z.existsSync)(this.dirName)||(0,z.mkdirSync)(this.dirName),(0,z.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function S(e,t=!0){let r=e.profile??"default",o=new j(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:c,accessToken:d,tokenUrl:l,authorizeUrl:w,clientId:A,clientSecret:b}=Rn(e,o),T=e.fetch??fetch,H=new ur.MedplumClient({fetch:T,baseUrl:i,tokenUrl:l,fhirUrlPath:c,authorizeUrl:w,storage:o,onUnauthenticated:Tn,verbose:e.verbose});return t&&(d?H.setAccessToken(d):A&&b&&(H.setBasicAuth(A,b),n?.authType!=="basic"&&await H.startClientLogin(A,b))),H}function Rn(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,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,c=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,d=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,w=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:i,tokenUrl:c,authorizeUrl:d,clientId:l,clientSecret:w}}function Tn(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Fe=require("commander");function h(e){return new Fe.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 Fe.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var ce=require("@medplum/core"),Ee=require("crypto"),ie=require("fs");var mr=require("buffer");var k=new TextEncoder,N=new TextDecoder,ns=2**32;function F(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var L=e=>mr.Buffer.from(e).toString("base64url");var fe=class extends Error{constructor(r){super(r);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}static get code(){return"ERR_JOSE_GENERIC"}};var E=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var M=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},ne=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var hr=K(require("util"),1),W=e=>hr.types.isKeyObject(e);var yr=K(require("crypto"),1),gr=K(require("util"),1),Nn=yr.webcrypto,wr=Nn,_=e=>gr.types.isCryptoKey(e);function Y(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Be(e,t){return e.name===t}function It(e){return parseInt(e.name.slice(4),10)}function _n(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Dn(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 Er(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Be(e.algorithm,"HMAC"))throw Y("HMAC");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Be(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Y("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Be(e.algorithm,"RSA-PSS"))throw Y("RSA-PSS");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw Y("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Be(e.algorithm,"ECDSA"))throw Y("ECDSA");let o=_n(t);if(e.algorithm.namedCurve!==o)throw Y(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Dn(e,r)}function Sr(e,t,...r){if(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 U=(e,...t)=>Sr("Key must be ",e,...t);function Pt(e,t,...r){return Sr(`Key for the ${e} algorithm must be `,t,...r)}var Rt=e=>W(e)||_(e),v=["KeyObject"];(globalThis.CryptoKey||wr?.CryptoKey)&&v.push("CryptoKey");var Mn=(...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 i of n){if(r.has(i))return!1;r.add(i)}}return!0},he=Mn;function Wn(e){return typeof e=="object"&&e!==null}function x(e){if(!Wn(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 Ge=require("crypto"),vr=require("util");var br=require("crypto");var Un=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 E("Unsupported key curve for this operation")}},Jn=(e,t)=>{let r;if(_(e))r=br.KeyObject.from(e);else if(W(e))r=e;else throw new TypeError(U(e,...v));if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return t?o:Un(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Tt=Jn;var Ec=(0,vr.promisify)(Ge.generateKeyPair);var Ir=require("util"),xt=require("crypto");var Hc=(0,Ir.promisify)(xt.pbkdf2);var xe=require("crypto"),Pr=require("util");var je=(e,t)=>{let{modulusLength:r}=e.asymmetricKeyDetails;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var Fc=(0,Pr.deprecate)(()=>xe.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var Bn=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Rt(t))throw new TypeError(Pt(e,t,...v,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${v.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Gn=(e,t,r)=>{if(!Rt(t))throw new TypeError(Pt(e,t,...v));if(t.type==="secret")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},jn=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Bn(e,t):Gn(e,t,r)},Ne=jn;function Zn(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(c=>typeof c!="string"||c.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let c of o.crit){if(!i.has(c))throw new E(`Extension Header Parameter "${c}" is not recognized`);if(n[c]===void 0)throw new e(`Extension Header Parameter "${c}" is missing`);if(i.get(c)&&o[c]===void 0)throw new e(`Extension Header Parameter "${c}" MUST be integrity protected`)}return new Set(o.crit)}var ye=Zn;var oi=Symbol();var Ht=K(require("crypto"),1),Nr=require("util");function Ve(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 E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Nt=require("crypto");var ni={padding:Nt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Nt.constants.RSA_PSS_SALTLEN_DIGEST},ii=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Xe(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return je(t,e),t;case"PS256":case"PS384":case"PS512":if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,i=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${i}`||o!==r))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>i>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return je(t,e),{key:t,...ni};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=Tt(t),o=ii.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var qe=K(require("crypto"),1),Or=require("util");function _t(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var _e=require("crypto");function ze(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(U(t,...v));return(0,_e.createSecretKey)(t)}if(t instanceof _e.KeyObject)return t;if(_(t))return Er(t,e,r),_e.KeyObject.from(t);throw new TypeError(U(t,...v,"Uint8Array"))}var ai=(0,Or.promisify)(qe.sign),si=async(e,t,r)=>{let o=ze(e,t,"sign");if(e.startsWith("HS")){let n=qe.createHmac(_t(e),o);return n.update(r),n.digest()}return ai(Ve(e),r,Xe(e,o))},Dt=si;var Tl=(0,Nr.promisify)(Ht.verify);var Z=e=>Math.floor(e.getTime()/1e3);var pi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,De=e=>{let t=pi.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 ge=class{constructor(t){P(this,"_payload");P(this,"_protectedHeader");P(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new M("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!he(this._protectedHeader,this._unprotectedHeader))throw new M("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=ye(M,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),i=!0;if(n.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new M('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:c}=o;if(typeof c!="string"||!c)throw new M('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ne(c,t,"sign");let d=this._payload;i&&(d=k.encode(L(d)));let l;this._protectedHeader?l=k.encode(L(JSON.stringify(this._protectedHeader))):l=k.encode("");let w=F(l,k.encode("."),d),A=await Dt(c,t,w),b={signature:L(A),payload:""};return i&&(b.payload=N.decode(d)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=N.decode(l)),b}};var He=class{constructor(t){P(this,"_flattened");this._flattened=new ge(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function se(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var we=class{constructor(t={}){P(this,"_payload");if(!x(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:se("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:se("setNotBefore",Z(t))}:this._payload={...this._payload,nbf:Z(new Date)+De(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:se("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:se("setExpirationTime",Z(t))}:this._payload={...this._payload,exp:Z(new Date)+De(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:t instanceof Date?this._payload={...this._payload,iat:se("setIssuedAt",Z(t))}:typeof t=="string"?this._payload={...this._payload,iat:se("setIssuedAt",Z(new Date)+De(t))}:this._payload={...this._payload,iat:se("setIssuedAt",t)},this}};var Ke=class extends we{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new He(k.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 ne("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var yi;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(yi="jose/v5.2.4");var Kt=require("crypto"),Hr=require("util");var Lm=(0,Hr.promisify)(Kt.generateKeyPair);var Q=require("path"),Kr=require("tar");function ee(e){console.log(JSON.stringify(e,null,2))}async function kt(e,t,r){let o=t.source,n=Ye(o);if(n)try{console.log("Saving source code...");let i=await e.createAttachment(n,(0,Q.basename)(o),Ai(o));console.log("Updating bot.....");let c=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+c.meta?.versionId)}catch(i){console.log("Update error: ",i)}}async function Lt(e,t,r){let o=t.dist??t.source,n=Ye(o);if(n)try{console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,Q.basename)(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}catch(i){console.log("Deploy error: ",i)}}async function Mt(e,t,r,o,n,i,c){try{let d={name:t,description:"",runtimeVersion:i},l=await e.post("admin/projects/"+r+"/bot",d),w=await e.readResource("Bot",l.id),A={name:t,id:l.id,source:o,dist:n};await kt(e,A,w),await Lt(e,A,w),console.log(`Success! Bot created: ${w.id}`),c&&Ei(A)}catch(d){console.log("Error while creating new bot: "+d)}}function kr(e){let t=new RegExp("^"+Si(e).replace(/\\\*/g,".*")+"$"),r=V()?.bots?.filter(o=>t.test(o.name));return r||[]}function te(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 R(e,t){(0,ie.writeFileSync)((0,Q.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function V(e,t){let r=te(e,t),o=Ye(r);if(o)return JSON.parse(o)}function Lr(e){let t=Ye(te(e,{server:!0}));if(t)return JSON.parse(t)}function Ye(e){let t=(0,Q.resolve)(e);return(0,ie.existsSync)(t)?(0,ie.readFileSync)(t,"utf8"):""}function Ei(e){let t=V()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ie.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Si(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Mr(e){let o=0,n=0;return(0,Kr.extract)({cwd:e,filter:(i,c)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=c.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Wt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Ai(e){let t=(0,Q.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?ce.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?ce.ContentType.TYPESCRIPT:ce.ContentType.TEXT}function Ze(e,t){let r=new j(e),o={name:e,...t};return r.setObject("options",o),o}function Wr(e){return new j(e).getObject("options")}async function Ur(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},i=(0,ce.encodeBase64)(JSON.stringify(r)),c=(0,ce.encodeBase64)(JSON.stringify(n)),d=`${i}.${c}`,l=(0,Ee.createHmac)("sha256",t.clientSecret).update(d).digest("base64url"),w=`${d}.${l}`;await e.startJwtBearerLogin(t.clientId,w,t.scope??"")}async function Jr(e,t){let r=(0,Ee.createPrivateKey)((0,ie.readFileSync)((0,Q.resolve)(t.privateKeyPath))),o=await new Ke({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,Ee.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Gr=B.MEDPLUM_CLI_CLIENT_ID,jr="http://localhost:9615",Ut=h("login"),Jt=h("whoami");Ut.action(async e=>{let t=e.profile??"default",r=Ze(t,e),o=await S(e,!1);await bi(o,r)});Jt.action(async e=>{let t=await S(e);Ii(t)});async function bi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Pi(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 Ur(e,t);break;case"jwt-assertion":await Jr(e,t);break}}async function vi(e){let t=(0,Fr.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),i=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":B.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let c=await e.processCode(i,{clientId:Gr,redirectUri:jr});o.writeHead(200,{"Content-Type":B.ContentType.TEXT}),o.end(`Signed in as ${(0,B.getDisplayString)(c)}. You may close this window.`)}catch(c){o.writeHead(400,{"Content-Type":B.ContentType.TEXT}),o.end(`Error: ${(0,B.normalizeErrorString)(c)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":B.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function Ci(e){let t=(0,Br.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,$r.exec)(r)}function Ii(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 Pi(e){await vi(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Gr),t.searchParams.set("redirect_uri",jr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Ci(t.toString())}var Po=require("commander");var oe=require("@aws-sdk/client-cloudformation"),ct=require("@aws-sdk/client-cloudfront"),eo=require("@aws-sdk/client-ecs"),to=require("@aws-sdk/client-s3"),ve=require("@aws-sdk/client-ssm"),pt=require("@aws-sdk/client-sts"),ro=require("@medplum/core"),oo=require("fs"),no=K(require("node-fetch")),io=K(zt());var Zr=K(require("readline")),ot;function nt(){ot=Zr.default.createInterface({input:process.stdin,output:process.stdout})}function it(){ot.close()}function s(e){ot.write(e+`
|
|
3
3
|
`)}function I(e){s(`
|
|
4
4
|
`+e+`
|
|
5
|
-
`)}function H(e,t=""){return new Promise(r=>{ot.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function at(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await H(o)||r;if(t.includes(n))return n;s("Please choose one of the following options: "+t.join(", "))}}async function be(e,t,r){return parseInt(await at(e,t.map(o=>o.toString()),r.toString()),10)}async function le(e){return(await at(e,["y","n"])).toLowerCase()==="y"}async function We(e){if(!await le(e))throw s("Exiting..."),new Error("User cancelled")}var st=new oe.CloudFormationClient({}),da=new ct.CloudFrontClient({region:"us-east-1"}),ph=new eo.ECSClient({}),Ue=new to.S3Client({}),la="medplum:environment";async function qt(){return(await st.send(new oe.ListStacksCommand({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function Ce(e){let t=await qt();for(let r of t){let o=r.StackName,n=await Yt(o);if(n?.tag===e)return n}}async function Yt(e){let t={};if(await Qr(st,e,t),await st.config.region()!=="us-east-1")try{await Qr(new oe.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Qr(e,t,r){let o=new oe.DescribeStacksCommand({StackName:t}),i=(await e.send(o))?.Stacks?.[0],c=i?.Tags?.find(l=>l.Key===la);if(!c)return;let d=await e.send(new oe.DescribeStackResourcesCommand({StackName:t}));if(d.StackResources){e===st&&(r.stack=i,r.tag=c.Value);for(let l of d.StackResources)ua(l,r)}}function ua(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function dt(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${ma(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 ma(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function lt(e){let t=await da.send(new ct.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function ut(e){let o=(await(await(0,no.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,i)=>io.compare(i,n)),e?o.slice(0,o.indexOf(e)):o}async function mt(e,t,r){let o=new ve.SSMClient({region:e});for(let[n,i]of Object.entries(r)){let c=t+n,d=i.toString(),l=await fa(o,c);l!==void 0&&l!==d&&(s(`Parameter "${c}" exists with different value.`),await We(`Do you want to overwrite "${c}"?`)),await ha(o,c,d)}}async function fa(e,t){let r=new ve.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function ha(e,t,r){let o=new ve.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function ae(e,t){if(console.log(`Config not found: ${e} (${te(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,i]of o)console.log(` ${n}: ${i}`)}}console.log();let r=(0,oo.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 Ie(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,ro.normalizeErrorString)(t))}}async function ao(e){let t=await Ce(e);if(!t){await Ie(e);return}dt(t)}var ue=require("@aws-sdk/client-acm"),ft=require("@aws-sdk/client-cloudfront"),ht=require("@aws-sdk/client-sts"),co=require("@medplum/core"),Je=require("crypto"),po=require("fs");var ya=e=>`${e}DomainName`,lo=e=>`${e}SslCertArn`;async function uo(){let e={apiPort:8103,region:"us-east-1"};nt(),I("MEDPLUM"),s("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),s(""),s("Most Medplum infrastructure is deployed using the AWS CDK."),s("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),s("This tool will help you create those resources."),s(""),s("Upon completion, this tool will:"),s(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),s(" 2. Optionally generate an AWS CloudFront signing key"),s(" 3. Optionally request SSL certificates from AWS Certificate Manager"),s(" 4. Optionally write server config settings to AWS Parameter Store"),s(""),s("The Medplum infra config file is an input to the Medplum CDK."),s("The Medplum CDK will create and manage the necessary AWS resources."),s(""),s("We will ask a series of questions to generate your infra config file."),s("Some questions have predefined options in [square brackets]."),s("Some questions have default values in (parentheses), which you can accept by pressing Enter."),s("Press Ctrl+C at any time to exit.");let t=await ga(e.region);t||(s("It appears that you do not have AWS credentials configured."),s("AWS credentials are not strictly required, but will enable some additional features."),s("If you intend to use AWS credentials, please configure them now."),await We("Do you want to continue without AWS credentials?")),I("ENVIRONMENT NAME"),s('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),s("The environment name is used in multiple places:"),s(" 1. As part of config file names (i.e., medplum.demo.config.json)"),s(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),s(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await H("What is your environment name?","demo"),s('Using environment name "'+e.name+'"...'),I("CONFIG FILE"),s("Medplum Infrastructure will create a config file in the current directory.");let r=await H("What is the config file name?",`medplum.${e.name}.config.json`);(0,po.existsSync)(r)&&(s("Config file already exists."),await We("Do you want to overwrite the config file?")),s('Using config file "'+r+'"...'),R(r,e),I("AWS REGION"),s("Most Medplum resources will be created in a single AWS region."),e.region=await H("Enter your AWS region:","us-east-1"),R(r,e),I("AWS ACCOUNT NUMBER"),s("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&s("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await H("What is your AWS account number?",t),R(r,e),I("STACK NAME"),s("Medplum will create a CloudFormation stack to manage AWS resources."),s("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await H("Enter your CloudFormation stack name?",o),R(r,e),I("BASE DOMAIN NAME"),s("Please enter the base domain name for your Medplum deployment."),s(""),s("Medplum deploys multiple subdomains for various services."),s(""),s('For example, "api." for the REST API and "app." for the web application.'),s("The base domain name is the common suffix for all subdomains."),s(""),s('For example, if your base domain name is "example.com",'),s('then the REST API will be "api.example.com".'),s(""),s('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),s(""),s("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await H("Enter your base domain name:");R(r,e),I("SUPPORT EMAIL"),s("Medplum sends transactional emails to users."),s("For example, emails to new users or for password reset."),s("Medplum will use the support email address to send these emails."),s("Note that you must verify the support email address in SES.");let n=await H("Enter your support email address:");I("API DOMAIN NAME"),s("Medplum deploys a REST API for the backend services."),e.apiDomainName=await H("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,R(r,e),I("APP DOMAIN NAME"),s("Medplum deploys a web application for the user interface."),e.appDomainName=await H("Enter your web application domain name:","app."+e.domainName),R(r,e),I("STORAGE DOMAIN NAME"),s("Medplum deploys a storage service for file uploads."),e.storageDomainName=await H("Enter your storage domain name:","storage."+e.domainName),R(r,e),I("STORAGE BUCKET"),s("Medplum uses an S3 bucket to store binary content such as file uploads."),s("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await H("Enter your storage bucket name:",e.storageDomainName),R(r,e),I("MAX AVAILABILITY ZONES"),s("Medplum API servers can be deployed in multiple availability zones."),s("This provides redundancy and high availability."),s("However, it also increases the cost of the deployment."),s("If you want to use all availability zones, choose a large number such as 99."),s("If you want to restrict the number, for example to manage EIP limits,"),s("then choose a small number such as 2 or 3."),e.maxAzs=await be("Enter the maximum number of availability zones:",[2,3,99],2),I("DATABASE INSTANCES"),s("Medplum uses a relational database to store data."),s("Medplum can create a new RDS database as part of the CloudFormation stack,"),s("or can set up your own database and enter the database name, username, and password."),await le("Do you want to create a new RDS database as part of the CloudFormation stack?")?(s("Medplum will create a new RDS database as part of the CloudFormation stack."),s(""),s("If you need high availability, you can choose multiple instances."),s("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await be("Enter the number of database instances:",[1,2],1)):(s("Medplum will not create a new RDS database."),s("Please create a new RDS database and enter the database name, username, and password."),s('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),R(r,e),I("SERVER INSTANCES"),s("Medplum uses AWS Fargate to run the API servers."),s("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),s("Fargate will automatically scale the number of servers up and down."),s("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await be("Enter the number of server instances:",[1,2,3,4,6,8],1),R(r,e),I("SERVER MEMORY"),s("You can choose the amount of memory for each server instance."),s("The default is 512 MB, which is sufficient for getting started."),s("Note that only certain CPU units are compatible with memory units."),s('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await be("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),R(r,e),I("SERVER CPU"),s("You can choose the amount of CPU for each server instance."),s("CPU is expressed as an integer using AWS CPU units"),s("The default is 256, which is sufficient for getting started."),s("Note that only certain CPU units are compatible with memory units."),s('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await be("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),R(r,e),I("SERVER IMAGE"),s("Medplum uses Docker images for the API servers."),s("You can choose the image to use for the servers."),s("Docker images can be loaded from either Docker Hub or AWS ECR."),s("The default is the latest Medplum release.");let i=(await ut())[0]??"latest";e.serverImage=await H("Enter the server image:",`medplum/medplum-server:${i}`),R(r,e),I("SIGNING KEY"),s("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let c=await Aa(e.region,e.stackName+"SigningKey");c?(e.signingKeyId=c.keyId,e.storagePublicKey=c.publicKey,R(r,e)):(s("Unable to generate signing key."),s("Please manually create a signing key and enter the key ID and public key in the config file."),s('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),I("SSL CERTIFICATES"),s("Medplum will now check for existing SSL certificates for the subdomains.");let d=await wa(e.region);s("Found "+d.length+" certificate(s).");for(let{region:w,certName:A}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){s("");let b=await Ea(e,d,w,A);e[lo(A)]=b,R(r,e)}I("AWS PARAMETER STORE"),s("Medplum uses AWS Parameter Store to store sensitive configuration values."),s("These values will be encrypted at rest."),s(`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(c&&(l.signingKeyId=c.keyId,l.signingKey=c.privateKey,l.signingKeyPassphrase=c.passphrase),s(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await le("Do you want to store these values in AWS Parameter Store?"))await mt(e.region,`/medplum/${e.name}/`,l);else{let w=te(e.name,{server:!0});R(w,l),s("Skipping AWS Parameter Store."),s(`Writing values to local config file: ${w}`),s("Please add these values to AWS Parameter Store manually.")}I("DONE!"),s("Medplum configuration complete."),s("You can now proceed to deploying the Medplum infrastructure with CDK."),s("Run:"),s(""),s(` npx cdk bootstrap -c config=${r}`),s(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?s(` npx cdk deploy -c config=${r}`):s(` npx cdk deploy -c config=${r} --all`),s(""),s("See Medplum documentation for more information:"),s(""),s(" https://www.medplum.com/docs/self-hosting/install-on-aws"),s(""),it()}async function ga(e){try{let t=new ht.STSClient({region:e}),r=new ht.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function wa(e){let t=await so(e);if(e!=="us-east-1"){let r=await so("us-east-1");t.push(...r)}return t}async function so(e){try{let t=new ue.ACMClient({region:e}),r=new ue.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ea(e,t,r,o){let n=e[ya(o)],i=t.find(d=>d.CertificateArn?.includes(r)&&d.DomainName===n);if(i)return s(`Found existing certificate for "${n}" in "${r}.`),i.CertificateArn;if(s(`No existing certificate found for "${n}" in "${r}.`),!await le("Do you want to request a new certificate?"))return s(`Please add your certificate ARN to the config file in the "${lo(o)}" setting.`),"TODO";let c=await Sa(r,n);return s("Certificate ARN: "+c),c}async function Sa(e,t){try{let r=await at("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new ue.ACMClient({region:e}),n=new ue.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Aa(e,t){let r=(0,Je.randomUUID)(),o=(0,Je.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new ft.CloudFrontClient({region:e}).send(new ft.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,Je.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,co.normalizeErrorString)(n));return}}async function mo(){let e=await qt();for(let t of e){let r=t.StackName,o=await Yt(r);o&&(dt(o),console.log(""))}}var fo=require("@aws-sdk/client-s3"),G=require("@medplum/core"),ho=N(require("fast-glob")),$=require("fs"),Zt=N(require("node-fetch")),yo=require("os"),me=require("path"),go=require("stream/promises");async function wo(e,t){let r=V(e,t);if(!r){await ae(e,t);return}let o=await Ce(e);if(!o){await Ie(e);return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let i=t?.version??"latest",c=await va("@medplum/app",i);Eo(c,{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 Ia(c,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await lt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function ba(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Zt.default)(r)).json()}async function va(e,t){let o=(await ba(e,t)).dist.tarball,n=(0,$.mkdtempSync)((0,me.join)((0,yo.tmpdir)(),"tarball-"));try{let i=await(0,Zt.default)(o),c=Mr(n);return await(0,go.pipeline)(i.body,c),(0,me.join)(n,"package","dist")}catch(i){throw(0,$.rmSync)(n,{recursive:!0,force:!0}),i}}function Eo(e,t){for(let r of(0,$.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Eo(o,t):r.isFile()&&o.endsWith(".js")&&Ca(o,t)}}function Ca(e,t){let r=(0,$.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,$.writeFileSync)(e,r)}async function Ia(e,t,r){let o=[["assets/**/*.css",G.ContentType.CSS,!0],["assets/**/*.css.map",G.ContentType.JSON,!0],["assets/**/*.js",G.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",G.ContentType.JSON,!0],["assets/**/*.txt",G.ContentType.TEXT,!0],["assets/**/*.ico",G.ContentType.FAVICON,!0],["img/**/*.png",G.ContentType.PNG,!0],["img/**/*.svg",G.ContentType.SVG,!0],["robots.txt",G.ContentType.TEXT,!0],["index.html",G.ContentType.HTML,!1]];for(let n of o)await Pa({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Pa(e){let t=ho.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Ra((0,me.join)(e.rootDir,r),e)}async function Ra(e,t){let r=(0,$.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await Ue.send(new fo.PutObjectCommand(n))}var yt=require("@aws-sdk/client-s3");async function Ao(e,t){if(!V(e,t)){await ae(e,t);return}let o=await Ce(e);if(!o){await Ie(e);return}await So("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await So("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function So(e,t,r,o,n){if(!t?.PhysicalResourceId){console.log(`${e} bucket not found`);return}if(!r?.PhysicalResourceId){console.log(`${e} distribution not found`);return}if(!o?.PhysicalResourceId){console.log(`${e} OAI not found`);return}let i=t.PhysicalResourceId,c=o.PhysicalResourceId,d=await Ta(i);if(Oa(d,i,c)){console.log(`${e} bucket already has policy statement`);return}Na(d,i,c),console.log(`${e} bucket policy:`),console.log(JSON.stringify(d,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await xa(i,d),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await lt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Ta(e){let t=await Ue.send(new yt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function xa(e,t){await Ue.send(new yt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Oa(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 Na(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 bo(e,t){try{nt();let r=V(e,t);if(!r){await ae(e,t);return}let o=Lr(e)??{};_a(r,o),Ha(r,o),s("Medplum uses AWS Parameter Store to store sensitive configuration values."),s("These values will be encrypted at rest."),s(`The values will be stored in the "/medplum/${r.name}" path.`),s(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await le("Do you want to store these values in AWS Parameter Store?")&&await mt(r.region,`/medplum/${r.name}/`,o)}finally{it()}}function _a(e,t){gt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),gt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),gt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),gt(e.storageDomainName&&`https://${e.storageDomainName}/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function gt(e,t,r){if(Da(e,t))throw new Error(r)}function Da(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ha(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 Co=require("child_process"),Pe=N(zt());async function Io(e,t){let r=await S(t),o=V(e,t);if(!o){console.log(`Configuration file ${te(e)} not found`),await ae(e,t);return}let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),c=await Ka(r,o),d=await vo(c);for(;d;){if(t.version&&Pe.gt(d,t.version)){console.log(`Skipping update to v${d}`);break}console.log(`Performing update to v${d}`),o.serverImage=`${i}:${d}`,ka(e,o),await r.startAsyncRequest("/admin/super/migrate"),d=await vo(d)}}async function Ka(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let i=o.indexOf("-");i>-1&&(o=o.slice(0,i))}return o}async function vo(e,t){let r=await ut(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function ka(e,t){let r=te(e);R(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Co.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 Ro(){let e=new Po.Command("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(uo),e.command("list").description("List Medplum AWS CloudFormation stacks").action(mo),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(ao),e.command("update-config").alias("deploy-config").description("Update the AWS Parameter Store config values").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(bo),e.addCommand(h("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(Io)),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("--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.").action(wo),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(Ao),e}var To=require("commander");var xo=h("save"),Oo=h("deploy"),No=h("create"),_o=new To.Command("bot").addCommand(xo).addCommand(Oo).addCommand(No),Qt=h("save-bot"),er=h("deploy-bot"),tr=h("create-bot");xo.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e)});Oo.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e,!0)});No.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 i=await S(n);await Mt(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function wt(e,t,r=!1){let o=kr(t);for(let n of o){let i=await e.readResource("Bot",n.id);await kt(e,n,i),r&&await Lt(e,n,i)}console.log(`Number of bots deployed: ${o.length}`)}Qt.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e)});er.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e,!0)});tr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await S(n);await Mt(i,e,t,r,o)});var Ho=require("commander"),Et=require("fs"),rr=require("path"),Ko=require("readline");var ko=h("export"),Lo=h("import"),Mo=new Ho.Command("bulk").addCommand(ko).addCommand(Lo);ko.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,i=await S(e);(await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:d,url:l})=>{let w=new URL(l),A=await i.download(l),b=`${d}_${w.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",T=(0,rr.resolve)(n??"",b);(0,Et.writeFile)(`${T}`,await A.text(),()=>{console.log(`${T} is created`)})})});Lo.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,i=(0,rr.resolve)(n??process.cwd(),e),c=await S(t);await La(i,parseInt(r,10),c,o)});async function La(e,t,r,o){let n=[],i=(0,Et.createReadStream)(e),c=(0,Ko.createInterface)({input:i});for await(let d of c){let l=Ma(d,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await Do(n,r),n=[])}n.length>0&&await Do(n,r)}async function Do(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{ee(o.response)})}function Ma(e,t){let r=JSON.parse(e);return t?Wa(r):r}function Wa(e){return e.resourceType==="ExplanationOfBenefit"?Ua(e):e}function Ua(e){return e.provider||(e.provider=Wt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Wt())}),e}var St=require("@medplum/core");var Fo=require("net"),Bo=require("@medplum/core"),Vo=N(require("net"),1),$o=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Ja="\v",Wo="",Uo="\r",$a=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Jo=class extends Event{constructor(e){super("error"),this.error=e}},Go=class extends $o{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(Wo+Uo)){let n=Bo.Hl7Message.parse(r.substring(1,r.length-2));this.dispatchEvent(new $a(this,n)),r=""}}catch(n){this.dispatchEvent(new Jo(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new Jo(o))})}send(e){this.socket.write(Ja+e.toString()+Wo+Uo)}async sendAndWait(e){let t=new Promise(r=>{function o(n){n.target.removeEventListener("message",o),r(n.message)}this.addEventListener("message",o)});return this.send(e),t}close(){this.socket.end(),this.socket.destroy()}},jo=class extends $o{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port}connect(){return this.connection?Promise.resolve(this.connection):new Promise(e=>{let t=(0,Fo.connect)({host:this.host,port:this.port},()=>{this.connection=new Go(t),e(this.connection)})})}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)}},Xo=class{constructor(e){this.handler=e}start(e,t){let r=Vo.default.createServer(o=>{let n=new Go(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};var zo=require("commander"),qo=require("fs");var Fa=h("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").action(async(e,t,r,o)=>{if(o.generateExample?r=Ga():o.file&&(r=(0,qo.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new jo({host:e,port:parseInt(t,10)});try{let i=await n.sendAndWait(St.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
5
|
+
`)}function D(e,t=""){return new Promise(r=>{ot.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function at(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await D(o)||r;if(t.includes(n))return n;s("Please choose one of the following options: "+t.join(", "))}}async function be(e,t,r){return parseInt(await at(e,t.map(o=>o.toString()),r.toString()),10)}async function le(e){return(await at(e,["y","n"])).toLowerCase()==="y"}async function We(e){if(!await le(e))throw s("Exiting..."),new Error("User cancelled")}var st=new oe.CloudFormationClient({}),da=new ct.CloudFrontClient({region:"us-east-1"}),ph=new eo.ECSClient({}),Ue=new to.S3Client({}),la="medplum:environment";async function qt(){return(await st.send(new oe.ListStacksCommand({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function Ce(e){let t=await qt();for(let r of t){let o=r.StackName,n=await Yt(o);if(n?.tag===e)return n}}async function Yt(e){let t={};if(await Qr(st,e,t),await st.config.region()!=="us-east-1")try{await Qr(new oe.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Qr(e,t,r){let o=new oe.DescribeStacksCommand({StackName:t}),i=(await e.send(o))?.Stacks?.[0],c=i?.Tags?.find(l=>l.Key===la);if(!c)return;let d=await e.send(new oe.DescribeStackResourcesCommand({StackName:t}));if(d.StackResources){e===st&&(r.stack=i,r.tag=c.Value);for(let l of d.StackResources)ua(l,r)}}function ua(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function dt(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${ma(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 ma(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function lt(e){let t=await da.send(new ct.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function ut(e){let o=(await(await(0,no.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,i)=>io.compare(i,n)),e?o.slice(0,o.indexOf(e)):o}async function mt(e,t,r){let o=new ve.SSMClient({region:e});for(let[n,i]of Object.entries(r)){let c=t+n,d=i.toString(),l=await fa(o,c);l!==void 0&&l!==d&&(s(`Parameter "${c}" exists with different value.`),await We(`Do you want to overwrite "${c}"?`)),await ha(o,c,d)}}async function fa(e,t){let r=new ve.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function ha(e,t,r){let o=new ve.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function ae(e,t){if(console.log(`Config not found: ${e} (${te(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,i]of o)console.log(` ${n}: ${i}`)}}console.log();let r=(0,oo.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 Ie(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,ro.normalizeErrorString)(t))}}async function ao(e){let t=await Ce(e);if(!t){await Ie(e);return}dt(t)}var ue=require("@aws-sdk/client-acm"),ft=require("@aws-sdk/client-cloudfront"),ht=require("@aws-sdk/client-sts"),co=require("@medplum/core"),Je=require("crypto"),po=require("fs");var ya=e=>`${e}DomainName`,lo=e=>`${e}SslCertArn`;async function uo(){let e={apiPort:8103,region:"us-east-1"};nt(),I("MEDPLUM"),s("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),s(""),s("Most Medplum infrastructure is deployed using the AWS CDK."),s("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),s("This tool will help you create those resources."),s(""),s("Upon completion, this tool will:"),s(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),s(" 2. Optionally generate an AWS CloudFront signing key"),s(" 3. Optionally request SSL certificates from AWS Certificate Manager"),s(" 4. Optionally write server config settings to AWS Parameter Store"),s(""),s("The Medplum infra config file is an input to the Medplum CDK."),s("The Medplum CDK will create and manage the necessary AWS resources."),s(""),s("We will ask a series of questions to generate your infra config file."),s("Some questions have predefined options in [square brackets]."),s("Some questions have default values in (parentheses), which you can accept by pressing Enter."),s("Press Ctrl+C at any time to exit.");let t=await ga(e.region);t||(s("It appears that you do not have AWS credentials configured."),s("AWS credentials are not strictly required, but will enable some additional features."),s("If you intend to use AWS credentials, please configure them now."),await We("Do you want to continue without AWS credentials?")),I("ENVIRONMENT NAME"),s('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),s("The environment name is used in multiple places:"),s(" 1. As part of config file names (i.e., medplum.demo.config.json)"),s(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),s(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await D("What is your environment name?","demo"),s('Using environment name "'+e.name+'"...'),I("CONFIG FILE"),s("Medplum Infrastructure will create a config file in the current directory.");let r=await D("What is the config file name?",`medplum.${e.name}.config.json`);(0,po.existsSync)(r)&&(s("Config file already exists."),await We("Do you want to overwrite the config file?")),s('Using config file "'+r+'"...'),R(r,e),I("AWS REGION"),s("Most Medplum resources will be created in a single AWS region."),e.region=await D("Enter your AWS region:","us-east-1"),R(r,e),I("AWS ACCOUNT NUMBER"),s("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&s("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await D("What is your AWS account number?",t),R(r,e),I("STACK NAME"),s("Medplum will create a CloudFormation stack to manage AWS resources."),s("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await D("Enter your CloudFormation stack name?",o),R(r,e),I("BASE DOMAIN NAME"),s("Please enter the base domain name for your Medplum deployment."),s(""),s("Medplum deploys multiple subdomains for various services."),s(""),s('For example, "api." for the REST API and "app." for the web application.'),s("The base domain name is the common suffix for all subdomains."),s(""),s('For example, if your base domain name is "example.com",'),s('then the REST API will be "api.example.com".'),s(""),s('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),s(""),s("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await D("Enter your base domain name:");R(r,e),I("SUPPORT EMAIL"),s("Medplum sends transactional emails to users."),s("For example, emails to new users or for password reset."),s("Medplum will use the support email address to send these emails."),s("Note that you must verify the support email address in SES.");let n=await D("Enter your support email address:");I("API DOMAIN NAME"),s("Medplum deploys a REST API for the backend services."),e.apiDomainName=await D("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,R(r,e),I("APP DOMAIN NAME"),s("Medplum deploys a web application for the user interface."),e.appDomainName=await D("Enter your web application domain name:","app."+e.domainName),R(r,e),I("STORAGE DOMAIN NAME"),s("Medplum deploys a storage service for file uploads."),e.storageDomainName=await D("Enter your storage domain name:","storage."+e.domainName),R(r,e),I("STORAGE BUCKET"),s("Medplum uses an S3 bucket to store binary content such as file uploads."),s("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await D("Enter your storage bucket name:",e.storageDomainName),R(r,e),I("MAX AVAILABILITY ZONES"),s("Medplum API servers can be deployed in multiple availability zones."),s("This provides redundancy and high availability."),s("However, it also increases the cost of the deployment."),s("If you want to use all availability zones, choose a large number such as 99."),s("If you want to restrict the number, for example to manage EIP limits,"),s("then choose a small number such as 2 or 3."),e.maxAzs=await be("Enter the maximum number of availability zones:",[2,3,99],2),I("DATABASE INSTANCES"),s("Medplum uses a relational database to store data."),s("Medplum can create a new RDS database as part of the CloudFormation stack,"),s("or can set up your own database and enter the database name, username, and password."),await le("Do you want to create a new RDS database as part of the CloudFormation stack?")?(s("Medplum will create a new RDS database as part of the CloudFormation stack."),s(""),s("If you need high availability, you can choose multiple instances."),s("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await be("Enter the number of database instances:",[1,2],1)):(s("Medplum will not create a new RDS database."),s("Please create a new RDS database and enter the database name, username, and password."),s('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),R(r,e),I("SERVER INSTANCES"),s("Medplum uses AWS Fargate to run the API servers."),s("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),s("Fargate will automatically scale the number of servers up and down."),s("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await be("Enter the number of server instances:",[1,2,3,4,6,8],1),R(r,e),I("SERVER MEMORY"),s("You can choose the amount of memory for each server instance."),s("The default is 512 MB, which is sufficient for getting started."),s("Note that only certain CPU units are compatible with memory units."),s('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await be("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),R(r,e),I("SERVER CPU"),s("You can choose the amount of CPU for each server instance."),s("CPU is expressed as an integer using AWS CPU units"),s("The default is 256, which is sufficient for getting started."),s("Note that only certain CPU units are compatible with memory units."),s('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await be("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),R(r,e),I("SERVER IMAGE"),s("Medplum uses Docker images for the API servers."),s("You can choose the image to use for the servers."),s("Docker images can be loaded from either Docker Hub or AWS ECR."),s("The default is the latest Medplum release.");let i=(await ut())[0]??"latest";e.serverImage=await D("Enter the server image:",`medplum/medplum-server:${i}`),R(r,e),I("SIGNING KEY"),s("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let c=await Aa(e.region,e.stackName+"SigningKey");c?(e.signingKeyId=c.keyId,e.storagePublicKey=c.publicKey,R(r,e)):(s("Unable to generate signing key."),s("Please manually create a signing key and enter the key ID and public key in the config file."),s('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),I("SSL CERTIFICATES"),s("Medplum will now check for existing SSL certificates for the subdomains.");let d=await wa(e.region);s("Found "+d.length+" certificate(s).");for(let{region:w,certName:A}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){s("");let b=await Ea(e,d,w,A);e[lo(A)]=b,R(r,e)}I("AWS PARAMETER STORE"),s("Medplum uses AWS Parameter Store to store sensitive configuration values."),s("These values will be encrypted at rest."),s(`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(c&&(l.signingKeyId=c.keyId,l.signingKey=c.privateKey,l.signingKeyPassphrase=c.passphrase),s(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await le("Do you want to store these values in AWS Parameter Store?"))await mt(e.region,`/medplum/${e.name}/`,l);else{let w=te(e.name,{server:!0});R(w,l),s("Skipping AWS Parameter Store."),s(`Writing values to local config file: ${w}`),s("Please add these values to AWS Parameter Store manually.")}I("DONE!"),s("Medplum configuration complete."),s("You can now proceed to deploying the Medplum infrastructure with CDK."),s("Run:"),s(""),s(` npx cdk bootstrap -c config=${r}`),s(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?s(` npx cdk deploy -c config=${r}`):s(` npx cdk deploy -c config=${r} --all`),s(""),s("See Medplum documentation for more information:"),s(""),s(" https://www.medplum.com/docs/self-hosting/install-on-aws"),s(""),it()}async function ga(e){try{let t=new ht.STSClient({region:e}),r=new ht.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function wa(e){let t=await so(e);if(e!=="us-east-1"){let r=await so("us-east-1");t.push(...r)}return t}async function so(e){try{let t=new ue.ACMClient({region:e}),r=new ue.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ea(e,t,r,o){let n=e[ya(o)],i=t.find(d=>d.CertificateArn?.includes(r)&&d.DomainName===n);if(i)return s(`Found existing certificate for "${n}" in "${r}.`),i.CertificateArn;if(s(`No existing certificate found for "${n}" in "${r}.`),!await le("Do you want to request a new certificate?"))return s(`Please add your certificate ARN to the config file in the "${lo(o)}" setting.`),"TODO";let c=await Sa(r,n);return s("Certificate ARN: "+c),c}async function Sa(e,t){try{let r=await at("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new ue.ACMClient({region:e}),n=new ue.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Aa(e,t){let r=(0,Je.randomUUID)(),o=(0,Je.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new ft.CloudFrontClient({region:e}).send(new ft.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,Je.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,co.normalizeErrorString)(n));return}}async function mo(){let e=await qt();for(let t of e){let r=t.StackName,o=await Yt(r);o&&(dt(o),console.log(""))}}var fo=require("@aws-sdk/client-s3"),G=require("@medplum/core"),ho=K(require("fast-glob")),$=require("fs"),Zt=K(require("node-fetch")),yo=require("os"),me=require("path"),go=require("stream/promises");async function wo(e,t){let r=V(e,t);if(!r){await ae(e,t);return}let o=await Ce(e);if(!o){await Ie(e);return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let i=t?.version??"latest",c=await va("@medplum/app",i);Eo(c,{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 Ia(c,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await lt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function ba(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Zt.default)(r)).json()}async function va(e,t){let o=(await ba(e,t)).dist.tarball,n=(0,$.mkdtempSync)((0,me.join)((0,yo.tmpdir)(),"tarball-"));try{let i=await(0,Zt.default)(o),c=Mr(n);return await(0,go.pipeline)(i.body,c),(0,me.join)(n,"package","dist")}catch(i){throw(0,$.rmSync)(n,{recursive:!0,force:!0}),i}}function Eo(e,t){for(let r of(0,$.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Eo(o,t):r.isFile()&&o.endsWith(".js")&&Ca(o,t)}}function Ca(e,t){let r=(0,$.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,$.writeFileSync)(e,r)}async function Ia(e,t,r){let o=[["assets/**/*.css",G.ContentType.CSS,!0],["assets/**/*.css.map",G.ContentType.JSON,!0],["assets/**/*.js",G.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",G.ContentType.JSON,!0],["assets/**/*.txt",G.ContentType.TEXT,!0],["assets/**/*.ico",G.ContentType.FAVICON,!0],["img/**/*.png",G.ContentType.PNG,!0],["img/**/*.svg",G.ContentType.SVG,!0],["robots.txt",G.ContentType.TEXT,!0],["index.html",G.ContentType.HTML,!1]];for(let n of o)await Pa({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Pa(e){let t=ho.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Ra((0,me.join)(e.rootDir,r),e)}async function Ra(e,t){let r=(0,$.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await Ue.send(new fo.PutObjectCommand(n))}var yt=require("@aws-sdk/client-s3");async function Ao(e,t){if(!V(e,t)){await ae(e,t);return}let o=await Ce(e);if(!o){await Ie(e);return}await So("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await So("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function So(e,t,r,o,n){if(!t?.PhysicalResourceId){console.log(`${e} bucket not found`);return}if(!r?.PhysicalResourceId){console.log(`${e} distribution not found`);return}if(!o?.PhysicalResourceId){console.log(`${e} OAI not found`);return}let i=t.PhysicalResourceId,c=o.PhysicalResourceId,d=await Ta(i);if(Oa(d,i,c)){console.log(`${e} bucket already has policy statement`);return}Na(d,i,c),console.log(`${e} bucket policy:`),console.log(JSON.stringify(d,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await xa(i,d),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await lt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Ta(e){let t=await Ue.send(new yt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function xa(e,t){await Ue.send(new yt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Oa(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 Na(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 bo(e,t){try{nt();let r=V(e,t);if(!r){await ae(e,t);return}let o=Lr(e)??{};_a(r,o),Ha(r,o),s("Medplum uses AWS Parameter Store to store sensitive configuration values."),s("These values will be encrypted at rest."),s(`The values will be stored in the "/medplum/${r.name}" path.`),s(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await le("Do you want to store these values in AWS Parameter Store?")&&await mt(r.region,`/medplum/${r.name}/`,o)}finally{it()}}function _a(e,t){gt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),gt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),gt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),gt(e.storageDomainName&&`https://${e.storageDomainName}/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function gt(e,t,r){if(Da(e,t))throw new Error(r)}function Da(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ha(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 Co=require("child_process"),Pe=K(zt());async function Io(e,t){let r=await S(t),o=V(e,t);if(!o){console.log(`Configuration file ${te(e)} not found`),await ae(e,t);return}let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),c=await Ka(r,o),d=await vo(c);for(;d;){if(t.version&&Pe.gt(d,t.version)){console.log(`Skipping update to v${d}`);break}console.log(`Performing update to v${d}`),o.serverImage=`${i}:${d}`,ka(e,o),await r.startAsyncRequest("/admin/super/migrate"),d=await vo(d)}}async function Ka(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let i=o.indexOf("-");i>-1&&(o=o.slice(0,i))}return o}async function vo(e,t){let r=await ut(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function ka(e,t){let r=te(e);R(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Co.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 Ro(){let e=new Po.Command("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(uo),e.command("list").description("List Medplum AWS CloudFormation stacks").action(mo),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(ao),e.command("update-config").alias("deploy-config").description("Update the AWS Parameter Store config values").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(bo),e.addCommand(h("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(Io)),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("--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.").action(wo),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(Ao),e}var To=require("commander");var xo=h("save"),Oo=h("deploy"),No=h("create"),_o=new To.Command("bot").addCommand(xo).addCommand(Oo).addCommand(No),Qt=h("save-bot"),er=h("deploy-bot"),tr=h("create-bot");xo.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e)});Oo.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e,!0)});No.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 i=await S(n);await Mt(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function wt(e,t,r=!1){let o=kr(t);for(let n of o){let i=await e.readResource("Bot",n.id);await kt(e,n,i),r&&await Lt(e,n,i)}console.log(`Number of bots deployed: ${o.length}`)}Qt.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e)});er.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e,!0)});tr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await S(n);await Mt(i,e,t,r,o)});var Ho=require("commander"),Et=require("fs"),rr=require("path"),Ko=require("readline");var ko=h("export"),Lo=h("import"),Mo=new Ho.Command("bulk").addCommand(ko).addCommand(Lo);ko.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,i=await S(e);(await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:d,url:l})=>{let w=new URL(l),A=await i.download(l),b=`${d}_${w.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",T=(0,rr.resolve)(n??"",b);(0,Et.writeFile)(`${T}`,await A.text(),()=>{console.log(`${T} is created`)})})});Lo.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,i=(0,rr.resolve)(n??process.cwd(),e),c=await S(t);await La(i,parseInt(r,10),c,o)});async function La(e,t,r,o){let n=[],i=(0,Et.createReadStream)(e),c=(0,Ko.createInterface)({input:i});for await(let d of c){let l=Ma(d,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await Do(n,r),n=[])}n.length>0&&await Do(n,r)}async function Do(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{ee(o.response)})}function Ma(e,t){let r=JSON.parse(e);return t?Wa(r):r}function Wa(e){return e.resourceType==="ExplanationOfBenefit"?Ua(e):e}function Ua(e){return e.provider||(e.provider=Wt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Wt())}),e}var St=require("@medplum/core");var Fo=require("net"),Bo=require("@medplum/core"),Vo=K(require("net"),1),$o=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Ja="\v",Wo="",Uo="\r",$a=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Jo=class extends Event{constructor(e){super("error"),this.error=e}},Go=class extends $o{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(Wo+Uo)){let n=Bo.Hl7Message.parse(r.substring(1,r.length-2));this.dispatchEvent(new $a(this,n)),r=""}}catch(n){this.dispatchEvent(new Jo(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new Jo(o))})}send(e){this.socket.write(Ja+e.toString()+Wo+Uo)}async sendAndWait(e){let t=new Promise(r=>{function o(n){n.target.removeEventListener("message",o),r(n.message)}this.addEventListener("message",o)});return this.send(e),t}close(){this.socket.end(),this.socket.destroy()}},jo=class extends $o{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port}connect(){return this.connection?Promise.resolve(this.connection):new Promise(e=>{let t=(0,Fo.connect)({host:this.host,port:this.port},()=>{this.connection=new Go(t),e(this.connection)})})}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)}},Xo=class{constructor(e){this.handler=e}start(e,t){let r=Vo.default.createServer(o=>{let n=new Go(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};var zo=require("commander"),qo=require("fs");var Fa=h("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").action(async(e,t,r,o)=>{if(o.generateExample?r=Ga():o.file&&(r=(0,qo.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new jo({host:e,port:parseInt(t,10)});try{let i=await n.sendAndWait(St.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
6
6
|
`))}finally{n.close()}}),Ba=h("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").action(async e=>{new Xo(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
|
|
7
7
|
`)),r.send(o.buildAck())})}).start(parseInt(e,10)),console.log("Listening on port "+e)}),Yo=new zo.Command("hl7").addCommand(Fa).addCommand(Ba);function Ga(){let e=(0,St.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
|
|
8
8
|
EVN|A01|${e}||
|