@medplum/cli 2.0.30 → 2.0.31

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,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- var te=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):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 Uo,normalizeErrorString as Oo}from"@medplum/core";import{Command as Bo}from"commander";import Fo from"dotenv";import{ContentType as T,getDisplayString as Ze,normalizeErrorString as Qe}from"@medplum/core";import{exec as et}from"child_process";import{createServer as tt}from"http";import{platform as ot}from"os";import{MedplumClient as Ve}from"@medplum/core";import{ClientStorage as We}from"@medplum/core";import{existsSync as oe,mkdirSync as _e,readFileSync as Ke,writeFileSync as qe}from"fs";import{homedir as ze}from"os";import{resolve as ne}from"path";var S=class extends We{constructor(o){super();this.dirName=ne(ze(),".medplum"),this.fileName=ne(this.dirName,o+".json")}clear(){this.writeFile({})}getString(o){return this.readFile()?.[o]}setString(o,n){let a=this.readFile()??{};n?a[o]=n:delete a[o],this.writeFile(a)}getObject(o){let n=this.getString(o);return n?JSON.parse(n):void 0}setObject(o,n){this.setString(o,n?JSON.stringify(n):void 0)}readFile(){if(oe(this.fileName))return JSON.parse(Ke(this.fileName,"utf8"))}writeFile(o){oe(this.dirName)||_e(this.dirName),qe(this.fileName,JSON.stringify(o,null,2),"utf8")}};async function l(e){let t=e.profile??"default",o=new S(t);Je(o,t);let{baseUrl:n,fhirUrlPath:a,accessToken:i,tokenUrl:s,authorizeUrl:c,clientId:u,clientSecret:f}=Ge(e,o),v=e.fetch??fetch,h=new Ve({fetch:v,baseUrl:n,tokenUrl:s,fhirUrlPath:a,authorizeUrl:c,storage:o,onUnauthenticated:He});return i&&h.setAccessToken(i),u&&f&&(h.setBasicAuth(u,f),await h.startClientLogin(u,f)),h}function Ge(e,t){let o=t.getObject("options"),n=e.baseUrl??o?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",a=e.fhirUrlPath??o?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??o?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??o?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??o?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,u=e.clientId??o?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??o?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:n,fhirUrlPath:a,accessToken:i,tokenUrl:s,authorizeUrl:c,clientId:u,clientSecret:f}}function He(){console.log("Unauthenticated: run `npx medplum login` to sign in")}function Je(e,t){if(t==="default")return;if(!e.getObject("options"))throw new Error(`Profile ${t} does not exist`)}import{Command as Xe,Option as Ye}from"commander";function m(e){return new Xe(e).option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base url").option("--token-url <tokenUrl>","FHIR server token url").option("--authorize-url <authorizeUrl>","FHIR server authorize url").option("--fhir-url-path <fhirUrlPath>","FHIR server url path").option("-p, --profile <profile>","Profile name").addOption(new Ye("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange"]))}var re="medplum-cli",ae="http://localhost:9615",R=m("login"),U=m("whoami");R.action(async e=>{let t=await l(e);if(e.authType==="basic"){console.log("Basic authentication does not require login");return}await nt(t)});U.action(async e=>{let t=await l(e);it(t)});async function nt(e){await rt(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",re),t.searchParams.set("redirect_uri",ae),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await at(t.toString())}async function rt(e){let t=tt(async(o,n)=>{let a=new URL(o.url,"http://localhost:9615"),i=a.searchParams.get("code");if(a.pathname==="/"&&i)try{let s=await e.processCode(i,{clientId:re,redirectUri:ae});n.writeHead(200,{"Content-Type":T.TEXT}),n.end(`Signed in as ${Ze(s)}. You may close this window.`)}catch(s){n.writeHead(400,{"Content-Type":T.TEXT}),n.end(`Error: ${Qe(s)}`)}finally{t.close()}else n.writeHead(404,{"Content-Type":T.TEXT}),n.end("Not found")}).listen(9615)}async function at(e){let t=ot(),o;switch(t){case"openbsd":case"linux":o=`xdg-open '${e}'`;break;case"darwin":o=`open '${e}'`;break;case"win32":o=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}et(o)}function it(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")}import{Command as fo}from"commander";import{CloudFormationClient as st,DescribeStackResourcesCommand as ct,DescribeStacksCommand as mt,ListStacksCommand as lt}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as dt}from"@aws-sdk/client-cloudfront";import{ECSClient as ut}from"@aws-sdk/client-ecs";import{S3Client as pt}from"@aws-sdk/client-s3";var O=new st({}),ie=new dt({}),se=new ut({}),ce=new pt({}),ft="medplum:environment";async function B(){return(await O.send(new lt({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function b(e){let t=await B();for(let o of t){let n=o.StackName,a=await F(n);if(a?.tag===e)return a}}async function F(e){let t=new mt({StackName:e}),n=(await O.send(t))?.Stacks?.[0],a=n?.Tags?.find(c=>c.Key===ft);if(!a)return;let i=await O.send(new ct({StackName:e}));if(!i.StackResources)return;let s={stack:n,tag:a.Value};for(let c of i.StackResources)c.ResourceType==="AWS::ECS::Cluster"?s.ecsCluster=c:c.ResourceType==="AWS::ECS::Service"?s.ecsService=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("FrontEndAppBucket")?s.appBucket=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("StorageStorageBucket")?s.storageBucket=c:c.ResourceType==="AWS::CloudFront::Distribution"&&c.LogicalResourceId?.startsWith("FrontEndAppDistribution")&&(s.appDistribution=c);return s}function k(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: ${$(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`)}function $(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function me(e){let t=await b(e);if(!t){console.log("Stack not found");return}k(t)}import{ACMClient as de,ListCertificatesCommand as gt,RequestCertificateCommand as yt}from"@aws-sdk/client-acm";import{GetParameterCommand as ht,PutParameterCommand as St,SSMClient as wt}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Ct,STSClient as bt}from"@aws-sdk/client-sts";import{generateKeyPairSync as vt,randomUUID as Et}from"crypto";import{existsSync as Mt,writeFileSync as Pt}from"fs";import{resolve as kt}from"path";import At from"readline";var Nt=e=>`${e}DomainName`,ue=e=>`${e}SslCertArn`,N;async function pe(){let e={apiPort:8103,region:"us-east-1"};N=At.createInterface({input:process.stdin,output:process.stdout}),d("MEDPLUM"),r("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),r(""),r("Most Medplum infrastructure is deployed using the AWS CDK."),r("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),r("This tool will help you create those resources."),r(""),r("Upon completion, this tool will:"),r(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),r(" 2. Optionally generate an AWS CloudFront signing key"),r(" 3. Optionally request SSL certificates from AWS Certificate Manager"),r(" 4. Optionally write server config settings to AWS Parameter Store"),r(""),r("The Medplum infra config file is an input to the Medplum CDK."),r("The Medplum CDK will create and manage the necessary AWS resources."),r(""),r("We will ask a series of questions to generate your infra config file."),r("Some questions have predefined options in [square brackets]."),r("Some questions have default values in (parentheses), which you can accept by pressing Enter."),r("Press Ctrl+C at any time to exit.");let t=await xt(e.region);t||(r("It appears that you do not have AWS credentials configured."),r("AWS credentials are not strictly required, but will enable some additional features."),r("If you intend to use AWS credentials, please configure them now."),await A("Do you want to continue without AWS credentials?")),d("ENVIRONMENT NAME"),r('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),r("The environment name is used in multiple places:"),r(" 1. As part of config file names (i.e., medplum.demo.config.json)"),r(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),r(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await g("What is your environment name?","demo"),r('Using environment name "'+e.name+'"...'),d("CONFIG FILE"),r("Medplum Infrastructure will create a config file in the current directory.");let o=await g("What is the config file name?",`medplum.${e.name}.config.json`);Mt(o)&&(r("Config file already exists."),await A("Do you want to overwrite the config file?")),r('Using config file "'+o+'"...'),p(o,e),d("AWS REGION"),r("Most Medplum resources will be created in a single AWS region."),e.region=await g("Enter your AWS region:","us-east-1"),p(o,e),d("AWS ACCOUNT NUMBER"),r("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&r("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await g("What is your AWS account number?",t),p(o,e),d("STACK NAME"),r("Medplum will create a CloudFormation stack to manage AWS resources."),r("AWS CloudFormation stack names ");let n="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await g("Enter your CloudFormation stack name?",n),p(o,e),d("BASE DOMAIN NAME"),r("Please enter the base domain name for your Medplum deployment."),r(""),r("Medplum deploys multiple subdomains for various services."),r(""),r('For example, "api." for the REST API and "app." for the web application.'),r("The base domain name is the common suffix for all subdomains."),r(""),r('For example, if your base domain name is "example.com",'),r('then the REST API will be "api.example.com".'),r(""),r('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),r(""),r("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await g("Enter your base domain name:");p(o,e),d("SUPPORT EMAIL"),r("Medplum sends transactional emails to users."),r("For example, emails to new users or for password reset."),r("Medplum will use the support email address to send these emails."),r("Note that you must verify the support email address in SES.");let a=await g("Enter your support email address:");d("API DOMAIN NAME"),r("Medplum deploys a REST API for the backend services."),e.apiDomainName=await g("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,p(o,e),d("APP DOMAIN NAME"),r("Medplum deploys a web application for the user interface."),e.appDomainName=await g("Enter your web application domain name:","app."+e.domainName),p(o,e),d("STORAGE DOMAIN NAME"),r("Medplum deploys a storage service for file uploads."),e.storageDomainName=await g("Enter your storage domain name:","storage."+e.domainName),p(o,e),d("STORAGE BUCKET"),r("Medplum uses an S3 bucket to store binary content such as file uploads."),r("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await g("Enter your storage bucket name:","medplum-"+e.name+"-storage"),p(o,e),d("MAX AVAILABILITY ZONES"),r("Medplum API servers can be deployed in multiple availability zones."),r("This provides redundancy and high availability."),r("However, it also increases the cost of the deployment."),r("If you want to use all availability zones, choose a large number such as 99."),r("If you want to restrict the number, for example to manage EIP limits,"),r("then choose a small number such as 1 or 2."),e.maxAzs=await E("Enter the maximum number of availability zones:",[1,2,3,99],2),d("DATABASE INSTANCES"),r("Medplum uses a relational database to store data."),r("You can set up your own database,"),r("or Medplum can create a new RDS database as part of the CloudFormation stack."),await L("Do you want to create a new RDS database as part of the CloudFormation stack?")?(r("Medplum will create a new RDS database as part of the CloudFormation stack."),r(""),r("If you need high availability, you can choose multiple instances."),r("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await E("Enter the number of database instances:",[1,2],1)):(r("Medplum will not create a new RDS database."),r("Please create a new RDS database and enter the database name, username, and password."),r('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),p(o,e),d("SERVER INSTANCES"),r("Medplum uses AWS Fargate to run the API servers."),r("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),r("Fargate will automatically scale the number of servers up and down."),r("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await E("Enter the number of server instances:",[1,2,3,4,6,8],1),p(o,e),d("SERVER MEMORY"),r("You can choose the amount of memory for each server instance."),r("The default is 512 MB, which is sufficient for getting started."),r("Note that only certain CPU units are compatible with memory units."),r('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await E("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),p(o,e),d("SERVER CPU"),r("You can choose the amount of CPU for each server instance."),r("CPU is expressed as an integer using AWS CPU units"),r("The default is 256, which is sufficient for getting started."),r("Note that only certain CPU units are compatible with memory units."),r('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await E("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),p(o,e),d("SERVER IMAGE"),r("Medplum uses Docker images for the API servers."),r("You can choose the image to use for the servers."),r("Docker images can be loaded from either Docker Hub or AWS ECR."),r("The default is the latest Medplum release."),e.serverImage=await g("Enter the server image:","medplum/medplum-server:latest"),p(o,e),d("SIGNING KEY"),r("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let{privateKey:i,publicKey:s,passphrase:c}=Rt();e.storagePublicKey=s,p(o,e),d("SSL CERTIFICATES"),r("Medplum will now check for existing SSL certificates for the subdomains.");let u=await Dt(e.region);r("Found "+u.length+" certificate(s).");for(let{region:v,certName:h}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){r("");let P=await It(e,u,v,h);e[ue(h)]=P,p(o,e)}d("AWS PARAMETER STORE"),r("Medplum uses AWS Parameter Store to store sensitive configuration values."),r("These values will be encrypted at rest."),r(`The values will be stored in the "/medplum/${e.name}" path.`);let f={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,signingKey:i,signingKeyPassphrase:c,supportEmail:a};r(JSON.stringify({...f,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await A("Do you want to store these values in AWS Parameter Store?"),await Bt(e.region,`/medplum/${e.name}/`,f),d("DONE!"),r("Medplum configuration complete."),r("You can now proceed to deploying the Medplum infrastructure with CDK."),r("Run:"),r(""),r(` npx cdk bootstrap -c config=${o}`),r(` npx cdk synth -c config=${o}`),e.region==="us-east-1"?r(` npx cdk deploy -c config=${o}`):r(` npx cdk deploy -c config=${o} --all`),r(""),r("See Medplum documentation for more information:"),r(""),r(" https://www.medplum.com/docs/self-hosting/install-on-aws"),r(""),N.close()}function r(e){N.write(e+`
3
- `)}function d(e){r(`
2
+ var ot=(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 _i,normalizeErrorString as Ki}from"@medplum/core";import{Command as Ti}from"commander";import Ii from"dotenv";import{ContentType as Ne,getDisplayString as Qo,normalizeErrorString as en}from"@medplum/core";import{exec as tn}from"child_process";import{createServer as rn}from"http";import{platform as on}from"os";import{ClientStorage as fr}from"@medplum/core";import{existsSync as nt,mkdirSync as hr,readFileSync as yr,writeFileSync as gr}from"fs";import{homedir as wr}from"os";import{resolve as it}from"path";var E=class extends fr{constructor(r){super();this.dirName=it(wr(),".medplum"),this.fileName=it(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if(nt(this.fileName))return JSON.parse(yr(this.fileName,"utf8"))}writeFile(r){nt(this.dirName)||hr(this.dirName),gr(this.fileName,JSON.stringify(r,null,2),"utf8")}};import{MedplumClient as Sr}from"@medplum/core";async function u(e){let t=e.profile??"default",r=new E(t),o=r.getObject("options");if(t!=="default"&&!o)throw new Error(`Profile "${t}" does not exist`);let{baseUrl:n,fhirUrlPath:a,accessToken:s,tokenUrl:c,authorizeUrl:p,clientId:f,clientSecret:y}=Er(e,r),T=e.fetch??fetch,I=new Sr({fetch:T,baseUrl:n,tokenUrl:c,fhirUrlPath:a,authorizeUrl:p,storage:r,onUnauthenticated:br});return s&&I.setAccessToken(s),o?.authType==="client_credentials"?(I.setBasicAuth(f,y),await I.startClientLogin(f,y)):o?.authType==="basic"&&I.setBasicAuth(f,y),I}function Er(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,a=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,p=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:p,clientSecret:f}}function br(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as Cr,Option as vr}from"commander";function m(e){return new Cr(e).option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base url").option("--token-url <tokenUrl>","FHIR server token url").option("--authorize-url <authorizeUrl>","FHIR server authorize url").option("--fhir-url-path <fhirUrlPath>","FHIR server url path").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer, <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("--audience <audience>","Audience for JWT assertion").option("-p, --profile <profile>","Profile name").addOption(new vr("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as We,encodeBase64 as At}from"@medplum/core";import{createHmac as No,createPrivateKey as Uo,randomBytes as Lo}from"crypto";import{existsSync as $o,readFileSync as xt,writeFile as Bo}from"fs";import{Buffer as be}from"buffer";var A=new TextEncoder,b=new TextDecoder,ji=2**32;function H(...e){let t=e.reduce((n,{length:a})=>n+a,0),r=new Uint8Array(t),o=0;return e.forEach(n=>{r.set(n,o),o+=n.length}),r}var w;be.isEncoding("base64url")?w=e=>be.from(e).toString("base64url"):w=e=>be.from(e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var U=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};var d=class extends U{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var x=class extends U{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},R=class extends U{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};import{KeyObject as Pr}from"crypto";import*as ve from"util";var P=ve.types.isKeyObject?e=>ve.types.isKeyObject(e):e=>e!=null&&e instanceof Pr;import*as st from"crypto";import*as Ae from"util";var _r=st.webcrypto,oe=_r,C=Ae.types.isCryptoKey?e=>Ae.types.isCryptoKey(e):e=>!1;function O(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ne(e,t){return e.name===t}function xe(e){return parseInt(e.name.slice(4),10)}function Kr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Tr(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 ct(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ne(e.algorithm,"HMAC"))throw O("HMAC");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ne(e.algorithm,"RSASSA-PKCS1-v1_5"))throw O("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ne(e.algorithm,"RSA-PSS"))throw O("RSA-PSS");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw O("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ne(e.algorithm,"ECDSA"))throw O("ECDSA");let o=Kr(t);if(e.algorithm.namedCurve!==o)throw O(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Tr(e,r)}function dt(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var _=(e,...t)=>dt("Key must be ",e,...t);function Pe(e,t,...r){return dt(`Key for the ${e} algorithm must be `,t,...r)}var _e=e=>P(e)||C(e),l=["KeyObject"];(globalThis.CryptoKey||!(oe===null||oe===void 0)&&oe.CryptoKey)&&l.push("CryptoKey");import{promisify as mt}from"util";import{inflateRaw as Wr,deflateRaw as Rr}from"zlib";var Da=mt(Wr),Ja=mt(Rr);var Mr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let a of n){if(r.has(a))return!1;r.add(a)}}return!0},L=Mr;function Dr(e){return typeof e=="object"&&e!==null}function S(e){if(!Dr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{diffieHellman as ds,generateKeyPair as Gr,KeyObject as ps}from"crypto";import{promisify as zr}from"util";import{Buffer as ie}from"buffer";import{createPublicKey as Jr,KeyObject as Nr}from"crypto";var Ur=ie.from([42,134,72,206,61,3,1,7]),Lr=ie.from([43,129,4,0,34]),$r=ie.from([43,129,4,0,35]),Br=ie.from([43,129,4,0,10]),Ke=new WeakMap,Fr=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 d("Unsupported key curve for this operation")}},ut=(e,t)=>{var r;let o;if(C(e))o=Nr.from(e);else if(P(e))o=e;else throw new TypeError(_(e,...l));if(o.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(o.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${o.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${o.asymmetricKeyType.slice(1)}`;case"ec":{if(Ke.has(o))return Ke.get(o);let n=(r=o.asymmetricKeyDetails)===null||r===void 0?void 0:r.namedCurve;if(!n&&o.type==="private")n=ut(Jr(o),!0);else if(!n){let s=o.export({format:"der",type:"spki"}),c=s[1]<128?14:15,p=s[c],f=s.slice(c+1,c+1+p);if(f.equals(Ur))n="prime256v1";else if(f.equals(Lr))n="secp384r1";else if(f.equals($r))n="secp521r1";else if(f.equals(Br))n="secp256k1";else throw new d("Unsupported key curve for this operation")}if(t)return n;let a=Fr(n);return Ke.set(o,a),a}default:throw new TypeError("Invalid asymmetric key type for this operation")}};var ae=ut;var Es=zr(Gr);import{promisify as qr}from"util";import{KeyObject as _s,pbkdf2 as Xr}from"crypto";var Js=qr(Xr);var Te=new WeakMap,se=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return t===0?r:se(e.subarray(2+r),t-1);let o=r&127;r=0;for(let n=0;n<o;n++){r<<=8;let a=e.readUInt8(2+n);r|=a}return t===0?r:se(e.subarray(2+r),t-1)},Yr=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return se(e.subarray(2),t);let o=r&127;return se(e.subarray(2+o),t)},Zr=e=>{var t,r;if(Te.has(e))return Te.get(e);let o=(r=(t=e.asymmetricKeyDetails)===null||t===void 0?void 0:t.modulusLength)!==null&&r!==void 0?r:Yr(e.export({format:"der",type:"pkcs1"}),e.type==="private"?1:0)-1<<3;return Te.set(e,o),o};var q=(e,t)=>{if(Zr(e)<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};import{Buffer as v}from"buffer";var Qr=2,eo=3,to=4,ro=48,nc=v.from([0]),ic=v.from([Qr]),ac=v.from([eo]),sc=v.from([ro]),cc=v.from([to]);var dc=new Map([["P-256",v.from("06 08 2A 86 48 CE 3D 03 01 07".replace(/ /g,""),"hex")],["secp256k1",v.from("06 05 2B 81 04 00 0A".replace(/ /g,""),"hex")],["P-384",v.from("06 05 2B 81 04 00 22".replace(/ /g,""),"hex")],["P-521",v.from("06 05 2B 81 04 00 23".replace(/ /g,""),"hex")],["ecPublicKey",v.from("06 07 2A 86 48 CE 3D 02 01".replace(/ /g,""),"hex")],["X25519",v.from("06 03 2B 65 6E".replace(/ /g,""),"hex")],["X448",v.from("06 03 2B 65 6F".replace(/ /g,""),"hex")],["Ed25519",v.from("06 03 2B 65 70".replace(/ /g,""),"hex")],["Ed448",v.from("06 03 2B 65 71".replace(/ /g,""),"hex")]]);var[D,ce]=process.versions.node.split(".").map(e=>parseInt(e,10)),ft=D>=16||D===15&&ce>=13,J=!("electron"in process.versions)&&(D>=17||D===16&&ce>=9),oo=D>=16||D===15&&ce>=9,no=D>=16||D===15&&ce>=12;var ao=(e,t)=>{if(!(t instanceof Uint8Array)){if(!_e(t))throw new TypeError(Pe(e,t,...l,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${l.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},so=(e,t,r)=>{if(!_e(t))throw new TypeError(Pe(e,t,...l));if(t.type==="secret")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},co=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ao(e,t):so(e,t,r)},X=co;function yo(e,t,r,o,n){if(n.crit!==void 0&&o.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of o.crit){if(!a.has(s))throw new d(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var B=yo;var bo=Symbol();import*as Y from"crypto";import{promisify as Po}from"util";function de(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"EdDSA":return;default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as wt}from"crypto";var St={padding:wt.RSA_PKCS1_PSS_PADDING,saltLength:wt.RSA_PSS_SALTLEN_DIGEST},Co=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function pe(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return q(t,e),t;case(J&&"PS256"):case(J&&"PS384"):case(J&&"PS512"):if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,a=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${a}`||o!==r))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>a>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return q(t,e),{key:t,...St};case(!J&&"PS256"):case(!J&&"PS384"):case(!J&&"PS512"):if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return q(t,e),{key:t,...St};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=ae(t),o=Co.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import*as F from"crypto";import{promisify as Ao}from"util";function He(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Et,createSecretKey as vo}from"crypto";function me(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(_(t,...l));return vo(t)}if(t instanceof Et)return t;if(C(t))return ct(t,e,r),Et.from(t);throw new TypeError(_(t,...l,"Uint8Array"))}var ke;F.sign.length>3?ke=Ao(F.sign):ke=F.sign;var xo=async(e,t,r)=>{let o=me(e,t,"sign");if(e.startsWith("HS")){let n=F.createHmac(He(e),o);return n.update(r),n.digest()}return ke(de(e),r,pe(e,o))},Oe=xo;var bt;Y.verify.length>4&&ft?bt=Po(Y.verify):bt=Y.verify;var Z=e=>Math.floor(e.getTime()/1e3);var Ko=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ue=e=>{let t=Ko.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var G=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new x("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!L(this._protectedHeader,this._unprotectedHeader))throw new x("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=B(x,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new x('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new x('JWS "alg" (Algorithm) Header Parameter missing or invalid');X(s,t,"sign");let c=this._payload;a&&(c=A.encode(w(c)));let p;this._protectedHeader?p=A.encode(w(JSON.stringify(this._protectedHeader))):p=A.encode("");let f=H(p,A.encode("."),c),y=await Oe(s,t,f),T={signature:w(y),payload:""};return a&&(T.payload=b.decode(c)),this._unprotectedHeader&&(T.header=this._unprotectedHeader),this._protectedHeader&&(T.protected=b.decode(p)),T}};var Q=class{constructor(t){this._flattened=new G(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};var z=class{constructor(t){if(!S(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:Z(new Date)+ue(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:Z(new Date)+ue(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:this._payload={...this._payload,iat:t},this}};var ee=class extends z{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var o;let n=new Q(A.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray((o=this._protectedHeader)===null||o===void 0?void 0:o.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new R("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};import{createSecretKey as sl,generateKeyPair as Do}from"crypto";import{promisify as Jo}from"util";var ul=Jo(Do);import{homedir as Fo}from"os";import{basename as Go,extname as zo,join as jo,resolve as Vo}from"path";import qo from"tar";function W(e){console.log(JSON.stringify(e,null,2))}async function Re(e,t,r){let o=t.source,n=De(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,Go(o),Zo(o));console.log("Updating bot.....");let s=await e.updateResource({...r,sourceCode:a});console.log("Success! New bot version: "+s.meta?.versionId)}catch(a){console.log("Update error: ",a)}}async function Pt(e,t,r){let o=t.dist??t.source,n=De(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function Me(e,t){if(t.length<4){console.log("Error: command needs to be npx medplum <new-bot-name> <project-id> <source-file> <dist-file>");return}let r=t[0],o=t[1],n=t[2],a=t[3];try{let s={name:r,description:""},c=await e.post("admin/projects/"+o+"/bot",s),p=await e.readResource("Bot",c.id),f={name:r,id:c.id,source:n,dist:a};await Re(e,f,p),console.log(`Success! Bot created: ${p.id}`),Xo(f)}catch(s){console.log("Error while creating new bot: "+s)}}function _t(e){let t=new RegExp("^"+Yo(e).replace(/\\\*/g,".*")+"$"),r=le()?.bots?.filter(o=>t.test(o.name));return r||[]}function le(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=De(t);if(r)return JSON.parse(r)}function De(e){let t=Vo(process.cwd(),e);return $o(t)?xt(t,"utf8"):(console.log("Error: File does not exist: "+t),"")}function Xo(e){let t=le();t?.bots?.push(e),Bo("medplum.config.json",JSON.stringify(t),()=>{console.log(`Bot added to config: ${e.id}`)})}function Yo(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Kt(e){let o=0,n=0;return qo.x({cwd:e,filter:(a,s)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=s.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Je(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function Zo(e){let t=zo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?We.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?We.TYPESCRIPT:We.TEXT}function fe(e,t){let r=new E(e),o={name:e,...t};r.setObject("options",o),console.log(`${e} profile created`)}function he(e){return new E(e).getObject("options")}function Tt(e,t){return t==="default"?!0:!!e.getObject("options")}async function It(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},a=At(JSON.stringify(r)),s=At(JSON.stringify(n)),c=`${a}.${s}`,p=No("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${p}`,y=new URLSearchParams;y.set("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer"),y.set("client_id",t.clientId),y.set("assertion",f),y.set("scope",t.scope??"");let T=await e.post(t.tokenUrl,y.toString(),"application/x-www-form-urlencoded",{credentials:"include"});return(await JSON.parse(T)).access_token}async function Ht(e,t){let r=Fo(),o=jo(r,t.privateKeyPath),n=xt(o),a=Uo(n),s=await new ee({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Lo(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(a),c=new URLSearchParams;c.append("grant_type","client_credentials"),c.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),c.append("client_assertion",s);let p=await e.post(t.tokenUrl,c.toString(),"application/x-www-form-urlencoded",{credentials:"include"});if(!p.access_token)throw new Error(`Failed to login: ${p}`);return p.access_token}var kt="medplum-cli",Ot="http://localhost:9615",Ue=m("login"),Le=m("whoami");Ue.action(async e=>{let t=e.profile??"default",r=new E(t);if(Tt(r,t)||(console.log("Creating new profile..."),fe(t,e)),e.authType==="basic"){console.log("Basic authentication does not require login");return}let o=he(t),n=await u(e);await nn(n,o)});Le.action(async e=>{let t=await u(e);cn(t)});async function nn(e,t){if(!t?.authType){await dn(e);return}if(t.authType==="jwt-bearer"){if(!t.clientId||!t.clientSecret)throw new Error("Missing values, make sure to add --client-id, and --client-secret for JWT Bearer login");console.log("Starting JWT login...");let r=await It(e,t);new E(t.name).setObject("activeLogin",{accessToken:r})}else if(t.authType==="jwt-assertion"){let r=await Ht(e,t);new E(t.name).setObject("activeLogin",{accessToken:r})}console.log("Login successful")}async function an(e){let t=rn(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),a=n.searchParams.get("code");if(n.pathname==="/"&&a)try{let s=await e.processCode(a,{clientId:kt,redirectUri:Ot});o.writeHead(200,{"Content-Type":Ne.TEXT}),o.end(`Signed in as ${Qo(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Ne.TEXT}),o.end(`Error: ${en(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Ne.TEXT}),o.end("Not found")}).listen(9615)}async function sn(e){let t=on(),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)}tn(r)}function cn(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 dn(e){await an(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",kt),t.searchParams.set("redirect_uri",Ot),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await sn(t.toString())}import{Command as si}from"commander";import{CloudFormationClient as pn,DescribeStackResourcesCommand as mn,DescribeStacksCommand as un,ListStacksCommand as ln}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as fn}from"@aws-sdk/client-cloudfront";import{ECSClient as hn}from"@aws-sdk/client-ecs";import{S3Client as yn}from"@aws-sdk/client-s3";var $e=new pn({}),Wt=new fn({}),Rt=new hn({}),Mt=new yn({}),gn="medplum:environment";async function Be(){return(await $e.send(new ln({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function j(e){let t=await Be();for(let r of t){let o=r.StackName,n=await Fe(o);if(n?.tag===e)return n}}async function Fe(e){let t=new un({StackName:e}),o=(await $e.send(t))?.Stacks?.[0],n=o?.Tags?.find(c=>c.Key===gn);if(!n)return;let a=await $e.send(new mn({StackName:e}));if(!a.StackResources)return;let s={stack:o,tag:n.Value};for(let c of a.StackResources)c.ResourceType==="AWS::ECS::Cluster"?s.ecsCluster=c:c.ResourceType==="AWS::ECS::Service"?s.ecsService=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("FrontEndAppBucket")?s.appBucket=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("StorageStorageBucket")?s.storageBucket=c:c.ResourceType==="AWS::CloudFront::Distribution"&&c.LogicalResourceId?.startsWith("FrontEndAppDistribution")&&(s.appDistribution=c);return s}function ye(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: ${Ge(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`)}function Ge(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Dt(e){let t=await j(e);if(!t){console.log("Stack not found");return}ye(t)}import{ACMClient as Ut,ListCertificatesCommand as wn,RequestCertificateCommand as Sn}from"@aws-sdk/client-acm";import{CloudFrontClient as En,CreatePublicKeyCommand as bn}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as Cn,PutParameterCommand as vn,SSMClient as An}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as xn,STSClient as Pn}from"@aws-sdk/client-sts";import{generateKeyPairSync as _n,randomUUID as Jt}from"crypto";import{existsSync as Kn,writeFileSync as Tn}from"fs";import{resolve as In}from"path";import Hn from"readline";var kn=e=>`${e}DomainName`,Lt=e=>`${e}SslCertArn`,we;async function $t(){let e={apiPort:8103,region:"us-east-1"};we=Hn.createInterface({input:process.stdin,output:process.stdout}),h("MEDPLUM"),i("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),i(""),i("Most Medplum infrastructure is deployed using the AWS CDK."),i("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),i("This tool will help you create those resources."),i(""),i("Upon completion, this tool will:"),i(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),i(" 2. Optionally generate an AWS CloudFront signing key"),i(" 3. Optionally request SSL certificates from AWS Certificate Manager"),i(" 4. Optionally write server config settings to AWS Parameter Store"),i(""),i("The Medplum infra config file is an input to the Medplum CDK."),i("The Medplum CDK will create and manage the necessary AWS resources."),i(""),i("We will ask a series of questions to generate your infra config file."),i("Some questions have predefined options in [square brackets]."),i("Some questions have default values in (parentheses), which you can accept by pressing Enter."),i("Press Ctrl+C at any time to exit.");let t=await On(e.region);t||(i("It appears that you do not have AWS credentials configured."),i("AWS credentials are not strictly required, but will enable some additional features."),i("If you intend to use AWS credentials, please configure them now."),await ge("Do you want to continue without AWS credentials?")),h("ENVIRONMENT NAME"),i('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),i("The environment name is used in multiple places:"),i(" 1. As part of config file names (i.e., medplum.demo.config.json)"),i(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),i(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await K("What is your environment name?","demo"),i('Using environment name "'+e.name+'"...'),h("CONFIG FILE"),i("Medplum Infrastructure will create a config file in the current directory.");let r=await K("What is the config file name?",`medplum.${e.name}.config.json`);Kn(r)&&(i("Config file already exists."),await ge("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),g(r,e),h("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await K("Enter your AWS region:","us-east-1"),g(r,e),h("AWS ACCOUNT NUMBER"),i("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&i("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await K("What is your AWS account number?",t),g(r,e),h("STACK NAME"),i("Medplum will create a CloudFormation stack to manage AWS resources."),i("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await K("Enter your CloudFormation stack name?",o),g(r,e),h("BASE DOMAIN NAME"),i("Please enter the base domain name for your Medplum deployment."),i(""),i("Medplum deploys multiple subdomains for various services."),i(""),i('For example, "api." for the REST API and "app." for the web application.'),i("The base domain name is the common suffix for all subdomains."),i(""),i('For example, if your base domain name is "example.com",'),i('then the REST API will be "api.example.com".'),i(""),i('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),i(""),i("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await K("Enter your base domain name:");g(r,e),h("SUPPORT EMAIL"),i("Medplum sends transactional emails to users."),i("For example, emails to new users or for password reset."),i("Medplum will use the support email address to send these emails."),i("Note that you must verify the support email address in SES.");let n=await K("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await K("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,g(r,e),h("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await K("Enter your web application domain name:","app."+e.domainName),g(r,e),h("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await K("Enter your storage domain name:","storage."+e.domainName),g(r,e),h("STORAGE BUCKET"),i("Medplum uses an S3 bucket to store binary content such as file uploads."),i("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await K("Enter your storage bucket name:","medplum-"+e.name+"-storage"),g(r,e),h("MAX AVAILABILITY ZONES"),i("Medplum API servers can be deployed in multiple availability zones."),i("This provides redundancy and high availability."),i("However, it also increases the cost of the deployment."),i("If you want to use all availability zones, choose a large number such as 99."),i("If you want to restrict the number, for example to manage EIP limits,"),i("then choose a small number such as 1 or 2."),e.maxAzs=await te("Enter the maximum number of availability zones:",[1,2,3,99],2),h("DATABASE INSTANCES"),i("Medplum uses a relational database to store data."),i("You can set up your own database,"),i("or Medplum can create a new RDS database as part of the CloudFormation stack."),await je("Do you want to create a new RDS database as part of the CloudFormation stack?")?(i("Medplum will create a new RDS database as part of the CloudFormation stack."),i(""),i("If you need high availability, you can choose multiple instances."),i("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await te("Enter the number of database instances:",[1,2],1)):(i("Medplum will not create a new RDS database."),i("Please create a new RDS database and enter the database name, username, and password."),i('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),g(r,e),h("SERVER INSTANCES"),i("Medplum uses AWS Fargate to run the API servers."),i("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),i("Fargate will automatically scale the number of servers up and down."),i("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await te("Enter the number of server instances:",[1,2,3,4,6,8],1),g(r,e),h("SERVER MEMORY"),i("You can choose the amount of memory for each server instance."),i("The default is 512 MB, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await te("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),g(r,e),h("SERVER CPU"),i("You can choose the amount of CPU for each server instance."),i("CPU is expressed as an integer using AWS CPU units"),i("The default is 256, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await te("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),g(r,e),h("SERVER IMAGE"),i("Medplum uses Docker images for the API servers."),i("You can choose the image to use for the servers."),i("Docker images can be loaded from either Docker Hub or AWS ECR."),i("The default is the latest Medplum release."),e.serverImage=await K("Enter the server image:","medplum/medplum-server:latest"),g(r,e),h("SIGNING KEY"),i("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let{keyId:a,privateKey:s,publicKey:c,passphrase:p}=await Dn(e.stackName+"SigningKey");e.signingKeyId=a,e.storagePublicKey=c,g(r,e),h("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let f=await Wn(e.region);i("Found "+f.length+" certificate(s).");for(let{region:T,certName:I}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let lr=await Rn(e,f,T,I);e[Lt(I)]=lr,g(r,e)}h("AWS PARAMETER STORE"),i("Medplum uses AWS Parameter Store to store sensitive configuration values."),i("These values will be encrypted at rest."),i(`The values will be stored in the "/medplum/${e.name}" path.`);let y={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,signingKeyId:e.signingKeyId,signingKey:s,signingKeyPassphrase:p,supportEmail:n};i(JSON.stringify({...y,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ge("Do you want to store these values in AWS Parameter Store?"),await Un(e.region,`/medplum/${e.name}/`,y),h("DONE!"),i("Medplum configuration complete."),i("You can now proceed to deploying the Medplum infrastructure with CDK."),i("Run:"),i(""),i(` npx cdk bootstrap -c config=${r}`),i(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?i(` npx cdk deploy -c config=${r}`):i(` npx cdk deploy -c config=${r} --all`),i(""),i("See Medplum documentation for more information:"),i(""),i(" https://www.medplum.com/docs/self-hosting/install-on-aws"),i(""),we.close()}function i(e){we.write(e+`
3
+ `)}function h(e){i(`
4
4
  `+e+`
5
- `)}function g(e,t=""){return new Promise(o=>{N.question(e+(t?" ("+t+")":"")+" ",n=>{o(n||t.toString())})})}async function j(e,t,o=""){let n=e+" ["+t.map(a=>a===o?"("+a+")":a).join("|")+"]";for(;;){let a=await g(n)||o;if(t.includes(a))return a;r("Please choose one of the following options: "+t.join(", "))}}async function E(e,t,o){return parseInt(await j(e,t.map(n=>n.toString()),o.toString()),10)}async function L(e){return(await j(e,["y","n"])).toLowerCase()==="y"}async function A(e){if(!await L(e))throw r("Exiting..."),new Error("User cancelled")}function p(e,t){Pt(kt(e),JSON.stringify(t,void 0,2),"utf-8")}async function xt(e){try{let t=new bt({region:e}),o=new Ct({});return(await t.send(o)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Dt(e){let t=await le(e);if(e!=="us-east-1"){let o=await le("us-east-1");t.push(...o)}return t}async function le(e){try{let t=new de({region:e}),o=new gt({MaxItems:1e3});return(await t.send(o)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function It(e,t,o,n){let a=e[Nt(n)],i=t.find(c=>c.CertificateArn?.includes(o)&&c.DomainName===a);if(i)return r(`Found existing certificate for "${a}" in "${o}.`),i.CertificateArn;if(r(`No existing certificate found for "${a}" in "${o}.`),!await L("Do you want to request a new certificate?"))return r(`Please add your certificate ARN to the config file in the "${ue(n)}" setting.`),"TODO";let s=await Tt(o,a);return r("Certificate ARN: "+s),s}async function Tt(e,t){try{let o=await j("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new de({region:e}),a=new yt({DomainName:t,ValidationMethod:o.toUpperCase()});return(await n.send(a)).CertificateArn}catch(o){return console.log("Error: Unable to request certificate",o.message),"TODO"}}function Rt(){let e=Et(),t=vt("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:e}});return{publicKey:t.publicKey,privateKey:t.privateKey,passphrase:e}}async function Ut(e,t){let o=new ht({Name:t,WithDecryption:!0});try{return(await e.send(o)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function Ot(e,t,o){let n=new St({Name:t,Value:o,Type:"SecureString",Overwrite:!0});await e.send(n)}async function Bt(e,t,o){let n=new wt({region:e});for(let[a,i]of Object.entries(o)){let s=t+a,c=i.toString(),u=await Ut(n,s);u!==void 0&&u!==c&&(r(`Parameter "${s}" exists with different value.`),await A(`Do you want to overwrite "${s}"?`)),await Ot(n,s,c)}}async function fe(){let e=await B();for(let t of e){let o=t.StackName,n=await F(o);n&&(k(n),console.log(""))}}import{CreateInvalidationCommand as Gt}from"@aws-sdk/client-cloudfront";import{PutObjectCommand as Ht}from"@aws-sdk/client-s3";import{ContentType as y}from"@medplum/core";import Jt from"fast-glob";import{createReadStream as Xt,mkdtempSync as Yt,readdirSync as Zt,readFileSync as Qt,rmSync as eo,writeFileSync as to}from"fs";import Se from"node-fetch";import{tmpdir as oo}from"os";import{join as D,sep as no}from"path";import{pipeline as ro}from"stream/promises";import{ContentType as W}from"@medplum/core";import{existsSync as Ft,readFileSync as $t,writeFile as jt}from"fs";import{basename as Lt,extname as Wt,resolve as _t}from"path";import Kt from"tar";function w(e){console.log(JSON.stringify(e,null,2))}async function _(e,t,o){let n=t.source,a=q(n);if(a)try{console.log("Saving source code...");let i=await e.createAttachment(a,Lt(n),Vt(n));console.log("Updating bot.....");let s=await e.updateResource({...o,sourceCode:i});console.log("Success! New bot version: "+s.meta?.versionId)}catch(i){console.log("Update error: ",i)}}async function ge(e,t,o){let n=t.dist??t.source,a=q(n);if(a)try{console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",o.id,"$deploy"),{code:a});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}catch(i){console.log("Deploy error: ",i)}}async function K(e,t){if(t.length<4){console.log("Error: command needs to be npx medplum <new-bot-name> <project-id> <source-file> <dist-file>");return}let o=t[0],n=t[1],a=t[2],i=t[3];try{let s={name:o,description:""},c=await e.post("admin/projects/"+n+"/bot",s),u=await e.readResource("Bot",c.id),f={name:o,id:c.id,source:a,dist:i};await _(e,f,u),console.log(`Success! Bot created: ${u.id}`),qt(f)}catch(s){console.log("Error while creating new bot: "+s)}}function ye(e){let t=new RegExp("^"+zt(e).replace(/\\\*/g,".*")+"$"),o=x()?.bots?.filter(n=>t.test(n.name));return o||[]}function x(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",o=q(t);if(o)return JSON.parse(o)}function q(e){let t=_t(process.cwd(),e);return Ft(t)?$t(t,"utf8"):(console.log("Error: File does not exist: "+t),"")}function qt(e){let t=x();t?.bots?.push(e),jt("medplum.config.json",JSON.stringify(t),()=>{console.log(`Bot added to config: ${e.id}`)})}function zt(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function he(e){let n=0,a=0;return Kt.x({cwd:e,filter:(i,s)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(a+=s.size,a>10485760)throw new Error("Tar extractor reached max size");return!0}})}function z(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function Vt(e){let t=Wt(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?W.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?W.TYPESCRIPT:W.TEXT}async function we(e,t){let o=x(e);if(!o){console.log("Config not found");return}let n=await b(e);if(!n){console.log("Stack not found");return}let a=n.appBucket;if(!a){console.log("App bucket not found");return}let i=await io("@medplum/app","latest");Ce(i,{MEDPLUM_BASE_URL:o.baseUrl,MEDPLUM_CLIENT_ID:o.clientId??"",GOOGLE_CLIENT_ID:o.googleClientId??"",RECAPTCHA_SITE_KEY:o.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:o.registerEnabled?"true":"false"}),await co(i,a.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await uo(n.appDistribution.PhysicalResourceId),console.log("Done")}async function ao(e,t){let o=`https://registry.npmjs.org/${e}/${t}`;return(await Se(o)).json()}async function io(e,t){let n=(await ao(e,t)).dist.tarball,a=Yt(D(oo(),"tarball-"));try{let i=await Se(n),s=he(a);return await ro(i.body,s),D(a,"package","dist")}catch(i){throw eo(a,{recursive:!0,force:!0}),i}}function Ce(e,t){for(let o of Zt(e,{withFileTypes:!0})){let n=D(e,o.name);o.isDirectory()?Ce(n,t):o.isFile()&&n.endsWith(".js")&&so(n,t)}}function so(e,t){let o=Qt(e,"utf-8");for(let[n,a]of Object.entries(t))o=o.replaceAll(`__${n}__`,a);to(e,o)}async function co(e,t,o){let n=[["assets/**/*.css",y.CSS,!0],["assets/**/*.css.map",y.JSON,!0],["assets/**/*.js",y.JAVASCRIPT,!0],["assets/**/*.js.map",y.JSON,!0],["assets/**/*.txt",y.TEXT,!0],["assets/**/*.ico",y.FAVICON,!0],["img/**/*.png",y.PNG,!0],["img/**/*.svg",y.SVG,!0],["robots.txt",y.TEXT,!0],["index.html",y.HTML,!1]];for(let a of n)await mo({rootDir:e,bucketName:t,fileNamePattern:a[0],contentType:a[1],cached:a[2],dryrun:o.dryrun})}async function mo(e){let t=Jt.sync(e.fileNamePattern,{cwd:e.rootDir});for(let o of t)await lo(D(e.rootDir,o),e)}async function lo(e,t){let o=Xt(e),n=e.substring(t.rootDir.length+1).split(no).join("/"),a={Bucket:t.bucketName,Key:n,Body:o,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${n} to ${t.bucketName}...`),t.dryrun||await ce.send(new Ht(a))}async function uo(e){let t=await ie.send(new Gt({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}import{UpdateServiceCommand as po}from"@aws-sdk/client-ecs";async function be(e){let t=await b(e);if(!t){console.log("Stack not found");return}let o=t.ecsCluster?.PhysicalResourceId;if(!o){console.log("ECS Cluster not found");return}let n=$(t.ecsService);if(!n){console.log("ECS Service not found");return}await se.send(new po({cluster:o,service:n,forceNewDeployment:!0})),console.log(`Service "${n}" updated successfully.`)}var C=new fo("aws").description("Commands to manage AWS resources");C.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(pe);C.command("list").description("List Medplum AWS CloudFormation stacks").action(fe);C.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(me);C.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(be);C.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(we);import{Command as go}from"commander";var ve=m("save"),Ee=m("deploy"),Me=m("create"),Pe=new go("bot").addCommand(ve).addCommand(Ee).addCommand(Me),V=m("save-bot"),G=m("deploy-bot"),H=m("create-bot");ve.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let o=await l(t);await I(o,e)});Ee.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let o=await l(t);await I(o,e,!0)});Me.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").action(async(e,t,o,n,a)=>{let i=await l(a);await K(i,[e,t,o,n])});async function I(e,t,o=!1){let n=ye(t);for(let a of n){let i=await e.readResource("Bot",a.id);await _(e,a,i),o&&await ge(e,a,i)}console.log(`Number of bots deployed: ${n.length}`)}V.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let o=await l(t);await I(o,e)});G.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let o=await l(t);await I(o,e,!0)});H.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,o,n,a)=>{let i=await l(a);await K(i,[e,t,o,n])});import{Command as yo}from"commander";import{createReadStream as ho,writeFile as So}from"fs";import{resolve as Ae}from"path";import{createInterface as wo}from"readline";var Ne=m("export"),xe=m("import"),De=new yo("bulk").addCommand(Ne).addCommand(xe);Ne.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:o,since:n,targetDirectory:a}=e,i=await l(e);(await i.bulkExport(t,o,n)).output?.forEach(async({type:c,url:u})=>{let f=new URL(u),v=await i.download(u),h=`${c}_${f.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",P=Ae(a??"",h);So(`${P}`,await v.text(),()=>{console.log(`${P} is created`)})})});xe.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:o,addExtensionsForMissingValues:n,targetDirectory:a}=t,i=Ae(a??process.cwd(),e),s=await l(t);await Co(i,parseInt(o,10),s,n)});async function Co(e,t,o,n){let a=[],i=ho(e),s=wo({input:i});for await(let c of s){let u=bo(c,n);a.push({resource:u,request:{method:"POST",url:u.resourceType}}),a.length%t===0&&(await ke(a,o),a=[])}a.length>0&&await ke(a,o)}async function ke(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(n=>{w(n.response)})}function bo(e,t){let o=JSON.parse(e);return t?vo(o):o}function vo(e){return e.resourceType==="ExplanationOfBenefit"?Eo(e):e}function Eo(e){return e.provider||(e.provider=z()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=z())}),e}import{Command as Mo,Option as Po}from"commander";var Ie=m("list"),Te=m("current"),Re=m("switch"),Ue=m("invite"),Oe=new Mo("project").addCommand(Ie).addCommand(Te).addCommand(Re).addCommand(Ue);Ie.description("List of current projects").action(async e=>{let t=await l(e);ko(t)});function ko(e){let o=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
5
+ `)}function K(e,t=""){return new Promise(r=>{we.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function ze(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await K(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function te(e,t,r){return parseInt(await ze(e,t.map(o=>o.toString()),r.toString()),10)}async function je(e){return(await ze(e,["y","n"])).toLowerCase()==="y"}async function ge(e){if(!await je(e))throw i("Exiting..."),new Error("User cancelled")}function g(e,t){Tn(In(e),JSON.stringify(t,void 0,2),"utf-8")}async function On(e){try{let t=new Pn({region:e}),r=new xn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Wn(e){let t=await Nt(e);if(e!=="us-east-1"){let r=await Nt("us-east-1");t.push(...r)}return t}async function Nt(e){try{let t=new Ut({region:e}),r=new wn({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Rn(e,t,r,o){let n=e[kn(o)],a=t.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===n);if(a)return i(`Found existing certificate for "${n}" in "${r}.`),a.CertificateArn;if(i(`No existing certificate found for "${n}" in "${r}.`),!await je("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${Lt(o)}" setting.`),"TODO";let s=await Mn(r,n);return i("Certificate ARN: "+s),s}async function Mn(e,t){try{let r=await ze("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Ut({region:e}),n=new Sn({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Dn(e){let t=Jt(),r=_n("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});return{keyId:(await new En({}).send(new bn({PublicKeyConfig:{Name:e,CallerReference:Jt(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}async function Jn(e,t){let r=new Cn({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Nn(e,t,r){let o=new vn({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Un(e,t,r){let o=new An({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await Jn(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await ge(`Do you want to overwrite "${s}"?`)),await Nn(o,s,c)}}async function Bt(){let e=await Be();for(let t of e){let r=t.StackName,o=await Fe(r);o&&(ye(o),console.log(""))}}import{CreateInvalidationCommand as Ln}from"@aws-sdk/client-cloudfront";import{PutObjectCommand as $n}from"@aws-sdk/client-s3";import{ContentType as k}from"@medplum/core";import Bn from"fast-glob";import{createReadStream as Fn,mkdtempSync as Gn,readdirSync as zn,readFileSync as jn,rmSync as Vn,writeFileSync as qn}from"fs";import Ft from"node-fetch";import{tmpdir as Xn}from"os";import{join as Se,sep as Yn}from"path";import{pipeline as Zn}from"stream/promises";async function Gt(e,t){let r=le(e);if(!r){console.log("Config not found");return}let o=await j(e);if(!o){console.log("Stack not found");return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let a=await ei("@medplum/app","latest");zt(a,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await ri(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await ii(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Qn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Ft(r)).json()}async function ei(e,t){let o=(await Qn(e,t)).dist.tarball,n=Gn(Se(Xn(),"tarball-"));try{let a=await Ft(o),s=Kt(n);return await Zn(a.body,s),Se(n,"package","dist")}catch(a){throw Vn(n,{recursive:!0,force:!0}),a}}function zt(e,t){for(let r of zn(e,{withFileTypes:!0})){let o=Se(e,r.name);r.isDirectory()?zt(o,t):r.isFile()&&o.endsWith(".js")&&ti(o,t)}}function ti(e,t){let r=jn(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);qn(e,r)}async function ri(e,t,r){let o=[["assets/**/*.css",k.CSS,!0],["assets/**/*.css.map",k.JSON,!0],["assets/**/*.js",k.JAVASCRIPT,!0],["assets/**/*.js.map",k.JSON,!0],["assets/**/*.txt",k.TEXT,!0],["assets/**/*.ico",k.FAVICON,!0],["img/**/*.png",k.PNG,!0],["img/**/*.svg",k.SVG,!0],["robots.txt",k.TEXT,!0],["index.html",k.HTML,!1]];for(let n of o)await oi({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function oi(e){let t=Bn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await ni(Se(e.rootDir,r),e)}async function ni(e,t){let r=Fn(e),o=e.substring(t.rootDir.length+1).split(Yn).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await Mt.send(new $n(n))}async function ii(e){let t=await Wt.send(new Ln({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}import{UpdateServiceCommand as ai}from"@aws-sdk/client-ecs";async function jt(e){let t=await j(e);if(!t){console.log("Stack not found");return}let r=t.ecsCluster?.PhysicalResourceId;if(!r){console.log("ECS Cluster not found");return}let o=Ge(t.ecsService);if(!o){console.log("ECS Service not found");return}await Rt.send(new ai({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var N=new si("aws").description("Commands to manage AWS resources");N.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action($t);N.command("list").description("List Medplum AWS CloudFormation stacks").action(Bt);N.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Dt);N.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(jt);N.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Gt);import{Command as ci}from"commander";var Vt=m("save"),qt=m("deploy"),Xt=m("create"),Yt=new ci("bot").addCommand(Vt).addCommand(qt).addCommand(Xt),Ve=m("save-bot"),qe=m("deploy-bot"),Xe=m("create-bot");Vt.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e)});qt.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e,!0)});Xt.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Me(a,[e,t,r,o])});async function Ee(e,t,r=!1){let o=_t(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Re(e,n,a),r&&await Pt(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Ve.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e)});qe.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e,!0)});Xe.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Me(a,[e,t,r,o])});import{Command as di}from"commander";import{createReadStream as pi,writeFile as mi}from"fs";import{resolve as Qt}from"path";import{createInterface as ui}from"readline";var er=m("export"),tr=m("import"),rr=new di("bulk").addCommand(er).addCommand(tr);er.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,a=await u(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:p})=>{let f=new URL(p),y=await a.download(p),T=`${c}_${f.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",I=Qt(n??"",T);mi(`${I}`,await y.text(),()=>{console.log(`${I} is created`)})})});tr.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,a=Qt(n??process.cwd(),e),s=await u(t);await li(a,parseInt(r,10),s,o)});async function li(e,t,r,o){let n=[],a=pi(e),s=ui({input:a});for await(let c of s){let p=fi(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Zt(n,r),n=[])}n.length>0&&await Zt(n,r)}async function Zt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{W(o.response)})}function fi(e,t){let r=JSON.parse(e);return t?hi(r):r}function hi(e){return e.resourceType==="ExplanationOfBenefit"?yi(e):e}function yi(e){return e.provider||(e.provider=Je()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Je())}),e}import{Command as gi,Option as wi}from"commander";var or=m("list"),nr=m("current"),ir=m("switch"),ar=m("invite"),sr=new gi("project").addCommand(or).addCommand(nr).addCommand(ir).addCommand(ar);or.description("List of current projects").action(async e=>{let t=await u(e);Si(t)});function Si(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
6
6
 
7
- `);console.log(o)}Te.description("Project you are currently on").action(async e=>{let o=(await l(e)).getActiveLogin();if(!o)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${o.project.display} (${o.project.reference})`)});Re.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let o=await l(t);await Ao(o,e)});Ue.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 Po("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,o,n)=>{let a=await l(n),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 s=i.project.reference.split("/")[1],c={resourceType:n.role,firstName:e,lastName:t,email:o,sendEmail:!!n.sendEmail,admin:!!n.admin};await No(s,c,a)});async function Ao(e,t){let n=e.getLogins().find(a=>a.project.reference?.includes(t));n?(await e.setActiveLogin(n),console.log(`Switched to project ${t}
8
- `)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function No(e,t,o){try{await o.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}catch(n){console.log("Error while sending invite "+n)}}import{convertToTransactionBundle as xo}from"@medplum/core";var J=m("delete"),X=m("get"),Y=m("patch"),Z=m("post"),Q=m("put");J.argument("<url>","Resource/$id").action(async(e,t)=>{let o=await l(t);w(await o.delete(M(e,t)))});X.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let n=await(await l(t)).get(M(e,t));t.asTransaction?w(xo(n)):w(n)});Y.arguments("<url> <body>").action(async(e,t,o)=>{let n=await l(o);w(await n.patch(M(e,o),ee(t)))});Z.arguments("<url> <body>").action(async(e,t,o)=>{let n=await l(o);w(await n.post(M(e,o),ee(t)))});Q.arguments("<url> <body>").action(async(e,t,o)=>{let n=await l(o);w(await n.put(M(e,o),ee(t)))});function ee(e){if(e)try{return JSON.parse(e)}catch{return e}}function M(e,t){let o=["admin/","auth/","fhir/R4"],{fhirUrlPath:n}=t;return o.some(a=>e.startsWith(a))?e:n?`${n}/${e}`:"fhir/R4/"+e}import{Command as Do}from"commander";import{resolve as Io}from"path";import{readdirSync as To}from"fs";import{homedir as Ro}from"os";var Be=m("set"),Fe=m("remove"),$e=m("list"),je=m("describe"),Le=new Do("profile").addCommand(Be).addCommand(Fe).addCommand($e).addCommand(je);Be.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)=>{new S(e).setObject("options",t),console.log(`${e} profile created`)});Fe.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new S(e).setObject("options",void 0),console.log(`${e} profile removed`)});$e.description("List all profiles saved").action(async()=>{let e=Io(Ro(),".medplum"),t=To(e),o=[];t.forEach(n=>{let a=n.split(".")[0],s=new S(a).getObject("options");s&&o.push({profileName:a,profile:s})}),console.log(o)});je.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let o=new S(e).getObject("options");console.log(o)});async function $o(e){try{let t=new Bo("medplum").description("Command to access Medplum CLI");t.version(Uo),t.addCommand(R),t.addCommand(U),t.addCommand(X),t.addCommand(Z),t.addCommand(Y),t.addCommand(Q),t.addCommand(J),t.addCommand(Oe),t.addCommand(De),t.addCommand(Pe),t.addCommand(V),t.addCommand(G),t.addCommand(H),t.addCommand(Le),t.addCommand(C),await t.parseAsync(e)}catch(t){console.error("Error: "+Oo(t))}}async function jo(){Fo.config(),await $o(process.argv)}te.main===module&&jo().catch(e=>console.error("Unhandled error:",e));export{$o as main,jo as run};
7
+ `);console.log(r)}nr.description("Project you are currently on").action(async e=>{let r=(await u(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});ir.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await u(t);await Ei(r,e)});ar.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 wi("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await u(o),a=n.getActiveLogin();if(!a)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!a.project.reference)throw new Error("No current project to invite user to");let s=a.project.reference.split("/")[1],c={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await bi(s,c,n)});async function Ei(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));o?(await e.setActiveLogin(o),console.log(`Switched to project ${t}
8
+ `)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function bi(e,t,r){try{await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}catch(o){console.log("Error while sending invite "+o)}}import{convertToTransactionBundle as Ci}from"@medplum/core";var Ye=m("delete"),Ze=m("get"),Qe=m("patch"),et=m("post"),tt=m("put");Ye.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await u(t);W(await r.delete(re(e,t)))});Ze.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let o=await(await u(t)).get(re(e,t));t.asTransaction?W(Ci(o)):W(o)});Qe.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.patch(re(e,r),rt(t)))});et.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.post(re(e,r),rt(t)))});tt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.put(re(e,r),rt(t)))});function rt(e){if(e)try{return JSON.parse(e)}catch{return e}}function re(e,t){let r=["admin/","auth/","fhir/R4"],{fhirUrlPath:o}=t;return r.some(n=>e.startsWith(n))?e:o?`${o}/${e}`:"fhir/R4/"+e}import{Command as vi}from"commander";import{resolve as Ai}from"path";import{readdirSync as xi}from"fs";import{homedir as Pi}from"os";var cr=m("set"),dr=m("remove"),pr=m("list"),mr=m("describe"),ur=new vi("profile").addCommand(cr).addCommand(dr).addCommand(pr).addCommand(mr);cr.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)=>{fe(e,t)});dr.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new E(e).setObject("options",void 0),console.log(`${e} profile removed`)});pr.description("List all profiles saved").action(async()=>{let e=Ai(Pi(),".medplum"),t=xi(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new E(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});mr.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=he(e);console.log(t)});async function Hi(e){try{let t=new Ti("medplum").description("Command to access Medplum CLI");t.version(_i),t.addCommand(Ue),t.addCommand(Le),t.addCommand(Ze),t.addCommand(et),t.addCommand(Qe),t.addCommand(tt),t.addCommand(Ye),t.addCommand(sr),t.addCommand(rr),t.addCommand(Yt),t.addCommand(Ve),t.addCommand(qe),t.addCommand(Xe),t.addCommand(ur),t.addCommand(N),await t.parseAsync(e)}catch(t){console.error("Error: "+Ki(t))}}async function ki(){Ii.config(),await Hi(process.argv)}ot.main===module&&ki().catch(e=>console.error("Unhandled error:",e));export{Hi as main,ki as run};
9
9
  //# sourceMappingURL=index.mjs.map