@medplum/cli 2.2.7 → 2.2.10

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 hr=Object.defineProperty;var yr=(e,t,r)=>t in e?hr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var qe=(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 l=(e,t,r)=>(yr(e,typeof t!="symbol"?t+"":t,r),r);import{MEDPLUM_VERSION as Wi,normalizeErrorString as Mi}from"@medplum/core";import{Command as Ji}from"commander";import Ni from"dotenv";import{ContentType as Re,getDisplayString as Bo,normalizeErrorString as Fo}from"@medplum/core";import{exec as jo}from"child_process";import{createServer as Go}from"http";import{platform as Vo}from"os";import{MedplumClient as Cr}from"@medplum/core";import{ClientStorage as gr}from"@medplum/core";import{existsSync as Ye,mkdirSync as wr,readFileSync as Sr,writeFileSync as Er}from"fs";import{homedir as br}from"os";import{resolve as Ze}from"path";var K=class extends gr{constructor(r){super();this.dirName=Ze(br(),".medplum"),this.fileName=Ze(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if(Ye(this.fileName))return JSON.parse(Sr(this.fileName,"utf8"))}writeFile(r){Ye(this.dirName)||wr(this.dirName),Er(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function u(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}=Ar(e,o),ee=e.fetch??fetch,te=new Cr({fetch:ee,baseUrl:a,tokenUrl:p,fhirUrlPath:s,authorizeUrl:g,storage:o,onUnauthenticated:Pr,verbose:e.verbose});return t&&(c?te.setAccessToken(c):b&&T&&(te.setBasicAuth(b,T),n?.authType!=="basic"&&await te.startClientLogin(b,T))),te}function Ar(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 Pr(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as vr,Option as xr}from"commander";function d(e){return new vr(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 xr("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as _e,encodeBase64 as ht}from"@medplum/core";import{createHmac as Ro,createPrivateKey as Oo,randomBytes as Do}from"crypto";import{existsSync as Wo,readFileSync as yt,writeFileSync as Mo}from"fs";import{Buffer as Ir}from"buffer";var C=new TextEncoder,S=new TextDecoder,ra=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=>Ir.from(e).toString("base64url");var N=class extends Error{constructor(r){super(r);l(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 N{constructor(){super(...arguments);l(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var P=class extends N{constructor(){super(...arguments);l(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},O=class extends N{constructor(){super(...arguments);l(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Kr,ge=class extends N{constructor(){super(...arguments);l(this,Kr);l(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");l(this,"message","multiple matching keys found in the JSON Web Key Set")}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};Kr=Symbol.asyncIterator;import*as et from"util";var v=e=>et.types.isKeyObject(e);import*as tt from"crypto";import*as rt from"util";var Hr=tt.webcrypto,ot=Hr,E=e=>rt.types.isCryptoKey(e);function k(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function re(e,t){return e.name===t}function Se(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 Rr(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 nt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!re(e.algorithm,"HMAC"))throw k("HMAC");let o=parseInt(t.slice(2),10);if(Se(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw k("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Se(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!re(e.algorithm,"RSA-PSS"))throw k("RSA-PSS");let o=parseInt(t.slice(2),10);if(Se(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(!re(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")}Rr(e,r)}function it(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)=>it("Key must be ",e,...t);function Ee(e,t,...r){return it(`Key for the ${e} algorithm must be `,t,...r)}var be=e=>v(e)||E(e),f=["KeyObject"];(globalThis.CryptoKey||ot?.CryptoKey)&&f.push("CryptoKey");var Jr=(...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},U=Jr;function Nr(e){return typeof e=="object"&&e!==null}function w(e){if(!Nr(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 ls,generateKeyPair as Br,KeyObject as us}from"crypto";import{promisify as Fr}from"util";import{KeyObject as Ur}from"crypto";var Lr=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")}},$r=(e,t)=>{let r;if(E(e))r=Ur.from(e);else if(v(e))r=e;else throw new TypeError(x(e,...f));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:Lr(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Ce=$r;var As=Fr(Br);import{promisify as Vr}from"util";import{KeyObject as Ks,pbkdf2 as zr}from"crypto";var Ls=Vr(zr);import{KeyObject as js,publicEncrypt as Gs,constants as Xr,privateDecrypt as Vs}from"crypto";import{deprecate as qr}from"util";var oe=(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 tc=qr(()=>Xr.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var Yr=(e,t)=>{if(!(t instanceof Uint8Array)){if(!be(t))throw new TypeError(Ee(e,t,...f,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${f.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Zr=(e,t,r)=>{if(!be(t))throw new TypeError(Ee(e,t,...f));if(t.type==="secret")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Qr=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Yr(e,t):Zr(e,t,r)},z=Qr;function ao(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 L=ao;var lo=Symbol();import*as xe from"crypto";import{promisify as So}from"util";function ne(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 mt}from"crypto";var uo={padding:mt.RSA_PKCS1_PSS_PADDING,saltLength:mt.RSA_PSS_SALTLEN_DIGEST},fo=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ie(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 oe(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 oe(t,e),{key:t,...uo};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=Ce(t),o=fo.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 se from"crypto";import{promisify as yo}from"util";function Pe(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 lt,createSecretKey as ho}from"crypto";function ae(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(x(t,...f));return ho(t)}if(t instanceof lt)return t;if(E(t))return nt(t,e,r),lt.from(t);throw new TypeError(x(t,...f,"Uint8Array"))}var go=yo(se.sign),wo=async(e,t,r)=>{let o=ae(e,t,"sign");if(e.startsWith("HS")){let n=se.createHmac(Pe(e),o);return n.update(r),n.digest()}return go(ne(e),r,ie(e,o))},ve=wo;var Fp=So(xe.verify);var W=e=>Math.floor(e.getTime()/1e3);var bo=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ce=e=>{let t=bo.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var $=class{constructor(t){l(this,"_payload");l(this,"_protectedHeader");l(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(!U(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=L(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 ve(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 X=class{constructor(t){l(this,"_flattened");this._flattened=new $(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 B(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var F=class{constructor(t={}){l(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:B("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:B("setNotBefore",W(t))}:this._payload={...this._payload,nbf:W(new Date)+ce(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:B("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:B("setExpirationTime",W(t))}:this._payload={...this._payload,exp:W(new Date)+ce(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:W(new Date)}:t instanceof Date?this._payload={...this._payload,iat:B("setIssuedAt",W(t))}:this._payload={...this._payload,iat:B("setIssuedAt",t)},this}};var q=class extends F{constructor(){super(...arguments);l(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new X(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 O("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var Io;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Io="jose/v5.1.3");import{createSecretKey as Zl,generateKeyPair as Ho}from"crypto";import{promisify as ko}from"util";var ru=ko(Ho);import{basename as gt,extname as Jo,resolve as wt}from"path";import No from"tar";function R(e){console.log(JSON.stringify(e,null,2))}async function Ie(e,t,r){let o=t.source,n=He(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,gt(o),$o(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 Te(e,t,r){let o=t.dist??t.source,n=He(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:gt(o)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function Ke(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 Ie(e,b,g),await Te(e,b,g),console.log(`Success! Bot created: ${g.id}`),s&&Uo(b)}catch(c){console.log("Error while creating new bot: "+c)}}function St(e){let t=new RegExp("^"+Lo(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=He(t);if(r)return JSON.parse(r)}function He(e){let t=wt(process.cwd(),e);return Wo(t)?yt(t,"utf8"):""}function Uo(e){let t=j()??{};t.bots||(t.bots=[]),t.bots.push(e),Mo("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Lo(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Et(e){let o=0,n=0;return No.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 ke(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function $o(e){let t=Jo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?_e.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?_e.TYPESCRIPT:_e.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 bt(e){return new K(e).getObject("options")}async function Ct(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=ht(JSON.stringify(r)),s=ht(JSON.stringify(n)),c=`${a}.${s}`,p=Ro("sha256",t.clientSecret).update(c).digest("base64url"),g=`${c}.${p}`;await e.startJwtBearerLogin(t.clientId,g,t.scope??"")}async function At(e,t){let r=Oo(yt(wt(t.privateKeyPath))),o=await new q({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Do(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Pt="medplum-cli",vt="http://localhost:9615",Oe=d("login"),De=d("whoami");Oe.action(async e=>{let t=e.profile??"default",r=de(t,e),o=await u(e,!1);await zo(o,r)});De.action(async e=>{let t=await u(e);Yo(t)});async function zo(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Zo(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 Ct(e,t);break;case"jwt-assertion":await At(e,t);break}console.log("Login successful")}async function Xo(e){let t=Go(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:Pt,redirectUri:vt});o.writeHead(200,{"Content-Type":Re.TEXT}),o.end(`Signed in as ${Bo(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Re.TEXT}),o.end(`Error: ${Fo(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Re.TEXT}),o.end("Not found")}).listen(9615)}async function qo(e){let t=Vo(),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)}jo(r)}function Yo(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 Zo(e){await Xo(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Pt),t.searchParams.set("redirect_uri",vt),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await qo(t.toString())}import{Command as ni}from"commander";import{CloudFormationClient as _t,DescribeStackResourcesCommand as Qo,DescribeStacksCommand as en,ListStacksCommand as tn}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as rn,CreateInvalidationCommand as on}from"@aws-sdk/client-cloudfront";import{ECSClient as nn}from"@aws-sdk/client-ecs";import{S3Client as an}from"@aws-sdk/client-s3";var pe=new _t({}),sn=new rn({region:"us-east-1"}),It=new nn({}),Y=new an({}),cn="medplum:environment";async function We(){return(await pe.send(new tn({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function M(e){let t=await We();for(let r of t){let o=r.StackName,n=await Me(o);if(n?.tag===e)return n}}async function Me(e){let t={};return await xt(pe,e,t),await pe.config.region()!=="us-east-1"&&await xt(new _t({region:"us-east-1"}),e+"-us-east-1",t),t}async function xt(e,t,r){let o=new en({StackName:t}),a=(await e.send(o))?.Stacks?.[0],s=a?.Tags?.find(p=>p.Key===cn);if(!s)return;let c=await e.send(new Qo({StackName:t}));if(c.StackResources){e===pe&&(r.stack=a,r.tag=s.Value);for(let p of c.StackResources)dn(p,r)}}function dn(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: ${Je(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 Je(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function le(e){let t=await sn.send(new on({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Tt(e){let t=await M(e);if(!t){console.log("Stack not found");return}me(t)}import{ACMClient as kt,ListCertificatesCommand as pn,RequestCertificateCommand as mn}from"@aws-sdk/client-acm";import{CloudFrontClient as ln,CreatePublicKeyCommand as un}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as fn,PutParameterCommand as hn,SSMClient as yn}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as gn,STSClient as wn}from"@aws-sdk/client-sts";import{normalizeErrorString as Sn}from"@medplum/core";import{generateKeyPairSync as En,randomUUID as Kt}from"crypto";import{existsSync as bn,writeFileSync as Cn}from"fs";import{resolve as An}from"path";import Pn from"readline";var vn=e=>`${e}DomainName`,Rt=e=>`${e}SslCertArn`,ue;async function Ot(){let e={apiPort:8103,region:"us-east-1"};ue=Pn.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 xn(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 Ne("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`);bn(r)&&(i("Config file already exists."),await Ne("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 Z("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 Z("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 Z("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 Z("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 Z("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 Kn(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 _n(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 In(e,s,p,g);e[Rt(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 Rn(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+`
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
3
  `)}function h(e){i(`
4
4
  `+e+`
5
- `)}function _(e,t=""){return new Promise(r=>{ue.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Ue(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 Z(e,t,r){return parseInt(await Ue(e,t.map(o=>o.toString()),r.toString()),10)}async function fe(e){return(await Ue(e,["y","n"])).toLowerCase()==="y"}async function Ne(e){if(!await fe(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){Cn(An(e),JSON.stringify(t,void 0,2),"utf-8")}async function xn(e){try{let t=new wn({region:e}),r=new gn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function _n(e){let t=await Ht(e);if(e!=="us-east-1"){let r=await Ht("us-east-1");t.push(...r)}return t}async function Ht(e){try{let t=new kt({region:e}),r=new pn({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function In(e,t,r,o){let n=e[vn(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 "${Rt(o)}" setting.`),"TODO";let s=await Tn(r,n);return i("Certificate ARN: "+s),s}async function Tn(e,t){try{let r=await Ue("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new kt({region:e}),n=new mn({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 Kn(e){let t=Kt(),r=En("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});try{return{keyId:(await new ln({}).send(new un({PublicKeyConfig:{Name:e,CallerReference:Kt(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}catch(o){console.log("Error: Unable to create signing key: ",Sn(o));return}}async function Hn(e,t){let r=new fn({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 hn({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Rn(e,t,r){let o=new yn({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await Hn(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await Ne(`Do you want to overwrite "${s}"?`)),await kn(o,s,c)}}async function Dt(){let e=await We();for(let t of e){let r=t.StackName,o=await Me(r);o&&(me(o),console.log(""))}}import{PutObjectCommand as On}from"@aws-sdk/client-s3";import{ContentType as H}from"@medplum/core";import Dn from"fast-glob";import{createReadStream as Wn,mkdtempSync as Mn,readdirSync as Jn,readFileSync as Nn,rmSync as Un,writeFileSync as Ln}from"fs";import Wt from"node-fetch";import{tmpdir as $n}from"os";import{join as he,sep as Bn}from"path";import{pipeline as Fn}from"stream/promises";async function Mt(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 Gn("@medplum/app","latest");Jt(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 zn(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await le(o.appDistribution.PhysicalResourceId),console.log("Done")}async function jn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Wt(r)).json()}async function Gn(e,t){let o=(await jn(e,t)).dist.tarball,n=Mn(he($n(),"tarball-"));try{let a=await Wt(o),s=Et(n);return await Fn(a.body,s),he(n,"package","dist")}catch(a){throw Un(n,{recursive:!0,force:!0}),a}}function Jt(e,t){for(let r of Jn(e,{withFileTypes:!0})){let o=he(e,r.name);r.isDirectory()?Jt(o,t):r.isFile()&&o.endsWith(".js")&&Vn(o,t)}}function Vn(e,t){let r=Nn(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Ln(e,r)}async function zn(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 Xn({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Xn(e){let t=Dn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await qn(he(e.rootDir,r),e)}async function qn(e,t){let r=Wn(e),o=e.substring(t.rootDir.length+1).split(Bn).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 Y.send(new On(n))}import{GetBucketPolicyCommand as Yn,PutBucketPolicyCommand as Zn}from"@aws-sdk/client-s3";async function Ut(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 Nt("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Nt("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Nt(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 Qn(a);if(ti(c,a,s)){console.log(`${e} bucket already has policy statement`);return}ri(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 ei(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 Qn(e){let t=await Y.send(new Yn({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ei(e,t){await Y.send(new Zn({Bucket:e,Policy:JSON.stringify(t)}))}function ti(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 ri(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 oi}from"@aws-sdk/client-ecs";async function Lt(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=Je(t.ecsService);if(!o){console.log("ECS Service not found");return}await It.send(new oi({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var J=new ni("aws").description("Commands to manage AWS resources");J.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Ot);J.command("list").description("List Medplum AWS CloudFormation stacks").action(Dt);J.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Tt);J.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Lt);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(Mt);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(Ut);import{Command as ii}from"commander";var $t=d("save"),Bt=d("deploy"),Ft=d("create"),jt=new ii("bot").addCommand($t).addCommand(Bt).addCommand(Ft),Le=d("save-bot"),$e=d("deploy-bot"),Be=d("create-bot");$t.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e)});Bt.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e,!0)});Ft.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 u(n);await Ke(a,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function ye(e,t,r=!1){let o=St(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Ie(e,n,a),r&&await Te(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Le.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e)});$e.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e,!0)});Be.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Ke(a,e,t,r,o)});import{Command as ai}from"commander";import{createReadStream as si,writeFile as ci}from"fs";import{resolve as Vt}from"path";import{createInterface as di}from"readline";var zt=d("export"),Xt=d("import"),qt=new ai("bulk").addCommand(zt).addCommand(Xt);zt.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 u(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",ee=Vt(n??"",T);ci(`${ee}`,await b.text(),()=>{console.log(`${ee} is created`)})})});Xt.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=Vt(n??process.cwd(),e),s=await u(t);await pi(a,parseInt(r,10),s,o)});async function pi(e,t,r,o){let n=[],a=si(e),s=di({input:a});for await(let c of s){let p=mi(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Gt(n,r),n=[])}n.length>0&&await Gt(n,r)}async function Gt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{R(o.response)})}function mi(e,t){let r=JSON.parse(e);return t?li(r):r}function li(e){return e.resourceType==="ExplanationOfBenefit"?ui(e):e}function ui(e){return e.provider||(e.provider=ke()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=ke())}),e}import{formatHl7DateTime as Si,Hl7Message as Ei}from"@medplum/core";import{connect as fi}from"net";import{Hl7Message as hi}from"@medplum/core";import wi from"net";var er=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},yi="\v",Yt="",Zt="\r",gi=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Qt=class extends Event{constructor(e){super("error"),this.error=e}},tr=class extends er{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(Yt+Zt)){let n=hi.parse(r.substring(1,r.length-2));this.dispatchEvent(new gi(this,n)),r=""}}catch(n){this.dispatchEvent(new Qt(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new Qt(o))})}send(e){this.socket.write(yi+e.toString()+Yt+Zt)}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()}},rr=class extends er{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=fi({host:this.host,port:this.port},()=>{this.connection=new tr(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)}},or=class{constructor(e){this.handler=e}start(e,t){let r=wi.createServer(o=>{let n=new tr(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};import{Command as bi}from"commander";import{readFileSync as Ci}from"fs";var Ai=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=vi():o.file&&(r=Ci(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new rr({host:e,port:parseInt(t,10)});try{let a=await n.sendAndWait(Ei.parse(r));console.log(a.toString().replaceAll("\r",`
6
- `))}finally{n.close()}}),Pi=d("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").action(async e=>{new or(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)}),nr=new bi("hl7").addCommand(Ai).addCommand(Pi);function vi(){let e=Si(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
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|
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 xi}from"commander";import{resolve as _i}from"path";import{readdirSync as Ii}from"fs";import{homedir as Ti}from"os";var ir=d("set"),ar=d("remove"),sr=d("list"),cr=d("describe"),dr=new xi("profile").addCommand(ir).addCommand(ar).addCommand(sr).addCommand(cr);ir.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)});ar.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`)});sr.description("List all profiles saved").action(async()=>{let e=_i(Ti(),".medplum"),t=Ii(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)});cr.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=bt(e);console.log(t)});import{Command as Ki,Option as Hi}from"commander";var pr=d("list"),mr=d("current"),lr=d("switch"),ur=d("invite"),fr=new Ki("project").addCommand(pr).addCommand(mr).addCommand(lr).addCommand(ur);pr.description("List of current projects").action(async e=>{let t=await u(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 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(`
11
11
 
12
- `);console.log(r)}mr.description("Project you are currently on").action(async e=>{let r=(await u(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});lr.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await u(t);await Ri(r,e)});ur.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 Hi("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await u(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 Oi(s,c,n)});async function Ri(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 Oi(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 Di}from"@medplum/core";var Fe=d("delete"),je=d("get"),Ge=d("patch"),Ve=d("post"),ze=d("put");Fe.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await u(t);R(await r.delete(Q(r,e)))});je.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await u(t),o=await r.get(Q(r,e));t.asTransaction?R(Di(o)):R(o)});Ge.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.patch(Q(o,e),Xe(t)))});Ve.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.post(Q(o,e),Xe(t)))});ze.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.put(Q(o,e),Xe(t)))});function Xe(e){if(e)try{return JSON.parse(e)}catch{return e}}function Q(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function Ui(e){try{let t=new Ji("medplum").description("Command to access Medplum CLI");t.version(Wi),t.addCommand(Oe),t.addCommand(De),t.addCommand(je),t.addCommand(Ve),t.addCommand(Ge),t.addCommand(ze),t.addCommand(Fe),t.addCommand(fr),t.addCommand(qt),t.addCommand(jt),t.addCommand(Le),t.addCommand($e),t.addCommand(Be),t.addCommand(dr),t.addCommand(J),t.addCommand(nr),await t.parseAsync(e)}catch(t){console.error("Error: "+Mi(t))}}async function Li(){Ni.config(),await Ui(process.argv)}qe.main===module&&Li().catch(e=>console.error("Unhandled error:",e));export{Ui as main,Li as run};
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};
14
14
  //# sourceMappingURL=index.mjs.map