@medplum/cli 2.2.10 → 3.0.0

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