@medplum/cli 3.2.7 → 3.2.9
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 +4 -4
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/esm/index.mjs +4 -4
- package/dist/esm/index.mjs.map +1 -1
- package/package.json +12 -12
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var tn=Object.create;var ye=Object.defineProperty;var rn=Object.getOwnPropertyDescriptor;var on=Object.getOwnPropertyNames;var nn=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty;var an=(e,t,r)=>t in e?ye(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),ln=(e,t)=>{for(var r in t)ye(e,r,{get:t[r],enumerable:!0})},Zt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of on(t))!sn.call(e,n)&&n!==r&&ye(e,n,{get:()=>t[n],enumerable:!(o=rn(t,n))||o.enumerable});return e};var N=(e,t,r)=>(r=e!=null?tn(nn(e)):{},Zt(t||!e||!e.__esModule?ye(r,"default",{value:e,enumerable:!0}):r,e)),un=e=>Zt(ye({},"__esModule",{value:!0}),e);var T=(e,t,r)=>an(e,typeof t!="symbol"?t+"":t,r);var $t=cn((d,_r)=>{"use strict";d=_r.exports=m;var E;typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?E=function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:E=function(){};d.SEMVER_SPEC_VERSION="2.0.0";var Re=256,Be=Number.MAX_SAFE_INTEGER||9007199254740991,Lt=16,$n=Re-6,le=d.re=[],y=d.safeRe=[],l=d.src=[],s=d.tokens={},Mr=0;function f(e){s[e]=Mr++}var Dt="[a-zA-Z0-9-]",xt=[["\\s",1],["\\d",Re],[Dt,$n]];function Ae(e){for(var t=0;t<xt.length;t++){var r=xt[t][0],o=xt[t][1];e=e.split(r+"*").join(r+"{0,"+o+"}").split(r+"+").join(r+"{1,"+o+"}")}return e}f("NUMERICIDENTIFIER");l[s.NUMERICIDENTIFIER]="0|[1-9]\\d*";f("NUMERICIDENTIFIERLOOSE");l[s.NUMERICIDENTIFIERLOOSE]="\\d+";f("NONNUMERICIDENTIFIER");l[s.NONNUMERICIDENTIFIER]="\\d*[a-zA-Z-]"+Dt+"*";f("MAINVERSION");l[s.MAINVERSION]="("+l[s.NUMERICIDENTIFIER]+")\\.("+l[s.NUMERICIDENTIFIER]+")\\.("+l[s.NUMERICIDENTIFIER]+")";f("MAINVERSIONLOOSE");l[s.MAINVERSIONLOOSE]="("+l[s.NUMERICIDENTIFIERLOOSE]+")\\.("+l[s.NUMERICIDENTIFIERLOOSE]+")\\.("+l[s.NUMERICIDENTIFIERLOOSE]+")";f("PRERELEASEIDENTIFIER");l[s.PRERELEASEIDENTIFIER]="(?:"+l[s.NUMERICIDENTIFIER]+"|"+l[s.NONNUMERICIDENTIFIER]+")";f("PRERELEASEIDENTIFIERLOOSE");l[s.PRERELEASEIDENTIFIERLOOSE]="(?:"+l[s.NUMERICIDENTIFIERLOOSE]+"|"+l[s.NONNUMERICIDENTIFIER]+")";f("PRERELEASE");l[s.PRERELEASE]="(?:-("+l[s.PRERELEASEIDENTIFIER]+"(?:\\."+l[s.PRERELEASEIDENTIFIER]+")*))";f("PRERELEASELOOSE");l[s.PRERELEASELOOSE]="(?:-?("+l[s.PRERELEASEIDENTIFIERLOOSE]+"(?:\\."+l[s.PRERELEASEIDENTIFIERLOOSE]+")*))";f("BUILDIDENTIFIER");l[s.BUILDIDENTIFIER]=Dt+"+";f("BUILD");l[s.BUILD]="(?:\\+("+l[s.BUILDIDENTIFIER]+"(?:\\."+l[s.BUILDIDENTIFIER]+")*))";f("FULL");f("FULLPLAIN");l[s.FULLPLAIN]="v?"+l[s.MAINVERSION]+l[s.PRERELEASE]+"?"+l[s.BUILD]+"?";l[s.FULL]="^"+l[s.FULLPLAIN]+"$";f("LOOSEPLAIN");l[s.LOOSEPLAIN]="[v=\\s]*"+l[s.MAINVERSIONLOOSE]+l[s.PRERELEASELOOSE]+"?"+l[s.BUILD]+"?";f("LOOSE");l[s.LOOSE]="^"+l[s.LOOSEPLAIN]+"$";f("GTLT");l[s.GTLT]="((?:<|>)?=?)";f("XRANGEIDENTIFIERLOOSE");l[s.XRANGEIDENTIFIERLOOSE]=l[s.NUMERICIDENTIFIERLOOSE]+"|x|X|\\*";f("XRANGEIDENTIFIER");l[s.XRANGEIDENTIFIER]=l[s.NUMERICIDENTIFIER]+"|x|X|\\*";f("XRANGEPLAIN");l[s.XRANGEPLAIN]="[v=\\s]*("+l[s.XRANGEIDENTIFIER]+")(?:\\.("+l[s.XRANGEIDENTIFIER]+")(?:\\.("+l[s.XRANGEIDENTIFIER]+")(?:"+l[s.PRERELEASE]+")?"+l[s.BUILD]+"?)?)?";f("XRANGEPLAINLOOSE");l[s.XRANGEPLAINLOOSE]="[v=\\s]*("+l[s.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+l[s.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+l[s.XRANGEIDENTIFIERLOOSE]+")(?:"+l[s.PRERELEASELOOSE]+")?"+l[s.BUILD]+"?)?)?";f("XRANGE");l[s.XRANGE]="^"+l[s.GTLT]+"\\s*"+l[s.XRANGEPLAIN]+"$";f("XRANGELOOSE");l[s.XRANGELOOSE]="^"+l[s.GTLT]+"\\s*"+l[s.XRANGEPLAINLOOSE]+"$";f("COERCE");l[s.COERCE]="(^|[^\\d])(\\d{1,"+Lt+"})(?:\\.(\\d{1,"+Lt+"}))?(?:\\.(\\d{1,"+Lt+"}))?(?:$|[^\\d])";f("COERCERTL");le[s.COERCERTL]=new RegExp(l[s.COERCE],"g");y[s.COERCERTL]=new RegExp(Ae(l[s.COERCE]),"g");f("LONETILDE");l[s.LONETILDE]="(?:~>?)";f("TILDETRIM");l[s.TILDETRIM]="(\\s*)"+l[s.LONETILDE]+"\\s+";le[s.TILDETRIM]=new RegExp(l[s.TILDETRIM],"g");y[s.TILDETRIM]=new RegExp(Ae(l[s.TILDETRIM]),"g");var Fn="$1~";f("TILDE");l[s.TILDE]="^"+l[s.LONETILDE]+l[s.XRANGEPLAIN]+"$";f("TILDELOOSE");l[s.TILDELOOSE]="^"+l[s.LONETILDE]+l[s.XRANGEPLAINLOOSE]+"$";f("LONECARET");l[s.LONECARET]="(?:\\^)";f("CARETTRIM");l[s.CARETTRIM]="(\\s*)"+l[s.LONECARET]+"\\s+";le[s.CARETTRIM]=new RegExp(l[s.CARETTRIM],"g");y[s.CARETTRIM]=new RegExp(Ae(l[s.CARETTRIM]),"g");var jn="$1^";f("CARET");l[s.CARET]="^"+l[s.LONECARET]+l[s.XRANGEPLAIN]+"$";f("CARETLOOSE");l[s.CARETLOOSE]="^"+l[s.LONECARET]+l[s.XRANGEPLAINLOOSE]+"$";f("COMPARATORLOOSE");l[s.COMPARATORLOOSE]="^"+l[s.GTLT]+"\\s*("+l[s.LOOSEPLAIN]+")$|^$";f("COMPARATOR");l[s.COMPARATOR]="^"+l[s.GTLT]+"\\s*("+l[s.FULLPLAIN]+")$|^$";f("COMPARATORTRIM");l[s.COMPARATORTRIM]="(\\s*)"+l[s.GTLT]+"\\s*("+l[s.LOOSEPLAIN]+"|"+l[s.XRANGEPLAIN]+")";le[s.COMPARATORTRIM]=new RegExp(l[s.COMPARATORTRIM],"g");y[s.COMPARATORTRIM]=new RegExp(Ae(l[s.COMPARATORTRIM]),"g");var Bn="$1$2$3";f("HYPHENRANGE");l[s.HYPHENRANGE]="^\\s*("+l[s.XRANGEPLAIN]+")\\s+-\\s+("+l[s.XRANGEPLAIN]+")\\s*$";f("HYPHENRANGELOOSE");l[s.HYPHENRANGELOOSE]="^\\s*("+l[s.XRANGEPLAINLOOSE]+")\\s+-\\s+("+l[s.XRANGEPLAINLOOSE]+")\\s*$";f("STAR");l[s.STAR]="(<|>)?=?\\s*\\*";for($=0;$<Mr;$++)E($,l[$]),le[$]||(le[$]=new RegExp(l[$]),y[$]=new RegExp(Ae(l[$])));var $;d.parse=te;function te(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m)return e;if(typeof e!="string"||e.length>Re)return null;var r=t.loose?y[s.LOOSE]:y[s.FULL];if(!r.test(e))return null;try{return new m(e,t)}catch{return null}}d.valid=Kn;function Kn(e,t){var r=te(e,t);return r?r.version:null}d.clean=Wn;function Wn(e,t){var r=te(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}d.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>Re)throw new TypeError("version is longer than "+Re+" characters");if(!(this instanceof m))return new m(e,t);E("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?y[s.LOOSE]:y[s.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>Be||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Be||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Be||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<Be)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 E("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)),ee(this.major,e.major)||ee(this.minor,e.minor)||ee(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(E("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 ee(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(E("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 ee(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};d.inc=Hn;function Hn(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}}d.diff=Gn;function Gn(e,t){if(Mt(e,t))return null;var r=te(e),o=te(t),n="";if(r.prerelease.length||o.prerelease.length){n="pre";var i="prerelease"}for(var a in r)if((a==="major"||a==="minor"||a==="patch")&&r[a]!==o[a])return n+a;return i}d.compareIdentifiers=ee;var xr=/^[0-9]+$/;function ee(e,t){var r=xr.test(e),o=xr.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1}d.rcompareIdentifiers=Vn;function Vn(e,t){return ee(t,e)}d.major=Jn;function Jn(e,t){return new m(e,t).major}d.minor=Xn;function Xn(e,t){return new m(e,t).minor}d.patch=qn;function qn(e,t){return new m(e,t).patch}d.compare=G;function G(e,t,r){return new m(e,r).compare(new m(t,r))}d.compareLoose=zn;function zn(e,t){return G(e,t,!0)}d.compareBuild=Yn;function Yn(e,t,r){var o=new m(e,r),n=new m(t,r);return o.compare(n)||o.compareBuild(n)}d.rcompare=Zn;function Zn(e,t,r){return G(t,e,r)}d.sort=Qn;function Qn(e,t){return e.sort(function(r,o){return d.compareBuild(r,o,t)})}d.rsort=ei;function ei(e,t){return e.sort(function(r,o){return d.compareBuild(o,r,t)})}d.gt=Ie;function Ie(e,t,r){return G(e,t,r)>0}d.lt=Ke;function Ke(e,t,r){return G(e,t,r)<0}d.eq=Mt;function Mt(e,t,r){return G(e,t,r)===0}d.neq=kr;function kr(e,t,r){return G(e,t,r)!==0}d.gte=kt;function kt(e,t,r){return G(e,t,r)>=0}d.lte=_t;function _t(e,t,r){return G(e,t,r)<=0}d.cmp=We;function We(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 Mt(e,r,o);case"!=":return kr(e,r,o);case">":return Ie(e,r,o);case">=":return kt(e,r,o);case"<":return Ke(e,r,o);case"<=":return _t(e,r,o);default:throw new TypeError("Invalid operator: "+t)}}d.Comparator=x;function x(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof x){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof x))return new x(e,t);e=e.trim().split(/\s+/).join(" "),E("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ue?this.value="":this.value=this.operator+this.semver.version,E("comp",this)}var ue={};x.prototype.parse=function(e){var t=this.options.loose?y[s.COMPARATORLOOSE]:y[s.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=ue};x.prototype.toString=function(){return this.value};x.prototype.test=function(e){if(E("Comparator.test",e,this.options.loose),this.semver===ue||e===ue)return!0;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}return We(e,this.operator,this.semver,this.options)};x.prototype.intersects=function(e,t){if(!(e instanceof x))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 I(e.value,t),He(this.value,r,t));if(e.operator==="")return e.value===""?!0:(r=new I(this.value,t),He(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,a=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),u=We(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),p=We(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return o||n||i&&a||u||p};d.Range=I;function I(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof I)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new I(e.raw,t);if(e instanceof x)return new I(e.value,t);if(!(this instanceof I))return new I(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()}I.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range};I.prototype.toString=function(){return this.range};I.prototype.parseRange=function(e){var t=this.options.loose,r=t?y[s.HYPHENRANGELOOSE]:y[s.HYPHENRANGE];e=e.replace(r,ui),E("hyphen replace",e),e=e.replace(y[s.COMPARATORTRIM],Bn),E("comparator trim",e,y[s.COMPARATORTRIM]),e=e.replace(y[s.TILDETRIM],Fn),e=e.replace(y[s.CARETTRIM],jn),e=e.split(/\s+/).join(" ");var o=t?y[s.COMPARATORLOOSE]:y[s.COMPARATOR],n=e.split(" ").map(function(i){return ri(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 x(i,this.options)},this),n};I.prototype.intersects=function(e,t){if(!(e instanceof I))throw new TypeError("a Range is required");return this.set.some(function(r){return Dr(r,t)&&e.set.some(function(o){return Dr(o,t)&&r.every(function(n){return o.every(function(i){return n.intersects(i,t)})})})})};function Dr(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}d.toComparators=ti;function ti(e,t){return new I(e,t).set.map(function(r){return r.map(function(o){return o.value}).join(" ").trim().split(" ")})}function ri(e,t){return E("comp",e,t),e=ii(e,t),E("caret",e),e=oi(e,t),E("tildes",e),e=ai(e,t),E("xrange",e),e=li(e,t),E("stars",e),e}function P(e){return!e||e.toLowerCase()==="x"||e==="*"}function oi(e,t){return e.trim().split(/\s+/).map(function(r){return ni(r,t)}).join(" ")}function ni(e,t){var r=t.loose?y[s.TILDELOOSE]:y[s.TILDE];return e.replace(r,function(o,n,i,a,u){E("tilde",e,o,n,i,a,u);var p;return P(n)?p="":P(i)?p=">="+n+".0.0 <"+(+n+1)+".0.0":P(a)?p=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":u?(E("replaceTilde pr",u),p=">="+n+"."+i+"."+a+"-"+u+" <"+n+"."+(+i+1)+".0"):p=">="+n+"."+i+"."+a+" <"+n+"."+(+i+1)+".0",E("tilde return",p),p})}function ii(e,t){return e.trim().split(/\s+/).map(function(r){return si(r,t)}).join(" ")}function si(e,t){E("caret",e,t);var r=t.loose?y[s.CARETLOOSE]:y[s.CARET];return e.replace(r,function(o,n,i,a,u){E("caret",e,o,n,i,a,u);var p;return P(n)?p="":P(i)?p=">="+n+".0.0 <"+(+n+1)+".0.0":P(a)?n==="0"?p=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":p=">="+n+"."+i+".0 <"+(+n+1)+".0.0":u?(E("replaceCaret pr",u),n==="0"?i==="0"?p=">="+n+"."+i+"."+a+"-"+u+" <"+n+"."+i+"."+(+a+1):p=">="+n+"."+i+"."+a+"-"+u+" <"+n+"."+(+i+1)+".0":p=">="+n+"."+i+"."+a+"-"+u+" <"+(+n+1)+".0.0"):(E("no pr"),n==="0"?i==="0"?p=">="+n+"."+i+"."+a+" <"+n+"."+i+"."+(+a+1):p=">="+n+"."+i+"."+a+" <"+n+"."+(+i+1)+".0":p=">="+n+"."+i+"."+a+" <"+(+n+1)+".0.0"),E("caret return",p),p})}function ai(e,t){return E("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return ci(r,t)}).join(" ")}function ci(e,t){e=e.trim();var r=t.loose?y[s.XRANGELOOSE]:y[s.XRANGE];return e.replace(r,function(o,n,i,a,u,p){E("xRange",e,o,n,i,a,u,p);var g=P(i),w=g||P(a),R=w||P(u),v=R;return n==="="&&v&&(n=""),p=t.includePrerelease?"-0":"",g?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&v?(w&&(a=0),u=0,n===">"?(n=">=",w?(i=+i+1,a=0,u=0):(a=+a+1,u=0)):n==="<="&&(n="<",w?i=+i+1:a=+a+1),o=n+i+"."+a+"."+u+p):w?o=">="+i+".0.0"+p+" <"+(+i+1)+".0.0"+p:R&&(o=">="+i+"."+a+".0"+p+" <"+i+"."+(+a+1)+".0"+p),E("xRange return",o),o})}function li(e,t){return E("replaceStars",e,t),e.trim().replace(y[s.STAR],"")}function ui(e,t,r,o,n,i,a,u,p,g,w,R,v){return P(r)?t="":P(o)?t=">="+r+".0.0":P(n)?t=">="+r+"."+o+".0":t=">="+t,P(p)?u="":P(g)?u="<"+(+p+1)+".0.0":P(w)?u="<"+p+"."+(+g+1)+".0":R?u="<="+p+"."+g+"."+w+"-"+R:u="<="+u,(t+" "+u).trim()}I.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(pi(this.set[t],e,this.options))return!0;return!1};function pi(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(E(e[o].semver),e[o].semver!==ue&&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}d.satisfies=He;function He(e,t,r){try{t=new I(t,r)}catch{return!1}return t.test(e)}d.maxSatisfying=di;function di(e,t,r){var o=null,n=null;try{var i=new I(t,r)}catch{return null}return e.forEach(function(a){i.test(a)&&(!o||n.compare(a)===-1)&&(o=a,n=new m(o,r))}),o}d.minSatisfying=mi;function mi(e,t,r){var o=null,n=null;try{var i=new I(t,r)}catch{return null}return e.forEach(function(a){i.test(a)&&(!o||n.compare(a)===1)&&(o=a,n=new m(o,r))}),o}d.minVersion=fi;function fi(e,t){e=new I(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 a=new m(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!r||Ie(r,a))&&(r=a);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+i.operator)}})}return r&&e.test(r)?r:null}d.validRange=hi;function hi(e,t){try{return new I(e,t).range||"*"}catch{return null}}d.ltr=gi;function gi(e,t,r){return Ut(e,t,"<",r)}d.gtr=yi;function yi(e,t,r){return Ut(e,t,">",r)}d.outside=Ut;function Ut(e,t,r,o){e=new m(e,o),t=new I(t,o);var n,i,a,u,p;switch(r){case">":n=Ie,i=_t,a=Ke,u=">",p=">=";break;case"<":n=Ke,i=kt,a=Ie,u="<",p="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(He(e,t,o))return!1;for(var g=0;g<t.set.length;++g){var w=t.set[g],R=null,v=null;if(w.forEach(function(O){O.semver===ue&&(O=new x(">=0.0.0")),R=R||O,v=v||O,n(O.semver,R.semver,o)?R=O:a(O.semver,v.semver,o)&&(v=O)}),R.operator===u||R.operator===p||(!v.operator||v.operator===u)&&i(e,v.semver))return!1;if(v.operator===p&&a(e,v.semver))return!1}return!0}d.prerelease=Ei;function Ei(e,t){var r=te(e,t);return r&&r.prerelease.length?r.prerelease:null}d.intersects=Si;function Si(e,t,r){return e=new I(e,r),t=new I(t,r),e.intersects(t)}d.coerce=wi;function wi(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[s.COERCE]);else{for(var o;(o=y[s.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[s.COERCERTL].lastIndex=o.index+o[1].length+o[2].length;y[s.COERCERTL].lastIndex=-1}return r===null?null:te(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}});var is={};ln(is,{handleError:()=>Qo,main:()=>Zo,run:()=>en});module.exports=un(is);var ge=require("@medplum/core"),be=require("commander"),Yo=N(require("dotenv"));var M=require("@medplum/core"),Pr=require("child_process"),br=require("http"),Or=require("os");var tr=require("@medplum/core");var Qt=require("@medplum/core"),F=require("fs"),er=require("os"),dt=require("path"),_=class extends Qt.ClientStorage{constructor(t){super(),this.dirName=(0,dt.resolve)((0,er.homedir)(),".medplum"),this.fileName=(0,dt.resolve)(this.dirName,t+".json")}clear(){this.writeFile({})}getString(t){return this.readFile()?.[t]}setString(t,r){let o=this.readFile()??{};r?o[t]=r:delete o[t],this.writeFile(o)}getObject(t){let r=this.getString(t);return r?JSON.parse(r):void 0}setObject(t,r){this.setString(t,r?JSON.stringify(r):void 0)}readFile(){if((0,F.existsSync)(this.fileName))return JSON.parse((0,F.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,F.existsSync)(this.dirName)||(0,F.mkdirSync)(this.dirName),(0,F.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function S(e,t=!0){let r=e.profile??"default",o=new _(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:a,accessToken:u,tokenUrl:p,authorizeUrl:g,clientId:w,clientSecret:R}=pn(e,o),v=e.fetch??fetch,O=new tr.MedplumClient({fetch:v,baseUrl:i,tokenUrl:p,fhirUrlPath:a,authorizeUrl:g,storage:o,onUnauthenticated:dn,verbose:e.verbose});return t&&(u?O.setAccessToken(u):w&&R&&(O.setBasicAuth(w,R),n?.authType!=="basic"&&await O.startClientLogin(w,R))),O}function pn(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,a=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,u=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,p=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,g=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:i,tokenUrl:a,authorizeUrl:u,clientId:p,clientSecret:g}}function dn(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Oe=require("commander");function h(e){return new Oe.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 Oe.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var Q=require("@medplum/core");var or=require("buffer");var Y=new TextEncoder,mt=new TextDecoder,ds=2**32;function rr(...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 Ne=e=>or.Buffer.from(e).toString("base64url");var ie=class extends Error{constructor(r){super(r);T(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}static get code(){return"ERR_JOSE_GENERIC"}};var L=class extends ie{constructor(){super(...arguments);T(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var J=class extends ie{constructor(){super(...arguments);T(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},Le=class extends ie{constructor(){super(...arguments);T(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var ir,sr,nr=class extends(sr=ie,ir=Symbol.asyncIterator,sr){constructor(){super(...arguments);T(this,ir);T(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");T(this,"message","multiple matching keys found in the JSON Web Key Set")}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};var ar=N(require("util"),1),xe=e=>ar.types.isKeyObject(e);var cr=N(require("crypto"),1),lr=N(require("util"),1),fn=cr.webcrypto,ur=fn,se=e=>lr.types.isCryptoKey(e);function j(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function De(e,t){return e.name===t}function ft(e){return parseInt(e.name.slice(4),10)}function hn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function gn(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 pr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!De(e.algorithm,"HMAC"))throw j("HMAC");let o=parseInt(t.slice(2),10);if(ft(e.algorithm.hash)!==o)throw j(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!De(e.algorithm,"RSASSA-PKCS1-v1_5"))throw j("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(ft(e.algorithm.hash)!==o)throw j(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!De(e.algorithm,"RSA-PSS"))throw j("RSA-PSS");let o=parseInt(t.slice(2),10);if(ft(e.algorithm.hash)!==o)throw j(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw j("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!De(e.algorithm,"ECDSA"))throw j("ECDSA");let o=hn(t);if(e.algorithm.namedCurve!==o)throw j(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}gn(e,r)}function dr(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 Ee=(e,...t)=>dr("Key must be ",e,...t);function ht(e,t,...r){return dr(`Key for the ${e} algorithm must be `,t,...r)}var gt=e=>xe(e)||se(e),B=["KeyObject"];(globalThis.CryptoKey||ur?.CryptoKey)&&B.push("CryptoKey");var yn=(...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},mr=yn;function En(e){return typeof e=="object"&&e!==null}function yt(e){if(!En(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 fr=require("crypto");var Sn=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new L("Unsupported key curve for this operation")}},wn=(e,t)=>{let r;if(se(e))r=fr.KeyObject.from(e);else if(xe(e))r=e;else throw new TypeError(Ee(e,...B));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:Sn(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},hr=wn;var Et=(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 ae=e=>e?.[Symbol.toStringTag],Rn=(e,t)=>{if(!(t instanceof Uint8Array)){if(!gt(t))throw new TypeError(ht(e,t,...B,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ae(t)} instances for symmetric algorithms must be of type "secret"`)}},In=(e,t,r)=>{if(!gt(t))throw new TypeError(ht(e,t,...B));if(t.type==="secret")throw new TypeError(`${ae(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ae(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ae(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ae(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ae(t)} instances for asymmetric algorithm encryption must be of type "public"`)},An=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Rn(e,t):In(e,t,r)},gr=An;function Cn(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(a=>typeof a!="string"||a.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 a of o.crit){if(!i.has(a))throw new L(`Extension Header Parameter "${a}" is not recognized`);if(n[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&o[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(o.crit)}var yr=Cn;function St(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 L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var wt=require("crypto");var vn={padding:wt.constants.RSA_PKCS1_PSS_PADDING,saltLength:wt.constants.RSA_PSS_SALTLEN_DIGEST},Tn=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Rt(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 Et(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 Et(t,e),{key:t,...vn};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=hr(t),o=Tn.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 L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Me=N(require("crypto"),1),Er=require("util");function It(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Se=require("crypto");function At(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ee(t,...B));return(0,Se.createSecretKey)(t)}if(t instanceof Se.KeyObject)return t;if(se(t))return pr(t,e,r),Se.KeyObject.from(t);throw new TypeError(Ee(t,...B,"Uint8Array"))}var Pn=(0,Er.promisify)(Me.sign),bn=async(e,t,r)=>{let o=At(e,t,"sign");if(e.startsWith("HS")){let n=Me.createHmac(It(e),o);return n.update(r),n.digest()}return Pn(St(e),r,Rt(e,o))},Sr=bn;var X=e=>Math.floor(e.getTime()/1e3);var On=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ke=e=>{let t=On.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 _e=class{constructor(t){T(this,"_payload");T(this,"_protectedHeader");T(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 J("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!mr(this._protectedHeader,this._unprotectedHeader))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=yr(J,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),i=!0;if(n.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');gr(a,t,"sign");let u=this._payload;i&&(u=Y.encode(Ne(u)));let p;this._protectedHeader?p=Y.encode(Ne(JSON.stringify(this._protectedHeader))):p=Y.encode("");let g=rr(p,Y.encode("."),u),w=await Sr(a,t,g),R={signature:Ne(w),payload:""};return i&&(R.payload=mt.decode(u)),this._unprotectedHeader&&(R.header=this._unprotectedHeader),this._protectedHeader&&(R.protected=mt.decode(p)),R}};var Ue=class{constructor(t){T(this,"_flattened");this._flattened=new _e(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 Z(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var $e=class{constructor(t={}){T(this,"_payload");if(!yt(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:Z("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:Z("setNotBefore",X(t))}:this._payload={...this._payload,nbf:X(new Date)+ke(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:Z("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:Z("setExpirationTime",X(t))}:this._payload={...this._payload,exp:X(new Date)+ke(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:X(new Date)}:t instanceof Date?this._payload={...this._payload,iat:Z("setIssuedAt",X(t))}:typeof t=="string"?this._payload={...this._payload,iat:Z("setIssuedAt",X(new Date)+ke(t))}:this._payload={...this._payload,iat:Z("setIssuedAt",t)},this}};var we=class extends $e{constructor(){super(...arguments);T(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new Ue(Y.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 Le("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var ce=require("crypto"),q=require("fs"),K=require("path"),wr=require("tar");function W(e){console.log(JSON.stringify(e,null,2))}async function Ct(e,t,r){let o=t.source,n=Fe(o);if(!n)return;console.log("Saving source code...");let i=await e.createAttachment(n,(0,K.basename)(o),xn(o));console.log("Updating bot...");let a=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+a.meta?.versionId)}async function vt(e,t,r){let o=t.dist??t.source,n=Fe(o);if(!n)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,K.basename)(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function Tt(e,t,r,o,n,i,a){let u={name:t,description:"",runtimeVersion:i},p=await e.post("admin/projects/"+r+"/bot",u),g=await e.readResource("Bot",p.id),w={name:t,id:p.id,source:o,dist:n};await Ct(e,w,g),await vt(e,w,g),console.log(`Success! Bot created: ${g.id}`),a&&Nn(w)}function Rr(e){let t=new RegExp("^"+Ln(e).replace(/\\\*/g,".*")+"$"),r=U()?.bots?.filter(o=>t.test(o.name));return r||[]}function H(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function C(e,t){(0,q.writeFileSync)((0,K.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function U(e,t){let r=H(e,t),o=Fe(r);if(o)return JSON.parse(o)}function Ir(e){let t=Fe(H(e,{server:!0}));if(t)return JSON.parse(t)}function Fe(e){let t=(0,K.resolve)(e);return(0,q.existsSync)(t)?(0,q.readFileSync)(t,"utf8"):""}function Nn(e){let t=U()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,q.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Ln(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Ar(e){let o=0,n=0;return(0,wr.extract)({cwd:e,filter:(i,a)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=a.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Pt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function xn(e){let t=(0,K.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Q.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Q.ContentType.TYPESCRIPT:Q.ContentType.TEXT}function je(e,t){let r=new _(e),o={name:e,...t};return r.setObject("options",o),o}function Cr(e){return new _(e).getObject("options")}async function vr(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,Q.encodeBase64)(JSON.stringify(r)),a=(0,Q.encodeBase64)(JSON.stringify(n)),u=`${i}.${a}`,p=(0,ce.createHmac)("sha256",t.clientSecret).update(u).digest("base64url"),g=`${u}.${p}`;await e.startJwtBearerLogin(t.clientId,g,t.scope??"")}async function Tr(e,t){let r=(0,ce.createPrivateKey)((0,q.readFileSync)((0,K.resolve)(t.privateKeyPath))),o=await new we({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ce.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Nr=M.MEDPLUM_CLI_CLIENT_ID,Lr="http://localhost:9615",bt=h("login"),Ot=h("whoami"),Nt=h("token");bt.action(async e=>{let t=e.profile??"default",r=je(t,e),o=await S(e,!1);await Dn(o,r)});Ot.action(async e=>{let t=await S(e);_n(t)});Nt.action(async e=>{let t=await S(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log("Access token:"),console.log(),console.log(r)});async function Dn(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Un(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 vr(e,t);break;case"jwt-assertion":await Tr(e,t);break}}async function Mn(e){let t=(0,br.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":M.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let a=await e.processCode(i,{clientId:Nr,redirectUri:Lr});o.writeHead(200,{"Content-Type":M.ContentType.TEXT}),o.end(`Signed in as ${(0,M.getDisplayString)(a)}. You may close this window.`)}catch(a){o.writeHead(400,{"Content-Type":M.ContentType.TEXT}),o.end(`Error: ${(0,M.normalizeErrorString)(a)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":M.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function kn(e){let t=(0,Or.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,Pr.exec)(r,(o,n,i)=>{if(o)throw o;if(i)throw new Error("Could not open browser: "+i)})}function _n(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 Un(e){await Mn(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Nr),t.searchParams.set("redirect_uri",Lr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await kn(t.toString())}var uo=require("commander");var V=require("@aws-sdk/client-cloudformation"),ze=require("@aws-sdk/client-cloudfront"),Fr=require("@aws-sdk/client-ecs"),jr=require("@aws-sdk/client-s3"),de=require("@aws-sdk/client-ssm"),Ye=require("@aws-sdk/client-sts"),Br=require("@medplum/core"),Kr=N(require("node-fetch")),Wr=require("fs"),Hr=N($t());var Ur=N(require("readline")),Ge;function Ve(){Ge=Ur.default.createInterface({input:process.stdin,output:process.stdout})}function Je(){Ge.close()}function c(e){Ge.write(e+`
|
|
2
|
+
"use strict";var tn=Object.create;var ye=Object.defineProperty;var rn=Object.getOwnPropertyDescriptor;var on=Object.getOwnPropertyNames;var nn=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty;var an=(e,t,r)=>t in e?ye(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),ln=(e,t)=>{for(var r in t)ye(e,r,{get:t[r],enumerable:!0})},Zt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of on(t))!sn.call(e,n)&&n!==r&&ye(e,n,{get:()=>t[n],enumerable:!(o=rn(t,n))||o.enumerable});return e};var N=(e,t,r)=>(r=e!=null?tn(nn(e)):{},Zt(t||!e||!e.__esModule?ye(r,"default",{value:e,enumerable:!0}):r,e)),un=e=>Zt(ye({},"__esModule",{value:!0}),e);var T=(e,t,r)=>an(e,typeof t!="symbol"?t+"":t,r);var $t=cn((d,_r)=>{"use strict";d=_r.exports=m;var E;typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?E=function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:E=function(){};d.SEMVER_SPEC_VERSION="2.0.0";var Re=256,Be=Number.MAX_SAFE_INTEGER||9007199254740991,Lt=16,$n=Re-6,le=d.re=[],y=d.safeRe=[],l=d.src=[],s=d.tokens={},Mr=0;function f(e){s[e]=Mr++}var Dt="[a-zA-Z0-9-]",xt=[["\\s",1],["\\d",Re],[Dt,$n]];function Ae(e){for(var t=0;t<xt.length;t++){var r=xt[t][0],o=xt[t][1];e=e.split(r+"*").join(r+"{0,"+o+"}").split(r+"+").join(r+"{1,"+o+"}")}return e}f("NUMERICIDENTIFIER");l[s.NUMERICIDENTIFIER]="0|[1-9]\\d*";f("NUMERICIDENTIFIERLOOSE");l[s.NUMERICIDENTIFIERLOOSE]="\\d+";f("NONNUMERICIDENTIFIER");l[s.NONNUMERICIDENTIFIER]="\\d*[a-zA-Z-]"+Dt+"*";f("MAINVERSION");l[s.MAINVERSION]="("+l[s.NUMERICIDENTIFIER]+")\\.("+l[s.NUMERICIDENTIFIER]+")\\.("+l[s.NUMERICIDENTIFIER]+")";f("MAINVERSIONLOOSE");l[s.MAINVERSIONLOOSE]="("+l[s.NUMERICIDENTIFIERLOOSE]+")\\.("+l[s.NUMERICIDENTIFIERLOOSE]+")\\.("+l[s.NUMERICIDENTIFIERLOOSE]+")";f("PRERELEASEIDENTIFIER");l[s.PRERELEASEIDENTIFIER]="(?:"+l[s.NUMERICIDENTIFIER]+"|"+l[s.NONNUMERICIDENTIFIER]+")";f("PRERELEASEIDENTIFIERLOOSE");l[s.PRERELEASEIDENTIFIERLOOSE]="(?:"+l[s.NUMERICIDENTIFIERLOOSE]+"|"+l[s.NONNUMERICIDENTIFIER]+")";f("PRERELEASE");l[s.PRERELEASE]="(?:-("+l[s.PRERELEASEIDENTIFIER]+"(?:\\."+l[s.PRERELEASEIDENTIFIER]+")*))";f("PRERELEASELOOSE");l[s.PRERELEASELOOSE]="(?:-?("+l[s.PRERELEASEIDENTIFIERLOOSE]+"(?:\\."+l[s.PRERELEASEIDENTIFIERLOOSE]+")*))";f("BUILDIDENTIFIER");l[s.BUILDIDENTIFIER]=Dt+"+";f("BUILD");l[s.BUILD]="(?:\\+("+l[s.BUILDIDENTIFIER]+"(?:\\."+l[s.BUILDIDENTIFIER]+")*))";f("FULL");f("FULLPLAIN");l[s.FULLPLAIN]="v?"+l[s.MAINVERSION]+l[s.PRERELEASE]+"?"+l[s.BUILD]+"?";l[s.FULL]="^"+l[s.FULLPLAIN]+"$";f("LOOSEPLAIN");l[s.LOOSEPLAIN]="[v=\\s]*"+l[s.MAINVERSIONLOOSE]+l[s.PRERELEASELOOSE]+"?"+l[s.BUILD]+"?";f("LOOSE");l[s.LOOSE]="^"+l[s.LOOSEPLAIN]+"$";f("GTLT");l[s.GTLT]="((?:<|>)?=?)";f("XRANGEIDENTIFIERLOOSE");l[s.XRANGEIDENTIFIERLOOSE]=l[s.NUMERICIDENTIFIERLOOSE]+"|x|X|\\*";f("XRANGEIDENTIFIER");l[s.XRANGEIDENTIFIER]=l[s.NUMERICIDENTIFIER]+"|x|X|\\*";f("XRANGEPLAIN");l[s.XRANGEPLAIN]="[v=\\s]*("+l[s.XRANGEIDENTIFIER]+")(?:\\.("+l[s.XRANGEIDENTIFIER]+")(?:\\.("+l[s.XRANGEIDENTIFIER]+")(?:"+l[s.PRERELEASE]+")?"+l[s.BUILD]+"?)?)?";f("XRANGEPLAINLOOSE");l[s.XRANGEPLAINLOOSE]="[v=\\s]*("+l[s.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+l[s.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+l[s.XRANGEIDENTIFIERLOOSE]+")(?:"+l[s.PRERELEASELOOSE]+")?"+l[s.BUILD]+"?)?)?";f("XRANGE");l[s.XRANGE]="^"+l[s.GTLT]+"\\s*"+l[s.XRANGEPLAIN]+"$";f("XRANGELOOSE");l[s.XRANGELOOSE]="^"+l[s.GTLT]+"\\s*"+l[s.XRANGEPLAINLOOSE]+"$";f("COERCE");l[s.COERCE]="(^|[^\\d])(\\d{1,"+Lt+"})(?:\\.(\\d{1,"+Lt+"}))?(?:\\.(\\d{1,"+Lt+"}))?(?:$|[^\\d])";f("COERCERTL");le[s.COERCERTL]=new RegExp(l[s.COERCE],"g");y[s.COERCERTL]=new RegExp(Ae(l[s.COERCE]),"g");f("LONETILDE");l[s.LONETILDE]="(?:~>?)";f("TILDETRIM");l[s.TILDETRIM]="(\\s*)"+l[s.LONETILDE]+"\\s+";le[s.TILDETRIM]=new RegExp(l[s.TILDETRIM],"g");y[s.TILDETRIM]=new RegExp(Ae(l[s.TILDETRIM]),"g");var Fn="$1~";f("TILDE");l[s.TILDE]="^"+l[s.LONETILDE]+l[s.XRANGEPLAIN]+"$";f("TILDELOOSE");l[s.TILDELOOSE]="^"+l[s.LONETILDE]+l[s.XRANGEPLAINLOOSE]+"$";f("LONECARET");l[s.LONECARET]="(?:\\^)";f("CARETTRIM");l[s.CARETTRIM]="(\\s*)"+l[s.LONECARET]+"\\s+";le[s.CARETTRIM]=new RegExp(l[s.CARETTRIM],"g");y[s.CARETTRIM]=new RegExp(Ae(l[s.CARETTRIM]),"g");var jn="$1^";f("CARET");l[s.CARET]="^"+l[s.LONECARET]+l[s.XRANGEPLAIN]+"$";f("CARETLOOSE");l[s.CARETLOOSE]="^"+l[s.LONECARET]+l[s.XRANGEPLAINLOOSE]+"$";f("COMPARATORLOOSE");l[s.COMPARATORLOOSE]="^"+l[s.GTLT]+"\\s*("+l[s.LOOSEPLAIN]+")$|^$";f("COMPARATOR");l[s.COMPARATOR]="^"+l[s.GTLT]+"\\s*("+l[s.FULLPLAIN]+")$|^$";f("COMPARATORTRIM");l[s.COMPARATORTRIM]="(\\s*)"+l[s.GTLT]+"\\s*("+l[s.LOOSEPLAIN]+"|"+l[s.XRANGEPLAIN]+")";le[s.COMPARATORTRIM]=new RegExp(l[s.COMPARATORTRIM],"g");y[s.COMPARATORTRIM]=new RegExp(Ae(l[s.COMPARATORTRIM]),"g");var Bn="$1$2$3";f("HYPHENRANGE");l[s.HYPHENRANGE]="^\\s*("+l[s.XRANGEPLAIN]+")\\s+-\\s+("+l[s.XRANGEPLAIN]+")\\s*$";f("HYPHENRANGELOOSE");l[s.HYPHENRANGELOOSE]="^\\s*("+l[s.XRANGEPLAINLOOSE]+")\\s+-\\s+("+l[s.XRANGEPLAINLOOSE]+")\\s*$";f("STAR");l[s.STAR]="(<|>)?=?\\s*\\*";for($=0;$<Mr;$++)E($,l[$]),le[$]||(le[$]=new RegExp(l[$]),y[$]=new RegExp(Ae(l[$])));var $;d.parse=te;function te(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m)return e;if(typeof e!="string"||e.length>Re)return null;var r=t.loose?y[s.LOOSE]:y[s.FULL];if(!r.test(e))return null;try{return new m(e,t)}catch{return null}}d.valid=Kn;function Kn(e,t){var r=te(e,t);return r?r.version:null}d.clean=Wn;function Wn(e,t){var r=te(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}d.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>Re)throw new TypeError("version is longer than "+Re+" characters");if(!(this instanceof m))return new m(e,t);E("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?y[s.LOOSE]:y[s.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>Be||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Be||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Be||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<Be)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 E("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)),ee(this.major,e.major)||ee(this.minor,e.minor)||ee(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(E("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 ee(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(E("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 ee(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};d.inc=Hn;function Hn(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}}d.diff=Gn;function Gn(e,t){if(Mt(e,t))return null;var r=te(e),o=te(t),n="";if(r.prerelease.length||o.prerelease.length){n="pre";var i="prerelease"}for(var a in r)if((a==="major"||a==="minor"||a==="patch")&&r[a]!==o[a])return n+a;return i}d.compareIdentifiers=ee;var xr=/^[0-9]+$/;function ee(e,t){var r=xr.test(e),o=xr.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1}d.rcompareIdentifiers=Vn;function Vn(e,t){return ee(t,e)}d.major=Jn;function Jn(e,t){return new m(e,t).major}d.minor=Xn;function Xn(e,t){return new m(e,t).minor}d.patch=qn;function qn(e,t){return new m(e,t).patch}d.compare=G;function G(e,t,r){return new m(e,r).compare(new m(t,r))}d.compareLoose=zn;function zn(e,t){return G(e,t,!0)}d.compareBuild=Yn;function Yn(e,t,r){var o=new m(e,r),n=new m(t,r);return o.compare(n)||o.compareBuild(n)}d.rcompare=Zn;function Zn(e,t,r){return G(t,e,r)}d.sort=Qn;function Qn(e,t){return e.sort(function(r,o){return d.compareBuild(r,o,t)})}d.rsort=ei;function ei(e,t){return e.sort(function(r,o){return d.compareBuild(o,r,t)})}d.gt=Ie;function Ie(e,t,r){return G(e,t,r)>0}d.lt=Ke;function Ke(e,t,r){return G(e,t,r)<0}d.eq=Mt;function Mt(e,t,r){return G(e,t,r)===0}d.neq=kr;function kr(e,t,r){return G(e,t,r)!==0}d.gte=kt;function kt(e,t,r){return G(e,t,r)>=0}d.lte=_t;function _t(e,t,r){return G(e,t,r)<=0}d.cmp=We;function We(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 Mt(e,r,o);case"!=":return kr(e,r,o);case">":return Ie(e,r,o);case">=":return kt(e,r,o);case"<":return Ke(e,r,o);case"<=":return _t(e,r,o);default:throw new TypeError("Invalid operator: "+t)}}d.Comparator=x;function x(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof x){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof x))return new x(e,t);e=e.trim().split(/\s+/).join(" "),E("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ue?this.value="":this.value=this.operator+this.semver.version,E("comp",this)}var ue={};x.prototype.parse=function(e){var t=this.options.loose?y[s.COMPARATORLOOSE]:y[s.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=ue};x.prototype.toString=function(){return this.value};x.prototype.test=function(e){if(E("Comparator.test",e,this.options.loose),this.semver===ue||e===ue)return!0;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}return We(e,this.operator,this.semver,this.options)};x.prototype.intersects=function(e,t){if(!(e instanceof x))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 I(e.value,t),He(this.value,r,t));if(e.operator==="")return e.value===""?!0:(r=new I(this.value,t),He(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,a=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),u=We(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),p=We(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return o||n||i&&a||u||p};d.Range=I;function I(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof I)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new I(e.raw,t);if(e instanceof x)return new I(e.value,t);if(!(this instanceof I))return new I(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()}I.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range};I.prototype.toString=function(){return this.range};I.prototype.parseRange=function(e){var t=this.options.loose,r=t?y[s.HYPHENRANGELOOSE]:y[s.HYPHENRANGE];e=e.replace(r,ui),E("hyphen replace",e),e=e.replace(y[s.COMPARATORTRIM],Bn),E("comparator trim",e,y[s.COMPARATORTRIM]),e=e.replace(y[s.TILDETRIM],Fn),e=e.replace(y[s.CARETTRIM],jn),e=e.split(/\s+/).join(" ");var o=t?y[s.COMPARATORLOOSE]:y[s.COMPARATOR],n=e.split(" ").map(function(i){return ri(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 x(i,this.options)},this),n};I.prototype.intersects=function(e,t){if(!(e instanceof I))throw new TypeError("a Range is required");return this.set.some(function(r){return Dr(r,t)&&e.set.some(function(o){return Dr(o,t)&&r.every(function(n){return o.every(function(i){return n.intersects(i,t)})})})})};function Dr(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}d.toComparators=ti;function ti(e,t){return new I(e,t).set.map(function(r){return r.map(function(o){return o.value}).join(" ").trim().split(" ")})}function ri(e,t){return E("comp",e,t),e=ii(e,t),E("caret",e),e=oi(e,t),E("tildes",e),e=ai(e,t),E("xrange",e),e=li(e,t),E("stars",e),e}function P(e){return!e||e.toLowerCase()==="x"||e==="*"}function oi(e,t){return e.trim().split(/\s+/).map(function(r){return ni(r,t)}).join(" ")}function ni(e,t){var r=t.loose?y[s.TILDELOOSE]:y[s.TILDE];return e.replace(r,function(o,n,i,a,u){E("tilde",e,o,n,i,a,u);var p;return P(n)?p="":P(i)?p=">="+n+".0.0 <"+(+n+1)+".0.0":P(a)?p=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":u?(E("replaceTilde pr",u),p=">="+n+"."+i+"."+a+"-"+u+" <"+n+"."+(+i+1)+".0"):p=">="+n+"."+i+"."+a+" <"+n+"."+(+i+1)+".0",E("tilde return",p),p})}function ii(e,t){return e.trim().split(/\s+/).map(function(r){return si(r,t)}).join(" ")}function si(e,t){E("caret",e,t);var r=t.loose?y[s.CARETLOOSE]:y[s.CARET];return e.replace(r,function(o,n,i,a,u){E("caret",e,o,n,i,a,u);var p;return P(n)?p="":P(i)?p=">="+n+".0.0 <"+(+n+1)+".0.0":P(a)?n==="0"?p=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":p=">="+n+"."+i+".0 <"+(+n+1)+".0.0":u?(E("replaceCaret pr",u),n==="0"?i==="0"?p=">="+n+"."+i+"."+a+"-"+u+" <"+n+"."+i+"."+(+a+1):p=">="+n+"."+i+"."+a+"-"+u+" <"+n+"."+(+i+1)+".0":p=">="+n+"."+i+"."+a+"-"+u+" <"+(+n+1)+".0.0"):(E("no pr"),n==="0"?i==="0"?p=">="+n+"."+i+"."+a+" <"+n+"."+i+"."+(+a+1):p=">="+n+"."+i+"."+a+" <"+n+"."+(+i+1)+".0":p=">="+n+"."+i+"."+a+" <"+(+n+1)+".0.0"),E("caret return",p),p})}function ai(e,t){return E("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return ci(r,t)}).join(" ")}function ci(e,t){e=e.trim();var r=t.loose?y[s.XRANGELOOSE]:y[s.XRANGE];return e.replace(r,function(o,n,i,a,u,p){E("xRange",e,o,n,i,a,u,p);var g=P(i),w=g||P(a),R=w||P(u),v=R;return n==="="&&v&&(n=""),p=t.includePrerelease?"-0":"",g?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&v?(w&&(a=0),u=0,n===">"?(n=">=",w?(i=+i+1,a=0,u=0):(a=+a+1,u=0)):n==="<="&&(n="<",w?i=+i+1:a=+a+1),o=n+i+"."+a+"."+u+p):w?o=">="+i+".0.0"+p+" <"+(+i+1)+".0.0"+p:R&&(o=">="+i+"."+a+".0"+p+" <"+i+"."+(+a+1)+".0"+p),E("xRange return",o),o})}function li(e,t){return E("replaceStars",e,t),e.trim().replace(y[s.STAR],"")}function ui(e,t,r,o,n,i,a,u,p,g,w,R,v){return P(r)?t="":P(o)?t=">="+r+".0.0":P(n)?t=">="+r+"."+o+".0":t=">="+t,P(p)?u="":P(g)?u="<"+(+p+1)+".0.0":P(w)?u="<"+p+"."+(+g+1)+".0":R?u="<="+p+"."+g+"."+w+"-"+R:u="<="+u,(t+" "+u).trim()}I.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(pi(this.set[t],e,this.options))return!0;return!1};function pi(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(E(e[o].semver),e[o].semver!==ue&&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}d.satisfies=He;function He(e,t,r){try{t=new I(t,r)}catch{return!1}return t.test(e)}d.maxSatisfying=di;function di(e,t,r){var o=null,n=null;try{var i=new I(t,r)}catch{return null}return e.forEach(function(a){i.test(a)&&(!o||n.compare(a)===-1)&&(o=a,n=new m(o,r))}),o}d.minSatisfying=mi;function mi(e,t,r){var o=null,n=null;try{var i=new I(t,r)}catch{return null}return e.forEach(function(a){i.test(a)&&(!o||n.compare(a)===1)&&(o=a,n=new m(o,r))}),o}d.minVersion=fi;function fi(e,t){e=new I(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 a=new m(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!r||Ie(r,a))&&(r=a);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+i.operator)}})}return r&&e.test(r)?r:null}d.validRange=hi;function hi(e,t){try{return new I(e,t).range||"*"}catch{return null}}d.ltr=gi;function gi(e,t,r){return Ut(e,t,"<",r)}d.gtr=yi;function yi(e,t,r){return Ut(e,t,">",r)}d.outside=Ut;function Ut(e,t,r,o){e=new m(e,o),t=new I(t,o);var n,i,a,u,p;switch(r){case">":n=Ie,i=_t,a=Ke,u=">",p=">=";break;case"<":n=Ke,i=kt,a=Ie,u="<",p="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(He(e,t,o))return!1;for(var g=0;g<t.set.length;++g){var w=t.set[g],R=null,v=null;if(w.forEach(function(O){O.semver===ue&&(O=new x(">=0.0.0")),R=R||O,v=v||O,n(O.semver,R.semver,o)?R=O:a(O.semver,v.semver,o)&&(v=O)}),R.operator===u||R.operator===p||(!v.operator||v.operator===u)&&i(e,v.semver))return!1;if(v.operator===p&&a(e,v.semver))return!1}return!0}d.prerelease=Ei;function Ei(e,t){var r=te(e,t);return r&&r.prerelease.length?r.prerelease:null}d.intersects=Si;function Si(e,t,r){return e=new I(e,r),t=new I(t,r),e.intersects(t)}d.coerce=wi;function wi(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[s.COERCE]);else{for(var o;(o=y[s.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[s.COERCERTL].lastIndex=o.index+o[1].length+o[2].length;y[s.COERCERTL].lastIndex=-1}return r===null?null:te(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}});var is={};ln(is,{handleError:()=>Qo,main:()=>Zo,run:()=>en});module.exports=un(is);var ge=require("@medplum/core"),be=require("commander"),Yo=N(require("dotenv"));var M=require("@medplum/core"),Pr=require("node:child_process"),br=require("node:http"),Or=require("node:os");var tr=require("@medplum/core");var Qt=require("@medplum/core"),F=require("node:fs"),er=require("node:os"),dt=require("node:path"),_=class extends Qt.ClientStorage{constructor(t){super(),this.dirName=(0,dt.resolve)((0,er.homedir)(),".medplum"),this.fileName=(0,dt.resolve)(this.dirName,t+".json")}clear(){this.writeFile({})}getString(t){return this.readFile()?.[t]}setString(t,r){let o=this.readFile()??{};r?o[t]=r:delete o[t],this.writeFile(o)}getObject(t){let r=this.getString(t);return r?JSON.parse(r):void 0}setObject(t,r){this.setString(t,r?JSON.stringify(r):void 0)}readFile(){if((0,F.existsSync)(this.fileName))return JSON.parse((0,F.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,F.existsSync)(this.dirName)||(0,F.mkdirSync)(this.dirName),(0,F.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function S(e,t=!0){let r=e.profile??"default",o=new _(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:a,accessToken:u,tokenUrl:p,authorizeUrl:g,clientId:w,clientSecret:R}=pn(e,o),v=e.fetch??fetch,O=new tr.MedplumClient({fetch:v,baseUrl:i,tokenUrl:p,fhirUrlPath:a,authorizeUrl:g,storage:o,onUnauthenticated:dn,verbose:e.verbose});return t&&(u?O.setAccessToken(u):w&&R&&(O.setBasicAuth(w,R),n?.authType!=="basic"&&await O.startClientLogin(w,R))),O}function pn(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,a=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,u=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,p=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,g=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:i,tokenUrl:a,authorizeUrl:u,clientId:p,clientSecret:g}}function dn(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Oe=require("commander");function h(e){return new Oe.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 Oe.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var Q=require("@medplum/core");var or=require("node:buffer");var Y=new TextEncoder,mt=new TextDecoder,ds=2**32;function rr(...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 Ne=e=>or.Buffer.from(e).toString("base64url");var ie=class extends Error{constructor(r){super(r);T(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}static get code(){return"ERR_JOSE_GENERIC"}};var L=class extends ie{constructor(){super(...arguments);T(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var J=class extends ie{constructor(){super(...arguments);T(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},Le=class extends ie{constructor(){super(...arguments);T(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var ir,sr,nr=class extends(sr=ie,ir=Symbol.asyncIterator,sr){constructor(){super(...arguments);T(this,ir);T(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");T(this,"message","multiple matching keys found in the JSON Web Key Set")}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};var ar=N(require("node:util"),1),xe=e=>ar.types.isKeyObject(e);var cr=N(require("node:crypto"),1),lr=N(require("node:util"),1),fn=cr.webcrypto,ur=fn,se=e=>lr.types.isCryptoKey(e);function j(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function De(e,t){return e.name===t}function ft(e){return parseInt(e.name.slice(4),10)}function hn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function gn(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 pr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!De(e.algorithm,"HMAC"))throw j("HMAC");let o=parseInt(t.slice(2),10);if(ft(e.algorithm.hash)!==o)throw j(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!De(e.algorithm,"RSASSA-PKCS1-v1_5"))throw j("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(ft(e.algorithm.hash)!==o)throw j(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!De(e.algorithm,"RSA-PSS"))throw j("RSA-PSS");let o=parseInt(t.slice(2),10);if(ft(e.algorithm.hash)!==o)throw j(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw j("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!De(e.algorithm,"ECDSA"))throw j("ECDSA");let o=hn(t);if(e.algorithm.namedCurve!==o)throw j(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}gn(e,r)}function dr(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 Ee=(e,...t)=>dr("Key must be ",e,...t);function ht(e,t,...r){return dr(`Key for the ${e} algorithm must be `,t,...r)}var gt=e=>xe(e)||se(e),B=["KeyObject"];(globalThis.CryptoKey||ur?.CryptoKey)&&B.push("CryptoKey");var yn=(...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},mr=yn;function En(e){return typeof e=="object"&&e!==null}function yt(e){if(!En(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 fr=require("node:crypto");var Sn=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new L("Unsupported key curve for this operation")}},wn=(e,t)=>{let r;if(se(e))r=fr.KeyObject.from(e);else if(xe(e))r=e;else throw new TypeError(Ee(e,...B));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:Sn(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},hr=wn;var Et=(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 ae=e=>e?.[Symbol.toStringTag],Rn=(e,t)=>{if(!(t instanceof Uint8Array)){if(!gt(t))throw new TypeError(ht(e,t,...B,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ae(t)} instances for symmetric algorithms must be of type "secret"`)}},In=(e,t,r)=>{if(!gt(t))throw new TypeError(ht(e,t,...B));if(t.type==="secret")throw new TypeError(`${ae(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ae(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ae(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ae(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ae(t)} instances for asymmetric algorithm encryption must be of type "public"`)},An=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Rn(e,t):In(e,t,r)},gr=An;function Cn(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(a=>typeof a!="string"||a.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 a of o.crit){if(!i.has(a))throw new L(`Extension Header Parameter "${a}" is not recognized`);if(n[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&o[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(o.crit)}var yr=Cn;function St(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 L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var wt=require("node:crypto");var vn={padding:wt.constants.RSA_PKCS1_PSS_PADDING,saltLength:wt.constants.RSA_PSS_SALTLEN_DIGEST},Tn=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Rt(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 Et(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 Et(t,e),{key:t,...vn};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=hr(t),o=Tn.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 L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Me=N(require("node:crypto"),1),Er=require("node:util");function It(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new L(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Se=require("node:crypto");function At(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ee(t,...B));return(0,Se.createSecretKey)(t)}if(t instanceof Se.KeyObject)return t;if(se(t))return pr(t,e,r),Se.KeyObject.from(t);throw new TypeError(Ee(t,...B,"Uint8Array"))}var Pn=(0,Er.promisify)(Me.sign),bn=async(e,t,r)=>{let o=At(e,t,"sign");if(e.startsWith("HS")){let n=Me.createHmac(It(e),o);return n.update(r),n.digest()}return Pn(St(e),r,Rt(e,o))},Sr=bn;var X=e=>Math.floor(e.getTime()/1e3);var On=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ke=e=>{let t=On.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 _e=class{constructor(t){T(this,"_payload");T(this,"_protectedHeader");T(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 J("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!mr(this._protectedHeader,this._unprotectedHeader))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=yr(J,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),i=!0;if(n.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');gr(a,t,"sign");let u=this._payload;i&&(u=Y.encode(Ne(u)));let p;this._protectedHeader?p=Y.encode(Ne(JSON.stringify(this._protectedHeader))):p=Y.encode("");let g=rr(p,Y.encode("."),u),w=await Sr(a,t,g),R={signature:Ne(w),payload:""};return i&&(R.payload=mt.decode(u)),this._unprotectedHeader&&(R.header=this._unprotectedHeader),this._protectedHeader&&(R.protected=mt.decode(p)),R}};var Ue=class{constructor(t){T(this,"_flattened");this._flattened=new _e(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 Z(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var $e=class{constructor(t={}){T(this,"_payload");if(!yt(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:Z("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:Z("setNotBefore",X(t))}:this._payload={...this._payload,nbf:X(new Date)+ke(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:Z("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:Z("setExpirationTime",X(t))}:this._payload={...this._payload,exp:X(new Date)+ke(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:X(new Date)}:t instanceof Date?this._payload={...this._payload,iat:Z("setIssuedAt",X(t))}:typeof t=="string"?this._payload={...this._payload,iat:Z("setIssuedAt",X(new Date)+ke(t))}:this._payload={...this._payload,iat:Z("setIssuedAt",t)},this}};var we=class extends $e{constructor(){super(...arguments);T(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new Ue(Y.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 Le("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var ce=require("node:crypto"),q=require("node:fs"),K=require("node:path"),wr=require("tar");function W(e){console.log(JSON.stringify(e,null,2))}async function Ct(e,t,r){let o=t.source,n=Fe(o);if(!n)return;console.log("Saving source code...");let i=await e.createAttachment(n,(0,K.basename)(o),xn(o));console.log("Updating bot...");let a=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+a.meta?.versionId)}async function vt(e,t,r){let o=t.dist??t.source,n=Fe(o);if(!n)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,K.basename)(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function Tt(e,t,r,o,n,i,a){let u={name:t,description:"",runtimeVersion:i},p=await e.post("admin/projects/"+r+"/bot",u),g=await e.readResource("Bot",p.id),w={name:t,id:p.id,source:o,dist:n};await Ct(e,w,g),await vt(e,w,g),console.log(`Success! Bot created: ${g.id}`),a&&Nn(w)}function Rr(e){let t=new RegExp("^"+Ln(e).replace(/\\\*/g,".*")+"$"),r=U()?.bots?.filter(o=>t.test(o.name));return r||[]}function H(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function C(e,t){(0,q.writeFileSync)((0,K.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function U(e,t){let r=H(e,t),o=Fe(r);if(o)return JSON.parse(o)}function Ir(e){let t=Fe(H(e,{server:!0}));if(t)return JSON.parse(t)}function Fe(e){let t=(0,K.resolve)(e);return(0,q.existsSync)(t)?(0,q.readFileSync)(t,"utf8"):""}function Nn(e){let t=U()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,q.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Ln(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Ar(e){let o=0,n=0;return(0,wr.extract)({cwd:e,filter:(i,a)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=a.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Pt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function xn(e){let t=(0,K.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Q.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Q.ContentType.TYPESCRIPT:Q.ContentType.TEXT}function je(e,t){let r=new _(e),o={name:e,...t};return r.setObject("options",o),o}function Cr(e){return new _(e).getObject("options")}async function vr(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,Q.encodeBase64)(JSON.stringify(r)),a=(0,Q.encodeBase64)(JSON.stringify(n)),u=`${i}.${a}`,p=(0,ce.createHmac)("sha256",t.clientSecret).update(u).digest("base64url"),g=`${u}.${p}`;await e.startJwtBearerLogin(t.clientId,g,t.scope??"")}async function Tr(e,t){let r=(0,ce.createPrivateKey)((0,q.readFileSync)((0,K.resolve)(t.privateKeyPath))),o=await new we({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ce.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Nr=M.MEDPLUM_CLI_CLIENT_ID,Lr="http://localhost:9615",bt=h("login"),Ot=h("whoami"),Nt=h("token");bt.action(async e=>{let t=e.profile??"default",r=je(t,e),o=await S(e,!1);await Dn(o,r)});Ot.action(async e=>{let t=await S(e);_n(t)});Nt.action(async e=>{let t=await S(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log("Access token:"),console.log(),console.log(r)});async function Dn(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Un(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 vr(e,t);break;case"jwt-assertion":await Tr(e,t);break}}async function Mn(e){let t=(0,br.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":M.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let a=await e.processCode(i,{clientId:Nr,redirectUri:Lr});o.writeHead(200,{"Content-Type":M.ContentType.TEXT}),o.end(`Signed in as ${(0,M.getDisplayString)(a)}. You may close this window.`)}catch(a){o.writeHead(400,{"Content-Type":M.ContentType.TEXT}),o.end(`Error: ${(0,M.normalizeErrorString)(a)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":M.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function kn(e){let t=(0,Or.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,Pr.exec)(r,(o,n,i)=>{if(o)throw o;if(i)throw new Error("Could not open browser: "+i)})}function _n(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 Un(e){await Mn(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Nr),t.searchParams.set("redirect_uri",Lr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await kn(t.toString())}var uo=require("commander");var V=require("@aws-sdk/client-cloudformation"),ze=require("@aws-sdk/client-cloudfront"),Fr=require("@aws-sdk/client-ecs"),jr=require("@aws-sdk/client-s3"),de=require("@aws-sdk/client-ssm"),Ye=require("@aws-sdk/client-sts"),Br=require("@medplum/core"),Kr=N(require("node-fetch")),Wr=require("node:fs"),Hr=N($t());var Ur=N(require("node:readline")),Ge;function Ve(){Ge=Ur.default.createInterface({input:process.stdin,output:process.stdout})}function Je(){Ge.close()}function c(e){Ge.write(e+`
|
|
3
3
|
`)}function A(e){c(`
|
|
4
4
|
`+e+`
|
|
5
|
-
`)}function b(e,t=""){return new Promise(r=>{Ge.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Xe(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await b(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function pe(e,t,r){return parseInt(await Xe(e,t.map(o=>o.toString()),r.toString()),10)}async function re(e){return(await Xe(e,["y","n"])).toLowerCase()==="y"}async function Ce(e){if(!await re(e))throw c("Exiting..."),new Error("User cancelled")}var qe=new V.CloudFormationClient({}),Ri=new ze.CloudFrontClient({region:"us-east-1"}),Ga=new Fr.ECSClient({}),ve=new jr.S3Client({}),Ii="medplum:environment";async function Ft(){let e=[],t=(0,V.paginateListStacks)({client:qe},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)if(r.StackSummaries)for(let o of r.StackSummaries)e.push(o);return e}async function me(e){let t=await Ft();for(let r of t){let o=r.StackName,n=await jt(o);if(n?.tag===e)return n}}async function jt(e){let t={};if(await $r(qe,e,t),await qe.config.region()!=="us-east-1")try{await $r(new V.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function $r(e,t,r){let o=new V.DescribeStacksCommand({StackName:t}),i=(await e.send(o))?.Stacks?.[0],a=i?.Tags?.find(p=>p.Key===Ii);if(!a)return;let u=await e.send(new V.DescribeStackResourcesCommand({StackName:t}));if(u.StackResources){e===qe&&(r.stack=i,r.tag=a.Value);for(let p of u.StackResources)Ai(p,r)}}function Ai(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 Ze(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: ${Ci(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 Ci(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Qe(e){let t=await Ri.send(new ze.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function et(e){let o=(await(await(0,Kr.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)=>Hr.compare(i,n)),e?o.slice(0,o.indexOf(e)):o}async function tt(e,t,r){let o=new de.SSMClient({region:e});for(let[n,i]of Object.entries(r)){let a=t+n,u=i.toString(),p=await vi(o,a);p!==void 0&&p!==u&&(c(`Parameter "${a}" exists with different value.`),await Ce(`Do you want to overwrite "${a}"?`)),await Ti(o,a,u)}}async function vi(e,t){let r=new de.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Ti(e,t,r){let o=new de.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function z(e,t){if(console.log(`Config not found: ${e} (${H(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,Wr.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 fe(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new Ye.STSClient,r=new Ye.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,Br.normalizeErrorString)(t))}}async function Gr(e){let t=await me(e);if(!t)throw await fe(e),new Error(`Stack not found: ${e}`);Ze(t)}var oe=require("@aws-sdk/client-acm"),rt=require("@aws-sdk/client-cloudfront"),ot=require("@aws-sdk/client-sts"),Jr=require("@medplum/core"),Te=require("crypto"),Xr=require("fs");var Pi=e=>`${e}DomainName`,qr=e=>`${e}SslCertArn`;async function zr(){let e={apiPort:8103,region:"us-east-1"};Ve(),A("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await bi(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await Ce("Do you want to continue without AWS credentials?")),A("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await b("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),A("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await b("What is the config file name?",`medplum.${e.name}.config.json`);(0,Xr.existsSync)(r)&&(c("Config file already exists."),await Ce("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),A("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await b("Enter your AWS region:","us-east-1"),C(r,e),A("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await b("What is your AWS account number?",t),C(r,e),A("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await b("Enter your CloudFormation stack name?",o),C(r,e),A("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await b("Enter your base domain name:");C(r,e),A("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await b("Enter your support email address:");A("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await b("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,C(r,e),A("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await b("Enter your web application domain name:","app."+e.domainName),C(r,e),A("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await b("Enter your storage domain name:","storage."+e.domainName),C(r,e),A("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await b("Enter your storage bucket name:",e.storageDomainName),C(r,e),A("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await pe("Enter the maximum number of availability zones:",[2,3,99],2),A("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await re("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await pe("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),C(r,e),A("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await pe("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),A("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await pe("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),A("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await pe("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),A("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let i=(await et())[0]??"latest";e.serverImage=await b("Enter the server image:",`medplum/medplum-server:${i}`),C(r,e),A("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let a=await xi(e.region,e.stackName+"SigningKey");a?(e.signingKeyId=a.keyId,e.storagePublicKey=a.publicKey,C(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),A("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let u=await Oi(e.region);c("Found "+u.length+" certificate(s).");for(let{region:g,certName:w}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let R=await Ni(e,u,g,w);e[qr(w)]=R,C(r,e)}A("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let p={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(a&&(p.signingKeyId=a.keyId,p.signingKey=a.privateKey,p.signingKeyPassphrase=a.passphrase),c(JSON.stringify({...p,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await re("Do you want to store these values in AWS Parameter Store?"))await tt(e.region,`/medplum/${e.name}/`,p);else{let g=H(e.name,{server:!0});C(g,p),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${g}`),c("Please add these values to AWS Parameter Store manually.")}A("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),Je()}async function bi(e){try{let t=new ot.STSClient({region:e}),r=new ot.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Oi(e){let t=await Vr(e);if(e!=="us-east-1"){let r=await Vr("us-east-1");t.push(...r)}return t}async function Vr(e){try{let t=new oe.ACMClient({region:e}),r=new oe.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ni(e,t,r,o){let n=e[Pi(o)],i=t.find(u=>u.CertificateArn?.includes(r)&&u.DomainName===n);if(i)return c(`Found existing certificate for "${n}" in "${r}.`),i.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await re("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${qr(o)}" setting.`),"TODO";let a=await Li(r,n);return c("Certificate ARN: "+a),a}async function Li(e,t){try{let r=await Xe("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new oe.ACMClient({region:e}),n=new oe.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 xi(e,t){let r=(0,Te.randomUUID)(),o=(0,Te.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 rt.CloudFrontClient({region:e}).send(new rt.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,Te.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,Jr.normalizeErrorString)(n));return}}async function Yr(){let e=await Ft();for(let t of e){let r=t.StackName,o=await jt(r);o&&(Ze(o),console.log(""))}}var Zr=require("@aws-sdk/client-s3"),k=require("@medplum/core"),Qr=N(require("fast-glob")),Bt=N(require("node-fetch")),D=require("fs"),eo=require("os"),ne=require("path"),to=require("stream/promises");async function ro(e,t){let r=U(e,t);if(!r)throw z(e,t),new Error(`Config not found: ${e}`);let o=await me(e);if(!o)throw await fe(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let i;if(t.tarPath)i=t.tarPath;else{let a=t?.toVersion??"latest";i=await Mi("@medplum/app",a)}oo(i,{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 _i(i,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Qe(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Di(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Bt.default)(r)).json()}async function Mi(e,t){let o=(await Di(e,t)).dist.tarball,n=(0,D.mkdtempSync)((0,ne.join)((0,eo.tmpdir)(),"tarball-"));try{let i=await(0,Bt.default)(o),a=Ar(n);return await(0,to.pipeline)(i.body,a),(0,ne.join)(n,"package","dist")}catch(i){throw(0,D.rmSync)(n,{recursive:!0,force:!0}),i}}function oo(e,t){for(let r of(0,D.readdirSync)(e,{withFileTypes:!0})){let o=(0,ne.join)(e,r.name);r.isDirectory()?oo(o,t):r.isFile()&&o.endsWith(".js")&&ki(o,t)}}function ki(e,t){let r=(0,D.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,D.writeFileSync)(e,r)}async function _i(e,t,r){let o=[["assets/**/*.css",k.ContentType.CSS,!0],["assets/**/*.css.map",k.ContentType.JSON,!0],["assets/**/*.js",k.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",k.ContentType.JSON,!0],["assets/**/*.txt",k.ContentType.TEXT,!0],["assets/**/*.ico",k.ContentType.FAVICON,!0],["img/**/*.png",k.ContentType.PNG,!0],["img/**/*.svg",k.ContentType.SVG,!0],["robots.txt",k.ContentType.TEXT,!0],["index.html",k.ContentType.HTML,!1]];for(let n of o)await Ui({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Ui(e){let t=Qr.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await $i((0,ne.join)(e.rootDir,r),e)}async function $i(e,t){let r=(0,D.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(ne.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 ve.send(new Zr.PutObjectCommand(n))}var nt=require("@aws-sdk/client-s3");async function io(e,t){if(!U(e,t))throw z(e,t),new Error(`Config not found: ${e}`);let o=await me(e);if(!o)throw await fe(e),new Error(`Stack not found: ${e}`);await no("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await no("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function no(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let i=t.PhysicalResourceId,a=o.PhysicalResourceId,u=await Fi(i);if(Bi(u,i,a))throw new Error(`${e} bucket already has policy statement`);Ki(u,i,a),console.log(`${e} bucket policy:`),console.log(JSON.stringify(u,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await ji(i,u),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Qe(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Fi(e){let t=await ve.send(new nt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ji(e,t){await ve.send(new nt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Bi(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 Ki(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 so(e,t){try{Ve();let r=U(e,t);if(!r)throw z(e,t),new Error(`Config not found: ${e}`);let o=Ir(e)??{};Wi(r,o),Gi(r,o),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),(t.yes||await re("Do you want to store these values in AWS Parameter Store?"))&&await tt(r.region,`/medplum/${r.name}/`,o)}finally{Je()}}function Wi(e,t){it(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),it(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),it(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),it(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function it(e,t,r){if(Hi(e,t))throw new Error(r)}function Hi(e,t){return e!==void 0&&t!==void 0&&e!==t}function Gi(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"),he=N($t());async function lo(e,t){let r=await S(t),o=U(e,t);if(!o)throw console.log(`Configuration file ${H(e)} not found`),z(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),a=await Vi(r,o),u=await ao(a);for(;u;){if(t.toVersion&&he.gt(u,t.toVersion)){console.log(`Skipping update to v${u}`);break}console.log(`Performing update to v${u}`),o.serverImage=`${i}:${u}`,Ji(e,o),await r.startAsyncRequest("/admin/super/migrate"),u=await ao(u)}}async function Vi(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 ao(e,t){let r=await et(e),o=r[0];return r.filter(n=>n===o||n===t||he.gte(n,he.inc(e,"minor"))).pop()}function Ji(e,t){let r=H(e);C(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 po(){let e=new uo.Command("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(zr),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Yr),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Gr),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.").option("--yes","Automatically confirm the update").action(so),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("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(lo)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(ro),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(io),e}var mo=require("commander");var fo=h("save"),ho=h("deploy"),go=h("create"),yo=new mo.Command("bot").addCommand(fo).addCommand(ho).addCommand(go),Kt=h("save-bot"),Wt=h("deploy-bot"),Ht=h("create-bot");fo.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await st(r,e)});ho.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await st(r,e,!0)});go.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 Tt(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function st(e,t,r=!1){let o=Rr(t),n=[],i=[],a=0,u=0;for(let p of o)try{let g=await e.readResource("Bot",p.id);await Ct(e,p,g),a++,r&&(await vt(e,p,g),u++)}catch(g){n.push(g),i.push(`${p.name} [${p.id}]`)}if(console.log(`Number of bots saved: ${a}`),console.log(`Number of bots deployed: ${u}`),console.log(`Number of errors: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
|
|
5
|
+
`)}function b(e,t=""){return new Promise(r=>{Ge.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Xe(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await b(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function pe(e,t,r){return parseInt(await Xe(e,t.map(o=>o.toString()),r.toString()),10)}async function re(e){return(await Xe(e,["y","n"])).toLowerCase()==="y"}async function Ce(e){if(!await re(e))throw c("Exiting..."),new Error("User cancelled")}var qe=new V.CloudFormationClient({}),Ri=new ze.CloudFrontClient({region:"us-east-1"}),Ga=new Fr.ECSClient({}),ve=new jr.S3Client({}),Ii="medplum:environment";async function Ft(){let e=[],t=(0,V.paginateListStacks)({client:qe},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)if(r.StackSummaries)for(let o of r.StackSummaries)e.push(o);return e}async function me(e){let t=await Ft();for(let r of t){let o=r.StackName,n=await jt(o);if(n?.tag===e)return n}}async function jt(e){let t={};if(await $r(qe,e,t),await qe.config.region()!=="us-east-1")try{await $r(new V.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function $r(e,t,r){let o=new V.DescribeStacksCommand({StackName:t}),i=(await e.send(o))?.Stacks?.[0],a=i?.Tags?.find(p=>p.Key===Ii);if(!a)return;let u=await e.send(new V.DescribeStackResourcesCommand({StackName:t}));if(u.StackResources){e===qe&&(r.stack=i,r.tag=a.Value);for(let p of u.StackResources)Ai(p,r)}}function Ai(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 Ze(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: ${Ci(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 Ci(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Qe(e){let t=await Ri.send(new ze.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function et(e){let o=(await(await(0,Kr.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)=>Hr.compare(i,n)),e?o.slice(0,o.indexOf(e)):o}async function tt(e,t,r){let o=new de.SSMClient({region:e});for(let[n,i]of Object.entries(r)){let a=t+n,u=i.toString(),p=await vi(o,a);p!==void 0&&p!==u&&(c(`Parameter "${a}" exists with different value.`),await Ce(`Do you want to overwrite "${a}"?`)),await Ti(o,a,u)}}async function vi(e,t){let r=new de.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Ti(e,t,r){let o=new de.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function z(e,t){if(console.log(`Config not found: ${e} (${H(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,Wr.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 fe(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new Ye.STSClient,r=new Ye.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,Br.normalizeErrorString)(t))}}async function Gr(e){let t=await me(e);if(!t)throw await fe(e),new Error(`Stack not found: ${e}`);Ze(t)}var oe=require("@aws-sdk/client-acm"),rt=require("@aws-sdk/client-cloudfront"),ot=require("@aws-sdk/client-sts"),Jr=require("@medplum/core"),Te=require("node:crypto"),Xr=require("node:fs");var Pi=e=>`${e}DomainName`,qr=e=>`${e}SslCertArn`;async function zr(){let e={apiPort:8103,region:"us-east-1"};Ve(),A("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await bi(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await Ce("Do you want to continue without AWS credentials?")),A("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await b("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),A("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await b("What is the config file name?",`medplum.${e.name}.config.json`);(0,Xr.existsSync)(r)&&(c("Config file already exists."),await Ce("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),A("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await b("Enter your AWS region:","us-east-1"),C(r,e),A("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await b("What is your AWS account number?",t),C(r,e),A("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await b("Enter your CloudFormation stack name?",o),C(r,e),A("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await b("Enter your base domain name:");C(r,e),A("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await b("Enter your support email address:");A("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await b("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,C(r,e),A("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await b("Enter your web application domain name:","app."+e.domainName),C(r,e),A("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await b("Enter your storage domain name:","storage."+e.domainName),C(r,e),A("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await b("Enter your storage bucket name:",e.storageDomainName),C(r,e),A("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await pe("Enter the maximum number of availability zones:",[2,3,99],2),A("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await re("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await pe("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),C(r,e),A("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await pe("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),A("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await pe("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),A("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await pe("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),A("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let i=(await et())[0]??"latest";e.serverImage=await b("Enter the server image:",`medplum/medplum-server:${i}`),C(r,e),A("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let a=await xi(e.region,e.stackName+"SigningKey");a?(e.signingKeyId=a.keyId,e.storagePublicKey=a.publicKey,C(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),A("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let u=await Oi(e.region);c("Found "+u.length+" certificate(s).");for(let{region:g,certName:w}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let R=await Ni(e,u,g,w);e[qr(w)]=R,C(r,e)}A("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let p={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(a&&(p.signingKeyId=a.keyId,p.signingKey=a.privateKey,p.signingKeyPassphrase=a.passphrase),c(JSON.stringify({...p,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await re("Do you want to store these values in AWS Parameter Store?"))await tt(e.region,`/medplum/${e.name}/`,p);else{let g=H(e.name,{server:!0});C(g,p),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${g}`),c("Please add these values to AWS Parameter Store manually.")}A("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),Je()}async function bi(e){try{let t=new ot.STSClient({region:e}),r=new ot.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Oi(e){let t=await Vr(e);if(e!=="us-east-1"){let r=await Vr("us-east-1");t.push(...r)}return t}async function Vr(e){try{let t=new oe.ACMClient({region:e}),r=new oe.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ni(e,t,r,o){let n=e[Pi(o)],i=t.find(u=>u.CertificateArn?.includes(r)&&u.DomainName===n);if(i)return c(`Found existing certificate for "${n}" in "${r}.`),i.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await re("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${qr(o)}" setting.`),"TODO";let a=await Li(r,n);return c("Certificate ARN: "+a),a}async function Li(e,t){try{let r=await Xe("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new oe.ACMClient({region:e}),n=new oe.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 xi(e,t){let r=(0,Te.randomUUID)(),o=(0,Te.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 rt.CloudFrontClient({region:e}).send(new rt.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,Te.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,Jr.normalizeErrorString)(n));return}}async function Yr(){let e=await Ft();for(let t of e){let r=t.StackName,o=await jt(r);o&&(Ze(o),console.log(""))}}var Zr=require("@aws-sdk/client-s3"),k=require("@medplum/core"),Qr=N(require("fast-glob")),Bt=N(require("node-fetch")),D=require("node:fs"),eo=require("node:os"),ne=require("node:path"),to=require("node:stream/promises");async function ro(e,t){let r=U(e,t);if(!r)throw z(e,t),new Error(`Config not found: ${e}`);let o=await me(e);if(!o)throw await fe(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let i;if(t.tarPath)i=t.tarPath;else{let a=t?.toVersion??"latest";i=await Mi("@medplum/app",a)}oo(i,{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 _i(i,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Qe(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Di(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Bt.default)(r)).json()}async function Mi(e,t){let o=(await Di(e,t)).dist.tarball,n=(0,D.mkdtempSync)((0,ne.join)((0,eo.tmpdir)(),"tarball-"));try{let i=await(0,Bt.default)(o),a=Ar(n);return await(0,to.pipeline)(i.body,a),(0,ne.join)(n,"package","dist")}catch(i){throw(0,D.rmSync)(n,{recursive:!0,force:!0}),i}}function oo(e,t){for(let r of(0,D.readdirSync)(e,{withFileTypes:!0})){let o=(0,ne.join)(e,r.name);r.isDirectory()?oo(o,t):r.isFile()&&o.endsWith(".js")&&ki(o,t)}}function ki(e,t){let r=(0,D.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,D.writeFileSync)(e,r)}async function _i(e,t,r){let o=[["assets/**/*.css",k.ContentType.CSS,!0],["assets/**/*.css.map",k.ContentType.JSON,!0],["assets/**/*.js",k.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",k.ContentType.JSON,!0],["assets/**/*.txt",k.ContentType.TEXT,!0],["assets/**/*.ico",k.ContentType.FAVICON,!0],["img/**/*.png",k.ContentType.PNG,!0],["img/**/*.svg",k.ContentType.SVG,!0],["robots.txt",k.ContentType.TEXT,!0],["index.html",k.ContentType.HTML,!1]];for(let n of o)await Ui({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Ui(e){let t=Qr.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await $i((0,ne.join)(e.rootDir,r),e)}async function $i(e,t){let r=(0,D.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(ne.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 ve.send(new Zr.PutObjectCommand(n))}var nt=require("@aws-sdk/client-s3");async function io(e,t){if(!U(e,t))throw z(e,t),new Error(`Config not found: ${e}`);let o=await me(e);if(!o)throw await fe(e),new Error(`Stack not found: ${e}`);await no("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await no("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function no(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let i=t.PhysicalResourceId,a=o.PhysicalResourceId,u=await Fi(i);if(Bi(u,i,a))throw new Error(`${e} bucket already has policy statement`);Ki(u,i,a),console.log(`${e} bucket policy:`),console.log(JSON.stringify(u,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await ji(i,u),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Qe(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Fi(e){let t=await ve.send(new nt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ji(e,t){await ve.send(new nt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Bi(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 Ki(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 so(e,t){try{Ve();let r=U(e,t);if(!r)throw z(e,t),new Error(`Config not found: ${e}`);let o=Ir(e)??{};Wi(r,o),Gi(r,o),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),(t.yes||await re("Do you want to store these values in AWS Parameter Store?"))&&await tt(r.region,`/medplum/${r.name}/`,o)}finally{Je()}}function Wi(e,t){it(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),it(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),it(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),it(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function it(e,t,r){if(Hi(e,t))throw new Error(r)}function Hi(e,t){return e!==void 0&&t!==void 0&&e!==t}function Gi(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("node:child_process"),he=N($t());async function lo(e,t){let r=await S(t),o=U(e,t);if(!o)throw console.log(`Configuration file ${H(e)} not found`),z(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),a=await Vi(r,o),u=await ao(a);for(;u;){if(t.toVersion&&he.gt(u,t.toVersion)){console.log(`Skipping update to v${u}`);break}console.log(`Performing update to v${u}`),o.serverImage=`${i}:${u}`,Ji(e,o),await r.startAsyncRequest("/admin/super/migrate"),u=await ao(u)}}async function Vi(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 ao(e,t){let r=await et(e),o=r[0];return r.filter(n=>n===o||n===t||he.gte(n,he.inc(e,"minor"))).pop()}function Ji(e,t){let r=H(e);C(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 po(){let e=new uo.Command("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(zr),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Yr),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Gr),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.").option("--yes","Automatically confirm the update").action(so),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("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(lo)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(ro),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(io),e}var mo=require("commander");var fo=h("save"),ho=h("deploy"),go=h("create"),yo=new mo.Command("bot").addCommand(fo).addCommand(ho).addCommand(go),Kt=h("save-bot"),Wt=h("deploy-bot"),Ht=h("create-bot");fo.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await st(r,e)});ho.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await st(r,e,!0)});go.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 Tt(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function st(e,t,r=!1){let o=Rr(t),n=[],i=[],a=0,u=0;for(let p of o)try{let g=await e.readResource("Bot",p.id);await Ct(e,p,g),a++,r&&(await vt(e,p,g),u++)}catch(g){n.push(g),i.push(`${p.name} [${p.id}]`)}if(console.log(`Number of bots saved: ${a}`),console.log(`Number of bots deployed: ${u}`),console.log(`Number of errors: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
|
|
6
6
|
|
|
7
7
|
${i.join(`
|
|
8
|
-
`)}`,{cause:n})}Kt.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await st(r,e)});Wt.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await st(r,e,!0)});Ht.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await S(n);await Tt(i,e,t,r,o)});var So=require("commander"),at=require("fs"),Gt=require("path"),wo=require("readline");var Ro=h("export"),Io=h("import"),Ao=new So.Command("bulk").addCommand(Ro).addCommand(Io);Ro.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:u,url:p})=>{let g=new URL(p),w=await i.download(p),R=`${u}_${g.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",v=(0,Gt.resolve)(n??"",R);(0,at.writeFile)(`${v}`,await w.text(),()=>{console.log(`${v} is created`)})})});Io.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,Gt.resolve)(n??process.cwd(),e),a=await S(t);await Xi(i,parseInt(r,10),a,o)});async function Xi(e,t,r,o){let n=[],i=(0,at.createReadStream)(e),a=(0,wo.createInterface)({input:i});for await(let u of a){let p=qi(u,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Eo(n,r),n=[])}n.length>0&&await Eo(n,r)}async function Eo(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{W(o.response)})}function qi(e,t){let r=JSON.parse(e);return t?zi(r):r}function zi(e){return e.resourceType==="ExplanationOfBenefit"?Yi(e):e}function Yi(e){return e.provider||(e.provider=Pt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Pt())}),e}var ut=require("@medplum/core");var vo=require("net"),To=require("@medplum/core"),lt=require("iconv-lite"),No=N(require("net"),1),Co=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Zi=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},ct=class extends Event{constructor(e){super("error"),this.error=e}},Po=class extends Event{constructor(){super("close")}},bo=class extends Co{constructor(e,t="utf-8"){super(),this.socket=e,this.encoding=t,this.chunks=[],this.messageQueue=[],e.on("data",r=>{try{if(this.appendData(r),r.at(-2)===28&&r.at(-1)===13){let o=Buffer.concat(this.chunks),n=o.subarray(1,o.length-2),i=(0,lt.decode)(n,this.encoding),a=To.Hl7Message.parse(i);this.dispatchEvent(new Zi(this,a)),this.resetBuffer()}}catch(o){this.dispatchEvent(new ct(o))}}),e.on("error",r=>{this.resetBuffer(),this.dispatchEvent(new ct(r))}),e.on("end",()=>{this.close()}),this.addEventListener("message",r=>{let o=this.messageQueue.shift();if(!o){this.dispatchEvent(new ct(new Error(`Received a message when no pending messages were in the queue. Message: ${r.message}`)));return}o.resolve?.(r.message)})}sendImpl(e,t){this.messageQueue.push(t);let r=e.toString(),o=(0,lt.encode)(r,this.encoding),n=Buffer.alloc(o.length+3);n.writeInt8(11,0),o.copy(n,1),n.writeInt8(28,o.length+1),n.writeInt8(13,o.length+2),this.socket.write(n)}send(e){this.sendImpl(e,{message:e})}async sendAndWait(e){return new Promise((t,r)=>{let o={message:e,resolve:t,reject:r};this.sendImpl(e,o)})}close(){this.socket.end(),this.socket.destroy(),this.dispatchEvent(new Po)}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}},Oo=class extends Co{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1}connect(){return this.connection?Promise.resolve(this.connection):new Promise((e,t)=>{let r=(0,vo.connect)({host:this.host,port:this.port,keepAlive:this.keepAlive},()=>{let o;this.connection=o=new bo(r,this.encoding),r.off("error",t),o.addEventListener("close",()=>this.dispatchEvent(new Po)),o.addEventListener("error",n=>this.dispatchEvent(new ct(n.error))),e(this.connection)});r.on("error",t)})}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.connection&&(this.connection.close(),delete this.connection)}},Lo=class{constructor(e){this.handler=e}start(e,t){let r=No.default.createServer(o=>{let n=new bo(o,t);this.handler(n)});r.listen(e),this.server=r}async stop(){return new Promise((e,t)=>{if(!this.server){t(new Error("Stop was called but there is no server running"));return}this.server.close(r=>{if(r){t(r);return}e()}),this.server=void 0})}};var xo=require("commander"),Do=require("fs");var Qi=h("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=ts():o.file&&(r=(0,Do.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new Oo({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await n.sendAndWait(ut.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
8
|
+
`)}`,{cause:n})}Kt.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await st(r,e)});Wt.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await st(r,e,!0)});Ht.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await S(n);await Tt(i,e,t,r,o)});var So=require("commander"),at=require("node:fs"),Gt=require("node:path"),wo=require("node:readline");var Ro=h("export"),Io=h("import"),Ao=new So.Command("bulk").addCommand(Ro).addCommand(Io);Ro.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:u,url:p})=>{let g=new URL(p),w=await i.download(p),R=`${u}_${g.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",v=(0,Gt.resolve)(n??"",R);(0,at.writeFile)(`${v}`,await w.text(),()=>{console.log(`${v} is created`)})})});Io.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,Gt.resolve)(n??process.cwd(),e),a=await S(t);await Xi(i,parseInt(r,10),a,o)});async function Xi(e,t,r,o){let n=[],i=(0,at.createReadStream)(e),a=(0,wo.createInterface)({input:i});for await(let u of a){let p=qi(u,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Eo(n,r),n=[])}n.length>0&&await Eo(n,r)}async function Eo(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{W(o.response)})}function qi(e,t){let r=JSON.parse(e);return t?zi(r):r}function zi(e){return e.resourceType==="ExplanationOfBenefit"?Yi(e):e}function Yi(e){return e.provider||(e.provider=Pt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Pt())}),e}var ut=require("@medplum/core");var vo=require("node:net"),To=require("@medplum/core"),lt=require("iconv-lite"),No=N(require("node:net"),1),Co=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Zi=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},ct=class extends Event{constructor(e){super("error"),this.error=e}},Po=class extends Event{constructor(){super("close")}},bo=class extends Co{constructor(e,t="utf-8"){super(),this.socket=e,this.encoding=t,this.chunks=[],this.messageQueue=[],e.on("data",r=>{try{if(this.appendData(r),r.at(-2)===28&&r.at(-1)===13){let o=Buffer.concat(this.chunks),n=o.subarray(1,o.length-2),i=(0,lt.decode)(n,this.encoding),a=To.Hl7Message.parse(i);this.dispatchEvent(new Zi(this,a)),this.resetBuffer()}}catch(o){this.dispatchEvent(new ct(o))}}),e.on("error",r=>{this.resetBuffer(),this.dispatchEvent(new ct(r))}),e.on("end",()=>{this.close()}),this.addEventListener("message",r=>{let o=this.messageQueue.shift();if(!o){this.dispatchEvent(new ct(new Error(`Received a message when no pending messages were in the queue. Message: ${r.message}`)));return}o.resolve?.(r.message)})}sendImpl(e,t){this.messageQueue.push(t);let r=e.toString(),o=(0,lt.encode)(r,this.encoding),n=Buffer.alloc(o.length+3);n.writeInt8(11,0),o.copy(n,1),n.writeInt8(28,o.length+1),n.writeInt8(13,o.length+2),this.socket.write(n)}send(e){this.sendImpl(e,{message:e})}async sendAndWait(e){return new Promise((t,r)=>{let o={message:e,resolve:t,reject:r};this.sendImpl(e,o)})}close(){this.socket.end(),this.socket.destroy(),this.dispatchEvent(new Po)}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}},Oo=class extends Co{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1}connect(){return this.connection?Promise.resolve(this.connection):new Promise((e,t)=>{let r=(0,vo.connect)({host:this.host,port:this.port,keepAlive:this.keepAlive},()=>{let o;this.connection=o=new bo(r,this.encoding),r.off("error",t),o.addEventListener("close",()=>this.dispatchEvent(new Po)),o.addEventListener("error",n=>this.dispatchEvent(new ct(n.error))),e(this.connection)});r.on("error",t)})}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.connection&&(this.connection.close(),delete this.connection)}},Lo=class{constructor(e){this.handler=e}start(e,t){let r=No.default.createServer(o=>{let n=new bo(o,t);this.handler(n)});r.listen(e),this.server=r}async stop(){return new Promise((e,t)=>{if(!this.server){t(new Error("Stop was called but there is no server running"));return}this.server.close(r=>{if(r){t(r);return}e()}),this.server=void 0})}};var xo=require("commander"),Do=require("node:fs");var Qi=h("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=ts():o.file&&(r=(0,Do.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new Oo({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await n.sendAndWait(ut.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
9
9
|
`))}finally{n.close()}}),es=h("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{new Lo(o=>{o.addEventListener("message",({message:n})=>{console.log(n.toString().replaceAll("\r",`
|
|
10
10
|
`)),o.send(n.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),Mo=new xo.Command("hl7").addCommand(Qi).addCommand(es);function ts(){let e=(0,ut.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
|
|
11
11
|
EVN|A01|${e}||
|
|
12
12
|
PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|
|
|
13
|
-
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var ko=require("commander"),_o=require("fs"),Uo=require("os"),$o=require("path");var Fo=h("set"),jo=h("remove"),Bo=h("list"),Ko=h("describe"),Wo=new ko.Command("profile").addCommand(Fo).addCommand(jo).addCommand(Bo).addCommand(Ko);Fo.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{je(e,t)});jo.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new _(e).setObject("options",void 0),console.log(`${e} profile removed`)});Bo.description("List all profiles saved").action(async()=>{let e=(0,$o.resolve)((0,Uo.homedir)(),".medplum"),t=(0,_o.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],a=new _(n).getObject("options");a&&r.push({profileName:n,profile:a})}),console.log(r)});Ko.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Cr(e);console.log(t)});var pt=require("commander");var Ho=h("list"),Go=h("current"),Vo=h("switch"),Jo=h("invite"),Xo=new pt.Command("project").addCommand(Ho).addCommand(Go).addCommand(Vo).addCommand(Jo);Ho.description("List of current projects").action(async e=>{let t=await S(e);rs(t)});function rs(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
|
|
13
|
+
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var ko=require("commander"),_o=require("node:fs"),Uo=require("node:os"),$o=require("node:path");var Fo=h("set"),jo=h("remove"),Bo=h("list"),Ko=h("describe"),Wo=new ko.Command("profile").addCommand(Fo).addCommand(jo).addCommand(Bo).addCommand(Ko);Fo.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{je(e,t)});jo.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new _(e).setObject("options",void 0),console.log(`${e} profile removed`)});Bo.description("List all profiles saved").action(async()=>{let e=(0,$o.resolve)((0,Uo.homedir)(),".medplum"),t=(0,_o.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],a=new _(n).getObject("options");a&&r.push({profileName:n,profile:a})}),console.log(r)});Ko.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Cr(e);console.log(t)});var pt=require("commander");var Ho=h("list"),Go=h("current"),Vo=h("switch"),Jo=h("invite"),Xo=new pt.Command("project").addCommand(Ho).addCommand(Go).addCommand(Vo).addCommand(Jo);Ho.description("List of current projects").action(async e=>{let t=await S(e);rs(t)});function rs(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
|
|
14
14
|
|
|
15
15
|
`);console.log(r)}Go.description("Project you are currently on").action(async e=>{let r=(await S(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});Vo.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await S(t);await os(r,e)});Jo.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new pt.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await S(o),i=n.getActiveLogin();if(!i)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!i?.project?.reference)throw new Error("No current project to invite user to");let a=i.project.reference.split("/")[1],u={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await ns(a,u,n)});async function os(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));if(!o)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(o),console.log(`Switched to project ${t}
|
|
16
16
|
`)}async function ns(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var qo=require("@medplum/core");var Vt=h("delete"),Jt=h("get"),Xt=h("patch"),qt=h("post"),zt=h("put");Vt.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await S(t);W(await r.delete(Pe(r,e)))});Jt.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await S(t),o=await r.get(Pe(r,e));t.asTransaction?W((0,qo.convertToTransactionBundle)(o)):W(o)});Xt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);W(await o.patch(Pe(o,e),Yt(t)))});qt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);W(await o.post(Pe(o,e),Yt(t)))});zt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);W(await o.put(Pe(o,e),Yt(t)))});function Yt(e){if(e)try{return JSON.parse(e)}catch{return e}}function Pe(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function Zo(e){let t=new be.Command("medplum").description("Command to access Medplum CLI");t.exitOverride(),t.version(ge.MEDPLUM_VERSION),t.addCommand(bt),t.addCommand(Ot),t.addCommand(Nt),t.addCommand(Jt),t.addCommand(qt),t.addCommand(Xt),t.addCommand(zt),t.addCommand(Vt),t.addCommand(Xo),t.addCommand(Ao),t.addCommand(yo),t.addCommand(Kt),t.addCommand(Wt),t.addCommand(Ht),t.addCommand(Wo),t.addCommand(po()),t.addCommand(Mo);try{await t.parseAsync(e)}catch(r){Qo(r)}}function Qo(e){zo(e);let t=e.cause;if(Array.isArray(t))for(let o of t)zo(o);let r=1;e instanceof be.CommanderError&&(r=e.exitCode),process.exit(r)}function zo(e){e instanceof be.CommanderError&&process.stderr.write(`${(0,ge.normalizeErrorString)(e)}
|