medplum 4.3.7 → 4.3.9

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