medplum 5.1.39 → 5.1.41

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,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../cli/node_modules/semver/internal/constants.js", "../../../cli/node_modules/semver/internal/debug.js", "../../../cli/node_modules/semver/internal/re.js", "../../../cli/node_modules/semver/internal/parse-options.js", "../../../cli/node_modules/semver/internal/identifiers.js", "../../../cli/node_modules/semver/classes/semver.js", "../../../cli/node_modules/semver/functions/parse.js", "../../../cli/node_modules/semver/functions/valid.js", "../../../cli/node_modules/semver/functions/clean.js", "../../../cli/node_modules/semver/functions/inc.js", "../../../cli/node_modules/semver/functions/diff.js", "../../../cli/node_modules/semver/functions/major.js", "../../../cli/node_modules/semver/functions/minor.js", "../../../cli/node_modules/semver/functions/patch.js", "../../../cli/node_modules/semver/functions/prerelease.js", "../../../cli/node_modules/semver/functions/compare.js", "../../../cli/node_modules/semver/functions/rcompare.js", "../../../cli/node_modules/semver/functions/compare-loose.js", "../../../cli/node_modules/semver/functions/compare-build.js", "../../../cli/node_modules/semver/functions/sort.js", "../../../cli/node_modules/semver/functions/rsort.js", "../../../cli/node_modules/semver/functions/gt.js", "../../../cli/node_modules/semver/functions/lt.js", "../../../cli/node_modules/semver/functions/eq.js", "../../../cli/node_modules/semver/functions/neq.js", "../../../cli/node_modules/semver/functions/gte.js", "../../../cli/node_modules/semver/functions/lte.js", "../../../cli/node_modules/semver/functions/cmp.js", "../../../cli/node_modules/semver/functions/coerce.js", "../../../cli/node_modules/semver/functions/truncate.js", "../../../cli/node_modules/semver/internal/lrucache.js", "../../../cli/node_modules/semver/classes/range.js", "../../../cli/node_modules/semver/classes/comparator.js", "../../../cli/node_modules/semver/functions/satisfies.js", "../../../cli/node_modules/semver/ranges/to-comparators.js", "../../../cli/node_modules/semver/ranges/max-satisfying.js", "../../../cli/node_modules/semver/ranges/min-satisfying.js", "../../../cli/node_modules/semver/ranges/min-version.js", "../../../cli/node_modules/semver/ranges/valid.js", "../../../cli/node_modules/semver/ranges/outside.js", "../../../cli/node_modules/semver/ranges/gtr.js", "../../../cli/node_modules/semver/ranges/ltr.js", "../../../cli/node_modules/semver/ranges/intersects.js", "../../../cli/node_modules/semver/ranges/simplify.js", "../../../cli/node_modules/semver/ranges/subset.js", "../../../cli/node_modules/semver/index.js", "../../../cli/src/index.ts", "../../../cli/src/agent.ts", "../../../cli/src/util/client.ts", "../../../cli/src/storage.ts", "../../../cli/src/utils.ts", "../../../../node_modules/jose/dist/webapi/lib/buffer_utils.js", "../../../../node_modules/jose/dist/webapi/util/errors.js", "../../../../node_modules/jose/dist/webapi/util/base64url.js", "../../../../node_modules/jose/dist/webapi/lib/validate.js", "../../../../node_modules/jose/dist/webapi/lib/key.js", "../../../../node_modules/jose/dist/webapi/lib/key_descriptor.js", "../../../../node_modules/jose/dist/webapi/lib/jws_algorithms.js", "../../../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js", "../../../../node_modules/jose/dist/webapi/lib/jws_sign.js", "../../../../node_modules/jose/dist/webapi/jwt/sign.js", "../../../cli/src/auth.ts", "../../../cli/src/util/color.ts", "../../../cli/src/aws/utils.ts", "../../../cli/src/aws/terminal.ts", "../../../cli/src/aws/describe.ts", "../../../cli/src/aws/init.ts", "../../../cli/src/aws/list.ts", "../../../cli/src/aws/update-app.ts", "../../../cli/src/aws/update-bucket-policies.ts", "../../../cli/src/aws/update-config.ts", "../../../cli/src/aws/update-server.ts", "../../../cli/src/aws/index.ts", "../../../cli/src/bots.ts", "../../../cli/src/bulk.ts", "../../../cli/src/dicomweb.ts", "../../../cli/src/hl7.ts", "../../../hl7/src/base.ts", "../../../hl7/src/client.ts", "../../../hl7/src/connection.ts", "../../../hl7/src/constants.ts", "../../../hl7/src/events.ts", "../../../hl7/src/free-port.ts", "../../../hl7/src/server.ts", "../../../cli/src/profiles.ts", "../../../cli/src/project.ts", "../../../cli/src/rest.ts"],
4
- "sourcesContent": ["'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifier, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\n\nconst isPrereleaseIdentifier = (prerelease, identifier) => {\n const identifiers = identifier.split('.')\n if (identifiers.length > prerelease.length) {\n return false\n }\n\n for (let i = 0; i < identifiers.length; i++) {\n if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {\n return false\n }\n }\n\n return true\n}\n\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (isPrereleaseIdentifier(this.prerelease, identifier)) {\n const prereleaseBase = this.prerelease[identifier.split('.').length]\n if (isNaN(prereleaseBase)) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "'use strict'\n\nconst parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n", "'use strict'\n\nconst parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // If the main part has no difference\n if (lowVersion.compareMain(highVersion) === 0) {\n if (lowVersion.minor && !lowVersion.patch) {\n return 'minor'\n }\n return 'patch'\n }\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are prereleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "'use strict'\n\nconst parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "'use strict'\n\nconst compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "'use strict'\n\nconst compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n", "'use strict'\n\nconst parse = require('./parse')\nconst constants = require('../internal/constants')\nconst SemVer = require('../classes/semver')\n\nconst truncate = (version, truncation, options) => {\n if (!constants.RELEASE_TYPES.includes(truncation)) {\n return null\n }\n\n const clonedVersion = cloneInputVersion(version, options)\n return clonedVersion && doTruncation(clonedVersion, truncation)\n}\n\nconst cloneInputVersion = (version, options) => {\n const versionStringToParse = (\n version instanceof SemVer ? version.version : version\n )\n\n return parse(versionStringToParse, options)\n}\n\nconst doTruncation = (version, truncation) => {\n if (isPrerelease(truncation)) {\n return version.version\n }\n\n version.prerelease = []\n\n switch (truncation) {\n case 'major':\n version.minor = 0\n version.patch = 0\n break\n case 'minor':\n version.patch = 0\n break\n }\n\n return version.format()\n}\n\nconst isPrerelease = (type) => {\n return type.startsWith('pre')\n}\n\nmodule.exports = truncate\n", "'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n", "'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // strip build metadata so it can't bleed into the version\n range = range.replace(BUILDSTRIPRE, '')\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n src,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\n// unbounded global build-metadata stripper used by parseRange\nconst BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\nconst invalidXRangeOrder = (M, m, p) => (\n (isX(M) && !isX(m)) ||\n (isX(m) && p && !isX(p))\n)\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n // if we're including prereleases in the match, then the lower bound is\n // -0, the lowest possible prerelease value, just like x-ranges and carets.\n // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as.\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n if (invalidXRangeOrder(M, m, p)) {\n return comp\n }\n\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "'use strict'\n\nconst Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n", "'use strict'\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "'use strict'\n\nconst outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n", "'use strict'\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n", "'use strict'\n\nconst Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If LT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !c.test(gt.semver)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !c.test(lt.semver)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n", "'use strict'\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst truncate = require('./functions/truncate')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n truncate,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { MEDPLUM_VERSION, normalizeErrorString } from '@medplum/core';\nimport { CommanderError, Option } from 'commander';\nimport dotenv from 'dotenv';\nimport { agent } from './agent';\nimport { login, token, whoami } from './auth';\nimport { buildAwsCommand } from './aws/index';\nimport { bot, createBotDeprecate, deployBotDeprecate, saveBotDeprecate } from './bots';\nimport { bulk } from './bulk';\nimport { dicomweb } from './dicomweb';\nimport { hl7 } from './hl7';\nimport { profile } from './profiles';\nimport { project } from './project';\nimport { deleteObject, get, patch, post, put } from './rest';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nexport async function main(argv: string[]): Promise<void> {\n const index = new MedplumCommand('medplum')\n .description('Command to access Medplum CLI')\n .option('--client-id <clientId>', 'FHIR server client id')\n .option('--client-secret <clientSecret>', 'FHIR server client secret')\n .option('--base-url <baseUrl>', 'FHIR server base URL, must be absolute')\n .option('--token-url <tokenUrl>', 'FHIR server token URL, absolute or relative to base URL')\n .option('--authorize-url <authorizeUrl>', 'FHIR server authorize URL, absolute or relative to base URL')\n .option('--fhir-url, --fhir-url-path <fhirUrlPath>', 'FHIR server URL, absolute or relative to base URL')\n .option('--scope <scope>', 'OAuth scope (e.g., \"openid offline_access\")')\n .option('--access-token <accessToken>', 'Access token for token exchange authentication')\n .option('--callback-url <callbackUrl>', 'Callback URL for authorization code flow')\n .option('--subject <subject>', 'Subject for JWT authentication')\n .option('--audience <audience>', 'Audience for JWT authentication')\n .option('--issuer <issuer>', 'Issuer for JWT authentication')\n .option('--private-key-path <privateKeyPath>', 'Private key path for JWT assertion')\n .option('-p, --profile <profile>', 'Profile name')\n .option('-v --verbose', 'Verbose output')\n .addOption(\n new Option('--auth-type <authType>', 'Type of authentication').choices([\n 'basic',\n 'client-credentials',\n 'authorization-code',\n 'jwt-bearer',\n 'token-exchange',\n 'jwt-assertion',\n ])\n )\n .on('option:verbose', () => {\n process.env.VERBOSE = '1';\n });\n\n // Configure CLI\n index.exitOverride();\n index.version(MEDPLUM_VERSION);\n index.configureHelp({ showGlobalOptions: true });\n\n // Auth commands\n addSubcommand(index, login);\n addSubcommand(index, whoami);\n addSubcommand(index, token);\n\n // REST commands\n addSubcommand(index, get);\n addSubcommand(index, post);\n addSubcommand(index, patch);\n addSubcommand(index, put);\n addSubcommand(index, deleteObject);\n\n // Project\n addSubcommand(index, project);\n\n // Bulk Commands\n addSubcommand(index, bulk);\n\n // Bot Commands\n addSubcommand(index, bot);\n\n // Agent Commands\n addSubcommand(index, agent);\n\n // Deprecated Bot Commands\n addSubcommand(index, saveBotDeprecate);\n addSubcommand(index, deployBotDeprecate);\n addSubcommand(index, createBotDeprecate);\n\n // Profile Commands\n addSubcommand(index, profile);\n\n // AWS commands\n addSubcommand(index, buildAwsCommand());\n\n // HL7 commands\n addSubcommand(index, hl7);\n\n // DICOMweb commands\n addSubcommand(index, dicomweb);\n\n try {\n await index.parseAsync(argv);\n } catch (err) {\n handleError(err as Error);\n }\n}\n\nexport function handleError(err: Error | CommanderError): void {\n let exitCode = 1;\n let shouldPrint = true;\n if (err instanceof CommanderError) {\n // We return if not in verbose mode for CommanderErrors\n // Since commander.js will already log the error to console for us\n // Previously we didn't have this guard here and it would always double print errors\n if (!process.env.VERBOSE) {\n shouldPrint = false;\n }\n exitCode = err.exitCode;\n }\n if (exitCode !== 0 && shouldPrint) {\n writeErrorToStderr(err, !!process.env.VERBOSE);\n const cause = err.cause;\n if (process.env.VERBOSE) {\n if (Array.isArray(cause)) {\n for (const err of cause as Error[]) {\n writeErrorToStderr(err, true);\n }\n } else if (cause instanceof Error) {\n writeErrorToStderr(cause, true);\n }\n }\n }\n process.exit(exitCode);\n}\n\nfunction writeErrorToStderr(err: unknown, verbose = false): void {\n if (verbose) {\n console.error(err);\n return;\n }\n if (err instanceof CommanderError) {\n process.stderr.write(`${normalizeErrorString(err)}\\n`);\n } else {\n process.stderr.write(`Error: ${normalizeErrorString(err)}\\n`);\n }\n}\n\nexport async function run(): Promise<void> {\n dotenv.config({ quiet: true });\n await main(process.argv);\n}\n\nif (import.meta.main) {\n run().catch((err) => {\n console.error('Unhandled error:', normalizeErrorString(err));\n process.exit(1);\n });\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type {\n AgentChannelStats,\n AgentStats,\n AgentStatValue,\n IssueSeverity,\n MedplumClient,\n MedplumClientOptions,\n WithId,\n} from '@medplum/core';\nimport { ContentType, EMPTY, isOk, isUUID, normalizeErrorString } from '@medplum/core';\nimport type { Agent, Bundle, OperationOutcome, Parameters, ParametersParameter, Reference } from '@medplum/fhirtypes';\nimport { Option } from 'commander';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nexport type ValidIdsOrCriteria = { type: 'ids'; ids: string[] } | { type: 'criteria'; criteria: string };\n\nexport type ParsedParametersMap<R extends string[], O extends string[]> = Record<R[number], string> &\n Record<O[number], string | undefined>;\n\nexport type ParamNames<R extends string[], O extends string[] = []> = {\n required: R;\n optional?: O;\n};\n\nexport type AgentBulkOpResponse<T extends Parameters | OperationOutcome = Parameters | OperationOutcome> = {\n agent: WithId<Agent>;\n result: T;\n};\n\nexport type CallAgentBulkOperationArgs<T extends Record<string, unknown>, R extends Parameters | OperationOutcome> = {\n operation: string;\n agentIds: string[];\n options: MedplumClientOptions & { criteria: string; output?: 'json' };\n params?: Record<string, string | boolean | number>;\n parseSuccessfulResponse: (response: AgentBulkOpResponse<R>) => T;\n renderSuccessfulRows?: (rows: T[]) => void;\n};\n\nexport type FailedRow = {\n id: string;\n name: string;\n severity: IssueSeverity;\n code: string;\n details: string;\n};\n\nexport type StatusRow = {\n id: string;\n name: string;\n enabledStatus: string;\n connectionStatus: string;\n version: string;\n statusLastUpdated: string;\n};\n\nconst agentStatusCommand = new MedplumCommand('status').aliases(['info', 'list', 'ls']);\nconst agentPingCommand = new MedplumCommand('ping');\nconst agentPushCommand = new MedplumCommand('push');\nconst agentReloadConfigCommand = new MedplumCommand('reload-config');\nconst agentUpgradeCommand = new MedplumCommand('upgrade');\nconst agentStatsCommand = new MedplumCommand('stats');\n\nexport const agent = new MedplumCommand('agent');\naddSubcommand(agent, agentStatusCommand);\naddSubcommand(agent, agentPingCommand);\naddSubcommand(agent, agentPushCommand);\naddSubcommand(agent, agentReloadConfigCommand);\naddSubcommand(agent, agentUpgradeCommand);\naddSubcommand(agent, agentStatsCommand);\n\nagentStatusCommand\n .description('Get the status of a specified agent')\n .argument('[agentIds...]', 'The ID(s) of the agent(s) to get the status of')\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg'\n )\n .addOption(\n new Option('--output <format>', 'An optional output format, defaults to table')\n .choices(['table', 'json'])\n .default('table')\n )\n .action(async (agentIds, options) => {\n await callAgentBulkOperation({\n operation: '$bulk-status',\n agentIds,\n options,\n parseSuccessfulResponse: (response: AgentBulkOpResponse<Parameters>) => {\n const statusEntry = parseParameterValues(response.result, {\n required: ['status', 'version'],\n optional: ['lastUpdated'],\n });\n\n return {\n id: response.agent.id,\n name: response.agent.name,\n enabledStatus: response.agent.status,\n version: statusEntry.version,\n connectionStatus: statusEntry.status,\n statusLastUpdated: statusEntry.lastUpdated ?? 'N/A',\n } satisfies StatusRow;\n },\n });\n });\n\nagentPingCommand\n .description('Ping a host from a specified agent')\n .argument('<ipOrDomain>', 'The IPv4 address or domain name to ping')\n .argument(\n '[agentId]',\n 'Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option'\n )\n .option('--count <count>', 'An optional amount of pings to issue before returning results', '1')\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg'\n )\n .action(async (ipOrDomain, agentId, options) => {\n const medplum = await createMedplumClient(options);\n const agentRef = await resolveAgentReference(medplum, agentId, options);\n\n const count = Number.parseInt(options.count, 10);\n if (Number.isNaN(count)) {\n throw new Error('--count <count> must be an integer if specified');\n }\n\n try {\n const pingResult = (await medplum.pushToAgent(agentRef, ipOrDomain, `PING ${count}`, ContentType.PING, true, {\n maxRetries: 0,\n })) as string;\n console.info(pingResult);\n } catch (err) {\n throw new Error('Unexpected response from agent while pinging', { cause: err });\n }\n });\n\nagentPushCommand\n .description('Push a message to a target device via a specified agent')\n .argument('<deviceId>', 'The ID of the device to push the message to')\n .argument('<message>', 'The message to send to the destination device')\n .argument(\n '[agentId]',\n 'Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option'\n )\n .option('--content-type <contentType>', 'The content type of the message', ContentType.HL7_V2)\n .option('--no-wait', 'Tells the server not to wait for a response from the destination device')\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg'\n )\n .action(async (deviceId, message, agentId, options) => {\n const medplum = await createMedplumClient(options);\n const agentRef = await resolveAgentReference(medplum, agentId, options);\n\n let pushResult: string;\n try {\n pushResult = (await medplum.pushToAgent(\n agentRef,\n { reference: `Device/${deviceId}` },\n message,\n options.contentType,\n options.wait !== false,\n { maxRetries: 0 }\n )) as string;\n } catch (err) {\n throw new Error('Unexpected response from agent while pushing message to agent', { cause: err });\n }\n\n console.info(pushResult);\n });\n\nagentReloadConfigCommand\n .description('Reload the config for the specified agent(s)')\n .argument(\n '[agentIds...]',\n 'The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag'\n )\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg'\n )\n .addOption(\n new Option('--output <format>', 'An optional output format, defaults to table')\n .choices(['table', 'json'])\n .default('table')\n )\n .action(async (agentIds, options) => {\n await callAgentBulkOperation({\n operation: '$reload-config',\n agentIds,\n options,\n parseSuccessfulResponse: (response: AgentBulkOpResponse<OperationOutcome>) => {\n return {\n id: response.agent.id,\n name: response.agent.name,\n };\n },\n });\n });\n\nagentUpgradeCommand\n .description('Upgrade the version for the specified agent(s)')\n .argument(\n '[agentIds...]',\n 'The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag'\n )\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg'\n )\n .option(\n '--agentVersion <version>',\n 'An optional agent version to upgrade to. Defaults to the latest version if flag not included'\n )\n .option('--force', 'Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.')\n .addOption(\n new Option('--output <format>', 'An optional output format, defaults to table')\n .choices(['table', 'json'])\n .default('table')\n )\n .action(async (agentIds, options) => {\n const params: Record<string, string | boolean | number> = {};\n if (options.agentVersion) {\n params.version = options.agentVersion;\n }\n if (options.force) {\n params.force = true;\n }\n\n await callAgentBulkOperation({\n operation: '$upgrade',\n agentIds,\n options,\n params,\n parseSuccessfulResponse: (response: AgentBulkOpResponse<OperationOutcome>) => {\n return {\n id: response.agent.id,\n name: response.agent.name,\n version: options.agentVersion ?? 'latest',\n };\n },\n });\n });\n\nagentStatsCommand\n .description('Get runtime statistics for the specified agent(s)')\n .argument(\n '[agentIds...]',\n 'The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag'\n )\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg'\n )\n .addOption(\n new Option('--output <format>', 'An optional output format, defaults to table')\n .choices(['table', 'json'])\n .default('table')\n )\n .action(async (agentIds, options) => {\n await callAgentBulkOperation({\n operation: '$stats',\n agentIds,\n options,\n parseSuccessfulResponse: (response: AgentBulkOpResponse<Parameters>) => {\n const { stats } = parseParameterValues(response.result, { required: ['stats'] });\n let parsed: AgentStats | undefined;\n try {\n parsed = JSON.parse(stats) as AgentStats;\n } catch (err) {\n console.error(`Failed to parse stats for agent ${response.agent.id}: ${normalizeErrorString(err)}`);\n }\n return {\n id: response.agent.id,\n name: response.agent.name,\n stats: parsed,\n };\n },\n renderSuccessfulRows: (rows) => {\n for (let i = 0; i < rows.length; i++) {\n if (i > 0) {\n console.info();\n }\n renderAgentStats(rows[i]);\n }\n },\n });\n });\n\nconst SUMMARY_STAT_KEYS = [\n 'live',\n 'ping',\n 'hl7ConnectionsOpen',\n 'hl7ClientCount',\n 'hl7QueueDepth',\n 'webSocketQueueDepth',\n 'outstandingHeartbeats',\n] as const satisfies readonly (keyof AgentStats)[];\n\nfunction formatStatValue(value: AgentStatValue | undefined): string {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return value.toString();\n}\n\nfunction buildChannelStatsRows(\n entries: Record<string, AgentChannelStats> | undefined\n): Record<string, number | string>[] {\n if (!entries) {\n return [];\n }\n return Object.entries(entries)\n .filter(([, value]) => value?.rtt)\n .map(([name, value]) => ({\n name,\n count: value.rtt.count,\n pending: value.rtt.pendingCount,\n 'min (ms)': value.rtt.min,\n 'avg (ms)': value.rtt.average,\n 'max (ms)': value.rtt.max,\n 'p50 (ms)': value.rtt.p50,\n 'p95 (ms)': value.rtt.p95,\n 'p99 (ms)': value.rtt.p99,\n }));\n}\n\nfunction renderAgentStats(row: { id: string; name?: string; stats: AgentStats | undefined }): void {\n const heading = row.name ? `${row.name} (${row.id})` : row.id;\n console.info(`Agent: ${heading}`);\n if (!row.stats) {\n console.info(' (stats unavailable)');\n return;\n }\n\n const summary: Record<string, string> = {};\n for (const key of SUMMARY_STAT_KEYS) {\n summary[key] = formatStatValue(row.stats[key]);\n }\n const knownKeys = new Set<string>([...SUMMARY_STAT_KEYS, 'channelStats', 'clientStats']);\n for (const [key, value] of Object.entries(row.stats)) {\n if (!knownKeys.has(key)) {\n summary[key] = formatStatValue(value);\n }\n }\n console.table(summary);\n\n const channelRows = buildChannelStatsRows(row.stats.channelStats);\n if (channelRows.length) {\n console.info('Channel Stats:');\n console.table(channelRows);\n }\n\n const clientRows = buildChannelStatsRows(row.stats.clientStats);\n if (clientRows.length) {\n console.info('Client Stats:');\n console.table(clientRows);\n }\n}\n\nexport async function callAgentBulkOperation<\n T extends Record<string, unknown>,\n R extends Parameters | OperationOutcome,\n>({\n operation,\n agentIds,\n options,\n params = {},\n parseSuccessfulResponse,\n renderSuccessfulRows,\n}: CallAgentBulkOperationArgs<T, R>): Promise<void> {\n const normalized = parseEitherIdsOrCriteria(agentIds, options);\n const medplum = await createMedplumClient(options);\n const usedCriteria = normalized.type === 'criteria' ? normalized.criteria : `Agent?_id=${normalized.ids.join(',')}`;\n const searchParams = new URLSearchParams(usedCriteria.split('?')[1]);\n for (const [paramName, paramVal] of Object.entries(params)) {\n searchParams.append(paramName, paramVal.toString());\n }\n\n let result: Bundle<Parameters> | Parameters | OperationOutcome;\n try {\n const url = medplum.fhirUrl('Agent', operation);\n url.search = searchParams.toString();\n result = await medplum.get(url, {\n cache: 'reload',\n });\n } catch (err) {\n throw new Error(`Operation '${operation}' failed`, { cause: err });\n }\n\n if (options.output === 'json') {\n console.info(JSON.stringify(result, null, 2));\n return;\n }\n\n const successfulResponses = [] as AgentBulkOpResponse<R>[];\n const failedResponses = [] as AgentBulkOpResponse<OperationOutcome>[];\n\n switch (result.resourceType) {\n case 'Bundle': {\n const responses = parseAgentBulkOpBundle(result);\n for (const response of responses) {\n if (response.result.resourceType === 'Parameters' || isOk(response.result)) {\n successfulResponses.push(response as AgentBulkOpResponse<R>);\n } else {\n failedResponses.push(response as AgentBulkOpResponse<OperationOutcome>);\n }\n }\n break;\n }\n case 'Parameters':\n case 'OperationOutcome': {\n const agent = await medplum.searchOne('Agent', searchParams, { cache: 'reload' });\n if (!agent) {\n throw new Error('Agent not found');\n }\n if (result.resourceType === 'Parameters') {\n successfulResponses.push({ agent, result } as AgentBulkOpResponse<R>);\n } else {\n failedResponses.push({ agent, result });\n }\n break;\n }\n default:\n throw new Error(`Invalid result received for '${operation}' operation: ${JSON.stringify(result)}`);\n }\n\n const successfulRows = [] as T[];\n for (const response of successfulResponses) {\n const row = parseSuccessfulResponse(response);\n successfulRows.push(row);\n }\n\n const failedRows = [] as FailedRow[];\n for (const response of failedResponses) {\n const outcome = response.result;\n const issue = outcome.issue?.[0];\n const row = {\n id: response.agent.id,\n name: response.agent.name,\n severity: issue.severity,\n code: issue.code,\n details: issue.details?.text ?? 'No details to show',\n } satisfies FailedRow;\n failedRows.push(row);\n }\n\n console.info(`\\n${successfulRows.length} successful response(s):\\n`);\n if (renderSuccessfulRows) {\n if (successfulRows.length) {\n renderSuccessfulRows(successfulRows);\n } else {\n console.info('No successful responses received');\n }\n } else {\n console.table(successfulRows.length ? successfulRows : 'No successful responses received');\n }\n console.info();\n\n if (failedRows.length) {\n console.info(`${failedRows.length} failed response(s):`);\n console.info();\n console.table(failedRows);\n }\n}\n\nexport async function resolveAgentReference(\n medplum: MedplumClient,\n agentId: string | undefined,\n options: Record<string, string>\n): Promise<Reference<Agent>> {\n if (!(agentId || options.criteria)) {\n throw new Error('This command requires either an [agentId] or a --criteria <criteria> flag');\n }\n if (agentId && options.criteria) {\n throw new Error(\n 'Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive'\n );\n }\n\n let usedId: string;\n if (agentId) {\n usedId = agentId;\n } else {\n assertValidAgentCriteria(options.criteria);\n const result = await medplum.search('Agent', `${options.criteria.split('?')[1]}&_count=2`);\n if (!result?.entry?.length) {\n throw new Error('Could not find an agent matching the provided criteria');\n }\n if (result.entry.length !== 1) {\n throw new Error(\n 'Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent'\n );\n }\n usedId = result.entry[0].resource?.id as string;\n }\n\n return { reference: `Agent/${usedId}` };\n}\n\nexport function parseAgentBulkOpBundle(bundle: Bundle<Parameters>): AgentBulkOpResponse[] {\n const responses = [];\n for (const entry of bundle.entry ?? EMPTY) {\n if (!entry.resource) {\n throw new Error('No Parameter resource found in entry');\n }\n responses.push(parseAgentBulkOpParameters(entry.resource));\n }\n return responses;\n}\n\nexport function parseAgentBulkOpParameters(params: Parameters): AgentBulkOpResponse {\n const agent = params.parameter?.find((p) => p.name === 'agent')?.resource as WithId<Agent>;\n if (!agent) {\n throw new Error(\"Agent bulk operation response missing 'agent'\");\n }\n if (agent.resourceType !== 'Agent') {\n throw new Error(`Agent bulk operation returned 'agent' with type '${agent.resourceType}'`);\n }\n const result = params.parameter?.find((p) => p.name === 'result')?.resource;\n if (!result) {\n throw new Error(\"Agent bulk operation response missing result'\");\n }\n if (!(result.resourceType === 'Parameters' || result.resourceType === 'OperationOutcome')) {\n throw new Error(`Agent bulk operation returned 'result' with type '${result.resourceType}'`);\n }\n return { agent, result };\n}\n\nexport function parseParameterValues<const R extends string[], const O extends string[] = []>(\n params: Parameters,\n paramNames: ParamNames<R, O>\n): ParsedParametersMap<R, O> {\n const map = {} as ParsedParametersMap<R, O>;\n const requiredParams = paramNames.required;\n const optionalParams = paramNames.optional;\n\n for (const paramName of requiredParams) {\n const paramsParam = params.parameter?.find((p) => p.name === paramName);\n if (!paramsParam) {\n throw new Error(`Failed to find parameter '${paramName}'`);\n }\n let valueProp: string | undefined;\n for (const prop in paramsParam) {\n // This technically could lead to parsing invalid values (ie. valueAbc123) but for now we can pretend this always works\n if (prop.startsWith('value')) {\n if (valueProp) {\n throw new Error(`Found multiple values for parameter '${paramName}'`);\n }\n valueProp = prop;\n }\n }\n if (!valueProp) {\n throw new Error(`Failed to find a value for parameter '${paramName}'`);\n }\n\n // @ts-expect-error ParsedParameterMap expects key to be T[number], which it is, but unable to be inferred in for-of loop\n map[paramName] = paramsParam[valueProp] as string;\n }\n\n if (optionalParams?.length) {\n for (const paramName of optionalParams) {\n const paramsParam = params.parameter?.find((p) => p.name === paramName);\n if (!paramsParam) {\n continue;\n }\n const value = extractValueFromParametersParameter(paramName, paramsParam);\n // @ts-expect-error ParsedParameterMap expects key to be T[number], which it is, but unable to be inferred in for-of loop\n map[paramName] = value;\n }\n }\n\n return map;\n}\n\nexport function extractValueFromParametersParameter(paramName: string, paramsParam: ParametersParameter): string {\n let valueProp: string | undefined;\n for (const prop in paramsParam) {\n // This technically could lead to parsing invalid values (ie. valueAbc123) but for now we can pretend this always works\n if (prop.startsWith('value')) {\n if (valueProp) {\n throw new Error(`Found multiple values for parameter '${paramName}'`);\n }\n valueProp = prop;\n }\n }\n if (!valueProp) {\n throw new Error(`Failed to find a value for parameter '${paramName}'`);\n }\n // @ts-expect-error valueProp is any string but it should only be choice-of-type `value[x]`\n return paramsParam[valueProp] as string;\n}\n\nexport function parseEitherIdsOrCriteria(agentIds: string[], options: { criteria: string }): ValidIdsOrCriteria {\n if (!Array.isArray(agentIds)) {\n throw new Error('Invalid agent IDs array');\n }\n if (agentIds.length) {\n // Check that options.criteria is not defined\n if (options.criteria) {\n throw new Error(\n 'Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive'\n );\n }\n for (const id of agentIds) {\n if (!isUUID(id)) {\n throw new Error(`Input '${id}' is not a valid agentId`);\n }\n }\n return { type: 'ids', ids: agentIds };\n }\n if (options.criteria) {\n assertValidAgentCriteria(options.criteria);\n return { type: 'criteria', criteria: options.criteria };\n }\n\n throw new Error('Either an [agentId...] arg or a --criteria <criteria> flag is required');\n}\n\nfunction assertValidAgentCriteria(criteria: string): void {\n const invalidCriteriaMsg =\n \"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`\";\n if (typeof criteria !== 'string') {\n throw new Error(invalidCriteriaMsg);\n }\n const [resourceType, queryStr] = criteria.split('?');\n if (resourceType !== 'Agent' || !queryStr) {\n throw new Error(invalidCriteriaMsg);\n }\n try {\n // eslint-disable-next-line no-new\n new URLSearchParams(queryStr);\n } catch (err) {\n throw new Error(invalidCriteriaMsg, { cause: err });\n }\n if (!queryStr.includes('=')) {\n throw new Error(invalidCriteriaMsg, { cause: new Error('Query string lacks at least one `=`') });\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClientOptions } from '@medplum/core';\nimport { MedplumClient } from '@medplum/core';\nimport { FileSystemStorage } from '../storage';\nimport type { Profile } from '../utils';\n\nexport async function createMedplumClient(\n options: MedplumClientOptions & { profile?: string },\n setupCredentials = true\n): Promise<MedplumClient> {\n const profileName = options.profile ?? 'default';\n\n const storage = new FileSystemStorage(profileName);\n const profile = storage.getObject('options') as Profile;\n if (profileName !== 'default' && !profile) {\n throw new Error(`Profile \"${profileName}\" does not exist`);\n }\n\n const { baseUrl, fhirUrlPath, accessToken, tokenUrl, authorizeUrl, clientId, clientSecret } = getClientValues(\n options,\n storage\n );\n const fetchApi = options.fetch ?? fetch;\n\n // Validate base URL if non-default is specified\n if (options.baseUrl && options.baseUrl !== 'https://api.medplum.com/') {\n await validateBaseUrl(options.baseUrl, fetchApi);\n }\n\n const medplumClient = new MedplumClient({\n fetch: fetchApi,\n baseUrl,\n tokenUrl,\n fhirUrlPath,\n authorizeUrl,\n storage,\n onUnauthenticated,\n verbose: options.verbose,\n });\n\n // In most commands, we want to automatically set up credentials.\n // However, in some cases such as \"login\", we don't want to do that.\n // Setup credentials if the user does not explicitly disable it.\n if (setupCredentials) {\n if (accessToken) {\n // If the access token is provided, use it.\n medplumClient.setAccessToken(accessToken);\n } else if (clientId && clientSecret) {\n // If the client ID and secret are provided, use them.\n medplumClient.setBasicAuth(clientId, clientSecret);\n if (profile?.authType !== 'basic') {\n // Unless the user explicitly specified basic auth, start the client login.\n await medplumClient.startClientLogin(clientId, clientSecret);\n }\n }\n }\n\n return medplumClient;\n}\n\nfunction getClientValues(options: MedplumClientOptions, storage: FileSystemStorage): MedplumClientOptions {\n const storageOptions = storage.getObject('options') as MedplumClientOptions;\n const baseUrl =\n options.baseUrl ?? storageOptions?.baseUrl ?? process.env['MEDPLUM_BASE_URL'] ?? 'https://api.medplum.com/';\n const fhirUrlPath = options.fhirUrlPath ?? storageOptions?.fhirUrlPath ?? process.env['MEDPLUM_FHIR_URL_PATH'];\n const accessToken = options.accessToken ?? storageOptions?.accessToken ?? process.env['MEDPLUM_CLIENT_ACCESS_TOKEN'];\n const tokenUrl = options.tokenUrl ?? storageOptions?.tokenUrl ?? process.env['MEDPLUM_TOKEN_URL'];\n const authorizeUrl = options.authorizeUrl ?? storageOptions?.authorizeUrl ?? process.env['MEDPLUM_AUTHORIZE_URL'];\n\n const clientId = options.clientId ?? storageOptions?.clientId ?? process.env['MEDPLUM_CLIENT_ID'];\n const clientSecret = options.clientSecret ?? storageOptions?.clientSecret ?? process.env['MEDPLUM_CLIENT_SECRET'];\n\n return { baseUrl, fhirUrlPath, accessToken, tokenUrl, authorizeUrl, clientId, clientSecret };\n}\n\nasync function validateBaseUrl(\n baseUrl: string,\n fetchApi: (input: string, init?: RequestInit) => Promise<Response>\n): Promise<void> {\n try {\n const url = new URL('healthcheck', baseUrl).toString();\n const response = await fetchApi(url);\n if (!response.ok) {\n throw new Error(`Healthcheck returned status ${response.status}`);\n }\n const data = (await response.json()) as { ok?: unknown };\n if (data.ok === true) {\n return;\n }\n throw new Error('Healthcheck response does not have \"ok\": true');\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(`Failed to validate base URL \"${baseUrl}\": ${message}`);\n }\n}\n\nexport function onUnauthenticated(): void {\n console.log('Unauthenticated: run `npx medplum login` to sign in');\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ClientStorage } from '@medplum/core';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\n\nexport class FileSystemStorage extends ClientStorage {\n private readonly dirName: string;\n private readonly fileName: string;\n\n constructor(profile: string) {\n super();\n this.dirName = resolve(homedir(), '.medplum');\n this.fileName = resolve(this.dirName, profile + '.json');\n }\n\n clear(): void {\n this.writeFile({});\n }\n\n getString(key: string): string | undefined {\n return this.readFile()?.[key];\n }\n\n setString(key: string, value: string | undefined): void {\n const data = this.readFile() ?? {};\n if (value) {\n data[key] = value;\n } else {\n delete data[key];\n }\n this.writeFile(data);\n }\n\n getObject<T>(key: string): T | undefined {\n const str = this.getString(key);\n return str ? (JSON.parse(str) as T) : undefined;\n }\n\n setObject<T>(key: string, value: T): void {\n this.setString(key, value ? JSON.stringify(value) : undefined);\n }\n\n private readFile(): Record<string, string> | undefined {\n if (existsSync(this.fileName)) {\n return JSON.parse(readFileSync(this.fileName, 'utf8'));\n }\n return undefined;\n }\n\n private writeFile(data: Record<string, string>): void {\n if (!existsSync(this.dirName)) {\n mkdirSync(this.dirName);\n }\n writeFileSync(this.fileName, JSON.stringify(data, null, 2), 'utf8');\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, WithId } from '@medplum/core';\nimport { ContentType, encodeBase64, isOk, normalizeErrorString, OAuthSigningAlgorithm } from '@medplum/core';\nimport type { Bot, Extension, OperationOutcome } from '@medplum/fhirtypes';\nimport { Command } from 'commander';\nimport { SignJWT } from 'jose';\nimport { createHmac, createPrivateKey, randomBytes } from 'node:crypto';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, extname, resolve } from 'node:path';\nimport { isPromise } from 'node:util/types';\nimport { extract } from 'tar';\nimport { FileSystemStorage } from './storage';\n\nexport interface MedplumConfig {\n baseUrl?: string;\n clientId?: string;\n googleClientId?: string;\n recaptchaSiteKey?: string;\n registerEnabled?: boolean;\n bots?: MedplumBotConfig[];\n}\n\nexport interface MedplumBotConfig {\n readonly name: string;\n readonly id: string;\n readonly source: string;\n readonly dist?: string;\n}\n\nexport interface Profile {\n readonly name?: string;\n readonly authType?: string;\n readonly baseUrl?: string;\n readonly clientId?: string;\n readonly clientSecret?: string;\n readonly tokenUrl?: string;\n readonly authorizeUrl?: string;\n readonly fhirUrlPath?: string;\n readonly scope?: string;\n readonly accessToken?: string;\n readonly callbackUrl?: string;\n readonly subject?: string;\n readonly audience?: string;\n readonly issuer?: string;\n readonly privateKeyPath?: string;\n}\n\nexport function prettyPrint(input: unknown): void {\n console.log(JSON.stringify(input, null, 2));\n}\n\nexport async function saveBot(medplum: MedplumClient, botConfig: MedplumBotConfig, bot: Bot): Promise<void> {\n const codePath = botConfig.source;\n const code = readFileContents(codePath);\n if (!code) {\n return;\n }\n\n console.log('Saving source code...');\n const sourceCode = await medplum.createAttachment({\n data: code,\n filename: basename(codePath),\n contentType: getCodeContentType(codePath),\n });\n\n console.log('Updating bot...');\n const updateResult = await medplum.updateResource({\n ...bot,\n sourceCode,\n });\n console.log('Success! New bot version: ' + updateResult.meta?.versionId);\n}\n\nexport async function deployBot(medplum: MedplumClient, botConfig: MedplumBotConfig, bot: WithId<Bot>): Promise<void> {\n const codePath = botConfig.dist ?? botConfig.source;\n const code = readFileContents(codePath);\n if (!code) {\n return;\n }\n\n console.log('Deploying bot...');\n const deployResult = await medplum.post<OperationOutcome>(medplum.fhirUrl('Bot', bot.id, '$deploy'), {\n code,\n filename: basename(codePath),\n });\n console.log('Deploy result: ' + deployResult.issue?.[0]?.details?.text);\n if (!isOk(deployResult)) {\n throw new Error(`Bot deploy failed: ${normalizeErrorString(deployResult)}`);\n }\n}\n\nexport async function createBot(\n medplum: MedplumClient,\n botName: string,\n projectId: string,\n sourceFile: string,\n distFile: string,\n runtimeVersion?: string,\n writeConfig?: boolean\n): Promise<void> {\n const body = {\n name: botName,\n description: '',\n runtimeVersion,\n };\n const newBot = await medplum.post<WithId<Bot>>('admin/projects/' + projectId + '/bot', body);\n const bot = await medplum.readResource('Bot', newBot.id);\n\n const botConfig = {\n name: botName,\n id: newBot.id,\n source: sourceFile,\n dist: distFile,\n };\n\n await saveBot(medplum, botConfig, bot);\n await deployBot(medplum, botConfig, bot);\n console.log(`Success! Bot created: ${bot.id}`);\n\n if (writeConfig) {\n addBotToConfig(botConfig);\n }\n}\n\nexport function readBotConfigs(botName: string): MedplumBotConfig[] {\n const regExBotName = new RegExp('^' + escapeRegex(botName).replaceAll(String.raw`\\*`, '.*') + '$');\n const botConfigs = readConfig()?.bots?.filter((b) => regExBotName.test(b.name));\n if (!botConfigs) {\n return [];\n }\n return botConfigs;\n}\n\n/**\n * Returns the config file name.\n * @param tagName - Optional environment tag name.\n * @param options - Optional command line options.\n * @returns The config file name.\n */\nexport function getConfigFileName(tagName?: string, options?: Record<string, any>): string {\n if (options?.file) {\n return options.file;\n }\n const parts = ['medplum'];\n if (tagName) {\n parts.push(tagName);\n }\n parts.push('config');\n if (options?.server) {\n parts.push('server');\n }\n parts.push('json');\n return parts.join('.');\n}\n\n/**\n * Writes a config file to disk.\n * @param configFileName - The config file name.\n * @param config - The config file contents.\n */\nexport function writeConfig(configFileName: string, config: Record<string, any>): void {\n writeFileSync(resolve(configFileName), JSON.stringify(config, undefined, 2), 'utf-8');\n}\n\nexport function readConfig(tagName?: string, options?: { file?: string }): MedplumConfig | undefined {\n const fileName = getConfigFileName(tagName, options);\n const content = readFileContents(fileName);\n if (!content) {\n return undefined;\n }\n return JSON.parse(content);\n}\n\nexport function readServerConfig(tagName?: string): Record<string, string | number> | undefined {\n const content = readFileContents(getConfigFileName(tagName, { server: true }));\n if (!content) {\n return undefined;\n }\n return JSON.parse(content);\n}\n\nfunction readFileContents(fileName: string): string {\n const path = resolve(fileName);\n if (!existsSync(path)) {\n return '';\n }\n return readFileSync(path, 'utf8');\n}\n\nfunction addBotToConfig(botConfig: MedplumBotConfig): void {\n const config = readConfig() ?? {};\n if (!config.bots) {\n config.bots = [];\n }\n config.bots.push(botConfig);\n writeFileSync('medplum.config.json', JSON.stringify(config, null, 2), 'utf8');\n console.log(`Bot added to config: ${botConfig.id}`);\n}\n\nfunction escapeRegex(str: string): string {\n return str.replaceAll(/[/\\-\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n}\n\n/**\n * Creates a safe tar extractor that limits the number of files and total size.\n *\n * Expanding archive files without controlling resource consumption is security-sensitive\n *\n * See: https://sonarcloud.io/organizations/medplum/rules?open=typescript%3AS5042&rule_key=typescript%3AS5042\n * @param destinationDir - The destination directory where all files will be extracted.\n * @returns A tar file extractor.\n */\nexport function safeTarExtractor(destinationDir: string): NodeJS.WritableStream {\n const MAX_FILES = 100;\n const MAX_SIZE = 10 * 1024 * 1024; // 10 MB\n\n let fileCount = 0;\n let totalSize = 0;\n\n return extract({\n cwd: destinationDir,\n filter: (_path, entry) => {\n fileCount++;\n if (fileCount > MAX_FILES) {\n throw new Error('Tar extractor reached max number of files');\n }\n\n totalSize += entry.size;\n if (totalSize > MAX_SIZE) {\n throw new Error('Tar extractor reached max size');\n }\n\n return true;\n },\n });\n}\n\nexport function getUnsupportedExtension(): Extension {\n return {\n url: 'http://hl7.org/fhir/StructureDefinition/data-absent-reason',\n valueCode: 'unsupported',\n };\n}\n\nexport function getCodeContentType(filename: string): string {\n const ext = extname(filename).toLowerCase();\n if (['.cjs', '.mjs', '.js'].includes(ext)) {\n return ContentType.JAVASCRIPT;\n }\n if (['.cts', '.mts', '.ts'].includes(ext)) {\n return ContentType.TYPESCRIPT;\n }\n return ContentType.TEXT;\n}\n\nexport function saveProfile(profileName: string, options: Profile): Profile {\n const storage = new FileSystemStorage(profileName);\n const optionsObject = { name: profileName, ...options };\n storage.setObject('options', optionsObject);\n return optionsObject;\n}\n\nexport function loadProfile(profileName: string): Profile {\n const storage = new FileSystemStorage(profileName);\n return storage.getObject('options') as Profile;\n}\n\nexport function profileExists(storage: FileSystemStorage, profile: string): boolean {\n if (profile === 'default') {\n return true;\n }\n const optionsObject = storage.getObject('options');\n if (!optionsObject) {\n return false;\n }\n return true;\n}\n\nexport async function jwtBearerLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n const header = {\n typ: 'JWT',\n alg: OAuthSigningAlgorithm.HS256,\n };\n\n const currentTimestamp = Math.floor(Date.now() / 1000);\n const data = {\n aud: `${profile.baseUrl}${profile.audience}`,\n iss: profile.issuer,\n sub: profile.subject,\n nbf: currentTimestamp,\n iat: currentTimestamp,\n exp: currentTimestamp + 604800, // expiry time is 7 days from time of creation\n };\n const encodedHeader = encodeBase64(JSON.stringify(header));\n const encodedData = encodeBase64(JSON.stringify(data));\n const token = `${encodedHeader}.${encodedData}`;\n const signature = createHmac('sha256', profile.clientSecret as string)\n .update(token)\n .digest('base64url');\n const signedToken = `${token}.${signature}`;\n await medplum.startJwtBearerLogin(profile.clientId as string, signedToken, profile.scope ?? '');\n}\n\nexport async function jwtAssertionLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n const privateKey = createPrivateKey(readFileSync(resolve(profile.privateKeyPath as string)));\n const jwt = await new SignJWT({})\n .setProtectedHeader({ typ: 'JWT', alg: OAuthSigningAlgorithm.RS384 })\n .setIssuer(profile.clientId as string)\n .setSubject(profile.clientId as string)\n .setAudience(`${profile.baseUrl}${profile.audience}`)\n .setJti(randomBytes(16).toString('hex'))\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(privateKey);\n await medplum.startJwtAssertionLogin(jwt);\n}\n\n/**\n * Attaches the provided subcommand to the provided parent command.\n *\n * We use this rather than directly calling the `addCommand` method on the parent command because we need\n * to modify some additional settings on each command before adding them to the parent.\n *\n * @param command - The parent command.\n * @param subcommand - The command to attach to the provided parent command.\n */\nexport function addSubcommand(command: Command, subcommand: Command): void {\n subcommand.configureHelp({ showGlobalOptions: true });\n command.addCommand(subcommand);\n}\n\nexport class MedplumCommand extends Command {\n action(fn: (...args: any[]) => void | Promise<void>): this {\n // This is the only way to get both global and local options propagated to all subcommands automatically\n // Otherwise you have to call `command.optsWithGlobals()` within every function to get merged global and local options\n const wrappedFn = withMergedOptions(this, fn);\n // @ts-expect-error Access to hidden member\n // This is the function that gets called when a command is executed\n // We overwrite it with the wrapped version\n super._actionHandler = wrappedFn;\n return this;\n }\n\n /**\n * We use this method to reset the option state\n * Which is not cleared between executions of the main function during tests\n *\n * This is because all of our subcommands are declared in the global scope\n *\n * Rather than re-architect the entire CLI package, I added this to make sure all options are reset between executions of main\n */\n resetOptionDefaults(): void {\n // @ts-expect-error Overriding private field\n this._optionValues = {};\n for (const option of this.options) {\n // So we also set options that default to false\n // We explicitly check strict equality to undefined\n if (option.defaultValue !== undefined) {\n // We use the attributeName since that's the camelCase'd name that is used to access options\n // @ts-expect-error Overriding private field\n this._optionValues[option.attributeName()] = option.defaultValue;\n }\n }\n }\n}\n\nexport function withMergedOptions(\n command: MedplumCommand,\n fn: ((...args: any[]) => Promise<void>) | ((...args: any[]) => void)\n): (args: any[]) => Promise<void> {\n // The .action callback takes an extra parameter which is the command or options.\n return async (args: any[]): Promise<void> => {\n const expectedArgsCount = command.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n actionArgs[expectedArgsCount] = command.optsWithGlobals();\n try {\n const result: Promise<void> | void = fn(...actionArgs);\n if (isPromise(result)) {\n await result;\n }\n } finally {\n // We want to always make sure to reset the options to default at the end of each execution,\n // We do it in a finally block in case the command errors\n command.resetOptionDefaults();\n }\n };\n}\n", "const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder(\"utf-8\", { fatal: !0 }), MAX_INT32 = 2 ** 32;\nfunction concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers)\n buf.set(buffer, i), i += buffer.length;\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32)\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);\n}\nfunction uint64be(value) {\n const high = Math.floor(value / MAX_INT32), low = value % MAX_INT32, buf = new Uint8Array(8);\n return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf;\n}\nfunction uint32be(value) {\n const buf = new Uint8Array(4);\n return writeUInt32BE(buf, value), buf;\n}\nconst NON_ASCII = /[^\\x00-\\x7f]/;\nfunction encode(string) {\n if (typeof string == \"string\" && string.length >= 128) {\n if (NON_ASCII.test(string))\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n return encoder.encode(string);\n }\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127)\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n bytes[i] = code;\n }\n return bytes;\n}\nfunction encodeBase64(input, url = !1) {\n if (Uint8Array.prototype.toBase64)\n return input.toBase64({ alphabet: url ? \"base64url\" : \"base64\", omitPadding: url });\n const CHUNK_SIZE = 32768, arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE)\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n const encoded = btoa(arr.join(\"\"));\n return url ? encoded.replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\") : encoded;\n}\nfunction decodeBase64(encoded, url = !1) {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(encoded, { alphabet: url ? \"base64url\" : \"base64\" });\n if (url) {\n if (encoded.includes(\"+\") || encoded.includes(\"/\"))\n throw new TypeError(\"Invalid base64url\");\n encoded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n }\n const binary = atob(encoded), bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\nasync function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\nexport {\n concat,\n decodeBase64,\n decoder,\n digest,\n encode,\n encodeBase64,\n encoder,\n strictDecoder,\n uint32be,\n uint64be\n};\n", "class JOSEError extends Error {\n static code = \"ERR_JOSE_GENERIC\";\n code = \"ERR_JOSE_GENERIC\";\n constructor(message, options) {\n super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);\n }\n}\nclass JWTClaimValidationFailed extends JOSEError {\n static code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JWTExpired extends JOSEError {\n static code = \"ERR_JWT_EXPIRED\";\n code = \"ERR_JWT_EXPIRED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JOSEAlgNotAllowed extends JOSEError {\n static code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n}\nclass JOSENotSupported extends JOSEError {\n static code = \"ERR_JOSE_NOT_SUPPORTED\";\n code = \"ERR_JOSE_NOT_SUPPORTED\";\n}\nclass JWEDecryptionFailed extends JOSEError {\n static code = \"ERR_JWE_DECRYPTION_FAILED\";\n code = \"ERR_JWE_DECRYPTION_FAILED\";\n constructor(message = \"decryption operation failed\", options) {\n super(message, options);\n }\n}\nclass JWEInvalid extends JOSEError {\n static code = \"ERR_JWE_INVALID\";\n code = \"ERR_JWE_INVALID\";\n}\nclass JWSInvalid extends JOSEError {\n static code = \"ERR_JWS_INVALID\";\n code = \"ERR_JWS_INVALID\";\n}\nclass JWTInvalid extends JOSEError {\n static code = \"ERR_JWT_INVALID\";\n code = \"ERR_JWT_INVALID\";\n}\nclass JWKInvalid extends JOSEError {\n static code = \"ERR_JWK_INVALID\";\n code = \"ERR_JWK_INVALID\";\n}\nclass JWKSInvalid extends JOSEError {\n static code = \"ERR_JWKS_INVALID\";\n code = \"ERR_JWKS_INVALID\";\n}\nclass JWKSNoMatchingKey extends JOSEError {\n static code = \"ERR_JWKS_NO_MATCHING_KEY\";\n code = \"ERR_JWKS_NO_MATCHING_KEY\";\n constructor(message = \"no applicable key found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator] = async function* () {\n };\n static code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n constructor(message = \"multiple matching keys found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSTimeout extends JOSEError {\n static code = \"ERR_JWKS_TIMEOUT\";\n code = \"ERR_JWKS_TIMEOUT\";\n constructor(message = \"request timed out\", options) {\n super(message, options);\n }\n}\nclass JWSSignatureVerificationFailed extends JOSEError {\n static code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n constructor(message = \"signature verification failed\", options) {\n super(message, options);\n }\n}\nexport {\n JOSEAlgNotAllowed,\n JOSEError,\n JOSENotSupported,\n JWEDecryptionFailed,\n JWEInvalid,\n JWKInvalid,\n JWKSInvalid,\n JWKSMultipleMatchingKeys,\n JWKSNoMatchingKey,\n JWKSTimeout,\n JWSInvalid,\n JWSSignatureVerificationFailed,\n JWTClaimValidationFailed,\n JWTExpired,\n JWTInvalid\n};\n", "import { encoder, decoder, encodeBase64, decodeBase64 } from \"../lib/buffer_utils.js\";\nconst invalid = \"The input to be decoded is not correctly encoded.\";\nfunction decode(input) {\n try {\n return decodeBase64(typeof input == \"string\" ? input : decoder.decode(input), !0);\n } catch (cause) {\n throw new TypeError(invalid, { cause });\n }\n}\nfunction encode(input) {\n return encodeBase64(typeof input == \"string\" ? encoder.encode(input) : input, !0);\n}\nexport {\n decode,\n encode\n};\n", "import { JOSENotSupported, JWSInvalid } from \"../util/errors.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { encode, strictDecoder } from \"./buffer_utils.js\";\nfunction assertUint8Array(input, label) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`${label} must be an instance of Uint8Array`);\n}\nfunction isObject(input) {\n if (typeof input != \"object\" || input === null || Object.prototype.toString.call(input) !== \"[object Object]\")\n return !1;\n const prototype = Object.getPrototypeOf(input);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\nfunction isJwkSet(input) {\n return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);\n}\nfunction isDisjoint(...headers) {\n const parameters = /* @__PURE__ */ new Set();\n for (const header of headers)\n if (header)\n for (const parameter of Object.keys(header)) {\n if (parameters.has(parameter))\n return !1;\n parameters.add(parameter);\n }\n return !0;\n}\nfunction assertNotSet(value, name) {\n if (value !== void 0)\n throw new TypeError(`${name} can only be called once`);\n}\nfunction decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n } catch {\n throw new ErrorClass(`Failed to base64url decode the ${label}`);\n }\n}\nfunction encodeBase64url(value, label, ErrorClass) {\n try {\n return encode(value);\n } catch {\n throw new ErrorClass(`The ${label} is not a valid base64url string`);\n }\n}\nfunction parseJoseHeader(b64, ErrorClass, message) {\n let parsed;\n try {\n parsed = JSON.parse(strictDecoder.decode(decode(b64)));\n } catch {\n throw new ErrorClass(message);\n }\n if (!isObject(parsed))\n throw new ErrorClass(message);\n return parsed;\n}\nconst JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null };\nfunction validateAlgorithms(option, algorithms) {\n if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != \"string\")))\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n return algorithms === void 0 ? void 0 : new Set(algorithms);\n}\nfunction validateCritDuplicates(Err, protectedHeader) {\n const { crit } = protectedHeader ?? {};\n if (Array.isArray(crit) && new Set(crit).size !== crit.length)\n throw new Err('\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values');\n}\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n if (!protectedHeader || protectedHeader.crit === void 0)\n return [];\n if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != \"string\" || input.length === 0))\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };\n for (const parameter of protectedHeader.crit) {\n if (!(parameter in recognized))\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n return protectedHeader.crit;\n}\nfunction validateB64(protectedHeader, extensions) {\n if (extensions.includes(\"b64\")) {\n const b64 = protectedHeader.b64;\n if (typeof b64 != \"boolean\")\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n return b64;\n }\n return !0;\n}\nfunction serializeJoseHeader(Err, header) {\n let serialized, parsed;\n try {\n serialized = JSON.stringify(header), parsed = JSON.parse(serialized);\n } catch (cause) {\n throw new Err(\"JOSE Header is not valid JSON\", { cause });\n }\n if (!isObject(parsed))\n throw new Err(\"JOSE Header is not a JSON object\");\n return [parsed, serialized];\n}\nexport {\n JWE_RECOGNIZED,\n JWS_RECOGNIZED,\n assertNotSet,\n assertUint8Array,\n decodeBase64url,\n encodeBase64url,\n isDisjoint,\n isJwkSet,\n isObject,\n parseJoseHeader,\n serializeJoseHeader,\n validateAlgorithms,\n validateB64,\n validateCrit,\n validateCritDuplicates\n};\n", "import { isObject } from \"./validate.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nconst tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {\n const { alg } = entry;\n if (key.use !== void 0) {\n const expected = usage === \"sign\" || usage === \"verify\" ? \"sig\" : \"enc\";\n if (key.use !== expected)\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n if (key.alg !== void 0 && key.alg !== alg)\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n if (Array.isArray(key.key_ops)) {\n const expectedKeyOp = usage === \"encrypt\" || usage === \"decrypt\" ? entry.ops?.[usage === \"encrypt\" ? 0 : 1] : usage;\n if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n};\nasync function prepareKey(entry, key, usage) {\n const { alg, secret } = entry, privateKey = usage === \"decrypt\" || usage === \"sign\";\n if (secret && key instanceof Uint8Array)\n return key;\n let normalized, keyObject;\n if (isObject(key)) {\n if (normalized = normalizeJwk(key), typeof normalized.kty != \"string\")\n throw invalidKeyType(alg, key, secret);\n if (!(secret ? normalized.kty === \"oct\" && typeof normalized.k == \"string\" : normalized.kty !== \"oct\" && (privateKey ? normalized.kty === \"AKP\" && typeof normalized.priv == \"string\" || typeof normalized.d == \"string\" : normalized.d === void 0 && normalized.priv === void 0)))\n throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present' : `JSON Web Key for this operation must be a ${privateKey ? \"private\" : \"public\"} JWK`);\n if (jwkMatchesOp(entry, normalized, usage), normalized.kty === \"oct\")\n return decode(normalized.k);\n if (!Object.isFrozen(key)) {\n const { key_ops } = key;\n Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);\n }\n } else {\n if (!isKeyLike(key))\n throw invalidKeyType(alg, key, secret);\n const expectedType = secret ? \"secret\" : privateKey ? \"private\" : \"public\";\n if (key.type !== expectedType && (secret || [\"secret\", \"public\", \"private\"].includes(key.type)))\n throw new TypeError(`${tag(key)} instances must be of type \"${expectedType}\" for the ${alg} algorithm`);\n if (isCryptoKey(key))\n return key;\n if (keyObject = key, keyObject.type === \"secret\")\n return keyObject.export();\n }\n cache ||= /* @__PURE__ */ new WeakMap();\n const cacheKey = key;\n let cached = cache.get(cacheKey);\n if (cached?.[alg])\n return cached[alg];\n if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == \"function\") {\n const isPublic = keyObject.type === \"public\", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;\n return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);\n }\n return normalized ??= keyObject.export({ format: \"jwk\" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);\n}\nlet cache;\nconst nist = {\n __proto__: null,\n prime256v1: \"P-256\",\n secp384r1: \"P-384\",\n secp521r1: \"P-521\"\n};\nfunction assertCryptoKey(key) {\n if (!isCryptoKey(key))\n throw new Error(\"CryptoKey instance expected\");\n}\nconst isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === \"CryptoKey\")\n return !0;\n try {\n return key instanceof CryptoKey;\n } catch {\n return !1;\n }\n}, isKeyObject = (key) => key?.[Symbol.toStringTag] === \"KeyObject\", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\nfunction message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}.`;\n } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;\n return actual == null ? msg += ` Received ${actual}` : typeof actual == \"function\" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == \"object\" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;\n}\nconst invalidKeyInput = (actual, ...types) => message(\"Key must be \", actual, ...types);\nfunction invalidKeyType(alg, actual, secret) {\n const types = [\"CryptoKey\", \"KeyObject\", \"JSON Web Key\"];\n return secret && types.push(\"Uint8Array\"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));\n}\nconst unusable = (name, prop = \"algorithm.name\") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage))\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n}\nfunction checkModulusLength(alg, key) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength != \"number\" || modulusLength < 2048)\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n}\nfunction checkCryptoKey(key, expected, usage) {\n const algorithm = key.algorithm;\n if (algorithm.name !== expected.name)\n throw unusable(expected.name);\n if (expected.hash && algorithm.hash?.name !== expected.hash)\n throw unusable(expected.hash, \"algorithm.hash\");\n if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)\n throw unusable(expected.namedCurve, \"algorithm.namedCurve\");\n if (expected.length !== void 0 && algorithm.length !== expected.length)\n throw unusable(expected.length, \"algorithm.length\");\n checkUsage(key, usage);\n}\nfunction snapshotJwk(jwk) {\n return { __proto__: null, ...jwk };\n}\nfunction normalizeJwk(jwk) {\n const normalized = snapshotJwk(jwk);\n if (normalized.ext !== void 0 && typeof normalized.ext != \"boolean\")\n throw new TypeError('\"ext\" (Extractable) Parameter must be a boolean');\n if (normalized.key_ops !== void 0) {\n const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;\n if (!keyOps || keyOps.some((operation) => typeof operation != \"string\") || new Set(keyOps).size !== keyOps.length)\n throw new TypeError('\"key_ops\" (Key Operations) Parameter must be an array of unique strings');\n normalized.key_ops = keyOps;\n }\n return normalized;\n}\nfunction validateExtractableOption(extractable) {\n if (extractable !== void 0 && typeof extractable != \"boolean\")\n throw new TypeError('\"extractable\" option must be a boolean');\n return extractable;\n}\nasync function jwkToKey(entry, jwk, extractable) {\n if (!entry.kty.includes(jwk.kty))\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };\n return keyData.kty !== \"AKP\" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey(\"jwk\", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);\n}\nasync function rawKey(key, expected, usage, extractable = !1) {\n return key instanceof Uint8Array && (key = await crypto.subtle.importKey(\"raw\", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;\n}\nexport {\n assertCryptoKey,\n checkCryptoKey,\n checkModulusLength,\n checkUsage,\n invalidKeyInput,\n isCryptoKey,\n isKeyLike,\n isKeyObject,\n jwkToKey,\n normalizeJwk,\n prepareKey,\n rawKey,\n snapshotJwk,\n validateExtractableOption\n};\n", "function table(entries) {\n const out = { __proto__: null };\n for (const alg in entries)\n out[alg] = { ...entries[alg], alg };\n return out;\n}\nexport {\n table\n};\n", "import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst sig = [[\"verify\"], [\"sign\"]];\nfunction hmac(bits) {\n const subtle = { name: \"HMAC\", hash: `SHA-${bits}` };\n return { kty: [\"oct\"], secret: !0, subtle, signing: subtle, usages: sig };\n}\nfunction rsa(bits, saltLength) {\n const subtle = { name: saltLength ? \"RSA-PSS\" : \"RSASSA-PKCS1-v1_5\", hash: `SHA-${bits}` };\n return {\n kty: [\"RSA\"],\n subtle,\n signing: saltLength ? { ...subtle, saltLength } : subtle,\n usages: sig,\n minRsaBits: 2048\n };\n}\nfunction ecdsa(crv, bits) {\n return {\n kty: [\"EC\"],\n crv,\n subtle: { name: \"ECDSA\", namedCurve: crv },\n signing: { name: \"ECDSA\", hash: `SHA-${bits}` },\n usages: sig\n };\n}\nfunction eddsa() {\n const subtle = { name: \"Ed25519\" };\n return {\n kty: [\"OKP\"],\n crv: \"Ed25519\",\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nfunction mldsa(bits) {\n const subtle = { name: `ML-DSA-${bits}` };\n return {\n kty: [\"AKP\"],\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nconst JWS = table({\n HS256: hmac(256),\n HS384: hmac(384),\n HS512: hmac(512),\n RS256: rsa(256),\n RS384: rsa(384),\n RS512: rsa(512),\n PS256: rsa(256, 32),\n PS384: rsa(384, 48),\n PS512: rsa(512, 64),\n ES256: ecdsa(\"P-256\", 256),\n ES384: ecdsa(\"P-384\", 384),\n ES512: ecdsa(\"P-521\", 512),\n EdDSA: eddsa(),\n Ed25519: eddsa(),\n \"ML-DSA-44\": mldsa(44),\n \"ML-DSA-65\": mldsa(65),\n \"ML-DSA-87\": mldsa(87)\n});\nfunction jwsAlgorithm(alg) {\n const entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry)\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n return entry;\n}\nexport {\n JWS,\n jwsAlgorithm\n};\n", "import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from \"../util/errors.js\";\nimport { encoder, strictDecoder } from \"./buffer_utils.js\";\nimport { isObject } from \"./validate.js\";\nconst epoch = (date) => Math.floor(date.getTime() / 1e3), multipliers = {\n s: 1,\n m: 60,\n h: 3600,\n d: 86400,\n w: 604800,\n y: 31557600\n}, REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, checkFailed = \"check_failed\";\nfunction invalidDuration() {\n throw new TypeError(\"Invalid time period format\");\n}\nfunction secs(str) {\n typeof str != \"string\" && invalidDuration();\n const matched = REGEX.exec(str);\n (!matched || matched[4] && matched[1]) && invalidDuration();\n const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);\n return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === \"-\" || matched[4] === \"ago\" ? -numericDate2 : numericDate2;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input))\n throw new TypeError(`Invalid ${label} input`);\n return input;\n}\nfunction validateStringClaim(claim, value) {\n if (typeof value != \"string\")\n throw new TypeError(`\"${claim}\" claim must be a string`);\n}\nfunction validateAudienceClaim(value) {\n if (typeof value != \"string\" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != \"string\")))\n throw new TypeError('\"aud\" claim must be a string or an array of strings');\n}\nfunction numericDate(value, label) {\n return typeof value == \"number\" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);\n}\nconst normalizeTyp = (value) => {\n const normalized = value.toLowerCase();\n return value.includes(\"/\") ? normalized : `application/${normalized}`;\n}, checkAudiencePresence = (audPayload, audOption) => typeof audPayload == \"string\" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;\nfunction validateNumericDate(payload, claim, required = !1) {\n const value = payload[claim];\n if (!(value === void 0 && !required)) {\n if (typeof value != \"number\")\n throw new JWTClaimValidationFailed(`\"${claim}\" claim must be a number`, payload, claim, \"invalid\");\n return value;\n }\n}\nfunction unexpectedClaim(payload, claim) {\n throw new JWTClaimValidationFailed(`unexpected \"${claim}\" claim value`, payload, claim, checkFailed);\n}\nfunction validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(strictDecoder.decode(encodedPayload));\n } catch {\n }\n if (!isObject(payload))\n throw new JWTInvalid(\"JWT Claims Set must be a top-level JSON object\");\n const { typ } = options;\n if (typ !== void 0 && (typeof protectedHeader.typ != \"string\" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, \"typ\", checkFailed);\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];\n maxTokenAge !== void 0 && presenceCheck.push(\"iat\"), audience !== void 0 && presenceCheck.push(\"aud\"), subject !== void 0 && presenceCheck.push(\"sub\"), issuer !== void 0 && presenceCheck.push(\"iss\");\n for (const claim of new Set(presenceCheck.reverse()))\n if (!Object.hasOwn(payload, claim))\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, \"missing\");\n issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, \"iss\"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, \"sub\"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == \"string\" ? [audience] : audience) && unexpectedClaim(payload, \"aud\");\n const { clockTolerance } = options;\n let tolerance = 0;\n if (typeof clockTolerance == \"string\")\n tolerance = secs(clockTolerance);\n else if (clockTolerance !== void 0) {\n if (typeof clockTolerance != \"number\")\n throw new TypeError(\"Invalid clockTolerance option type\");\n tolerance = clockTolerance;\n }\n validateInput(\"clockTolerance option\", tolerance);\n const { currentDate } = options, now = validateInput(\"currentDate option\", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, \"iat\", maxTokenAge !== void 0), nbf = validateNumericDate(payload, \"nbf\");\n if (nbf !== void 0 && nbf > now + tolerance)\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, \"nbf\", checkFailed);\n const exp = validateNumericDate(payload, \"exp\");\n if (exp !== void 0 && exp <= now - tolerance)\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, \"exp\", checkFailed);\n if (maxTokenAge !== void 0) {\n const age = now - iat, max = validateInput(\"maxTokenAge option\", typeof maxTokenAge == \"number\" ? maxTokenAge : secs(maxTokenAge));\n if (age - tolerance > max)\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, \"iat\", checkFailed);\n if (age < -tolerance)\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, \"iat\", checkFailed);\n }\n return payload;\n}\nlet producerPayloads;\nfunction producerPayload(producer) {\n return producerPayloads.get(producer);\n}\nfunction jwtData(producer) {\n const payload = producerPayload(producer);\n for (const claim of [\"iat\", \"nbf\", \"exp\"]) {\n const value = payload[claim];\n if (typeof value == \"number\" && !Number.isFinite(value))\n throw new TypeError(`\"${claim}\" claim must be a finite number`);\n }\n return encoder.encode(JSON.stringify(payload));\n}\nfunction jwtClaim(producer, claim) {\n return producerPayload(producer)[claim];\n}\nclass JWTClaimsBuilder {\n constructor(payload = {}) {\n if (!isObject(payload))\n throw new TypeError(\"JWT Claims Set MUST be an object\");\n (producerPayloads ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(payload));\n }\n setIssuer(value) {\n return validateStringClaim(\"iss\", value), producerPayload(this).iss = value, this;\n }\n setSubject(value) {\n return validateStringClaim(\"sub\", value), producerPayload(this).sub = value, this;\n }\n setAudience(value) {\n return validateAudienceClaim(value), producerPayload(this).aud = value, this;\n }\n setJti(value) {\n return validateStringClaim(\"jti\", value), producerPayload(this).jti = value, this;\n }\n setNotBefore(value) {\n return producerPayload(this).nbf = numericDate(value, \"setNotBefore\"), this;\n }\n setExpirationTime(value) {\n return producerPayload(this).exp = numericDate(value, \"setExpirationTime\"), this;\n }\n setIssuedAt(value) {\n const payload = producerPayload(this);\n return value === void 0 ? payload.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == \"string\" ? payload.iat = validateInput(\"setIssuedAt\", epoch(/* @__PURE__ */ new Date()) + secs(value)) : payload.iat = numericDate(value, \"setIssuedAt\"), this;\n }\n}\nexport {\n JWTClaimsBuilder,\n jwtClaim,\n jwtData,\n secs,\n validateClaimsSet\n};\n", "import { encode as b64u } from \"../util/base64url.js\";\nimport { jwsAlgorithm } from \"./jws_algorithms.js\";\nimport { isDisjoint, serializeJoseHeader, validateB64, validateCrit, validateCritDuplicates, JWS_RECOGNIZED } from \"./validate.js\";\nimport { JWSInvalid } from \"../util/errors.js\";\nimport { concat, encode, encoder } from \"./buffer_utils.js\";\nimport { prepareKey, rawKey, checkModulusLength } from \"./key.js\";\nasync function createSignature(input, key, rejectUnencoded) {\n let [payload, protectedHeader, unprotectedHeader, crit] = input, protectedHeaderString = \"\";\n if (protectedHeader !== void 0) {\n const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);\n protectedHeader = normalized[0], protectedHeaderString = b64u(normalized[1]);\n }\n if (unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWSInvalid, unprotectedHeader)[0]), !protectedHeader && !unprotectedHeader)\n throw new JWSInvalid(\"either setProtectedHeader or setUnprotectedHeader must be called before #sign()\");\n if (!isDisjoint(protectedHeader, unprotectedHeader))\n throw new JWSInvalid(\"JWS Protected and JWS Unprotected Header Parameter names must be disjoint\");\n const joseHeader = { ...protectedHeader, ...unprotectedHeader };\n validateCritDuplicates(JWSInvalid, protectedHeader);\n const b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));\n b64 || rejectUnencoded?.();\n const { alg } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n const entry = jwsAlgorithm(alg);\n let payloadS = \"\", payloadB = payload, data;\n if (b64) {\n const encoded = input[4];\n encoded ? (payloadS = encoded[0] ??= b64u(payload), payloadB = encoded[1] ??= encode(payloadS)) : (payloadS = b64u(payload), data = encoder.encode(`${protectedHeaderString}.${payloadS}`));\n }\n data ??= concat(encode(protectedHeaderString), encode(\".\"), payloadB);\n const k = await rawKey(await prepareKey(entry, key, \"sign\"), entry.subtle, \"sign\");\n entry.minRsaBits && checkModulusLength(entry.alg, k);\n const jws = {\n signature: b64u(new Uint8Array(await crypto.subtle.sign(entry.signing, k, data))),\n payload: payloadS\n };\n return protectedHeader && (jws.protected = protectedHeaderString), unprotectedHeader && (jws.header = unprotectedHeader), [jws, b64];\n}\nasync function createCompactSignature(payload, protectedHeader, crit, key, rejectUnencoded) {\n const [jws] = await createSignature([payload, protectedHeader, void 0, crit], key, rejectUnencoded);\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n}\nexport {\n createCompactSignature,\n createSignature\n};\n", "import { createCompactSignature } from \"../lib/jws_sign.js\";\nimport { JWTInvalid } from \"../util/errors.js\";\nimport { JWTClaimsBuilder, jwtData } from \"../lib/jwt_claims_set.js\";\nimport { assertNotSet } from \"../lib/validate.js\";\nconst SignJWT_base = JWTClaimsBuilder;\nclass SignJWT extends SignJWT_base {\n #protectedHeader;\n setProtectedHeader(protectedHeader) {\n return assertNotSet(this.#protectedHeader, \"setProtectedHeader\"), this.#protectedHeader = protectedHeader, this;\n }\n async sign(key, options) {\n return createCompactSignature(jwtData(this), this.#protectedHeader, options?.crit, key, () => {\n throw new JWTInvalid(\"JWTs MUST NOT use unencoded payload\");\n });\n }\n}\nexport {\n SignJWT\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { ContentType, getDisplayString, MEDPLUM_CLI_CLIENT_ID, normalizeErrorString } from '@medplum/core';\nimport { exec } from 'node:child_process';\nimport { createServer } from 'node:http';\nimport { platform } from 'node:os';\nimport { promisify } from 'node:util';\nimport { createMedplumClient } from './util/client';\nimport type { Profile } from './utils';\nimport { jwtAssertionLogin, jwtBearerLogin, MedplumCommand, saveProfile } from './utils';\n\nconst execAsync = promisify(exec);\n\nconst clientId = MEDPLUM_CLI_CLIENT_ID;\nconst redirectUri = 'http://localhost:9615';\n\nexport const login = new MedplumCommand('login');\nexport const whoami = new MedplumCommand('whoami');\nexport const token = new MedplumCommand('token');\n\nlogin.action(async (options) => {\n const profileName = options.profile ?? 'default';\n\n // Always save the profile to update settings\n const profile = saveProfile(profileName, options);\n\n const medplum = await createMedplumClient(options, false);\n await startLogin(medplum, profile);\n});\n\nwhoami.action(async (options) => {\n const medplum = await createMedplumClient(options);\n printMe(medplum);\n});\n\ntoken.action(async (options) => {\n const medplum = await createMedplumClient(options);\n await medplum.getProfileAsync();\n const token = medplum.getAccessToken();\n if (!token) {\n throw new Error('Not logged in');\n }\n console.log(token);\n});\n\nasync function startLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n const authType = profile?.authType ?? 'authorization-code';\n switch (authType) {\n case 'authorization-code':\n await medplumAuthorizationCodeLogin(medplum, profile);\n break;\n case 'basic':\n medplum.setBasicAuth(profile.clientId as string, profile.clientSecret as string);\n break;\n case 'client-credentials':\n medplum.setBasicAuth(profile.clientId as string, profile.clientSecret as string);\n await medplum.startClientLogin(profile.clientId as string, profile.clientSecret as string);\n break;\n case 'jwt-bearer':\n await jwtBearerLogin(medplum, profile);\n break;\n case 'jwt-assertion':\n await jwtAssertionLogin(medplum, profile);\n break;\n }\n}\n\nasync function startWebServer(medplum: MedplumClient): Promise<void> {\n const server = createServer(async (req, res) => {\n const url = new URL(req.url as string, 'http://localhost:9615');\n const code = url.searchParams.get('code');\n if (req.method === 'OPTIONS') {\n res.writeHead(200, {\n Allow: 'GET, POST',\n 'Content-Type': ContentType.TEXT,\n });\n res.end('OK');\n return;\n }\n if (url.pathname === '/' && code) {\n try {\n const profile = await medplum.processCode(code, { clientId, redirectUri });\n res.writeHead(200, { 'Content-Type': ContentType.TEXT });\n res.end(`Signed in as ${getDisplayString(profile)}. You may close this window.`);\n } catch (err) {\n res.writeHead(400, { 'Content-Type': ContentType.TEXT });\n res.end(`Error: ${normalizeErrorString(err)}`);\n } finally {\n server.close();\n process.exit(0);\n }\n } else {\n res.writeHead(404, { 'Content-Type': ContentType.TEXT });\n res.end('Not found');\n }\n }).listen(9615);\n}\n\n/**\n * Opens a web browser to the specified URL.\n * See: https://hasinthaindrajee.medium.com/browser-sso-for-cli-applications-b0be743fa656\n * @param url - The URL to open.\n */\nasync function openBrowser(url: string): Promise<void> {\n const os = platform();\n let cmd = undefined;\n switch (os) {\n case 'openbsd':\n case 'linux':\n cmd = `xdg-open '${url}'`;\n break;\n case 'darwin':\n cmd = `open '${url}'`;\n break;\n case 'win32':\n cmd = `cmd /c start \"\" \"${url}\"`;\n break;\n default:\n throw new Error('Unsupported platform: ' + os);\n }\n await execAsync(cmd);\n}\n\n/**\n * Prints the current user and project.\n * @param medplum - The Medplum client.\n */\nfunction printMe(medplum: MedplumClient): void {\n const loginState = medplum.getActiveLogin();\n if (loginState) {\n console.log(`Server: ${medplum.getBaseUrl()}`);\n console.log(`Profile: ${loginState.profile.display} (${loginState.profile.reference})`);\n console.log(`Project: ${loginState.project.display} (${loginState.project.reference})`);\n } else {\n console.log('Not logged in');\n }\n}\n\nasync function medplumAuthorizationCodeLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n await startWebServer(medplum);\n const loginUrl = new URL(medplum.getAuthorizeUrl());\n loginUrl.searchParams.set('client_id', clientId);\n loginUrl.searchParams.set('redirect_uri', redirectUri);\n loginUrl.searchParams.set('scope', profile.scope ?? 'openid offline_access');\n loginUrl.searchParams.set('response_type', 'code');\n loginUrl.searchParams.set('prompt', 'login');\n await openBrowser(loginUrl.toString());\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n// CLI color highlighting\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst RED = '\\x1b[31m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst BLUE = '\\x1b[34m';\n\nexport const color = {\n red: (text: string) => `${RED}${text}${RESET}`,\n green: (text: string) => `${GREEN}${text}${RESET}`,\n yellow: (text: string) => `${YELLOW}${text}${RESET}`,\n blue: (text: string) => `${BLUE}${text}${RESET}`,\n bold: (text: string) => `${BOLD}${text}${RESET}`,\n};\n\n// Bold text wrapped in ** **\nexport const processDescription = (desc: string): string => {\n return desc.replaceAll(/\\*\\*(.*?)\\*\\*/g, (_, text) => color.bold(text));\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Stack, StackResource, StackSummary } from '@aws-sdk/client-cloudformation';\nimport {\n CloudFormationClient,\n DescribeStackResourcesCommand,\n DescribeStacksCommand,\n paginateListStacks,\n} from '@aws-sdk/client-cloudformation';\nimport { CloudFrontClient, CreateInvalidationCommand } from '@aws-sdk/client-cloudfront';\nimport { ECSClient } from '@aws-sdk/client-ecs';\nimport { S3Client } from '@aws-sdk/client-s3';\nimport { GetParameterCommand, PutParameterCommand, SSMClient } from '@aws-sdk/client-ssm';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport { EMPTY, normalizeErrorString } from '@medplum/core';\nimport { readdirSync } from 'node:fs';\nimport * as semver from 'semver';\nimport { getConfigFileName } from '../utils';\nimport { checkOk, print } from './terminal';\n\nexport interface MedplumStackDetails {\n stack: Stack;\n tag: string;\n ecsCluster?: StackResource;\n ecsService?: StackResource;\n appBucket?: StackResource;\n appDistribution?: StackResource;\n appOriginAccessIdentity?: StackResource;\n storageBucket?: StackResource;\n storageDistribution?: StackResource;\n storageOriginAccessIdentity?: StackResource;\n}\n\nexport const cloudFormationClient = new CloudFormationClient({});\nexport const cloudFrontClient = new CloudFrontClient({ region: 'us-east-1' });\nexport const ecsClient = new ECSClient({});\nexport const s3Client = new S3Client({});\nexport const tagKey = 'medplum:environment';\n\n/**\n * Returns a list of all AWS CloudFormation stacks (both Medplum and non-Medplum).\n * @returns List of AWS CloudFormation stacks.\n */\nexport async function getAllStacks(): Promise<(StackSummary & { StackName: string })[]> {\n const listResult = [] as StackSummary[];\n const paginator = paginateListStacks(\n { client: cloudFormationClient },\n {\n StackStatusFilter: [\n 'CREATE_COMPLETE',\n 'CREATE_FAILED',\n 'CREATE_IN_PROGRESS',\n 'DELETE_FAILED',\n 'DELETE_IN_PROGRESS',\n 'IMPORT_COMPLETE',\n 'IMPORT_IN_PROGRESS',\n 'IMPORT_ROLLBACK_COMPLETE',\n 'IMPORT_ROLLBACK_FAILED',\n 'IMPORT_ROLLBACK_IN_PROGRESS',\n 'REVIEW_IN_PROGRESS',\n 'ROLLBACK_COMPLETE',\n 'ROLLBACK_FAILED',\n 'ROLLBACK_IN_PROGRESS',\n 'UPDATE_COMPLETE',\n 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_FAILED',\n 'UPDATE_IN_PROGRESS',\n 'UPDATE_ROLLBACK_COMPLETE',\n 'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_ROLLBACK_FAILED',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n ],\n }\n );\n\n for await (const page of paginator) {\n for (const stack of page.StackSummaries ?? EMPTY) {\n listResult.push(stack);\n }\n }\n\n return listResult as (StackSummary & { StackName: string })[];\n}\n\n/**\n * Returns Medplum stack details for the given tag.\n * @param tag - The Medplum stack tag.\n * @returns The Medplum stack details.\n */\nexport async function getStackByTag(tag: string): Promise<MedplumStackDetails | undefined> {\n const stackSummaries = await getAllStacks();\n for (const stackSummary of stackSummaries) {\n const stackName = stackSummary.StackName;\n const details = await getStackDetails(stackName);\n if (details?.tag === tag) {\n return details;\n }\n }\n return undefined;\n}\n\n/**\n * Returns Medplum stack details for the given stack name.\n * @param stackName - The CloudFormation stack name.\n * @returns The Medplum stack details.\n */\nexport async function getStackDetails(stackName: string): Promise<MedplumStackDetails | undefined> {\n const result = {} as Partial<MedplumStackDetails>;\n await buildStackDetails(cloudFormationClient, stackName, result);\n if ((await cloudFormationClient.config.region()) !== 'us-east-1') {\n try {\n await buildStackDetails(new CloudFormationClient({ region: 'us-east-1' }), stackName + '-us-east-1', result);\n } catch {\n // Fail gracefully\n }\n }\n return result as MedplumStackDetails;\n}\n\n/**\n * Builds the Medplum stack details for the given stack name and region.\n * @param client - The CloudFormation client.\n * @param stackName - The CloudFormation stack name.\n * @param result - The Medplum stack details builder.\n */\nasync function buildStackDetails(\n client: CloudFormationClient,\n stackName: string,\n result: Partial<MedplumStackDetails>\n): Promise<void> {\n const describeStacksCommand = new DescribeStacksCommand({ StackName: stackName });\n const stackDetails = await client.send(describeStacksCommand);\n const stack = stackDetails?.Stacks?.[0];\n const medplumTag = stack?.Tags?.find((tag) => tag.Key === tagKey);\n if (!medplumTag) {\n return;\n }\n\n const stackResources = await client.send(new DescribeStackResourcesCommand({ StackName: stackName }));\n if (!stackResources.StackResources) {\n return;\n }\n\n if (client === cloudFormationClient) {\n result.stack = stack;\n result.tag = medplumTag.Value;\n }\n\n for (const resource of stackResources.StackResources) {\n assignStackDetails(resource, result);\n }\n}\n\nfunction assignStackDetails(resource: StackResource, result: Partial<MedplumStackDetails>): void {\n if (resource.ResourceType === 'AWS::ECS::Cluster') {\n result.ecsCluster = resource;\n } else if (resource.ResourceType === 'AWS::ECS::Service') {\n result.ecsService = resource;\n } else if (\n resource.ResourceType === 'AWS::S3::Bucket' &&\n resource.LogicalResourceId?.startsWith('FrontEndAppBucket')\n ) {\n result.appBucket = resource;\n } else if (\n resource.ResourceType === 'AWS::CloudFront::Distribution' &&\n resource.LogicalResourceId?.startsWith('FrontEndAppDistribution')\n ) {\n result.appDistribution = resource;\n } else if (\n resource.ResourceType === 'AWS::CloudFront::CloudFrontOriginAccessIdentity' &&\n resource.LogicalResourceId?.startsWith('FrontEndOriginAccessIdentity')\n ) {\n result.appOriginAccessIdentity = resource;\n } else if (\n resource.ResourceType === 'AWS::S3::Bucket' &&\n resource.LogicalResourceId?.startsWith('StorageStorageBucket')\n ) {\n result.storageBucket = resource;\n } else if (\n resource.ResourceType === 'AWS::CloudFront::Distribution' &&\n resource.LogicalResourceId?.startsWith('StorageStorageDistribution')\n ) {\n result.storageDistribution = resource;\n } else if (\n resource.ResourceType === 'AWS::CloudFront::CloudFrontOriginAccessIdentity' &&\n resource.LogicalResourceId?.startsWith('StorageOriginAccessIdentity')\n ) {\n result.storageOriginAccessIdentity = resource;\n }\n}\n\n/**\n * Prints the given Medplum stack details to stdout.\n * @param details - The Medplum stack details.\n */\nexport function printStackDetails(details: MedplumStackDetails): void {\n console.log(`Medplum Tag: ${details.tag}`);\n console.log(`Stack Name: ${details.stack?.StackName}`);\n console.log(`Stack ID: ${details.stack?.StackId}`);\n console.log(`Status: ${details.stack?.StackStatus}`);\n console.log(`ECS Cluster: ${details.ecsCluster?.PhysicalResourceId}`);\n console.log(`ECS Service: ${getEcsServiceName(details.ecsService)}`);\n console.log(`App Bucket: ${details.appBucket?.PhysicalResourceId}`);\n console.log(`App Distribution: ${details.appDistribution?.PhysicalResourceId}`);\n console.log(`App OAI: ${details.appOriginAccessIdentity?.PhysicalResourceId}`);\n console.log(`Storage Bucket: ${details.storageBucket?.PhysicalResourceId}`);\n console.log(`Storage Distribution: ${details.storageDistribution?.PhysicalResourceId}`);\n console.log(`Storage OAI: ${details.storageOriginAccessIdentity?.PhysicalResourceId}`);\n}\n\n/**\n * Parses the ECS service name from the given AWS ECS service resource.\n * @param resource - The AWS ECS service resource.\n * @returns The ECS service name.\n */\nexport function getEcsServiceName(resource: StackResource | undefined): string | undefined {\n return resource?.PhysicalResourceId?.split('/')?.pop() || '';\n}\n\n/**\n * Creates a CloudFront invalidation to clear the cache for all files.\n * This is not strictly necessary, but it helps to ensure that the latest version of the app is served.\n * In a perfect world, every deploy is clean, and hashed resources should be cached forever.\n * However, we do not recalculate hashes after variable replacements.\n * So if variables change, we need to invalidate the cache.\n * @param distributionId - The CloudFront distribution ID.\n */\nexport async function createInvalidation(distributionId: string): Promise<void> {\n const response = await cloudFrontClient.send(\n new CreateInvalidationCommand({\n DistributionId: distributionId,\n InvalidationBatch: {\n CallerReference: `invalidate-all-${Date.now()}`,\n Paths: {\n Quantity: 1,\n Items: ['/*'],\n },\n },\n })\n );\n console.log(`Created invalidation with ID: ${response.Invalidation?.Id}`);\n}\n\nexport async function getServerVersions(from?: string): Promise<string[]> {\n const response = await fetch('https://api.github.com/repos/medplum/medplum/releases?per_page=100', {\n headers: {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n },\n });\n\n const json = (await response.json()) as { tag_name: string }[];\n const versions = json.map((release) =>\n release.tag_name.startsWith('v') ? release.tag_name.slice(1) : release.tag_name\n );\n\n // Sort in descending order\n versions.sort((a, b) => semver.compare(b, a));\n\n return from ? versions.slice(0, versions.indexOf(from)) : versions;\n}\n\n/**\n * Writes a collection of parameters to AWS Parameter Store.\n * @param region - The AWS region.\n * @param prefix - The AWS Parameter Store prefix.\n * @param params - The parameters to write.\n */\nexport async function writeParameters(\n region: string,\n prefix: string,\n params: Record<string, string | number | boolean | object>\n): Promise<void> {\n const client = new SSMClient({ region });\n for (const [key, value] of Object.entries(params)) {\n const name = prefix + key;\n const valueStr = typeof value === 'object' ? JSON.stringify(value) : value.toString();\n const existingValue = await readParameter(client, name);\n\n if (existingValue !== undefined && existingValue !== valueStr) {\n print(`Parameter \"${name}\" exists with different value.`);\n await checkOk(`Do you want to overwrite \"${name}\"?`);\n }\n\n await writeParameter(client, name, valueStr);\n }\n}\n\n/**\n * Reads a parameter from AWS Parameter Store.\n * @param client - The AWS SSM client.\n * @param name - The parameter name.\n * @returns The parameter value, or undefined if not found.\n */\nasync function readParameter(client: SSMClient, name: string): Promise<string | undefined> {\n const command = new GetParameterCommand({\n Name: name,\n WithDecryption: true,\n });\n try {\n const result = await client.send(command);\n return result.Parameter?.Value;\n } catch (err: any) {\n if (err.name === 'ParameterNotFound') {\n return undefined;\n }\n throw err;\n }\n}\n\n/**\n * Writes a parameter to AWS Parameter Store.\n * @param client - The AWS SSM client.\n * @param name - The parameter name.\n * @param value - The parameter value.\n */\nasync function writeParameter(client: SSMClient, name: string, value: string): Promise<void> {\n const command = new PutParameterCommand({\n Name: name,\n Value: value,\n Type: 'SecureString',\n Overwrite: true,\n });\n await client.send(command);\n}\n\n/**\n * Prints a \"config not found\" message to stdout.\n * Includes helpful debugging information such as available configs.\n * @param tagName - Medplum stack tag name.\n * @param options - Additional command line options.\n */\nexport function printConfigNotFound(tagName: string, options?: Record<string, any>): void {\n console.log(`Config not found: ${tagName} (${getConfigFileName(tagName, options)})`);\n\n if (options) {\n const entries = Object.entries(options);\n if (entries.length > 0) {\n console.log('Additional options:');\n for (const [key, value] of entries) {\n console.log(` ${key}: ${value}`);\n }\n }\n }\n\n console.log();\n\n let files: any[] = readdirSync('.', { withFileTypes: true });\n files = files\n .filter((f) => f.isFile() && f.name.startsWith('medplum.') && f.name.endsWith('.json'))\n .map((f) => f.name);\n\n if (files.length === 0) {\n console.log('No configs found');\n } else {\n console.log('Available configs:');\n for (const file of files) {\n console.log(\n ` ${file\n .replaceAll('medplum.', '')\n .replaceAll('.config', '')\n .replaceAll('.server', '')\n .replaceAll('.json', '')\n .padEnd(40, ' ')} (${file})`\n );\n }\n }\n}\n\n/**\n * Prints a \"stack not found\" message to stdout.\n * Includes helpful debugging information such as AWS account ID and region.\n * @param tagName - Medplum stack tag name.\n */\nexport async function printStackNotFound(tagName: string): Promise<void> {\n console.log(`Stack not found: ${tagName}`);\n console.log();\n\n try {\n const client = new STSClient();\n const command = new GetCallerIdentityCommand({});\n const response = await client.send(command);\n const region = await client.config.region();\n console.log('AWS Region: ', region);\n console.log('AWS Account ID: ', response.Account);\n console.log('AWS Account ARN: ', response.Arn);\n console.log('AWS User ID: ', response.UserId);\n } catch (err) {\n console.log('Warning: Unable to get AWS account ID', normalizeErrorString(err));\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport readline from 'node:readline';\n\nlet terminal: readline.Interface;\n\nexport function initTerminal(): void {\n terminal = readline.createInterface({ input: process.stdin, output: process.stdout });\n}\n\nexport function closeTerminal(): void {\n terminal.close();\n}\n\n/**\n * Prints to stdout.\n * @param text - The text to print.\n */\nexport function print(text: string): void {\n terminal.write(text + '\\n');\n}\n\n/**\n * Prints a header with extra line spacing.\n * @param text - The text to print.\n */\nexport function header(text: string): void {\n print('\\n' + text + '\\n');\n}\n\n/**\n * Prints a question and waits for user input.\n * @param text - The question text to print.\n * @param defaultValue - Optional default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport function ask(text: string, defaultValue: string | number = ''): Promise<string> {\n return new Promise((resolve) => {\n terminal.question(text + (defaultValue ? ' (' + defaultValue + ')' : '') + ' ', (answer: string) => {\n resolve(answer || defaultValue.toString());\n });\n });\n}\n\n/**\n * Prints a question and waits for user to choose one of the provided options.\n * @param text - The prompt text to print.\n * @param options - The list of options that the user can select.\n * @param defaultValue - Optional default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport async function choose(text: string, options: (string | number)[], defaultValue = ''): Promise<string> {\n const str = text + ' [' + options.map((o) => (o === defaultValue ? '(' + o + ')' : o)).join('|') + ']';\n\n while (true) {\n const answer = (await ask(str)) || defaultValue;\n if (options.includes(answer)) {\n return answer;\n }\n print('Please choose one of the following options: ' + options.join(', '));\n }\n}\n\n/**\n * Prints a question and waits for the user to choose a valid integer option.\n * @param text - The prompt text to print.\n * @param options - The list of options that the user can select.\n * @param defaultValue - Default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport async function chooseInt(text: string, options: number[], defaultValue: number): Promise<number> {\n return Number.parseInt(\n await choose(\n text,\n options.map((o) => o.toString()),\n defaultValue.toString()\n ),\n 10\n );\n}\n\n/**\n * Prints a question and waits for the user to choose yes or no.\n * @param text - The question to print.\n * @returns true on accept or false on reject.\n */\nexport async function yesOrNo(text: string): Promise<boolean> {\n return (await choose(text, ['y', 'n'])).toLowerCase() === 'y';\n}\n\n/**\n * Prints a question and waits for the user to confirm yes. Throws error on no, and exits the program.\n * @param text - The prompt text to print.\n */\nexport async function checkOk(text: string): Promise<void> {\n if (!(await yesOrNo(text))) {\n print('Exiting...');\n throw new Error('User cancelled');\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { getStackByTag, printStackDetails, printStackNotFound } from './utils';\n\n/**\n * The AWS \"describe\" command prints details about a Medplum CloudFormation stack.\n * @param tag - The Medplum stack tag.\n */\nexport async function describeStacksCommand(tag: string): Promise<void> {\n const details = await getStackByTag(tag);\n if (!details) {\n await printStackNotFound(tag);\n throw new Error(`Stack not found: ${tag}`);\n }\n printStackDetails(details);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { CertificateSummary, ValidationMethod } from '@aws-sdk/client-acm';\nimport { ACMClient, ListCertificatesCommand, RequestCertificateCommand } from '@aws-sdk/client-acm';\nimport { CloudFrontClient, CreatePublicKeyCommand } from '@aws-sdk/client-cloudfront';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport type { MedplumInfraConfig } from '@medplum/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { getConfigFileName, writeConfig } from '../utils';\nimport { ask, checkOk, choose, chooseInt, closeTerminal, header, initTerminal, print, yesOrNo } from './terminal';\nimport { getServerVersions, writeParameters } from './utils';\n\ntype MedplumDomainType = 'api' | 'app' | 'storage';\ntype MedplumDomainSetting = `${MedplumDomainType}DomainName`;\ntype MedplumDomainCertSetting = `${MedplumDomainType}SslCertArn`;\n\nconst getDomainSetting = (domain: MedplumDomainType): MedplumDomainSetting => `${domain}DomainName`;\nconst getDomainCertSetting = (domain: MedplumDomainType): MedplumDomainCertSetting => `${domain}SslCertArn`;\n\nexport async function initStackCommand(): Promise<void> {\n const config = { apiPort: 8103, region: 'us-east-1' } as MedplumInfraConfig;\n initTerminal();\n header('MEDPLUM');\n print('This tool prepares the necessary prerequisites for deploying Medplum in your AWS account.');\n print('');\n print('Most Medplum infrastructure is deployed using the AWS CDK.');\n print('However, some AWS resources must be created manually, such as email addresses and SSL certificates.');\n print('This tool will help you create those resources.');\n print('');\n print('Upon completion, this tool will:');\n print(' 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)');\n print(' 2. Optionally generate an AWS CloudFront signing key');\n print(' 3. Optionally request SSL certificates from AWS Certificate Manager');\n print(' 4. Optionally write server config settings to AWS Parameter Store');\n print('');\n print('The Medplum infra config file is an input to the Medplum CDK.');\n print('The Medplum CDK will create and manage the necessary AWS resources.');\n print('');\n print('We will ask a series of questions to generate your infra config file.');\n print('Some questions have predefined options in [square brackets].');\n print('Some questions have default values in (parentheses), which you can accept by pressing Enter.');\n print('Press Ctrl+C at any time to exit.');\n\n const currentAccountId = await getAccountId(config.region);\n if (!currentAccountId) {\n print('It appears that you do not have AWS credentials configured.');\n print('AWS credentials are not strictly required, but will enable some additional features.');\n print('If you intend to use AWS credentials, please configure them now.');\n await checkOk('Do you want to continue without AWS credentials?');\n }\n\n header('ENVIRONMENT NAME');\n print('Medplum deployments have a short environment name such as \"prod\", \"staging\", \"alice\", or \"demo\".');\n print('The environment name is used in multiple places:');\n print(' 1. As part of config file names (i.e., medplum.demo.config.json)');\n print(' 2. As the base of CloudFormation stack names (i.e., MedplumDemo)');\n print(' 3. AWS Parameter Store keys (i.e., /medplum/demo/...)');\n config.name = await ask('What is your environment name?', 'demo');\n print('Using environment name \"' + config.name + '\"...');\n\n header('CONFIG FILE');\n print('Medplum Infrastructure will create a config file in the current directory.');\n const configFileName = await ask('What is the config file name?', `medplum.${config.name}.config.json`);\n if (existsSync(configFileName)) {\n print('Config file already exists.');\n await checkOk('Do you want to overwrite the config file?');\n }\n print('Using config file \"' + configFileName + '\"...');\n writeConfig(configFileName, config);\n\n header('AWS REGION');\n print('Most Medplum resources will be created in a single AWS region.');\n config.region = await ask('Enter your AWS region:', 'us-east-1');\n writeConfig(configFileName, config);\n\n header('AWS ACCOUNT NUMBER');\n print('Medplum Infrastructure will use your AWS account number to create AWS resources.');\n if (currentAccountId) {\n print('Using the AWS CLI, your current account ID is: ' + currentAccountId);\n }\n config.accountNumber = await ask('What is your AWS account number?', currentAccountId);\n writeConfig(configFileName, config);\n\n header('STACK NAME');\n print('Medplum will create a CloudFormation stack to manage AWS resources.');\n print('AWS CloudFormation stack names ');\n const defaultStackName = 'Medplum' + config.name.charAt(0).toUpperCase() + config.name.slice(1);\n config.stackName = await ask('Enter your CloudFormation stack name?', defaultStackName);\n writeConfig(configFileName, config);\n\n header('BASE DOMAIN NAME');\n print('Please enter the base domain name for your Medplum deployment.');\n print('');\n print('Medplum deploys multiple subdomains for various services.');\n print('');\n print('For example, \"api.\" for the REST API and \"app.\" for the web application.');\n print('The base domain name is the common suffix for all subdomains.');\n print('');\n print('For example, if your base domain name is \"example.com\",');\n print('then the REST API will be \"api.example.com\".');\n print('');\n print('The base domain should include the TLD (i.e., \".com\", \".org\", \".net\").');\n print('');\n print('Note that you must own the base domain, and it must use Route53 DNS.');\n while (!config.domainName) {\n config.domainName = await ask('Enter your base domain name:');\n }\n writeConfig(configFileName, config);\n\n header('SUPPORT EMAIL');\n print('Medplum sends transactional emails to users.');\n print('For example, emails to new users or for password reset.');\n print('Medplum will use the support email address to send these emails.');\n print('Note that you must verify the support email address in SES.');\n const supportEmail = await ask('Enter your support email address:');\n\n header('API DOMAIN NAME');\n print('Medplum deploys a REST API for the backend services.');\n config.apiDomainName = await ask('Enter your REST API domain name:', 'api.' + config.domainName);\n config.baseUrl = `https://${config.apiDomainName}/`;\n writeConfig(configFileName, config);\n\n header('APP DOMAIN NAME');\n print('Medplum deploys a web application for the user interface.');\n config.appDomainName = await ask('Enter your web application domain name:', 'app.' + config.domainName);\n writeConfig(configFileName, config);\n\n header('STORAGE DOMAIN NAME');\n print('Medplum deploys a storage service for file uploads.');\n config.storageDomainName = await ask('Enter your storage domain name:', 'storage.' + config.domainName);\n writeConfig(configFileName, config);\n\n header('STORAGE BUCKET');\n print('Medplum uses an S3 bucket to store binary content such as file uploads.');\n print('Medplum will create a the S3 bucket as part of the CloudFormation stack.');\n config.storageBucketName = await ask('Enter your storage bucket name:', config.storageDomainName);\n writeConfig(configFileName, config);\n\n header('MAX AVAILABILITY ZONES');\n print('Medplum API servers can be deployed in multiple availability zones.');\n print('This provides redundancy and high availability.');\n print('However, it also increases the cost of the deployment.');\n print('If you want to use all availability zones, choose a large number such as 99.');\n print('If you want to restrict the number, for example to manage EIP limits,');\n print('then choose a small number such as 2 or 3.');\n config.maxAzs = await chooseInt('Enter the maximum number of availability zones:', [2, 3, 99], 2);\n\n header('DATABASE INSTANCES');\n print('Medplum uses a relational database to store data.');\n print('Medplum can create a new RDS database as part of the CloudFormation stack,');\n print('or can set up your own database and enter the database name, username, and password.');\n if (await yesOrNo('Do you want to create a new RDS database as part of the CloudFormation stack?')) {\n print('Medplum will create a new RDS database as part of the CloudFormation stack.');\n print('');\n print('If you need high availability, you can choose multiple instances.');\n print('Use 1 for a single instance, or 2 for a primary and a standby.');\n config.rdsInstances = await chooseInt('Enter the number of database instances:', [1, 2], 1);\n } else {\n print('Medplum will not create a new RDS database.');\n print('Please create a new RDS database and enter the database name, username, and password.');\n print('Set the AWS Secrets Manager secret ARN in the config file in the \"rdsSecretsArn\" setting.');\n config.rdsSecretsArn = 'TODO';\n }\n writeConfig(configFileName, config);\n\n header('SERVER INSTANCES');\n print('Medplum uses AWS Fargate to run the API servers.');\n print('Medplum will create a new Fargate cluster as part of the CloudFormation stack.');\n print('Fargate will automatically scale the number of servers up and down.');\n print('If you need high availability, you can choose multiple instances.');\n config.desiredServerCount = await chooseInt('Enter the number of server instances:', [1, 2, 3, 4, 6, 8], 1);\n writeConfig(configFileName, config);\n\n header('SERVER MEMORY');\n print('You can choose the amount of memory for each server instance.');\n print('The default is 512 MB, which is sufficient for getting started.');\n print('Note that only certain CPU units are compatible with memory units.');\n print('Consult AWS Fargate \"Task Definition Parameters\" for more information.');\n config.serverMemory = await chooseInt('Enter the server memory (MB):', [512, 1024, 2048, 4096, 8192, 16384], 512);\n writeConfig(configFileName, config);\n\n header('SERVER CPU');\n print('You can choose the amount of CPU for each server instance.');\n print('CPU is expressed as an integer using AWS CPU units');\n print('The default is 256, which is sufficient for getting started.');\n print('Note that only certain CPU units are compatible with memory units.');\n print('Consult AWS Fargate \"Task Definition Parameters\" for more information.');\n config.serverCpu = await chooseInt('Enter the server CPU:', [256, 512, 1024, 2048, 4096, 8192, 16384], 256);\n writeConfig(configFileName, config);\n\n header('SERVER IMAGE');\n print('Medplum uses Docker images for the API servers.');\n print('You can choose the image to use for the servers.');\n print('Docker images can be loaded from either Docker Hub or AWS ECR.');\n print('The default is the latest Medplum release.');\n const latestVersion = (await getServerVersions())[0] ?? 'latest';\n config.serverImage = await ask('Enter the server image:', `medplum/medplum-server:${latestVersion}`);\n writeConfig(configFileName, config);\n\n header('SIGNING KEY');\n print('Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.');\n const signingKey = await generateSigningKey(config.region, config.stackName + 'SigningKey');\n if (signingKey) {\n config.signingKeyId = signingKey.keyId;\n config.storagePublicKey = signingKey.publicKey;\n writeConfig(configFileName, config);\n } else {\n print('Unable to generate signing key.');\n print('Please manually create a signing key and enter the key ID and public key in the config file.');\n print('You must set the \"signingKeyId\", \"signingKey\", and \"signingKeyPassphrase\" settings.');\n }\n\n header('SSL CERTIFICATES');\n print(`Medplum will now check for existing SSL certificates for the subdomains.`);\n const allCerts = await listAllCertificates(config.region);\n print('Found ' + allCerts.length + ' certificate(s).');\n\n // Process certificates for each subdomain\n // Note: The \"api\" certificate must be created in the same region as the API\n // Note: The \"app\" and \"storage\" certificates must be created in us-east-1\n for (const { region, certName } of [\n { region: config.region, certName: 'api' },\n { region: 'us-east-1', certName: 'app' },\n { region: 'us-east-1', certName: 'storage' },\n ] as const) {\n print('');\n const arn = await processCert(config, allCerts, region, certName);\n config[getDomainCertSetting(certName)] = arn;\n writeConfig(configFileName, config);\n }\n\n header('AWS PARAMETER STORE');\n print('Medplum uses AWS Parameter Store to store sensitive configuration values.');\n print('These values will be encrypted at rest.');\n print(`The values will be stored in the \"/medplum/${config.name}\" path.`);\n\n const serverParams: Record<string, string | number> = {\n port: config.apiPort,\n baseUrl: config.baseUrl,\n appBaseUrl: `https://${config.appDomainName}/`,\n storageBaseUrl: `https://${config.storageDomainName}/binary/`,\n binaryStorage: `s3:${config.storageBucketName}`,\n supportEmail: supportEmail,\n };\n\n if (signingKey) {\n serverParams.signingKeyId = signingKey.keyId;\n serverParams.signingKey = signingKey.privateKey;\n serverParams.signingKeyPassphrase = signingKey.passphrase;\n }\n\n print(\n JSON.stringify(\n {\n ...serverParams,\n signingKey: '****',\n signingKeyPassphrase: '****',\n },\n null,\n 2\n )\n );\n\n if (await yesOrNo('Do you want to store these values in AWS Parameter Store?')) {\n await writeParameters(config.region, `/medplum/${config.name}/`, serverParams);\n } else {\n const serverConfigFileName = getConfigFileName(config.name, { server: true });\n writeConfig(serverConfigFileName, serverParams);\n print('Skipping AWS Parameter Store.');\n print(`Writing values to local config file: ${serverConfigFileName}`);\n print('Please add these values to AWS Parameter Store manually.');\n }\n\n header('DONE!');\n print('Medplum configuration complete.');\n print('You can now proceed to deploying the Medplum infrastructure with CDK.');\n print('Run:');\n print('');\n print(` npx cdk bootstrap -c config=${configFileName}`);\n print(` npx cdk synth -c config=${configFileName}`);\n if (config.region === 'us-east-1') {\n print(` npx cdk deploy -c config=${configFileName}`);\n } else {\n print(` npx cdk deploy -c config=${configFileName} --all`);\n }\n print('');\n print('See Medplum documentation for more information:');\n print('');\n print(' https://www.medplum.com/docs/self-hosting/install-on-aws');\n print('');\n closeTerminal();\n}\n\n/**\n * Returns the current AWS account ID.\n * This is used as the default value for the \"accountNumber\" config setting.\n * @param region - The AWS region.\n * @returns The AWS account ID.\n */\nasync function getAccountId(region: string): Promise<string | undefined> {\n try {\n const client = new STSClient({ region });\n const command = new GetCallerIdentityCommand({});\n const response = await client.send(command);\n return response.Account;\n } catch (err) {\n console.log('Warning: Unable to get AWS account ID', (err as Error).message);\n return undefined;\n }\n}\n\n/**\n * Returns a list of all AWS certificates.\n * This is used to find existing certificates for the subdomains.\n * If the primary region is not us-east-1, then certificates in us-east-1 will also be returned.\n * @param region - The AWS region.\n * @returns The list of AWS Certificates.\n */\nasync function listAllCertificates(region: string): Promise<CertificateSummary[]> {\n const result = await listCertificates(region);\n if (region !== 'us-east-1') {\n const usEast1Result = await listCertificates('us-east-1');\n result.push(...usEast1Result);\n }\n return result;\n}\n\n/**\n * Returns a list of AWS Certificates.\n * This is used to find existing certificates for the subdomains.\n * @param region - The AWS region.\n * @returns The list of AWS Certificates.\n */\nasync function listCertificates(region: string): Promise<CertificateSummary[]> {\n try {\n const client = new ACMClient({ region });\n const command = new ListCertificatesCommand({ MaxItems: 1000 });\n const response = await client.send(command);\n return response.CertificateSummaryList as CertificateSummary[];\n } catch (err) {\n console.log('Warning: Unable to list certificates', (err as Error).message);\n return [];\n }\n}\n\n/**\n * Processes a required certificate.\n *\n * 1. If the certificate already exists, return the ARN.\n * 2. If the certificate does not exist, and the user wants to create a new certificate, create it and return the ARN.\n * 3. If the certificate does not exist, and the user does not want to create a new certificate, return a placeholder.\n * @param config - In-progress config settings.\n * @param allCerts - List of all existing certificates.\n * @param region - The AWS region where the certificate is needed.\n * @param certName - The name of the certificate (api, app, or storage).\n * @returns The ARN of the certificate or placeholder if a new certificate is needed.\n */\nasync function processCert(\n config: MedplumInfraConfig,\n allCerts: CertificateSummary[],\n region: string,\n certName: 'api' | 'app' | 'storage'\n): Promise<string> {\n const domainName = config[getDomainSetting(certName)];\n const existingCert = allCerts.find((cert) => cert.CertificateArn?.includes(region) && cert.DomainName === domainName);\n if (existingCert) {\n print(`Found existing certificate for \"${domainName}\" in \"${region}.`);\n return existingCert.CertificateArn as string;\n }\n\n print(`No existing certificate found for \"${domainName}\" in \"${region}.`);\n if (!(await yesOrNo('Do you want to request a new certificate?'))) {\n print(`Please add your certificate ARN to the config file in the \"${getDomainCertSetting(certName)}\" setting.`);\n return 'TODO';\n }\n\n const arn = await requestCert(region, domainName);\n print('Certificate ARN: ' + arn);\n return arn;\n}\n\n/**\n * Requests an AWS Certificate.\n * @param region - The AWS region.\n * @param domain - The domain name.\n * @returns The AWS Certificate ARN on success, or undefined on failure.\n */\nasync function requestCert(region: string, domain: string): Promise<string> {\n try {\n const validationMethod = await choose(\n 'Validate certificate using DNS or email validation?',\n ['dns', 'email'],\n 'dns'\n );\n const client = new ACMClient({ region });\n const command = new RequestCertificateCommand({\n DomainName: domain,\n ValidationMethod: validationMethod.toUpperCase() as ValidationMethod,\n });\n const response = await client.send(command);\n return response.CertificateArn as string;\n } catch (err) {\n console.log('Error: Unable to request certificate', (err as Error).message);\n return 'TODO';\n }\n}\n\n/**\n * Generates an AWS CloudFront signing key.\n *\n * Requirements:\n *\n * 1. It must be an SSH-2 RSA key pair.\n * 2. It must be in base64-encoded PEM format.\n * 3. It must be a 2048-bit key pair.\n *\n * See: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html#private-content-creating-cloudfront-key-pairs\n *\n * @param region - The AWS region.\n * @param keyName - The key name.\n * @returns A new signing key.\n */\nasync function generateSigningKey(\n region: string,\n keyName: string\n): Promise<\n | {\n keyId: string;\n publicKey: string;\n privateKey: string;\n passphrase: string;\n }\n | undefined\n> {\n const passphrase = randomUUID();\n const signingKey = generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs1',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase,\n },\n });\n\n try {\n const response = await new CloudFrontClient({ region }).send(\n new CreatePublicKeyCommand({\n PublicKeyConfig: {\n Name: keyName,\n CallerReference: randomUUID(),\n EncodedKey: signingKey.publicKey,\n },\n })\n );\n\n return {\n keyId: response.PublicKey?.Id as string,\n publicKey: signingKey.publicKey,\n privateKey: signingKey.privateKey,\n passphrase,\n };\n } catch (err) {\n console.log('Error: Unable to create signing key: ', normalizeErrorString(err));\n return undefined;\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { getAllStacks, getStackDetails, printStackDetails } from './utils';\n\n/**\n * The AWS \"list\" command prints summary details about all Medplum CloudFormation stacks.\n */\nexport async function listStacksCommand(): Promise<void> {\n const stackSummaries = await getAllStacks();\n for (const stackSummary of stackSummaries) {\n const stackName = stackSummary.StackName;\n const details = await getStackDetails(stackName);\n if (!details) {\n continue;\n }\n printStackDetails(details);\n console.log('');\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { PutObjectCommand } from '@aws-sdk/client-s3';\nimport { ContentType } from '@medplum/core';\nimport fastGlob from 'fast-glob';\nimport { createReadStream, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join, sep } from 'node:path';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { readConfig, safeTarExtractor } from '../utils';\nimport { createInvalidation, getStackByTag, printConfigNotFound, printStackNotFound, s3Client } from './utils';\n\nexport interface UpdateAppOptions {\n file?: string;\n toVersion?: string;\n dryrun?: boolean;\n tarPath?: string;\n}\n\n/**\n * The AWS \"update-app\" command updates the Medplum app in a Medplum CloudFormation stack to the latest version.\n * @param tag - The Medplum stack tag.\n * @param options - The update options.\n */\nexport async function updateAppCommand(tag: string, options: UpdateAppOptions): Promise<void> {\n const config = readConfig(tag, options);\n if (!config) {\n printConfigNotFound(tag, options);\n throw new Error(`Config not found: ${tag}`);\n }\n const details = await getStackByTag(tag);\n if (!details) {\n await printStackNotFound(tag);\n throw new Error(`Stack not found: ${tag}`);\n }\n const appBucket = details.appBucket;\n if (!appBucket) {\n throw new Error(`App bucket not found for stack ${tag}`);\n }\n\n let tmpDir: string;\n\n if (options.tarPath) {\n tmpDir = options.tarPath;\n } else {\n const version = options?.toVersion ?? 'latest';\n tmpDir = await downloadNpmPackage('@medplum/app', version);\n }\n\n // Replace variables in the app\n replaceVariables(tmpDir, {\n MEDPLUM_BASE_URL: config.baseUrl as string,\n MEDPLUM_CLIENT_ID: config.clientId ?? '',\n GOOGLE_CLIENT_ID: config.googleClientId ?? '',\n RECAPTCHA_SITE_KEY: config.recaptchaSiteKey ?? '',\n MEDPLUM_REGISTER_ENABLED: config.registerEnabled ? 'true' : 'false',\n });\n\n // Upload the app to S3 with correct content-type and cache-control\n await uploadAppToS3(tmpDir, appBucket.PhysicalResourceId as string, options);\n\n // Create a CloudFront invalidation to clear any cached resources\n if (details.appDistribution?.PhysicalResourceId && !options.dryrun) {\n await createInvalidation(details.appDistribution.PhysicalResourceId);\n }\n\n console.log('Done');\n}\n\n/**\n * Returns NPM package metadata for a given package name.\n * See: https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#getpackageversion\n * @param packageName - The npm package name.\n * @param version - The npm package version string.\n * @returns The package.json metadata content.\n */\nasync function getNpmPackageMetadata(packageName: string, version: string): Promise<any> {\n const url = `https://registry.npmjs.org/${packageName}/${version}`;\n const response = await fetch(url);\n return response.json();\n}\n\n/**\n * Downloads and extracts an NPM package.\n * @param packageName - The NPM package name.\n * @param version - The NPM package version or \"latest\".\n * @returns Path to temporary directory where the package was downloaded and extracted.\n */\nasync function downloadNpmPackage(packageName: string, version: string): Promise<string> {\n const packageMetadata = await getNpmPackageMetadata(packageName, version);\n const tarballUrl = packageMetadata.dist.tarball as string;\n const tmpDir = mkdtempSync(join(tmpdir(), 'tarball-'));\n try {\n const response = await fetch(tarballUrl);\n if (!response.body) {\n throw new Error('Received empty response body');\n }\n const extractor = safeTarExtractor(tmpDir);\n await pipeline(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]), extractor);\n return join(tmpDir, 'package', 'dist');\n } catch (error) {\n rmSync(tmpDir, { recursive: true, force: true });\n throw error;\n }\n}\n\n/**\n * Replaces variables in all JS files in the given folder.\n * @param folderName - The folder name of the files.\n * @param replacements - The collection of variable placeholders and replacements.\n */\nfunction replaceVariables(folderName: string, replacements: Record<string, string>): void {\n for (const item of readdirSync(folderName, { withFileTypes: true })) {\n const itemPath = join(folderName, item.name);\n if (item.isDirectory()) {\n replaceVariables(itemPath, replacements);\n } else if (item.isFile() && itemPath.endsWith('.js')) {\n replaceVariablesInFile(itemPath, replacements);\n }\n }\n}\n\n/**\n * Replaces variables in the JS file.\n * @param fileName - The file name.\n * @param replacements - The collection of variable placeholders and replacements.\n */\nfunction replaceVariablesInFile(fileName: string, replacements: Record<string, string>): void {\n let contents = readFileSync(fileName, 'utf-8');\n for (const [placeholder, replacement] of Object.entries(replacements)) {\n contents = contents.replaceAll(`__${placeholder}__`, replacement);\n }\n writeFileSync(fileName, contents);\n}\n\n/**\n * Uploads the app to S3.\n * Ensures correct content-type and cache-control for each file.\n * @param tmpDir - The temporary directory where the app is located.\n * @param bucketName - The destination S3 bucket name.\n * @param options - The update options.\n */\nasync function uploadAppToS3(tmpDir: string, bucketName: string, options: UpdateAppOptions): Promise<void> {\n // Manually iterate and upload files\n // Automatic content-type detection is not reliable on Microsoft Windows\n // So we explicitly set content-type\n const uploadPatterns: [string, string, boolean][] = [\n // Cached\n // These files generally have a hash, so they can be cached forever\n // It is important to upload them first to avoid broken references from index.html\n ['assets/**/*.css', ContentType.CSS, true],\n ['assets/**/*.css.map', ContentType.JSON, true],\n ['assets/**/*.js', ContentType.JAVASCRIPT, true],\n ['assets/**/*.js.map', ContentType.JSON, true],\n ['assets/**/*.txt', ContentType.TEXT, true],\n ['assets/**/*.ico', ContentType.FAVICON, true],\n ['img/**/*.png', ContentType.PNG, true],\n ['img/**/*.svg', ContentType.SVG, true],\n ['robots.txt', ContentType.TEXT, true],\n\n // Not cached\n ['index.html', ContentType.HTML, false],\n ];\n for (const uploadPattern of uploadPatterns) {\n await uploadFolderToS3({\n rootDir: tmpDir,\n bucketName,\n fileNamePattern: uploadPattern[0],\n contentType: uploadPattern[1],\n cached: uploadPattern[2],\n dryrun: options.dryrun,\n });\n }\n}\n\n/**\n * Uploads a directory of files to S3.\n * @param options - The upload options such as bucket name, content type, and cache control.\n * @param options.rootDir - The root directory of the upload.\n * @param options.bucketName - The destination bucket name.\n * @param options.fileNamePattern - The glob file pattern to upload.\n * @param options.contentType - The content type MIME type.\n * @param options.cached - True to mark as public and cached forever.\n * @param options.dryrun - True to skip the upload.\n */\nasync function uploadFolderToS3(options: {\n rootDir: string;\n bucketName: string;\n fileNamePattern: string;\n contentType: string;\n cached: boolean;\n dryrun?: boolean;\n}): Promise<void> {\n const items = fastGlob.sync(options.fileNamePattern, { cwd: options.rootDir });\n for (const item of items) {\n await uploadFileToS3(join(options.rootDir, item), options);\n }\n}\n\n/**\n * Uploads a file to S3.\n * @param filePath - The file path.\n * @param options - The upload options such as bucket name, content type, and cache control.\n * @param options.rootDir - The root directory of the upload.\n * @param options.bucketName - The destination bucket name.\n * @param options.contentType - The content type MIME type.\n * @param options.cached - True to mark as public and cached forever.\n * @param options.dryrun - True to skip the upload.\n */\nasync function uploadFileToS3(\n filePath: string,\n options: {\n rootDir: string;\n bucketName: string;\n contentType: string;\n cached: boolean;\n dryrun?: boolean;\n }\n): Promise<void> {\n const fileStream = createReadStream(filePath);\n const s3Key = filePath\n .substring(options.rootDir.length + 1)\n .split(sep)\n .join('/');\n\n const putObjectParams = {\n Bucket: options.bucketName,\n Key: s3Key,\n Body: fileStream,\n ContentType: options.contentType,\n CacheControl: options.cached ? 'public, max-age=31536000' : 'no-cache, no-store, must-revalidate',\n };\n\n console.log(`Uploading ${s3Key} to ${options.bucketName}...`);\n if (!options.dryrun) {\n await s3Client.send(new PutObjectCommand(putObjectParams));\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { StackResource } from '@aws-sdk/client-cloudformation';\nimport { GetBucketPolicyCommand, PutBucketPolicyCommand } from '@aws-sdk/client-s3';\nimport { readConfig } from '../utils';\nimport { createInvalidation, getStackByTag, printConfigNotFound, printStackNotFound, s3Client } from './utils';\n\nexport interface UpdateBucketPoliciesOptions {\n file?: string;\n dryrun?: boolean;\n guarddutyMalwareProtection?: boolean;\n}\n\ninterface Policy {\n Version?: string;\n Statement?: PolicyStatement[];\n}\n\ninterface PolicyStatement {\n Sid?: string;\n Effect?: string;\n Principal?: { AWS?: string; CanonicalUser?: string };\n Action?: string | string[];\n Resource?: string | string[];\n Condition?: Record<string, Record<string, string | string[]>>;\n}\n\n/**\n * The AWS \"update-bucket-policies\" command adds necessary policy statements to S3 bucket policy documents.\n *\n * This is necessary for Medplum deployments outside of the us-east-1 region.\n *\n * @param tag - The Medplum stack tag.\n * @param options - The update options.\n */\nexport async function updateBucketPoliciesCommand(tag: string, options: UpdateBucketPoliciesOptions): Promise<void> {\n const config = readConfig(tag, options);\n if (!config) {\n printConfigNotFound(tag, options);\n throw new Error(`Config not found: ${tag}`);\n }\n\n const details = await getStackByTag(tag);\n if (!details) {\n await printStackNotFound(tag);\n throw new Error(`Stack not found: ${tag}`);\n }\n\n try {\n await updateBucketPolicy(\n 'App',\n details.appBucket,\n details.appDistribution,\n details.appOriginAccessIdentity,\n options\n );\n } catch (err) {\n console.error(`Error updating App bucket policy: ${(err as Error).message}`);\n }\n\n try {\n await updateBucketPolicy(\n 'Storage',\n details.storageBucket,\n details.storageDistribution,\n details.storageOriginAccessIdentity,\n options\n );\n } catch (err) {\n console.error(`Error updating Storage bucket policy: ${(err as Error).message}`);\n }\n\n console.log('Done');\n}\n\nexport async function updateBucketPolicy(\n friendlyName: string,\n bucketResource: StackResource | undefined,\n distributionResource: StackResource | undefined,\n oaiResource: StackResource | undefined,\n options: UpdateBucketPoliciesOptions\n): Promise<void> {\n if (!bucketResource?.PhysicalResourceId) {\n throw new Error(`${friendlyName} bucket not found`);\n }\n\n if (!distributionResource?.PhysicalResourceId) {\n throw new Error(`${friendlyName} distribution not found`);\n }\n\n if (!oaiResource?.PhysicalResourceId) {\n throw new Error(`${friendlyName} OAI not found`);\n }\n\n const bucketName = bucketResource.PhysicalResourceId;\n const oaiId = oaiResource.PhysicalResourceId;\n const bucketPolicy = await getPolicy(bucketName);\n if (policyHasAllowStatement(bucketPolicy, bucketName, oaiId)) {\n throw new Error(`${friendlyName} bucket already has policy statement`);\n }\n\n addAllowPolicyStatement(bucketPolicy, bucketName, oaiId);\n if (friendlyName === 'Storage' && options.guarddutyMalwareProtection) {\n addGuardDutyReadPolicyStatement(bucketPolicy, bucketName, oaiId);\n }\n console.log(`${friendlyName} bucket policy:`);\n console.log(JSON.stringify(bucketPolicy, undefined, 2));\n\n if (options.dryrun) {\n console.log('Dry run - skipping updates');\n } else {\n // Apply the updated policy\n console.log('Updating bucket policy...');\n await setPolicy(bucketName, bucketPolicy);\n console.log('Bucket policy updated');\n\n // Create a CloudFront invalidation to clear any cached responses\n console.log('Creating CloudFront invalidation...');\n await createInvalidation(distributionResource.PhysicalResourceId);\n console.log('CloudFront invalidation created');\n\n console.log(`${friendlyName} bucket policy updated`);\n }\n}\n\nasync function getPolicy(bucketName: string): Promise<Policy> {\n const policyResponse = await s3Client.send(\n new GetBucketPolicyCommand({\n Bucket: bucketName,\n })\n );\n return JSON.parse(policyResponse.Policy ?? '{}') as Policy;\n}\n\nasync function setPolicy(bucketName: string, policy: Policy): Promise<void> {\n await s3Client.send(\n new PutBucketPolicyCommand({\n Bucket: bucketName,\n Policy: JSON.stringify(policy),\n })\n );\n}\n\nfunction policyHasAllowStatement(policy: Policy, bucketName: string, oaiId: string): boolean {\n return !!policy?.Statement?.some((s: PolicyStatement) => {\n return (\n s?.Effect === 'Allow' &&\n s?.Principal?.AWS === `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}` &&\n Array.isArray(s?.Action) &&\n s?.Action?.includes('s3:GetObject*') &&\n s?.Action?.includes('s3:GetBucket*') &&\n s?.Action?.includes('s3:List*') &&\n Array.isArray(s?.Resource) &&\n s?.Resource?.includes(`arn:aws:s3:::${bucketName}`) &&\n s?.Resource?.includes(`arn:aws:s3:::${bucketName}/*`)\n );\n });\n}\n\nfunction addAllowPolicyStatement(policy: Policy, bucketName: string, oaiId: string): void {\n if (!policy.Version) {\n policy.Version = '2012-10-17';\n }\n\n if (!policy.Statement) {\n policy.Statement = [];\n }\n\n policy.Statement.push({\n Effect: 'Allow',\n Principal: {\n AWS: `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}`,\n },\n Action: ['s3:GetObject*', 's3:GetBucket*', 's3:List*'],\n Resource: [`arn:aws:s3:::${bucketName}`, `arn:aws:s3:::${bucketName}/*`],\n });\n}\n\nfunction addGuardDutyReadPolicyStatement(policy: Policy, bucketName: string, oaiId: string): void {\n if (\n policy.Statement?.some(\n (s) =>\n s?.Effect === 'Deny' &&\n s?.Principal?.AWS === `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}` &&\n statementHasAction(s, 's3:GetObject') &&\n statementHasAction(s, 's3:GetObjectVersion') &&\n s?.Condition?.StringNotEquals?.['s3:ExistingObjectTag/GuardDutyMalwareScanStatus'] === 'NO_THREATS_FOUND'\n )\n ) {\n return;\n }\n\n policy.Statement?.push({\n Sid: 'GuardDutyMalwareProtectionReadGate',\n Effect: 'Deny',\n Principal: {\n AWS: `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}`,\n },\n Action: ['s3:GetObject', 's3:GetObjectVersion'],\n Resource: `arn:aws:s3:::${bucketName}/*`,\n Condition: {\n StringNotEquals: {\n 's3:ExistingObjectTag/GuardDutyMalwareScanStatus': 'NO_THREATS_FOUND',\n },\n },\n });\n}\n\nfunction statementHasAction(statement: PolicyStatement, action: string): boolean {\n if (statement.Action === action) {\n return true;\n }\n return Array.isArray(statement.Action) && statement.Action.includes(action);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumInfraConfig } from '@medplum/core';\nimport { color } from '../util/color';\nimport { getConfigFileName, readConfig, readServerConfig } from '../utils';\nimport { closeTerminal, initTerminal, print, yesOrNo } from './terminal';\nimport { printConfigNotFound, writeParameters } from './utils';\n\nexport interface UpdateConfigOptions {\n file?: string;\n dryrun?: boolean;\n yes?: boolean;\n}\n\n/**\n * The AWS \"update-config\" command updates AWS Parameter Store values with values from the local config file.\n * @param tag - The Medplum stack tag.\n * @param options - Additional command line options.\n */\nexport async function updateConfigCommand(tag: string, options: UpdateConfigOptions): Promise<void> {\n try {\n initTerminal();\n\n const infraConfig = readConfig(tag, options) as MedplumInfraConfig;\n if (!infraConfig) {\n printConfigNotFound(tag, options);\n throw new Error(`Config not found: ${tag}`);\n }\n\n const serverConfig = readServerConfig(tag) ?? {};\n\n // If the server config is empty, prompt the user to proceed\n if (!options.yes && Object.keys(serverConfig).length === 0) {\n const serverConfigFileName = getConfigFileName(tag, { server: true });\n console.log(color.yellow(`Config file ${serverConfigFileName} not found!`));\n if (!(await yesOrNo('Do you want to proceed?'))) {\n console.log(color.red(`Run Aborted, please ensure ${serverConfigFileName} is present and try again.`));\n return;\n }\n }\n\n checkConfigConflicts(infraConfig, serverConfig);\n mergeConfigs(infraConfig, serverConfig);\n\n print('Medplum uses AWS Parameter Store to store sensitive configuration values.');\n print('These values will be encrypted at rest.');\n print(`The values will be stored in the \"/medplum/${infraConfig.name}\" path.`);\n\n print(\n JSON.stringify(\n {\n ...serverConfig,\n signingKey: '****',\n signingKeyPassphrase: '****',\n },\n null,\n 2\n )\n );\n\n if (options.dryrun) {\n console.log(color.yellow('Dry run - skipping updates!'));\n } else if (options.yes || (await yesOrNo('Do you want to store these values in AWS Parameter Store?'))) {\n await writeParameters(infraConfig.region, `/medplum/${infraConfig.name}/`, serverConfig);\n }\n } finally {\n closeTerminal();\n }\n}\n\nexport function checkConfigConflicts(\n infraConfig: MedplumInfraConfig,\n serverConfig: Record<string, string | number>\n): void {\n checkConflict(\n infraConfig.apiPort,\n serverConfig.port,\n `Infra \"apiPort\" (${infraConfig.apiPort}) does not match server \"port\" (${serverConfig.port})`\n );\n\n checkConflict(\n infraConfig.baseUrl,\n serverConfig.baseUrl,\n `Infra \"baseUrl\" (${infraConfig.baseUrl}) does not match server \"baseUrl\" (${serverConfig.baseUrl})`\n );\n\n checkConflict(\n infraConfig.appDomainName && `https://${infraConfig.appDomainName}/`,\n serverConfig.appBaseUrl,\n `Infra \"appDomainName\" (${infraConfig.appDomainName}) does not match server \"appBaseUrl\" (${serverConfig.appBaseUrl})`\n );\n\n checkConflict(\n infraConfig.storageDomainName && `https://${infraConfig.storageDomainName}/binary/`,\n serverConfig.storageBaseUrl,\n `Infra \"storageDomainName\" (${infraConfig.storageDomainName}) does not match server \"storageBaseUrl\" (${serverConfig.storageBaseUrl})`\n );\n}\n\nfunction checkConflict<T>(a: T, b: T, message: string): void {\n if (isConflict(a, b)) {\n throw new Error(message);\n }\n}\n\nfunction isConflict<T>(a: T, b: T): boolean {\n return a !== undefined && b !== undefined && a !== b;\n}\n\nexport function mergeConfigs(infraConfig: MedplumInfraConfig, serverConfig: Record<string, string | number>): void {\n if (infraConfig.apiPort) {\n serverConfig.port = infraConfig.apiPort;\n }\n if (infraConfig.baseUrl) {\n serverConfig.baseUrl = infraConfig.baseUrl;\n }\n if (infraConfig.appDomainName) {\n serverConfig.appBaseUrl = `https://${infraConfig.appDomainName}/`;\n }\n if (infraConfig.storageDomainName) {\n serverConfig.storageBaseUrl = `https://${infraConfig.storageDomainName}/binary/`;\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, MedplumClientOptions, MedplumInfraConfig } from '@medplum/core';\nimport { spawnSync } from 'node:child_process';\nimport * as semver from 'semver';\nimport { createMedplumClient } from '../util/client';\nimport { getConfigFileName, readConfig, writeConfig } from '../utils';\nimport { getServerVersions, printConfigNotFound } from './utils';\n\nexport interface UpdateServerOptions extends MedplumClientOptions {\n file?: string;\n toVersion?: string;\n}\n\n/**\n * The AWS \"update-server\" command updates the Medplum server in a Medplum CloudFormation stack.\n * @param tag - The Medplum stack tag.\n * @param options - Client options\n */\nexport async function updateServerCommand(tag: string, options: UpdateServerOptions): Promise<void> {\n const client = await createMedplumClient(options);\n const config = readConfig(tag, options) as MedplumInfraConfig;\n if (!config) {\n console.log(`Configuration file ${getConfigFileName(tag)} not found`);\n printConfigNotFound(tag, options);\n throw new Error(`Config not found: ${tag}`);\n }\n\n const separatorIndex = config.serverImage.lastIndexOf(':');\n const serverImagePrefix = config.serverImage.slice(0, separatorIndex);\n\n const initialVersion = await getCurrentVersion(client, config);\n\n let updateVersion = await nextUpdateVersion(initialVersion);\n while (updateVersion) {\n if (options.toVersion && semver.gt(updateVersion, options.toVersion)) {\n console.log(`Skipping update to v${updateVersion}`);\n break;\n }\n\n console.log(`Performing update to v${updateVersion}`);\n config.serverImage = `${serverImagePrefix}:${updateVersion}`;\n deployServerUpdate(tag, config);\n\n // Run data migrations\n await client.startAsyncRequest('/admin/super/migrate');\n\n updateVersion = await nextUpdateVersion(updateVersion);\n }\n}\n\nasync function getCurrentVersion(medplum: MedplumClient, config: MedplumInfraConfig): Promise<string> {\n const separatorIndex = config.serverImage.lastIndexOf(':');\n let initialVersion = config.serverImage.slice(separatorIndex + 1);\n if (initialVersion === 'latest') {\n const serverInfo = await medplum.get('/healthcheck');\n initialVersion = serverInfo.version as string;\n const sep = initialVersion.indexOf('-');\n if (sep > -1) {\n initialVersion = initialVersion.slice(0, sep);\n }\n }\n return initialVersion;\n}\n\nasync function nextUpdateVersion(currentVersion: string, targetVersion?: string): Promise<string | undefined> {\n // The list of server versions is sorted in descending order\n // The first entry is the latest version\n // The last entry is the oldest version\n // We want to find the \"next\" version after our current version\n // Filter the list to only include versions that are greater than or equal to the current minor version\n // Then pop the last entry from the list\n const allVersions = await getServerVersions(currentVersion);\n const latestVersion = allVersions[0];\n return allVersions\n .filter(\n (v) => v === latestVersion || v === targetVersion || semver.gte(v, semver.inc(currentVersion, 'minor') as string)\n )\n .pop();\n}\n\nfunction deployServerUpdate(tag: string, config: MedplumInfraConfig): void {\n const configFile = getConfigFileName(tag);\n writeConfig(configFile, config);\n\n const cmd = `npx cdk deploy -c config=${configFile}${config.region !== 'us-east-1' ? ' --all' : ''}`;\n console.log('> ' + cmd);\n const deploy = spawnSync(cmd, { stdio: 'inherit' });\n\n if (deploy.status !== 0) {\n throw new Error(`Deploy of ${config.serverImage} failed (exit code ${deploy.status}): ${deploy.stderr}`);\n }\n console.log(deploy.stdout);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { color, processDescription } from '../util/color';\nimport { addSubcommand, MedplumCommand } from '../utils';\nimport { describeStacksCommand } from './describe';\nimport { initStackCommand } from './init';\nimport { listStacksCommand } from './list';\nimport { updateAppCommand } from './update-app';\nimport { updateBucketPoliciesCommand } from './update-bucket-policies';\nimport { updateConfigCommand } from './update-config';\nimport { updateServerCommand } from './update-server';\n\nexport function buildAwsCommand(): MedplumCommand {\n const aws = new MedplumCommand('aws').description('Commands to manage AWS resources');\n\n aws.command('init').description('Initialize a new Medplum AWS CloudFormation stacks').action(initStackCommand);\n\n aws.command('list').description('List Medplum AWS CloudFormation stacks').action(listStacksCommand);\n\n aws\n .command('describe')\n .description('Describe a Medplum AWS CloudFormation stack by tag')\n .argument('<tag>', 'The Medplum stack tag')\n .action(describeStacksCommand);\n\n aws\n .command('update-config')\n .alias('deploy-config')\n .summary('Update the AWS Parameter Store config values.')\n .description(\n processDescription(\n 'Update the AWS Parameter Store config values.\\n\\nConfiguration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.\\n\\n' +\n color.yellow('**Services must be restarted to apply changes.**')\n )\n )\n .argument('<tag>', 'The Medplum stack tag')\n .option(\n '--file [file]',\n processDescription(\n 'File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.'\n )\n )\n .option(\n '--dryrun',\n 'Displays the operations that would be performed using the specified command without actually running them.'\n )\n .option('--yes', 'Automatically confirm the update')\n .action(updateConfigCommand);\n\n addSubcommand(\n aws,\n new MedplumCommand('update-server')\n .alias('deploy-server')\n .description('Update the server image')\n .argument('<tag>', 'The Medplum stack tag')\n .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n .option(\n '--to-version [version]',\n 'Specifies the version of the configuration to update. If not specified, the latest version is updated.'\n )\n .action(updateServerCommand)\n );\n\n aws\n .command('update-app')\n .alias('deploy-app')\n .description('Update the app site')\n .argument('<tag>', 'The Medplum stack tag')\n .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n .option(\n '--to-version [version]',\n 'Specifies the version of the configuration to update. If not specified, the latest version is updated.'\n )\n .option(\n '--dryrun',\n 'Displays the operations that would be performed using the specified command without actually running them.'\n )\n .option('--tar-path [tarPath]', 'Specifies the path to the extracted tarball of the @medplum/app package.')\n .action(updateAppCommand);\n\n aws\n .command('update-bucket-policies')\n .description('Update S3 bucket policies')\n .argument('<tag>', 'The Medplum stack tag')\n .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n .option(\n '--guardduty-malware-protection',\n 'Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.'\n )\n .option(\n '--dryrun',\n 'Displays the operations that would be performed using the specified command without actually running them.'\n )\n .action(updateBucketPoliciesCommand);\n\n return aws;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { createMedplumClient } from './util/client';\nimport { MedplumCommand, addSubcommand, createBot, deployBot, readBotConfigs, saveBot } from './utils';\n\nconst botSaveCommand = new MedplumCommand('save');\nconst botDeployCommand = new MedplumCommand('deploy');\nconst botCreateCommand = new MedplumCommand('create');\n\nexport const bot = new MedplumCommand('bot');\naddSubcommand(bot, botSaveCommand);\naddSubcommand(bot, botDeployCommand);\naddSubcommand(bot, botCreateCommand);\n\n// Commands to deprecate\nexport const saveBotDeprecate = new MedplumCommand('save-bot');\nexport const deployBotDeprecate = new MedplumCommand('deploy-bot');\nexport const createBotDeprecate = new MedplumCommand('create-bot');\n\nbotSaveCommand\n .description('Saving the bot')\n .argument('<botName>')\n .action(async (botName, options) => {\n const medplum = await createMedplumClient(options);\n\n await botWrapper(medplum, botName);\n });\n\nbotDeployCommand\n .description('Deploy the app to AWS')\n .argument('<botName>')\n .action(async (botName, options) => {\n const medplum = await createMedplumClient(options);\n\n await botWrapper(medplum, botName, true);\n });\n\nbotCreateCommand\n .arguments('<botName> <projectId> <sourceFile> <distFile>')\n .description('Creating a bot')\n .option('--runtime-version <runtimeVersion>', 'Runtime version (awslambda, vmcontext)')\n .option('--no-write-config', 'Do not write bot to config')\n .action(async (botName, projectId, sourceFile, distFile, options) => {\n const medplum = await createMedplumClient(options);\n\n await createBot(medplum, botName, projectId, sourceFile, distFile, options.runtimeVersion, !!options.writeConfig);\n });\n\nexport async function botWrapper(medplum: MedplumClient, botName: string, deploy = false): Promise<void> {\n const botConfigs = readBotConfigs(botName);\n const errors = [] as Error[];\n const errored = [] as string[];\n let saved = 0;\n let deployed = 0;\n\n for (const botConfig of botConfigs) {\n try {\n const bot = await medplum.readResource('Bot', botConfig.id);\n await saveBot(medplum, botConfig, bot);\n saved++;\n if (deploy) {\n await deployBot(medplum, botConfig, bot);\n deployed++;\n }\n } catch (err: unknown) {\n errors.push(err as Error);\n errored.push(`${botConfig.name} [${botConfig.id}]`);\n }\n }\n\n console.log(`Number of bots saved: ${saved}`);\n console.log(`Number of bots deployed: ${deployed}`);\n console.log(`Number of errors: ${errors.length}`);\n\n if (errors.length) {\n throw new Error(`${errors.length} bot(s) had failures. Bots with failures:\\n\\n ${errored.join('\\n ')}`, {\n cause: errors,\n });\n }\n}\n\n// Deprecate bot commands\nsaveBotDeprecate\n .description('Saves the bot')\n .argument('<botName>')\n .action(async (botName, options) => {\n const medplum = await createMedplumClient(options);\n\n await botWrapper(medplum, botName);\n });\n\ndeployBotDeprecate\n .description('Deploy the bot to AWS')\n .argument('<botName>')\n .action(async (botName, options) => {\n const medplum = await createMedplumClient(options);\n\n await botWrapper(medplum, botName, true);\n });\n\ncreateBotDeprecate\n .arguments('<botName> <projectId> <sourceFile> <distFile>')\n .description('Creates and saves the bot')\n .action(async (botName, projectId, sourceFile, distFile, options) => {\n const medplum = await createMedplumClient(options);\n\n await createBot(medplum, botName, projectId, sourceFile, distFile);\n });\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { EMPTY, getRateLimitReset, getStatus, OperationOutcomeError, sleep } from '@medplum/core';\nimport type { BundleEntry, ExplanationOfBenefit, ExplanationOfBenefitItem, Resource } from '@medplum/fhirtypes';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { createInterface } from 'node:readline';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport type { ReadableStream } from 'node:stream/web';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, getUnsupportedExtension, MedplumCommand, prettyPrint } from './utils';\n\nconst bulkExportCommand = new MedplumCommand('export');\nconst bulkImportCommand = new MedplumCommand('import');\n\nexport const bulk = new MedplumCommand('bulk');\naddSubcommand(bulk, bulkExportCommand);\naddSubcommand(bulk, bulkImportCommand);\n\nbulkExportCommand\n .option(\n '-e, --export-level <exportLevel>',\n 'Optional export level. Defaults to system level export. \"Group/:id\" - Group of Patients, \"Patient\" - All Patients.'\n )\n .option('-t, --types <types>', 'optional resource types to export')\n .option(\n '-s, --since <since>',\n '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).'\n )\n .option(\n '-d, --target-directory <targetDirectory>',\n 'optional target directory to save files from the bulk export operations.'\n )\n .action(async (options) => {\n const { exportLevel, types, since, targetDirectory } = options;\n const medplum = await createMedplumClient(options);\n const response = await medplum.bulkExport(exportLevel, types, since, { pollStatusOnAccepted: true });\n\n for (const { type, url } of response.output ?? EMPTY) {\n const fileUrl = new URL(url);\n const fileName = `${type}_${fileUrl.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g, '_') + '.ndjson';\n const path = resolve(targetDirectory ?? '', fileName);\n\n const res = await medplum.downloadResponse(url);\n if (!res.ok) {\n throw new Error(`Download failed: ${res.status} ${res.statusText}`);\n }\n if (!res.body) {\n throw new Error('Download response missing body');\n }\n\n const nodeStream = Readable.fromWeb(res.body as ReadableStream<Uint8Array>);\n await pipeline(nodeStream, createWriteStream(path));\n console.log(`${path} is created`);\n }\n });\n\nbulkImportCommand\n .argument('<filename>', 'File Name')\n .option(\n '--num-resources-per-request <numResourcesPerRequest>',\n 'optional number of resources to import per batch request. Defaults to 25.',\n '25'\n )\n .option(\n '--add-extensions-for-missing-values',\n 'optional flag to add extensions for missing values in a resource',\n false\n )\n .option('-d, --target-directory <targetDirectory>', 'optional target directory of file to be imported')\n .action(async (fileName, options) => {\n const { numResourcesPerRequest, addExtensionsForMissingValues, targetDirectory } = options;\n const path = resolve(targetDirectory ?? process.cwd(), fileName);\n const medplum = await createMedplumClient(options);\n\n await importFile(path, Number.parseInt(numResourcesPerRequest, 10), medplum, addExtensionsForMissingValues);\n });\n\nasync function importFile(\n path: string,\n numResourcesPerRequest: number,\n medplum: MedplumClient,\n addExtensionsForMissingValues: boolean\n): Promise<void> {\n let entries: BundleEntry[] = [];\n const fileStream = createReadStream(path);\n const rl = createInterface({\n input: fileStream,\n });\n\n for await (const line of rl) {\n const resource = parseResource(line, addExtensionsForMissingValues);\n entries.push({\n resource: resource,\n request: {\n method: 'POST',\n url: resource.resourceType,\n },\n });\n if (entries.length % numResourcesPerRequest === 0) {\n await sendBatchEntries(entries, medplum);\n entries = [];\n }\n }\n if (entries.length > 0) {\n await sendBatchEntries(entries, medplum);\n }\n}\n\nasync function sendBatchEntries(entries: BundleEntry[], medplum: MedplumClient): Promise<void> {\n let pendingEntries = entries;\n while (pendingEntries.length > 0) {\n let result;\n try {\n result = await medplum.executeBatch(\n {\n resourceType: 'Bundle',\n type: 'transaction',\n entry: pendingEntries,\n },\n { maxRetries: 0 }\n );\n } catch (err) {\n if (!(err instanceof OperationOutcomeError) || getStatus(err.outcome) !== 429) {\n throw err;\n }\n await sleep(getRateLimitRetryDelay(err.outcome, medplum));\n continue;\n }\n\n const retryEntries: BundleEntry[] = [];\n for (let i = 0; i < pendingEntries.length; i++) {\n const resultEntry = result.entry?.[i];\n if (resultEntry?.response?.outcome && getStatus(resultEntry.response.outcome) === 429) {\n retryEntries.push(pendingEntries[i]);\n } else {\n prettyPrint(resultEntry?.response);\n }\n }\n if (retryEntries.length > 0) {\n const rateLimitOutcome = result.entry?.find(\n (entry) => entry.response?.outcome && getStatus(entry.response.outcome) === 429\n )?.response?.outcome;\n await sleep(getRateLimitRetryDelay(rateLimitOutcome, medplum));\n }\n pendingEntries = retryEntries;\n }\n}\n\nfunction getRateLimitRetryDelay(\n outcome: NonNullable<BundleEntry['response']>['outcome'] | undefined,\n medplum: MedplumClient\n): number {\n const outcomeDelay = outcome && getRateLimitReset(outcome);\n if (outcomeDelay !== undefined) {\n return outcomeDelay;\n }\n return Math.max(\n 500,\n ...medplum\n .rateLimitStatus()\n .filter((limit) => limit.remainingUnits === 0)\n .map((limit) => limit.secondsUntilReset * 1000)\n );\n}\n\nfunction parseResource(jsonString: string, addExtensionsForMissingValues: boolean): Resource {\n const resource = JSON.parse(jsonString);\n\n if (addExtensionsForMissingValues) {\n return addExtensionsForMissingValuesResource(resource);\n }\n\n return resource;\n}\n\nfunction addExtensionsForMissingValuesResource(resource: Resource): Resource {\n if (resource.resourceType === 'ExplanationOfBenefit') {\n return addExtensionsForMissingValuesExplanationOfBenefits(resource);\n }\n return resource;\n}\n\nfunction addExtensionsForMissingValuesExplanationOfBenefits(resource: ExplanationOfBenefit): ExplanationOfBenefit {\n if (!resource.provider) {\n resource.provider = getUnsupportedExtension();\n }\n\n resource.item?.forEach((item: ExplanationOfBenefitItem) => {\n if (!item?.productOrService) {\n item.productOrService = getUnsupportedExtension();\n }\n });\n\n return resource;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport fastGlob from 'fast-glob';\nimport { once } from 'node:events';\nimport { createReadStream } from 'node:fs';\nimport { open, stat } from 'node:fs/promises';\nimport { basename, extname, resolve } from 'node:path';\nimport { PassThrough } from 'node:stream';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nconst DEFAULT_BATCH_SIZE = 25;\n\n/** Extensions unambiguously used for DICOM, to recognize raw datasets that carry no File Meta Information. */\nconst DICOM_EXTENSIONS = new Set(['.dcm', '.dicom', '.ima']);\n\n/** A DICOM Part 10 file starts with a 128 byte preamble followed by the \"DICM\" prefix. */\nconst DICOM_PREFIX = Buffer.from('DICM');\nconst DICOM_PREFIX_OFFSET = 128;\nconst DICOM_HEADER_LENGTH = DICOM_PREFIX_OFFSET + DICOM_PREFIX.length;\n\n/** The File Meta Information group, which a Part 10 file without a preamble starts with. */\nconst FILE_META_GROUP = 0x0002;\n\n/**\n * Returns true if the file appears to be a storable DICOM instance.\n *\n * Only used when expanding directories and glob patterns, where the user did not name the file\n * explicitly, so that stray files such as READMEs or JPEG previews do not get sent to the server.\n *\n * The two content checks mirror what the server's reader accepts, so that this does not reject\n * files the server would have stored. It accepts a third encoding - a raw dataset with no File\n * Meta Information - which has no distinguishing header to test for, hence the extension fallback.\n * @param filePath - The candidate file path.\n * @returns True if the file should be sent as a DICOM instance.\n */\nasync function isDicomFile(filePath: string): Promise<boolean> {\n // DICOMDIR is a media directory record rather than a storable instance\n if (basename(filePath).toUpperCase() === 'DICOMDIR') {\n return false;\n }\n\n const handle = await open(filePath, 'r');\n try {\n const buffer = Buffer.alloc(DICOM_HEADER_LENGTH);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n if (bytesRead === buffer.length && buffer.subarray(DICOM_PREFIX_OFFSET).equals(DICOM_PREFIX)) {\n return true;\n }\n // File Meta Information is always encoded little-endian, so the leading group number is too\n if (bytesRead >= 2 && buffer.readUInt16LE(0) === FILE_META_GROUP) {\n return true;\n }\n } finally {\n await handle.close();\n }\n\n return DICOM_EXTENSIONS.has(extname(filePath).toLowerCase());\n}\n\n/**\n * Expands the command line file arguments into a sorted list of DICOM file paths.\n *\n * Each input can be a file, a directory (searched recursively), or a glob pattern. Note that\n * POSIX shells expand unquoted patterns such as `*.dcm` before the CLI runs, so patterns only\n * reach here when quoted by the user or when running on a shell that does not expand them.\n * @param inputs - The file, directory, and glob pattern arguments.\n * @returns The de-duplicated and sorted list of absolute DICOM file paths.\n */\nexport async function resolveDicomFiles(inputs: string[]): Promise<string[]> {\n const results = new Set<string>();\n for (const input of inputs) {\n const stats = await stat(input).catch(() => undefined);\n if (stats?.isFile()) {\n // Explicitly named files are always sent, even if they do not look like DICOM\n results.add(resolve(input));\n continue;\n }\n\n let matches: string[];\n if (stats?.isDirectory()) {\n matches = await fastGlob('**/*', { cwd: input, onlyFiles: true, absolute: true });\n } else if (fastGlob.isDynamicPattern(input)) {\n // Matched case-insensitively because DICOM extensions are inconsistently cased in the wild,\n // and `*.dcm` silently matching none of a directory of `.DCM` files helps nobody\n matches = await fastGlob(input, { onlyFiles: true, absolute: true, caseSensitiveMatch: false });\n } else {\n throw new Error(`File not found: ${input}`);\n }\n\n let skipped = 0;\n for (const match of matches) {\n if (await isDicomFile(match)) {\n results.add(match);\n } else {\n skipped++;\n }\n }\n if (skipped > 0) {\n console.log(`Skipped ${skipped} non-DICOM file(s) in \"${input}\"`);\n }\n }\n return Array.from(results).sort((a, b) => a.localeCompare(b));\n}\n\nasync function writeBuffer(stream: PassThrough, buffer: Buffer): Promise<void> {\n if (!stream.write(buffer)) {\n await once(stream, 'drain');\n }\n}\n\nasync function pipeFileToStream(filePath: string, out: PassThrough): Promise<void> {\n const fileStream = createReadStream(filePath);\n try {\n for await (const chunk of fileStream) {\n if (!out.write(chunk as Buffer)) {\n await once(out, 'drain');\n }\n }\n } finally {\n fileStream.destroy();\n }\n}\n\nexport async function writeMultipartRelatedBody(\n out: PassThrough,\n filePaths: string[],\n boundary: string\n): Promise<void> {\n try {\n for (const filePath of filePaths) {\n await writeBuffer(out, Buffer.from(`--${boundary}\\r\\n`));\n await writeBuffer(out, Buffer.from('Content-Type: application/dicom\\r\\n'));\n await writeBuffer(out, Buffer.from('\\r\\n'));\n await pipeFileToStream(filePath, out);\n await writeBuffer(out, Buffer.from('\\r\\n'));\n }\n await writeBuffer(out, Buffer.from(`--${boundary}--\\r\\n`));\n out.end();\n } catch (err) {\n out.destroy(err as Error);\n throw err;\n }\n}\n\nconst stow = new MedplumCommand('stow')\n .description('Send DICOM instances via DICOMweb STOW-RS')\n .argument('<files...>', 'DICOM files, directories, or quoted glob patterns to send')\n .option('--batch-size <count>', 'Maximum number of instances per STOW-RS request', String(DEFAULT_BATCH_SIZE))\n .action(async (files: string[], options) => {\n const batchSize = Number.parseInt(options.batchSize, 10);\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new Error(`Invalid batch size: ${options.batchSize}`);\n }\n\n const filePaths = await resolveDicomFiles(files);\n if (filePaths.length === 0) {\n throw new Error('No DICOM files found');\n }\n console.log(`Sending ${filePaths.length} DICOM file(s)`);\n\n const medplum = await createMedplumClient(options);\n for (let i = 0; i < filePaths.length; i += batchSize) {\n const batch = filePaths.slice(i, i + batchSize);\n const boundary = `medplum-${Date.now()}`;\n const contentType = `multipart/related; type=application/dicom; boundary=${boundary}`;\n const stream = new PassThrough();\n const writePromise = writeMultipartRelatedBody(stream, batch, boundary);\n const requestPromise = medplum.post('/dicomweb/studies', stream, contentType);\n await writePromise;\n const text = await requestPromise;\n console.log('STOW-RS response received', text);\n }\n });\n\nexport const dicomweb = new MedplumCommand('dicomweb');\naddSubcommand(dicomweb, stow);\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { formatHl7DateTime, Hl7Message } from '@medplum/core';\nimport { Hl7Client, Hl7Server } from '@medplum/hl7';\nimport { readFileSync } from 'node:fs';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nconst send = new MedplumCommand('send')\n .description('Send an HL7 v2 message via MLLP')\n .argument('<host>', 'The destination host name or IP address')\n .argument('<port>', 'The destination port number')\n .argument('[body]', 'Optional HL7 message body')\n .option('--generate-example', 'Generate a sample HL7 message')\n .option('--file <file>', 'Read the HL7 message from a file')\n .option('--encoding <encoding>', 'The encoding to use')\n .action(async (host, port, body, options) => {\n if (options.generateExample) {\n body = generateSampleHl7Message();\n } else if (options.file) {\n body = readFileSync(options.file, 'utf8');\n }\n\n if (!body) {\n throw new Error('Missing HL7 message body');\n }\n\n const client = new Hl7Client({\n host,\n port: Number.parseInt(port, 10),\n encoding: options.encoding,\n });\n\n try {\n const response = await client.sendAndWait(Hl7Message.parse(body));\n console.log(response.toString().replaceAll('\\r', '\\n'));\n } finally {\n await client.close();\n }\n });\n\nconst listen = new MedplumCommand('listen')\n .description('Starts an HL7 v2 MLLP server')\n .argument('<port>')\n .option('--encoding <encoding>', 'The encoding to use')\n .action(async (port, options) => {\n const server = new Hl7Server((connection) => {\n connection.addEventListener('message', ({ message }) => {\n console.log(message.toString().replaceAll('\\r', '\\n'));\n connection.send(message.buildAck());\n });\n });\n\n await server.start(Number.parseInt(port, 10), options.encoding);\n console.log('Listening on port ' + port);\n });\n\nexport const hl7 = new MedplumCommand('hl7');\naddSubcommand(hl7, send);\naddSubcommand(hl7, listen);\n\nexport function generateSampleHl7Message(): string {\n const now = formatHl7DateTime(new Date());\n const controlId = Date.now().toString();\n return `MSH|^~\\\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${now}||ADT^A01|${controlId}|P|2.5|\nEVN|A01|${now}||\nPID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|\nPV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7CloseEvent, Hl7EnhancedAckSentEvent, Hl7ErrorEvent, Hl7MessageEvent, Hl7WarningEvent } from './events';\n\nexport interface Hl7EventMap {\n message: Hl7MessageEvent;\n error: Hl7ErrorEvent;\n warning: Hl7WarningEvent;\n close: Hl7CloseEvent;\n enhancedAckSent: Hl7EnhancedAckSentEvent;\n}\n\nexport abstract class Hl7Base extends EventTarget {\n addEventListener<K extends keyof Hl7EventMap>(\n type: K,\n listener: ((event: Hl7EventMap[K]) => void) | EventListenerObject | null,\n options?: boolean | AddEventListenerOptions\n ): void;\n\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n super.addEventListener(type, listener, options);\n }\n removeEventListener<K extends keyof Hl7EventMap>(\n type: K,\n listener: ((event: Hl7EventMap[K]) => void) | EventListenerObject | null,\n options?: boolean | AddEventListenerOptions\n ): void;\n\n removeEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n super.removeEventListener(type, listener, options);\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7Message } from '@medplum/core';\nimport assert from 'node:assert';\nimport type { Socket } from 'node:net';\nimport net from 'node:net';\nimport { Hl7Base } from './base';\nimport type { EnhancedMode, Hl7ConnectionOptions, SendAndWaitOptions } from './connection';\nimport { Hl7Connection } from './connection';\nimport { Hl7CloseEvent, Hl7ErrorEvent, Hl7WarningEvent } from './events';\n\nexport interface Hl7ClientOptions {\n host: string;\n port: number;\n encoding?: string;\n keepAlive?: boolean;\n connectTimeout?: number; // Add timeout option\n}\n\nexport interface DeferredConnectionPromise {\n promise: Promise<Hl7Connection>;\n resolve: (connection: Hl7Connection) => void;\n reject: (err: Error) => void;\n}\n\nexport class Hl7Client extends Hl7Base {\n options: Hl7ClientOptions;\n host: string;\n port: number;\n encoding?: string;\n connection?: Hl7Connection;\n keepAlive: boolean;\n private socket?: Socket;\n private connectTimeout: number;\n private deferredConnectionPromise?: DeferredConnectionPromise;\n\n constructor(options: Hl7ClientOptions) {\n super();\n this.options = options;\n this.host = this.options.host;\n this.port = this.options.port;\n this.encoding = this.options.encoding;\n this.keepAlive = this.options.keepAlive ?? false;\n this.connectTimeout = this.options.connectTimeout ?? 30000; // Default 30 seconds\n }\n\n connect(): Promise<Hl7Connection> {\n // If we are already waiting for a pending connection attempt, just return the deferred promise to that\n // In the case that the promise is already resolve, we will also return a resolved connection\n if (this.deferredConnectionPromise) {\n return this.deferredConnectionPromise.promise;\n }\n\n const deferredPromise = (this.deferredConnectionPromise = this.createDeferredConnectionPromise());\n\n // Create the socket\n this.socket = net.connect({\n host: this.host,\n port: this.port,\n keepAlive: this.keepAlive,\n });\n\n if (this.connectTimeout > 0) {\n this.socket.setTimeout(this.connectTimeout);\n this.registerSocketTimeoutListener(deferredPromise);\n }\n\n this.registerSocketConnectListener(deferredPromise);\n this.registerSocketErrorListener(deferredPromise);\n this.registerSocketCloseListener(deferredPromise);\n\n return deferredPromise.promise;\n }\n\n private registerSocketTimeoutListener(deferredPromise: DeferredConnectionPromise): void {\n assert(this.socket);\n const socket = this.socket;\n\n // Handle timeout event\n const timeoutListener = (): void => {\n this.cleanupSocket(socket);\n const error = new Error(`Connection timeout after ${this.connectTimeout}ms`);\n this.rejectDeferredPromise(deferredPromise, error);\n };\n\n socket.on('timeout', timeoutListener);\n }\n\n private registerSocketConnectListener(deferredPromise: DeferredConnectionPromise): void {\n assert(this.socket);\n const socket = this.socket;\n\n // Handle successful connection\n const connectListener = (): void => {\n if (socket !== this.socket) {\n this.cleanupSocket(socket);\n return;\n }\n\n // Create the HL7 connection via the factory method (allows subclasses to customize)\n let connection: Hl7Connection;\n this.connection = connection = this.createConnection(socket, this.encoding);\n\n // Remove the timeout listener as we're now connected\n socket.setTimeout(0);\n\n this.registerHl7ConnectionListeners(connection);\n\n deferredPromise.resolve(connection);\n };\n\n socket.on('connect', connectListener);\n }\n\n private registerSocketErrorListener(deferredPromise: DeferredConnectionPromise): void {\n assert(this.socket);\n const socket = this.socket;\n\n // Handle connection errors\n const errorListener = (err: Error | AggregateError): void => {\n this.cleanupSocket(socket);\n\n if (err.constructor.name === 'AggregateError') {\n this.rejectDeferredPromise(deferredPromise, (err as AggregateError).errors[0]);\n } else {\n this.rejectDeferredPromise(deferredPromise, err);\n }\n };\n\n socket.on('error', errorListener);\n }\n\n private registerSocketCloseListener(deferredPromise: DeferredConnectionPromise): void {\n assert(this.socket);\n const socket = this.socket;\n\n // Handle connection errors\n const closeListener = (): void => {\n this.cleanupSocket(socket);\n this.rejectDeferredPromise(deferredPromise, new Error('Socket closed before connection finished'));\n };\n socket.on('close', closeListener);\n }\n\n private registerHl7ConnectionListeners(connection: Hl7Connection): void {\n // Set up event handlers\n connection.addEventListener('close', () => {\n this.socket = undefined;\n this.connection = undefined;\n this.deferredConnectionPromise = undefined;\n this.dispatchEvent(new Hl7CloseEvent());\n });\n\n connection.addEventListener('error', (event) => {\n this.dispatchEvent(new Hl7ErrorEvent(event.error));\n });\n\n connection.addEventListener('warning', (event) => {\n this.dispatchEvent(new Hl7WarningEvent(event.error));\n });\n }\n\n private createDeferredConnectionPromise(): DeferredConnectionPromise {\n // Setup our deferred connection promise\n let resolve!: (connection: Hl7Connection) => void;\n let reject!: (err: Error) => void;\n\n const promise = new Promise<Hl7Connection>((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n\n return {\n promise,\n resolve,\n reject,\n };\n }\n\n private rejectDeferredPromise(deferredPromise: DeferredConnectionPromise, err: Error): void {\n // Reject this deferred promise with the given error\n deferredPromise.reject(err);\n\n // If the currently tracked deferred promise is this deferred promise, remove it from the client\n if (this.deferredConnectionPromise === deferredPromise) {\n this.deferredConnectionPromise = undefined;\n }\n }\n\n private cleanupSocket(socket: Socket): void {\n if (!socket.destroyed) {\n socket.destroy();\n }\n if (socket === this.socket) {\n this.socket = undefined;\n }\n }\n\n /**\n * Creates an `Hl7Connection` for the given socket.\n *\n * Subclasses may override this to return a customized connection\n * (e.g. one that delegates pending message tracking to a shared tracker).\n * @param socket - The connected socket.\n * @param encoding - The character encoding to use.\n * @param enhancedMode - Optional enhanced mode for the connection.\n * @param options - Optional connection options.\n * @returns A new `Hl7Connection`.\n */\n protected createConnection(\n socket: Socket,\n encoding?: string,\n enhancedMode?: EnhancedMode,\n options?: Hl7ConnectionOptions\n ): Hl7Connection {\n return new Hl7Connection(socket, encoding, enhancedMode, options);\n }\n\n async send(msg: Hl7Message): Promise<void> {\n return (await this.connect()).send(msg);\n }\n\n async sendAndWait(msg: Hl7Message, options?: SendAndWaitOptions): Promise<Hl7Message> {\n return (await this.connect()).sendAndWait(msg, options);\n }\n\n async close(): Promise<void> {\n if (this.deferredConnectionPromise) {\n this.rejectDeferredPromise(this.deferredConnectionPromise, new Error('Client closed while connecting'));\n }\n\n // Close established connection if it exists\n if (this.connection) {\n const connection = this.connection;\n delete this.connection;\n await connection.close();\n } else {\n // Emit close event because the connection will not be able to emit it for us\n // Since it has not connected at this point\n this.dispatchEvent(new Hl7CloseEvent());\n }\n // Close the socket if it exists\n if (this.socket) {\n this.socket.removeAllListeners();\n this.socket.destroy();\n this.socket = undefined;\n }\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Hl7Message, OperationOutcomeError, ReturnAckCategory, sleep, validationError } from '@medplum/core';\nimport iconv from 'iconv-lite';\nimport type net from 'node:net';\nimport { Hl7Base } from './base';\nimport { CR, FS, VT } from './constants';\nimport { Hl7CloseEvent, Hl7EnhancedAckSentEvent, Hl7ErrorEvent, Hl7MessageEvent, Hl7WarningEvent } from './events';\n\n// Export `ReturnAckCategory` for backwards-compat\nexport { ReturnAckCategory } from '@medplum/core';\n\n// iconv-lite docs have great examples and explanations for how to use Buffers with iconv-lite:\n// See: https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding\n\nexport type Hl7MessageQueueItem = {\n message: Hl7Message;\n resolve: (reply: Hl7Message) => void;\n reject: (err: Error) => void;\n returnAck: ReturnAckCategory;\n timer?: NodeJS.Timeout;\n};\n\nexport interface SendAndWaitOptions {\n /** The ACK-level that the Promise should resolve on. The default is `ReturnAckCategory.APPLICATION` (returns on the first application-level ACK). */\n returnAck?: ReturnAckCategory;\n /** The amount of milliseconds to wait before timing out when waiting for the response to a message. */\n timeoutMs?: number;\n}\n\nexport interface Hl7ConnectionOptions {\n messagesPerMin?: number;\n gracefulCloseTimeoutMs?: number;\n}\n\n/**\n * Enhanced mode for HL7 connections.\n * - `'standard'`: Standard enhanced mode behavior\n * - `'aaMode'`: AA mode - special enhanced mode that only accepts AA acknowledgements\n * - `undefined`: Enhanced mode is not enabled (standard behavior)\n */\nexport type EnhancedMode = 'standard' | 'aaMode' | undefined;\n\nexport const DEFAULT_ENCODING = 'utf-8';\nexport const GRACEFUL_CLOSE_TIMEOUT_MS = 5000;\nconst ONE_MINUTE = 60 * 1000;\n\nexport class Hl7Connection extends Hl7Base {\n readonly socket: net.Socket;\n encoding: string;\n enhancedMode: EnhancedMode = undefined;\n private messagesPerMin: number | undefined = undefined;\n private gracefulCloseTimeoutMs: number;\n private chunks: Buffer[] = [];\n private readonly pendingMessages: Map<string, Hl7MessageQueueItem> = new Map<string, Hl7MessageQueueItem>();\n private readonly responseQueue: Hl7MessageEvent[] = [];\n private lastMessageDispatchedTime = 0;\n private responseQueueProcessing = false;\n private closing = false;\n\n constructor(\n socket: net.Socket,\n encoding: string = DEFAULT_ENCODING,\n enhancedMode?: EnhancedMode,\n options: Hl7ConnectionOptions = {}\n ) {\n super();\n\n this.socket = socket;\n this.encoding = encoding;\n this.enhancedMode = enhancedMode;\n this.messagesPerMin = options.messagesPerMin;\n this.gracefulCloseTimeoutMs = options.gracefulCloseTimeoutMs ?? GRACEFUL_CLOSE_TIMEOUT_MS;\n\n socket.on('data', (data: Buffer) => {\n if (this.closing) {\n this.dispatchEvent(\n new Hl7WarningEvent(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'warning',\n code: 'transient',\n details: {\n text: 'Data received after close was initiated',\n },\n },\n ],\n })\n )\n );\n return;\n }\n try {\n this.appendData(data);\n const messages = this.parseMessages();\n for (const message of messages) {\n this.responseQueue.push(new Hl7MessageEvent(this, message));\n }\n this.processResponseQueue().catch((err) => {\n this.dispatchEvent(new Hl7ErrorEvent(err));\n });\n } catch (err) {\n this.dispatchEvent(new Hl7ErrorEvent(err as Error));\n }\n });\n\n socket.on('error', (err) => {\n this.resetBuffer();\n this.dispatchEvent(new Hl7ErrorEvent(err));\n });\n\n // The difference between \"end\" and \"close\", is that \"end\" is only emitted on half-close from the other side\n // If the connection from the other side does not close gracefully, but instead we destroy the socket, then the Hl7Connection will not emit close\n // if we listen only for \"end\"; \"close\" is always emitted, whether the close is graceful or forceful\n socket.on('close', () => {\n // Reject any messages that were still pending when the connection was closed externally (e.g. closed by peer)\n this.drainPendingMessages();\n this.dispatchEvent(new Hl7CloseEvent());\n });\n\n this.addEventListener('message', (event) => {\n // In standard enhanced mode, send commit ACK (CA) immediately, then later forward app-level ACKs\n // In aaMode, send application ACK (AA) immediately, then ignore any later app-level ACKs\n let response: Hl7Message | undefined;\n if (this.enhancedMode === 'standard') {\n response = event.message.buildAck({ ackCode: 'CA' });\n } else if (this.enhancedMode === 'aaMode') {\n response = event.message.buildAck({ ackCode: 'AA' });\n }\n if (response) {\n this.send(response);\n this.dispatchEvent(new Hl7EnhancedAckSentEvent(this, response));\n }\n const origMsgCtrlId = event.message.getSegment('MSA')?.getField(2)?.toString();\n // If there is no message control ID, just return\n if (!origMsgCtrlId) {\n return;\n }\n const queueItem = this.getPendingMessage(origMsgCtrlId);\n if (!queueItem) {\n this.dispatchEvent(\n new Hl7WarningEvent(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'warning',\n code: 'not-found',\n details: {\n text: 'Response received for unknown message control ID',\n },\n diagnostics: `Received ACK for message control ID '${origMsgCtrlId}' but there was no pending message with this control ID`,\n },\n ],\n })\n )\n );\n return;\n }\n // Check the ACK type we should return on\n const ackCode = event.message.getSegment('MSA')?.getField(1)?.toString()?.toUpperCase();\n if (!ackCode) {\n return;\n }\n\n // Two modes:\n // Application-level or first ACK\n\n // First should always return on any ACK message, this is the default\n // The exception is APPLICATION, which should not resolve when the ACK is a CA, but should resolve on all other ACK types\n // On CA, we return early\n if (queueItem.returnAck === ReturnAckCategory.APPLICATION && ackCode === 'CA') {\n return;\n }\n\n // Resolve the promise if there is one pending for this message and we didn't exit already because the ACK type matches\n if (queueItem.timer) {\n clearTimeout(queueItem.timer);\n }\n queueItem.resolve(event.message);\n this.deletePendingMessage(origMsgCtrlId);\n });\n }\n\n /** @returns A boolean representing whether the socket attached to this Hl7Connection has emitted the close event already or not. */\n isClosed(): boolean {\n return this.socket.closed;\n }\n\n private sendImpl(reply: Hl7Message): void {\n const replyString = reply.toString();\n const replyBuffer = iconv.encode(replyString, this.encoding);\n const outputBuffer = Buffer.alloc(replyBuffer.length + 3);\n outputBuffer.writeInt8(VT, 0);\n replyBuffer.copy(outputBuffer, 1);\n outputBuffer.writeInt8(FS, replyBuffer.length + 1);\n outputBuffer.writeInt8(CR, replyBuffer.length + 2);\n this.socket.write(outputBuffer);\n }\n\n private async processResponseQueue(): Promise<void> {\n if (this.responseQueueProcessing) {\n return;\n }\n\n this.responseQueueProcessing = true;\n while (this.responseQueue.length) {\n if (this.messagesPerMin) {\n const millisBetweenMsgs = ONE_MINUTE / this.messagesPerMin;\n const elapsedMillis = Date.now() - this.lastMessageDispatchedTime;\n if (millisBetweenMsgs > elapsedMillis) {\n await sleep(millisBetweenMsgs - elapsedMillis);\n }\n }\n const messageEvent = this.responseQueue.shift() as Hl7MessageEvent;\n if (messageEvent) {\n this.dispatchEvent(messageEvent);\n }\n this.lastMessageDispatchedTime = Date.now();\n }\n this.responseQueueProcessing = false;\n }\n\n /**\n * Parses complete HL7 messages from the accumulated buffer.\n * Continues parsing while the buffer starts with VT and contains FS+CR.\n * Keeps any incomplete message data in the buffer for the next chunk.\n * @returns An array of parsed HL7 messages.\n */\n private parseMessages(): Hl7Message[] {\n const messages: Hl7Message[] = [];\n const buffer = Buffer.concat(this.chunks);\n this.resetBuffer();\n\n // Check if buffer starts with VT (Vertical Tab)\n if (buffer.length === 0) {\n return messages;\n }\n\n let bufferIdx = 0;\n\n // Keep parsing while we have complete messages\n while (bufferIdx < buffer.length) {\n // Ignore bytes between message frames\n while (buffer[bufferIdx] !== VT && bufferIdx < buffer.length) {\n bufferIdx++;\n }\n\n // Look for FS+CR sequence to mark end of message\n let messageEndIndex = -1;\n\n for (let i = bufferIdx + 1; i < buffer.length - 1; i++) {\n if (buffer[i] === FS && buffer[i + 1] === CR) {\n messageEndIndex = i + 1; // Index of CR (end of message)\n break;\n }\n }\n\n // If we don't have a complete message yet, wait for more data\n if (messageEndIndex === -1) {\n break;\n }\n\n // Extract the complete message (including VT, FS, and CR)\n const messageBuffer = buffer.subarray(bufferIdx, messageEndIndex + 1);\n // Extract the content (without VT at start and FS+CR at end)\n const contentBuffer = messageBuffer.subarray(1, -2);\n const contentString = iconv.decode(contentBuffer, this.encoding);\n const message = Hl7Message.parse(contentString);\n\n messages.push(message);\n\n // Move past this message\n bufferIdx = messageEndIndex + 1;\n }\n\n // Keep any remaining unfinished chunk in this.chunks\n this.chunks = bufferIdx < buffer.length ? [buffer.subarray(bufferIdx)] : [];\n\n return messages;\n }\n\n send(reply: Hl7Message): void {\n this.sendImpl(reply);\n }\n\n async sendAndWait(msg: Hl7Message, options?: SendAndWaitOptions): Promise<Hl7Message> {\n return new Promise<Hl7Message>((resolve, reject) => {\n const msgCtrlId = msg.getSegment('MSH')?.getField(10)?.toString();\n if (!msgCtrlId) {\n reject(new OperationOutcomeError(validationError('Required field missing: MSH.10')));\n return;\n }\n\n let timer: NodeJS.Timeout | undefined;\n\n if (options?.timeoutMs) {\n timer = setTimeout(() => {\n this.deletePendingMessage(msgCtrlId);\n reject(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'error',\n code: 'timeout',\n details: {\n text: 'Client timeout',\n },\n diagnostics: `Request timed out after waiting ${options.timeoutMs} milliseconds for response`,\n },\n ],\n })\n );\n }, options.timeoutMs);\n }\n\n this.setPendingMessage(msgCtrlId, {\n message: msg,\n resolve,\n reject,\n returnAck: options?.returnAck ?? ReturnAckCategory.APPLICATION,\n timer,\n });\n this.sendImpl(msg);\n });\n }\n\n async close(): Promise<void> {\n // If we have already received the close event, then we can just return immediately\n if (this.isClosed()) {\n return;\n }\n this.closing = true;\n this.socket.end();\n // drainPendingMessages is also called by the socket 'close' handler, but we call it here first so\n // that rejections are delivered before the close event is dispatched when close() is called explicitly.\n // The socket 'close' handler's call will be a no-op since the map will already be empty.\n this.drainPendingMessages();\n await new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n this.socket.destroy();\n }, this.gracefulCloseTimeoutMs);\n\n this.socket.once('close', () => {\n clearTimeout(timer);\n resolve();\n });\n });\n }\n\n /**\n * Rejects all pending sendAndWait promises and clears the pending messages map.\n * Safe to call multiple times \u2014 subsequent calls are no-ops once the map is empty.\n *\n * Subclasses may override this to change the behavior when a connection closes\n * (e.g. to keep promises alive in an external tracker).\n */\n protected drainPendingMessages(): void {\n if (!this.pendingMessages.size) {\n return;\n }\n const pendingCount = this.pendingMessages.size;\n for (const queueItem of this.pendingMessages.values()) {\n if (queueItem.timer) {\n clearTimeout(queueItem.timer);\n }\n queueItem.reject(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'warning',\n code: 'incomplete',\n details: {\n text: 'Message was still pending when connection closed',\n },\n },\n ],\n })\n );\n }\n this.dispatchEvent(\n new Hl7ErrorEvent(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'warning',\n code: 'incomplete',\n details: {\n text: 'Messages were still pending when connection closed',\n },\n diagnostics: `Hl7Connection closed while ${pendingCount} messages were pending`,\n },\n ],\n })\n )\n );\n this.pendingMessages.clear();\n }\n\n private appendData(data: Buffer): void {\n this.chunks.push(data);\n }\n\n private resetBuffer(): void {\n this.chunks = [];\n }\n\n setEncoding(encoding: string | undefined): void {\n this.encoding = encoding ?? DEFAULT_ENCODING;\n }\n\n getEncoding(): string {\n return this.encoding;\n }\n\n setEnhancedMode(enhancedMode: EnhancedMode): void {\n this.enhancedMode = enhancedMode;\n }\n\n getEnhancedMode(): EnhancedMode {\n return this.enhancedMode;\n }\n\n setMessagesPerMin(messagesPerMin: number | undefined): void {\n this.messagesPerMin = messagesPerMin;\n }\n\n getMessagesPerMin(): number | undefined {\n return this.messagesPerMin;\n }\n\n getPendingMessageCount(): number {\n return this.pendingMessages.size;\n }\n\n /**\n * Looks up a pending message by its message control ID.\n * Subclasses may override this to use an external message store (e.g. a shared tracker).\n * @param msgCtrlId - The message control ID (MSH.10) to look up.\n * @returns The pending queue item, or undefined if not found.\n */\n protected getPendingMessage(msgCtrlId: string): Hl7MessageQueueItem | undefined {\n return this.pendingMessages.get(msgCtrlId);\n }\n\n /**\n * Stores a pending message by its message control ID.\n * Subclasses may override this to use an external message store (e.g. a shared tracker).\n * @param msgCtrlId - The message control ID (MSH.10).\n * @param item - The queue item containing the message and its resolve/reject callbacks.\n */\n protected setPendingMessage(msgCtrlId: string, item: Hl7MessageQueueItem): void {\n this.pendingMessages.set(msgCtrlId, item);\n }\n\n /**\n * Removes a pending message by its message control ID.\n * Subclasses may override this to use an external message store (e.g. a shared tracker).\n * @param msgCtrlId - The message control ID (MSH.10) to remove.\n */\n protected deletePendingMessage(msgCtrlId: string): void {\n this.pendingMessages.delete(msgCtrlId);\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * VT (Vertical Tab) character.\n *\n * In HL7 messages, this character is used to indicate the start of a message.\n */\nexport const VT = 0x0b;\n\n/**\n * CR (Carriage Return) character.\n *\n * In HL7 messages, this character is used to indicate the end of a message.\n */\nexport const CR = 0x0d;\n\n/**\n * FS (File Separator) character.\n *\n * In HL7 messages, this character is used to separate fields.\n */\nexport const FS = 0x1c;\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7Message } from '@medplum/core';\nimport type { Hl7Connection } from './connection';\n\nexport class Hl7MessageEvent extends Event {\n readonly connection: Hl7Connection;\n readonly message: Hl7Message;\n\n constructor(connection: Hl7Connection, message: Hl7Message) {\n super('message');\n this.connection = connection;\n this.message = message;\n }\n}\n\nexport class Hl7EnhancedAckSentEvent extends Event {\n readonly connection: Hl7Connection;\n readonly message: Hl7Message;\n\n constructor(connection: Hl7Connection, message: Hl7Message) {\n super('enhancedAckSent');\n this.connection = connection;\n this.message = message;\n }\n}\n\nexport class Hl7ErrorEvent extends Event {\n readonly error: Error;\n\n constructor(error: Error) {\n super('error');\n this.error = error;\n }\n}\n\nexport class Hl7WarningEvent extends Event {\n readonly error: Error;\n\n constructor(error: Error) {\n super('warning');\n this.error = error;\n }\n}\n\nexport class Hl7CloseEvent extends Event {\n constructor() {\n super('close');\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { AddressInfo } from 'node:net';\nimport { createServer } from 'node:net';\n\n// Every port ever handed out by `getFreePort`, so we never issue the same one twice\n// within a single test process \u2014 see the comment on `getFreePort` below.\nconst issuedPorts = new Set<number>();\n\n// Cap on how many ephemeral ports we probe before giving up looking for a fresh one.\nconst MAX_ATTEMPTS = 20;\n\n/**\n * Returns a TCP port number that is currently free, with *nothing* listening on it.\n *\n * Used only for tests that need a free port number. For tests that start an Hl7Server, prefer\n * `server.start(0)`, which returns the OS-assigned port and never has a release-then-rebind window.\n *\n * Because we close the probing server before returning, the port is freed immediately and the OS\n * may hand the *same* ephemeral port to a subsequent call. Callers that allocate two ports (e.g.\n * one per channel) would then collide. To avoid this, we remember every port we issue and keep any\n * probing server that lands on an already-issued port open until we find a fresh one, so the OS\n * can't reissue it in the same round.\n * @returns A promise that resolves with a free TCP port number.\n */\nexport async function getFreePort(): Promise<number> {\n const heldServers: ReturnType<typeof createServer>[] = [];\n const closeServer = async (server: ReturnType<typeof createServer>): Promise<void> =>\n new Promise((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n });\n try {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const server = createServer();\n const port = await new Promise<number>((resolve, reject) => {\n server.on('error', reject);\n server.listen(0, () => {\n resolve((server.address() as AddressInfo).port);\n });\n });\n if (issuedPorts.has(port)) {\n // Keep this server listening so the OS won't hand the same port out again this round.\n heldServers.push(server);\n continue;\n }\n issuedPorts.add(port);\n await closeServer(server);\n return port;\n }\n throw new Error(`Unable to find a free port after ${MAX_ATTEMPTS} attempts`);\n } finally {\n await Promise.all(heldServers.map((server) => closeServer(server).catch(() => undefined)));\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { sleep } from '@medplum/core';\nimport net from 'node:net';\nimport type { EnhancedMode, Hl7ConnectionOptions } from './connection';\nimport { Hl7Connection } from './connection';\n\n/**\n * Options for configuring the `Hl7Server#stop` method.\n */\nexport interface Hl7ServerStopOptions {\n /**\n * Time in milliseconds to allow client connections to gracefully close after the stop method has been called, before forcefully closing them.\n *\n * Can be set to `-1` to disable forceful draining of connections during stop.\n *\n * Defaults to `10_000`.\n */\n forceDrainTimeoutMs?: number;\n}\n\nexport const DEFAULT_FORCE_DRAIN_TIMEOUT_MS = 10_000;\n\nexport class Hl7Server {\n readonly handler: (connection: Hl7Connection) => void;\n server?: net.Server;\n private encoding: string | undefined = undefined;\n private enhancedMode: EnhancedMode = undefined;\n private messagesPerMin: number | undefined = undefined;\n private readonly connections = new Set<Hl7Connection>();\n\n constructor(handler: (connection: Hl7Connection) => void) {\n this.handler = handler;\n }\n\n async start(\n port: number,\n encoding?: string,\n enhancedMode?: EnhancedMode,\n connectionOptions?: Hl7ConnectionOptions\n ): Promise<number> {\n if (encoding) {\n this.setEncoding(encoding);\n }\n if (enhancedMode !== undefined) {\n this.setEnhancedMode(enhancedMode);\n }\n if (connectionOptions?.messagesPerMin !== undefined) {\n this.setMessagesPerMin(connectionOptions.messagesPerMin);\n }\n\n const server = net.createServer((socket) => {\n const connection = new Hl7Connection(socket, this.encoding, this.enhancedMode, {\n messagesPerMin: this.messagesPerMin,\n });\n this.handler(connection);\n this.connections.add(connection);\n connection.addEventListener('close', () => {\n this.connections.delete(connection);\n });\n });\n\n return new Promise<number>((resolve, reject) => {\n const listenOnPort = (port: number): void => {\n server.listen(port, () => {\n const boundPort = (server.address() as { port: number }).port;\n resolve(boundPort);\n });\n };\n\n const errorListener = (e: Error & { code?: string }): void => {\n if (e?.code === 'EADDRINUSE') {\n server.close(() => sleep(50).then(() => listenOnPort(port)));\n } else {\n reject(e);\n }\n };\n\n server.on('error', errorListener);\n\n server.once('listening', () => {\n server.off('error', errorListener);\n });\n\n listenOnPort(port);\n\n this.server = server;\n });\n }\n\n /**\n * Stops the HL7 server.\n *\n * By default, the server will stop accepting new connections after this method is called, and wait for current connections to close naturally.\n *\n * If all connections don't close within 10 seconds, the server will forcefully close them before shutting down.\n *\n * The default time to wait before forcefully closing connections can be changed by passing an integer value for the optional `options.forceDrainTimeoutMs`.\n *\n * Forced drain can also be disabled by passing `-1` for `options.forceDrainTimeoutMs`.\n * @param options - Optional options to configure the stopping of the server.\n * @returns Promise that resolves when the server has stopped, or rejects if an error prevents server from stopping.\n */\n async stop(options?: Hl7ServerStopOptions): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (!this.server) {\n reject(new Error('Stop was called but there is no server running'));\n return;\n }\n let forceDrainTimeout: NodeJS.Timeout | undefined;\n if (options?.forceDrainTimeoutMs !== -1) {\n forceDrainTimeout = setTimeout(() => {\n for (const connection of this.connections) {\n // Theoretically close should almost never throw as most errors are caught internal to the method and emitted as error events\n // We put a .catch here to prevent floating promises and log any errors that somehow make it through\n connection.close().catch(console.error);\n }\n }, options?.forceDrainTimeoutMs ?? DEFAULT_FORCE_DRAIN_TIMEOUT_MS);\n }\n this.server.close((err) => {\n if (err) {\n reject(err);\n return;\n }\n if (forceDrainTimeout) {\n clearTimeout(forceDrainTimeout);\n }\n this.connections.clear();\n this.server = undefined;\n resolve();\n });\n });\n }\n\n setEnhancedMode(enhancedMode: EnhancedMode): void {\n this.enhancedMode = enhancedMode;\n }\n\n getEnhancedMode(): EnhancedMode {\n return this.enhancedMode;\n }\n\n setEncoding(encoding: string | undefined): void {\n this.encoding = encoding;\n }\n\n getEncoding(): string | undefined {\n return this.encoding;\n }\n\n setMessagesPerMin(messagesPerMin: number | undefined): void {\n this.messagesPerMin = messagesPerMin;\n }\n\n getMessagesPerMin(): number | undefined {\n return this.messagesPerMin;\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { readdirSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\nimport { FileSystemStorage } from './storage';\nimport { MedplumCommand, addSubcommand, loadProfile, saveProfile } from './utils';\n\nconst setProfile = new MedplumCommand('set');\nconst removeProfile = new MedplumCommand('remove');\nconst listProfiles = new MedplumCommand('list');\nconst describeProfile = new MedplumCommand('describe');\n\nexport const profile = new MedplumCommand('profile');\naddSubcommand(profile, setProfile);\naddSubcommand(profile, removeProfile);\naddSubcommand(profile, listProfiles);\naddSubcommand(profile, describeProfile);\n\nsetProfile\n .argument('<profileName>', 'Name of the profile')\n .description('Create a new profile or replace it with the given name and its associated properties')\n .action(async (profileName, options) => {\n saveProfile(profileName, options);\n });\n\nremoveProfile\n .argument('<profileName>', 'Name of the profile')\n .description('Remove a profile by name')\n .action(async (profileName) => {\n const storage = new FileSystemStorage(profileName);\n storage.setObject('options', undefined);\n console.log(`${profileName} profile removed`);\n });\n\nlistProfiles.description('List all profiles saved').action(async () => {\n const dir = resolve(homedir(), '.medplum');\n const files = readdirSync(dir);\n const allProfiles: any[] = [];\n files.forEach((file) => {\n const fileName = file.split('.')[0];\n const storage = new FileSystemStorage(fileName);\n const profile = storage.getObject('options');\n if (profile) {\n allProfiles.push({ profileName: fileName, profile });\n }\n });\n console.log(allProfiles);\n});\n\ndescribeProfile\n .argument('<profileName>', 'Name of the profile')\n .description('Describes a profile')\n .action(async (profileName) => {\n const profile = loadProfile(profileName);\n console.log(profile);\n });\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { InviteRequest, LoginState, MedplumClient } from '@medplum/core';\nimport { Option } from 'commander';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nconst projectListCommand = new MedplumCommand('list');\nconst projectCurrentCommand = new MedplumCommand('current');\nconst projectSwitchCommand = new MedplumCommand('switch');\nconst projectInviteCommand = new MedplumCommand('invite');\n\nexport const project = new MedplumCommand('project');\naddSubcommand(project, projectListCommand);\naddSubcommand(project, projectCurrentCommand);\naddSubcommand(project, projectSwitchCommand);\naddSubcommand(project, projectInviteCommand);\n\nprojectListCommand.description('List of current projects').action(async (options) => {\n const medplum = await createMedplumClient(options);\n projectList(medplum);\n});\n\nfunction projectList(medplum: MedplumClient): void {\n const logins = medplum.getLogins();\n\n const projects = logins\n .map((login: LoginState) => `${login.project.display} (${login.project.reference})`)\n .join('\\n\\n');\n\n console.log(projects);\n}\n\nprojectCurrentCommand.description('Project you are currently on').action(async (options) => {\n const medplum = await createMedplumClient(options);\n const login = medplum.getActiveLogin();\n if (!login) {\n throw new Error('Unauthenticated: run `npx medplum login` to login');\n }\n console.log(`${login.project.display} (${login.project.reference})`);\n});\n\nprojectSwitchCommand\n .description('Switching to another project from the current one')\n .argument('<projectId>')\n .action(async (projectId, options) => {\n const medplum = await createMedplumClient(options);\n await switchProject(medplum, projectId);\n });\n\nprojectInviteCommand\n .description('Invite a member to your current project (run npx medplum project current to confirm)')\n .arguments('<firstName> <lastName> <email>')\n .option('--send-email', 'If you want to send the email when inviting the user')\n .option('--admin', 'If the user you are inviting is an admin')\n .addOption(\n new Option('-r, --role <role>', 'Role of user')\n .choices(['Practitioner', 'Patient', 'RelatedPerson'])\n .default('Practitioner')\n )\n .action(async (firstName, lastName, email, options) => {\n const medplum = await createMedplumClient(options);\n const login = medplum.getActiveLogin();\n if (!login) {\n throw new Error('Unauthenticated: run `npx medplum login` to login');\n }\n if (!login?.project?.reference) {\n throw new Error('No current project to invite user to');\n }\n\n const projectId = login.project.reference.split('/')[1];\n const inviteBody: InviteRequest = {\n resourceType: options.role,\n firstName,\n lastName,\n email,\n sendEmail: !!options.sendEmail,\n admin: !!options.admin,\n };\n await inviteUser(projectId, inviteBody, medplum);\n });\n\nasync function switchProject(medplum: MedplumClient, projectId: string): Promise<void> {\n const logins = medplum.getLogins();\n const login = logins.find((login: LoginState) => login.project.reference?.includes(projectId));\n if (!login) {\n throw new Error(`Project ${projectId} not found. Make sure you are added as a user to this project`);\n }\n await medplum.setActiveLogin(login);\n console.log(`Switched to project ${projectId}\\n`);\n}\n\nasync function inviteUser(projectId: string, inviteBody: InviteRequest, medplum: MedplumClient): Promise<void> {\n await medplum.invite(projectId, inviteBody);\n if (inviteBody.sendEmail) {\n console.log('Email sent');\n }\n console.log('See your users at https://app.medplum.com/admin/users');\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { convertToTransactionBundle } from '@medplum/core';\nimport { createMedplumClient } from './util/client';\nimport { MedplumCommand, prettyPrint } from './utils';\n\nexport const deleteObject = new MedplumCommand('delete');\nexport const get = new MedplumCommand('get');\nexport const patch = new MedplumCommand('patch');\nexport const post = new MedplumCommand('post');\nexport const put = new MedplumCommand('put');\n\ndeleteObject.argument('<url>', 'Resource/$id').action(async (url, options) => {\n const medplum = await createMedplumClient(options);\n prettyPrint(await medplum.delete(cleanUrl(medplum, url)));\n});\n\nget\n .argument('<url>', 'Resource/$id')\n .option('--as-transaction', 'Print out the bundle as a transaction type')\n .action(async (url, options) => {\n const medplum = await createMedplumClient(options);\n const response = await medplum.get(cleanUrl(medplum, url));\n if (options.asTransaction) {\n prettyPrint(convertToTransactionBundle(response));\n } else {\n prettyPrint(response);\n }\n });\n\npatch.arguments('<url> <body>').action(async (url, body, options) => {\n const medplum = await createMedplumClient(options);\n\n prettyPrint(await medplum.patch(cleanUrl(medplum, url), parseBody(body)));\n});\n\npost\n .arguments('<url> <body>')\n .option('--prefer-async', 'Sets the Prefer header to \"respond-async\"')\n .action(async (url, body, options) => {\n const medplum = await createMedplumClient(options);\n\n const headers = options.preferAsync ? { Prefer: 'respond-async' } : undefined;\n prettyPrint(await medplum.post(cleanUrl(medplum, url), parseBody(body), undefined, { headers }));\n });\n\nput.arguments('<url> <body>').action(async (url, body, options) => {\n const medplum = await createMedplumClient(options);\n\n prettyPrint(await medplum.put(cleanUrl(medplum, url), parseBody(body)));\n});\n\nfunction parseBody(input: string | undefined): any {\n if (!input) {\n return undefined;\n }\n try {\n return JSON.parse(input);\n } catch (_err) {\n return input;\n }\n}\n\nexport function cleanUrl(medplum: MedplumClient, input: string): string {\n const knownPrefixes = ['admin/', 'auth/', 'fhir/R4'];\n if (knownPrefixes.some((p) => input.startsWith(p))) {\n // If the URL starts with a known prefix, return it as-is\n return input;\n }\n\n // Otherwise, default to FHIR\n return medplum.fhirUrl(input).toString();\n}\n"],
5
- "mappings": ";we8CEA,IAAAA,GAAsD,yBACtDC,GAAuC,qBACvCC,GAAmB,wBCOnBF,GAAuE,yBAEvEC,GAAuB,qBCVvBD,GAA8B,yBCD9BA,GAA8B,yBAC9BG,GAAmE,mBACnEC,GAAwB,mBACxBC,GAAwB,qBCFxBL,EAA6F,yBAE7FC,GAAwB,qBAExBK,GAA0D,uBAC1DH,GAAwD,mBACxDE,GAA2C,qBAC3CE,GAA0B,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,EAAQ,EAE7B,GAAI,CACF,MAAMp5B,EAAM,WAAWs/B,CAAI,CAC7B,OAAS1qB,EAAK,CACZ4qB,GAAY5qB,CAAY,CAC1B,CACF,CAEO,SAAS4qB,GAAY5qB,EAAmC,CAC7D,IAAI6qB,EAAW,EACXC,EAAc,GAUlB,GATI9qB,aAAe+qB,GAAAA,iBAIZ,QAAQ,IAAI,UACfD,EAAc,IAEhBD,EAAW7qB,EAAI,UAEb6qB,IAAa,GAAKC,EAAa,CACjCE,GAAmBhrB,EAAK,CAAC,CAAC,QAAQ,IAAI,OAAO,EAC7C,IAAMkC,EAAQlC,EAAI,MAClB,GAAI,QAAQ,IAAI,QACd,GAAI,MAAM,QAAQkC,CAAK,EACrB,QAAWlC,KAAOkC,EAChB8oB,GAAmBhrB,EAAK,EAAI,OAErBkC,aAAiB,OAC1B8oB,GAAmB9oB,EAAO,EAAI,CAGpC,CACA,QAAQ,KAAK2oB,CAAQ,CACvB,CAEA,SAASG,GAAmBhrB,EAAcirB,EAAU,GAAa,CAC/D,GAAIA,EAAS,CACX,QAAQ,MAAMjrB,CAAG,EACjB,MACF,CACIA,aAAe+qB,GAAAA,eACjB,QAAQ,OAAO,MAAM,MAAG1gB,GAAAA,sBAAqBrK,CAAG,CAAC;CAAI,EAErD,QAAQ,OAAO,MAAM,aAAUqK,GAAAA,sBAAqBrK,CAAG,CAAC;CAAI,CAEhE,CAEA,eAAsBkrB,IAAqB,CACzCC,GAAAA,QAAO,OAAO,CAAE,MAAO,EAAK,CAAC,EAC7B,MAAMV,GAAK,QAAQ,IAAI,CACzB,CAGES,GAAI,EAAE,MAAOlrB,GAAQ,CACnB,QAAQ,MAAM,sBAAoBqK,GAAAA,sBAAqBrK,CAAG,CAAC,EAC3D,QAAQ,KAAK,CAAC,CAChB,CAAC",
6
- "names": ["import_core", "import_commander", "import_dotenv", "import_node_fs", "import_node_os", "import_node_path", "import_node_crypto", "import_types", "import_tar", "import_node_child_process", "import_node_http", "import_node_util", "import_client_cloudformation", "import_client_cloudfront", "import_client_ecs", "import_client_s3", "import_client_ssm", "import_client_sts", "import_node_readline", "import_client_acm", "import_fast_glob", "import_node_stream", "import_promises", "import_node_events", "import_node_assert", "import_node_net", "import_iconv_lite", "require_constants", "__commonJSMin", "exports", "module", "SEMVER_SPEC_VERSION", "MAX_SAFE_INTEGER", "MAX_SAFE_COMPONENT_LENGTH", "MAX_SAFE_BUILD_LENGTH", "RELEASE_TYPES", "require_debug", "debug", "args", "require_re", "MAX_LENGTH", "re", "ye", "safeRe", "src", "safeSrc", "t", "R", "LETTERDASHNUMBER", "safeRegexReplacements", "makeSafeRegex", "value", "token", "max", "createToken", "name", "isGlobal", "safe", "index", "require_parse_options", "looseOption", "emptyOpts", "parseOptions", "options", "require_identifiers", "numeric", "compareIdentifiers", "a", "b", "anum", "bnum", "rcompareIdentifiers", "require_semver", "ne", "Ue", "Dt", "isPrereleaseIdentifier", "prerelease", "identifier", "identifiers", "i", "SemVer", "_SemVer", "version", "m", "id", "num", "other", "release", "identifierBase", "match", "base", "prereleaseBase", "require_parse", "T", "parse", "throwErrors", "er", "require_valid", "J", "valid", "v", "require_clean", "clean", "s", "require_inc", "inc", "require_diff", "diff", "version1", "version2", "v1", "v2", "comparison", "v1Higher", "highVersion", "lowVersion", "highHasPre", "prefix", "require_major", "major", "loose", "require_minor", "minor", "require_patch", "patch", "require_prerelease", "parsed", "require_compare", "compare", "require_rcompare", "M", "rcompare", "require_compare_loose", "compareLoose", "require_compare_build", "compareBuild", "versionA", "versionB", "require_sort", "qe", "sort", "list", "require_rsort", "rsort", "require_gt", "gt", "require_lt", "lt", "require_eq", "eq", "require_neq", "neq", "require_gte", "gte", "require_lte", "lte", "require_cmp", "Ut", "_t", "we", "Ge", "We", "Ke", "cmp", "op", "require_coerce", "coerce", "coerceRtlRegex", "next", "build", "require_truncate", "constants", "truncate", "truncation", "clonedVersion", "cloneInputVersion", "doTruncation", "versionStringToParse", "isPrerelease", "type", "require_lrucache", "LRUCache", "key", "firstKey", "require_range", "SPACE_CHARACTERS", "Range", "_Range", "range", "Comparator", "r", "c", "first", "isNullSet", "isAny", "comps", "k", "BUILDSTRIPRE", "memoKey", "FLAG_INCLUDE_PRERELEASE", "FLAG_LOOSE", "cached", "cache", "hr", "hyphenReplace", "comparatorTrimReplace", "tildeTrimReplace", "caretTrimReplace", "rangeList", "comp", "parseComparator", "replaceGTE0", "rangeMap", "comparators", "result", "thisComparators", "isSatisfiable", "rangeComparators", "thisComparator", "rangeComparator", "testSet", "LRU", "bo", "Ee", "remainingComparators", "testComparator", "otherComparator", "replaceCarets", "replaceTildes", "replaceXRanges", "replaceStars", "isX", "invalidXRangeOrder", "p", "replaceTilde", "z", "_", "pr", "ret", "replaceCaret", "replaceXRange", "gtlt", "xM", "xm", "xp", "anyX", "incPr", "$0", "from", "fM", "fm", "fp", "fpr", "fb", "to", "tM", "tm", "tp", "tpr", "set", "allowed", "require_comparator", "ANY", "_Comparator", "Ft", "L", "require_satisfies", "satisfies", "require_to_comparators", "toComparators", "require_max_satisfying", "maxSatisfying", "versions", "maxSV", "rangeObj", "require_min_satisfying", "minSatisfying", "min", "minSV", "require_min_version", "minVersion", "minver", "setMin", "comparator", "compver", "validRange", "require_outside", "Re", "outside", "hilo", "gtfn", "ltefn", "ltfn", "ecomp", "high", "low", "require_gtr", "Je", "gtr", "require_ltr", "ltr", "require_intersects", "intersects", "r1", "r2", "require_simplify", "prev", "ranges", "simplified", "original", "require_subset", "subset", "sub", "dom", "sawNonNull", "OUTER", "simpleSub", "simpleDom", "isSub", "simpleSubset", "minimumVersionWithPreRelease", "minimumVersion", "eqSet", "higherGT", "lowerLT", "gtltComp", "higher", "lower", "hasDomLT", "hasDomGT", "needDomLTPre", "needDomGTPre", "internalRe", "Dn", "Ln", "Fn", "qn", "Vn", "Jn", "zn", "eo", "ro", "io", "co", "wo", "So", "Mo", "Uo", "Fo", "qo", "Go", "zo", "Qo", "ts", "simplifyRange", "ns", "ls", "FileSystemStorage", "ClientStorage", "profile", "__publicField", "resolve", "homedir", "data", "str", "existsSync", "readFileSync", "mkdirSync", "writeFileSync", "createMedplumClient", "setupCredentials", "profileName", "storage", "baseUrl", "fhirUrlPath", "accessToken", "tokenUrl", "authorizeUrl", "clientId", "clientSecret", "getClientValues", "fetchApi", "validateBaseUrl", "medplumClient", "MedplumClient", "onUnauthenticated", "storageOptions", "url", "response", "err", "message", "encoder", "decoder", "strictDecoder", "MAX_INT32", "concat", "buffers", "size", "acc", "length", "buf", "buffer", "NON_ASCII", "encode", "string", "bytes", "code", "encodeBase64", "input", "CHUNK_SIZE", "arr", "encoded", "decodeBase64", "binary", "JOSEError", "JOSENotSupported", "JWSInvalid", "JWTInvalid", "_a", "_b", "JWKSMultipleMatchingKeys", "invalid", "decode", "cause", "isObject", "prototype", "isDisjoint", "headers", "parameters", "header", "parameter", "assertNotSet", "JWS_RECOGNIZED", "validateCritDuplicates", "Err", "protectedHeader", "crit", "validateCrit", "recognizedDefault", "recognizedOption", "joseHeader", "recognized", "validateB64", "extensions", "b64", "serializeJoseHeader", "serialized", "tag", "jwkMatchesOp", "entry", "usage", "alg", "expected", "expectedKeyOp", "prepareKey", "secret", "privateKey", "normalized", "keyObject", "normalizeJwk", "invalidKeyType", "key_ops", "isKeyLike", "expectedType", "isCryptoKey", "cacheKey", "isPublic", "crv", "nist", "params", "jwkToKey", "isKeyObject", "msg", "actual", "types", "last", "unusable", "prop", "checkUsage", "checkModulusLength", "modulusLength", "checkCryptoKey", "algorithm", "snapshotJwk", "jwk", "keyOps", "operation", "extractable", "isPrivate", "keyData", "rawKey", "table", "entries", "out", "sig", "hmac", "bits", "subtle", "rsa", "saltLength", "ecdsa", "eddsa", "mldsa", "JWS", "jwsAlgorithm", "epoch", "date", "multipliers", "REGEX", "invalidDuration", "secs", "matched", "numericDate2", "validateInput", "label", "validateStringClaim", "claim", "validateAudienceClaim", "member", "numericDate", "producerPayloads", "producerPayload", "producer", "jwtData", "payload", "JWTClaimsBuilder", "createSignature", "rejectUnencoded", "unprotectedHeader", "protectedHeaderString", "payloadS", "payloadB", "jws", "createCompactSignature", "SignJWT_base", "_protectedHeader", "SignJWT", "__privateAdd", "__privateGet", "__privateSet", "prettyPrint", "saveBot", "medplum", "botConfig", "bot", "codePath", "readFileContents", "sourceCode", "basename", "getCodeContentType", "updateResult", "deployBot", "deployResult", "isOk", "normalizeErrorString", "createBot", "botName", "projectId", "sourceFile", "distFile", "runtimeVersion", "writeConfig", "body", "newBot", "addBotToConfig", "readBotConfigs", "regExBotName", "escapeRegex", "readConfig", "getConfigFileName", "tagName", "parts", "configFileName", "config", "fileName", "content", "readServerConfig", "path", "safeTarExtractor", "destinationDir", "fileCount", "totalSize", "extract", "_path", "getUnsupportedExtension", "filename", "ext", "extname", "ContentType", "saveProfile", "optionsObject", "loadProfile", "jwtBearerLogin", "OAuthSigningAlgorithm", "currentTimestamp", "encodedHeader", "encodedData", "signature", "createHmac", "signedToken", "jwtAssertionLogin", "createPrivateKey", "jwt", "randomBytes", "addSubcommand", "command", "subcommand", "MedplumCommand", "Command", "fn", "wrappedFn", "withMergedOptions", "option", "expectedArgsCount", "actionArgs", "isPromise", "agentStatusCommand", "agentPingCommand", "agentPushCommand", "agentReloadConfigCommand", "agentUpgradeCommand", "agentStatsCommand", "agent", "Option", "agentIds", "callAgentBulkOperation", "statusEntry", "parseParameterValues", "ipOrDomain", "agentId", "agentRef", "resolveAgentReference", "count", "pingResult", "deviceId", "pushResult", "stats", "rows", "renderAgentStats", "SUMMARY_STAT_KEYS", "formatStatValue", "buildChannelStatsRows", "row", "heading", "summary", "knownKeys", "channelRows", "clientRows", "parseSuccessfulResponse", "renderSuccessfulRows", "parseEitherIdsOrCriteria", "usedCriteria", "searchParams", "paramName", "paramVal", "successfulResponses", "failedResponses", "responses", "parseAgentBulkOpBundle", "successfulRows", "failedRows", "issue", "usedId", "assertValidAgentCriteria", "bundle", "EMPTY", "parseAgentBulkOpParameters", "paramNames", "map", "requiredParams", "optionalParams", "paramsParam", "valueProp", "extractValueFromParametersParameter", "isUUID", "criteria", "invalidCriteriaMsg", "resourceType", "queryStr", "execAsync", "promisify", "exec", "MEDPLUM_CLI_CLIENT_ID", "redirectUri", "login", "whoami", "startLogin", "printMe", "medplumAuthorizationCodeLogin", "startWebServer", "server", "createServer", "req", "res", "getDisplayString", "openBrowser", "os", "platform", "cmd", "loginState", "loginUrl", "RESET", "BOLD", "RED", "GREEN", "YELLOW", "BLUE", "color", "text", "processDescription", "desc", "semver", "wr", "Qt", "terminal", "initTerminal", "readline", "closeTerminal", "print", "ask", "defaultValue", "answer", "choose", "o", "chooseInt", "yesOrNo", "checkOk", "cloudFormationClient", "CloudFormationClient", "cloudFrontClient", "CloudFrontClient", "ecsClient", "ECSClient", "s3Client", "S3Client", "tagKey", "getAllStacks", "listResult", "paginator", "paginateListStacks", "page", "stack", "getStackByTag", "stackSummaries", "stackSummary", "stackName", "details", "getStackDetails", "buildStackDetails", "client", "describeStacksCommand", "DescribeStacksCommand", "medplumTag", "stackResources", "DescribeStackResourcesCommand", "resource", "assignStackDetails", "printStackDetails", "getEcsServiceName", "createInvalidation", "distributionId", "CreateInvalidationCommand", "getServerVersions", "gs", "writeParameters", "region", "SSMClient", "valueStr", "existingValue", "readParameter", "writeParameter", "GetParameterCommand", "PutParameterCommand", "printConfigNotFound", "files", "readdirSync", "f", "file", "printStackNotFound", "STSClient", "GetCallerIdentityCommand", "getDomainSetting", "domain", "getDomainCertSetting", "initStackCommand", "currentAccountId", "getAccountId", "defaultStackName", "supportEmail", "latestVersion", "signingKey", "generateSigningKey", "allCerts", "listAllCertificates", "certName", "arn", "processCert", "serverParams", "serverConfigFileName", "listCertificates", "usEast1Result", "ACMClient", "ListCertificatesCommand", "domainName", "existingCert", "cert", "requestCert", "validationMethod", "RequestCertificateCommand", "keyName", "passphrase", "randomUUID", "generateKeyPairSync", "CreatePublicKeyCommand", "listStacksCommand", "updateAppCommand", "appBucket", "tmpDir", "downloadNpmPackage", "replaceVariables", "uploadAppToS3", "getNpmPackageMetadata", "packageName", "tarballUrl", "mkdtempSync", "join", "tmpdir", "extractor", "pipeline", "Readable", "error", "rmSync", "folderName", "replacements", "item", "itemPath", "replaceVariablesInFile", "contents", "placeholder", "replacement", "bucketName", "uploadPatterns", "uploadPattern", "uploadFolderToS3", "items", "fastGlob", "uploadFileToS3", "filePath", "fileStream", "createReadStream", "s3Key", "sep", "putObjectParams", "PutObjectCommand", "updateBucketPoliciesCommand", "updateBucketPolicy", "friendlyName", "bucketResource", "distributionResource", "oaiResource", "oaiId", "bucketPolicy", "getPolicy", "policyHasAllowStatement", "addAllowPolicyStatement", "addGuardDutyReadPolicyStatement", "setPolicy", "policyResponse", "GetBucketPolicyCommand", "policy", "PutBucketPolicyCommand", "statementHasAction", "statement", "action", "updateConfigCommand", "infraConfig", "serverConfig", "checkConfigConflicts", "mergeConfigs", "checkConflict", "isConflict", "updateServerCommand", "separatorIndex", "serverImagePrefix", "initialVersion", "getCurrentVersion", "updateVersion", "nextUpdateVersion", "ae", "deployServerUpdate", "currentVersion", "targetVersion", "allVersions", "configFile", "deploy", "spawnSync", "buildAwsCommand", "aws", "botSaveCommand", "botDeployCommand", "botCreateCommand", "saveBotDeprecate", "deployBotDeprecate", "createBotDeprecate", "botWrapper", "botConfigs", "errors", "errored", "saved", "deployed", "bulkExportCommand", "bulkImportCommand", "bulk", "exportLevel", "since", "targetDirectory", "fileUrl", "nodeStream", "createWriteStream", "numResourcesPerRequest", "addExtensionsForMissingValues", "importFile", "rl", "createInterface", "line", "parseResource", "sendBatchEntries", "pendingEntries", "OperationOutcomeError", "getStatus", "sleep", "getRateLimitRetryDelay", "retryEntries", "resultEntry", "rateLimitOutcome", "outcome", "outcomeDelay", "getRateLimitReset", "limit", "jsonString", "addExtensionsForMissingValuesResource", "addExtensionsForMissingValuesExplanationOfBenefits", "DEFAULT_BATCH_SIZE", "DICOM_EXTENSIONS", "DICOM_PREFIX", "DICOM_PREFIX_OFFSET", "DICOM_HEADER_LENGTH", "FILE_META_GROUP", "isDicomFile", "handle", "open", "bytesRead", "resolveDicomFiles", "inputs", "results", "stat", "matches", "skipped", "writeBuffer", "stream", "once", "pipeFileToStream", "chunk", "writeMultipartRelatedBody", "filePaths", "boundary", "stow", "batchSize", "batch", "contentType", "PassThrough", "writePromise", "requestPromise", "dicomweb", "Pd", "Id", "Hl7Base", "listener", "Hl7MessageEvent", "connection", "Hl7EnhancedAckSentEvent", "Hl7ErrorEvent", "Hl7WarningEvent", "Hl7CloseEvent", "DEFAULT_ENCODING", "GRACEFUL_CLOSE_TIMEOUT_MS", "ONE_MINUTE", "Hl7Connection", "socket", "encoding", "enhancedMode", "messages", "event", "origMsgCtrlId", "queueItem", "ackCode", "ReturnAckCategory", "reply", "replyString", "replyBuffer", "iconv", "outputBuffer", "millisBetweenMsgs", "elapsedMillis", "messageEvent", "bufferIdx", "messageEndIndex", "contentBuffer", "contentString", "Hl7Message", "reject", "msgCtrlId", "validationError", "timer", "pendingCount", "messagesPerMin", "Hl7Client", "deferredPromise", "net", "assert", "timeoutListener", "connectListener", "errorListener", "closeListener", "_resolve", "_reject", "DEFAULT_FORCE_DRAIN_TIMEOUT_MS", "Hl7Server", "handler", "port", "connectionOptions", "listenOnPort", "boundPort", "e", "forceDrainTimeout", "send", "host", "generateSampleHl7Message", "A", "listen", "hl7", "now", "formatHl7DateTime", "controlId", "setProfile", "removeProfile", "listProfiles", "describeProfile", "dir", "allProfiles", "projectListCommand", "projectCurrentCommand", "projectSwitchCommand", "projectInviteCommand", "project", "projectList", "projects", "switchProject", "firstName", "lastName", "email", "inviteBody", "inviteUser", "deleteObject", "get", "post", "put", "cleanUrl", "convertToTransactionBundle", "parseBody", "main", "argv", "MEDPLUM_VERSION", "handleError", "exitCode", "shouldPrint", "CommanderError", "writeErrorToStderr", "verbose", "run", "dotenv"]
4
+ "sourcesContent": ["'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifier, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\n\nconst isPrereleaseIdentifier = (prerelease, identifier) => {\n const identifiers = identifier.split('.')\n if (identifiers.length > prerelease.length) {\n return false\n }\n\n for (let i = 0; i < identifiers.length; i++) {\n if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {\n return false\n }\n }\n\n return true\n}\n\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (isPrereleaseIdentifier(this.prerelease, identifier)) {\n const prereleaseBase = this.prerelease[identifier.split('.').length]\n if (isNaN(prereleaseBase)) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "'use strict'\n\nconst parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n", "'use strict'\n\nconst parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // If the main part has no difference\n if (lowVersion.compareMain(highVersion) === 0) {\n if (lowVersion.minor && !lowVersion.patch) {\n return 'minor'\n }\n return 'patch'\n }\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are prereleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "'use strict'\n\nconst parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "'use strict'\n\nconst compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "'use strict'\n\nconst compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n", "'use strict'\n\nconst parse = require('./parse')\nconst constants = require('../internal/constants')\nconst SemVer = require('../classes/semver')\n\nconst truncate = (version, truncation, options) => {\n if (!constants.RELEASE_TYPES.includes(truncation)) {\n return null\n }\n\n const clonedVersion = cloneInputVersion(version, options)\n return clonedVersion && doTruncation(clonedVersion, truncation)\n}\n\nconst cloneInputVersion = (version, options) => {\n const versionStringToParse = (\n version instanceof SemVer ? version.version : version\n )\n\n return parse(versionStringToParse, options)\n}\n\nconst doTruncation = (version, truncation) => {\n if (isPrerelease(truncation)) {\n return version.version\n }\n\n version.prerelease = []\n\n switch (truncation) {\n case 'major':\n version.minor = 0\n version.patch = 0\n break\n case 'minor':\n version.patch = 0\n break\n }\n\n return version.format()\n}\n\nconst isPrerelease = (type) => {\n return type.startsWith('pre')\n}\n\nmodule.exports = truncate\n", "'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n", "'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // strip build metadata so it can't bleed into the version\n range = range.replace(BUILDSTRIPRE, '')\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n src,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\n// unbounded global build-metadata stripper used by parseRange\nconst BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\nconst invalidXRangeOrder = (M, m, p) => (\n (isX(M) && !isX(m)) ||\n (isX(m) && p && !isX(p))\n)\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n // if we're including prereleases in the match, then the lower bound is\n // -0, the lowest possible prerelease value, just like x-ranges and carets.\n // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as.\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n if (invalidXRangeOrder(M, m, p)) {\n return comp\n }\n\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "'use strict'\n\nconst Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n", "'use strict'\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "'use strict'\n\nconst outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n", "'use strict'\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n", "'use strict'\n\nconst Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If LT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !c.test(gt.semver)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !c.test(lt.semver)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n", "'use strict'\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst truncate = require('./functions/truncate')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n truncate,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { MEDPLUM_VERSION, normalizeErrorString } from '@medplum/core';\nimport { CommanderError, Option } from 'commander';\nimport { existsSync } from 'node:fs';\nimport { agent } from './agent';\nimport { login, token, whoami } from './auth';\nimport { buildAwsCommand } from './aws/index';\nimport { bot, createBotDeprecate, deployBotDeprecate, saveBotDeprecate } from './bots';\nimport { bulk } from './bulk';\nimport { dicomweb } from './dicomweb';\nimport { hl7 } from './hl7';\nimport { profile } from './profiles';\nimport { project } from './project';\nimport { deleteObject, get, patch, post, put } from './rest';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nexport async function main(argv: string[]): Promise<void> {\n const index = new MedplumCommand('medplum')\n .description('Command to access Medplum CLI')\n .option('--client-id <clientId>', 'FHIR server client id')\n .option('--client-secret <clientSecret>', 'FHIR server client secret')\n .option('--base-url <baseUrl>', 'FHIR server base URL, must be absolute')\n .option('--token-url <tokenUrl>', 'FHIR server token URL, absolute or relative to base URL')\n .option('--authorize-url <authorizeUrl>', 'FHIR server authorize URL, absolute or relative to base URL')\n .option('--fhir-url, --fhir-url-path <fhirUrlPath>', 'FHIR server URL, absolute or relative to base URL')\n .option('--scope <scope>', 'OAuth scope (e.g., \"openid offline_access\")')\n .option('--access-token <accessToken>', 'Access token for token exchange authentication')\n .option('--callback-url <callbackUrl>', 'Callback URL for authorization code flow')\n .option('--subject <subject>', 'Subject for JWT authentication')\n .option('--audience <audience>', 'Audience for JWT authentication')\n .option('--issuer <issuer>', 'Issuer for JWT authentication')\n .option('--private-key-path <privateKeyPath>', 'Private key path for JWT assertion')\n .option('-p, --profile <profile>', 'Profile name')\n .option('-v --verbose', 'Verbose output')\n .addOption(\n new Option('--auth-type <authType>', 'Type of authentication').choices([\n 'basic',\n 'client-credentials',\n 'authorization-code',\n 'jwt-bearer',\n 'token-exchange',\n 'jwt-assertion',\n ])\n )\n .on('option:verbose', () => {\n process.env.VERBOSE = '1';\n });\n\n // Configure CLI\n index.exitOverride();\n index.version(MEDPLUM_VERSION);\n index.configureHelp({ showGlobalOptions: true });\n\n // Auth commands\n addSubcommand(index, login);\n addSubcommand(index, whoami);\n addSubcommand(index, token);\n\n // REST commands\n addSubcommand(index, get);\n addSubcommand(index, post);\n addSubcommand(index, patch);\n addSubcommand(index, put);\n addSubcommand(index, deleteObject);\n\n // Project\n addSubcommand(index, project);\n\n // Bulk Commands\n addSubcommand(index, bulk);\n\n // Bot Commands\n addSubcommand(index, bot);\n\n // Agent Commands\n addSubcommand(index, agent);\n\n // Deprecated Bot Commands\n addSubcommand(index, saveBotDeprecate);\n addSubcommand(index, deployBotDeprecate);\n addSubcommand(index, createBotDeprecate);\n\n // Profile Commands\n addSubcommand(index, profile);\n\n // AWS commands\n addSubcommand(index, buildAwsCommand());\n\n // HL7 commands\n addSubcommand(index, hl7);\n\n // DICOMweb commands\n addSubcommand(index, dicomweb);\n\n try {\n await index.parseAsync(argv);\n } catch (err) {\n handleError(err as Error);\n }\n}\n\nexport function handleError(err: Error | CommanderError): void {\n let exitCode = 1;\n let shouldPrint = true;\n if (err instanceof CommanderError) {\n // We return if not in verbose mode for CommanderErrors\n // Since commander.js will already log the error to console for us\n // Previously we didn't have this guard here and it would always double print errors\n if (!process.env.VERBOSE) {\n shouldPrint = false;\n }\n exitCode = err.exitCode;\n }\n if (exitCode !== 0 && shouldPrint) {\n writeErrorToStderr(err, !!process.env.VERBOSE);\n const cause = err.cause;\n if (process.env.VERBOSE) {\n if (Array.isArray(cause)) {\n for (const err of cause as Error[]) {\n writeErrorToStderr(err, true);\n }\n } else if (cause instanceof Error) {\n writeErrorToStderr(cause, true);\n }\n }\n }\n process.exit(exitCode);\n}\n\nfunction writeErrorToStderr(err: unknown, verbose = false): void {\n if (verbose) {\n console.error(err);\n return;\n }\n if (err instanceof CommanderError) {\n process.stderr.write(`${normalizeErrorString(err)}\\n`);\n } else {\n process.stderr.write(`Error: ${normalizeErrorString(err)}\\n`);\n }\n}\n\nexport async function run(): Promise<void> {\n if (existsSync('.env')) {\n process.loadEnvFile();\n }\n await main(process.argv);\n}\n\nif (import.meta.main) {\n run().catch((err) => {\n console.error('Unhandled error:', normalizeErrorString(err));\n process.exit(1);\n });\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type {\n AgentChannelStats,\n AgentStats,\n AgentStatValue,\n IssueSeverity,\n MedplumClient,\n MedplumClientOptions,\n WithId,\n} from '@medplum/core';\nimport { ContentType, EMPTY, isOk, isUUID, normalizeErrorString } from '@medplum/core';\nimport type { Agent, Bundle, OperationOutcome, Parameters, ParametersParameter, Reference } from '@medplum/fhirtypes';\nimport { Option } from 'commander';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nexport type ValidIdsOrCriteria = { type: 'ids'; ids: string[] } | { type: 'criteria'; criteria: string };\n\nexport type ParsedParametersMap<R extends string[], O extends string[]> = Record<R[number], string> &\n Record<O[number], string | undefined>;\n\nexport type ParamNames<R extends string[], O extends string[] = []> = {\n required: R;\n optional?: O;\n};\n\nexport type AgentBulkOpResponse<T extends Parameters | OperationOutcome = Parameters | OperationOutcome> = {\n agent: WithId<Agent>;\n result: T;\n};\n\nexport type CallAgentBulkOperationArgs<T extends Record<string, unknown>, R extends Parameters | OperationOutcome> = {\n operation: string;\n agentIds: string[];\n options: MedplumClientOptions & { criteria: string; output?: 'json' };\n params?: Record<string, string | boolean | number>;\n parseSuccessfulResponse: (response: AgentBulkOpResponse<R>) => T;\n renderSuccessfulRows?: (rows: T[]) => void;\n};\n\nexport type FailedRow = {\n id: string;\n name: string;\n severity: IssueSeverity;\n code: string;\n details: string;\n};\n\nexport type StatusRow = {\n id: string;\n name: string;\n enabledStatus: string;\n connectionStatus: string;\n version: string;\n statusLastUpdated: string;\n};\n\nconst agentStatusCommand = new MedplumCommand('status').aliases(['info', 'list', 'ls']);\nconst agentPingCommand = new MedplumCommand('ping');\nconst agentPushCommand = new MedplumCommand('push');\nconst agentReloadConfigCommand = new MedplumCommand('reload-config');\nconst agentUpgradeCommand = new MedplumCommand('upgrade');\nconst agentStatsCommand = new MedplumCommand('stats');\n\nexport const agent = new MedplumCommand('agent');\naddSubcommand(agent, agentStatusCommand);\naddSubcommand(agent, agentPingCommand);\naddSubcommand(agent, agentPushCommand);\naddSubcommand(agent, agentReloadConfigCommand);\naddSubcommand(agent, agentUpgradeCommand);\naddSubcommand(agent, agentStatsCommand);\n\nagentStatusCommand\n .description('Get the status of a specified agent')\n .argument('[agentIds...]', 'The ID(s) of the agent(s) to get the status of')\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg'\n )\n .addOption(\n new Option('--output <format>', 'An optional output format, defaults to table')\n .choices(['table', 'json'])\n .default('table')\n )\n .action(async (agentIds, options) => {\n await callAgentBulkOperation({\n operation: '$bulk-status',\n agentIds,\n options,\n parseSuccessfulResponse: (response: AgentBulkOpResponse<Parameters>) => {\n const statusEntry = parseParameterValues(response.result, {\n required: ['status', 'version'],\n optional: ['lastUpdated'],\n });\n\n return {\n id: response.agent.id,\n name: response.agent.name,\n enabledStatus: response.agent.status,\n version: statusEntry.version,\n connectionStatus: statusEntry.status,\n statusLastUpdated: statusEntry.lastUpdated ?? 'N/A',\n } satisfies StatusRow;\n },\n });\n });\n\nagentPingCommand\n .description('Ping a host from a specified agent')\n .argument('<ipOrDomain>', 'The IPv4 address or domain name to ping')\n .argument(\n '[agentId]',\n 'Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option'\n )\n .option('--count <count>', 'An optional amount of pings to issue before returning results', '1')\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg'\n )\n .action(async (ipOrDomain, agentId, options) => {\n const medplum = await createMedplumClient(options);\n const agentRef = await resolveAgentReference(medplum, agentId, options);\n\n const count = Number.parseInt(options.count, 10);\n if (Number.isNaN(count)) {\n throw new Error('--count <count> must be an integer if specified');\n }\n\n try {\n const pingResult = (await medplum.pushToAgent(agentRef, ipOrDomain, `PING ${count}`, ContentType.PING, true, {\n maxRetries: 0,\n })) as string;\n console.info(pingResult);\n } catch (err) {\n throw new Error('Unexpected response from agent while pinging', { cause: err });\n }\n });\n\nagentPushCommand\n .description('Push a message to a target device via a specified agent')\n .argument('<deviceId>', 'The ID of the device to push the message to')\n .argument('<message>', 'The message to send to the destination device')\n .argument(\n '[agentId]',\n 'Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option'\n )\n .option('--content-type <contentType>', 'The content type of the message', ContentType.HL7_V2)\n .option('--no-wait', 'Tells the server not to wait for a response from the destination device')\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg'\n )\n .action(async (deviceId, message, agentId, options) => {\n const medplum = await createMedplumClient(options);\n const agentRef = await resolveAgentReference(medplum, agentId, options);\n\n let pushResult: string;\n try {\n pushResult = (await medplum.pushToAgent(\n agentRef,\n { reference: `Device/${deviceId}` },\n message,\n options.contentType,\n options.wait !== false,\n { maxRetries: 0 }\n )) as string;\n } catch (err) {\n throw new Error('Unexpected response from agent while pushing message to agent', { cause: err });\n }\n\n console.info(pushResult);\n });\n\nagentReloadConfigCommand\n .description('Reload the config for the specified agent(s)')\n .argument(\n '[agentIds...]',\n 'The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag'\n )\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg'\n )\n .addOption(\n new Option('--output <format>', 'An optional output format, defaults to table')\n .choices(['table', 'json'])\n .default('table')\n )\n .action(async (agentIds, options) => {\n await callAgentBulkOperation({\n operation: '$reload-config',\n agentIds,\n options,\n parseSuccessfulResponse: (response: AgentBulkOpResponse<OperationOutcome>) => {\n return {\n id: response.agent.id,\n name: response.agent.name,\n };\n },\n });\n });\n\nagentUpgradeCommand\n .description('Upgrade the version for the specified agent(s)')\n .argument(\n '[agentIds...]',\n 'The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag'\n )\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg'\n )\n .option(\n '--agentVersion <version>',\n 'An optional agent version to upgrade to. Defaults to the latest version if flag not included'\n )\n .option('--force', 'Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.')\n .addOption(\n new Option('--output <format>', 'An optional output format, defaults to table')\n .choices(['table', 'json'])\n .default('table')\n )\n .action(async (agentIds, options) => {\n const params: Record<string, string | boolean | number> = {};\n if (options.agentVersion) {\n params.version = options.agentVersion;\n }\n if (options.force) {\n params.force = true;\n }\n\n await callAgentBulkOperation({\n operation: '$upgrade',\n agentIds,\n options,\n params,\n parseSuccessfulResponse: (response: AgentBulkOpResponse<OperationOutcome>) => {\n return {\n id: response.agent.id,\n name: response.agent.name,\n version: options.agentVersion ?? 'latest',\n };\n },\n });\n });\n\nagentStatsCommand\n .description('Get runtime statistics for the specified agent(s)')\n .argument(\n '[agentIds...]',\n 'The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag'\n )\n .option(\n '--criteria <criteria>',\n 'An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg'\n )\n .addOption(\n new Option('--output <format>', 'An optional output format, defaults to table')\n .choices(['table', 'json'])\n .default('table')\n )\n .action(async (agentIds, options) => {\n await callAgentBulkOperation({\n operation: '$stats',\n agentIds,\n options,\n parseSuccessfulResponse: (response: AgentBulkOpResponse<Parameters>) => {\n const { stats } = parseParameterValues(response.result, { required: ['stats'] });\n let parsed: AgentStats | undefined;\n try {\n parsed = JSON.parse(stats) as AgentStats;\n } catch (err) {\n console.error(`Failed to parse stats for agent ${response.agent.id}: ${normalizeErrorString(err)}`);\n }\n return {\n id: response.agent.id,\n name: response.agent.name,\n stats: parsed,\n };\n },\n renderSuccessfulRows: (rows) => {\n for (let i = 0; i < rows.length; i++) {\n if (i > 0) {\n console.info();\n }\n renderAgentStats(rows[i]);\n }\n },\n });\n });\n\nconst SUMMARY_STAT_KEYS = [\n 'live',\n 'ping',\n 'hl7ConnectionsOpen',\n 'hl7ClientCount',\n 'hl7QueueDepth',\n 'webSocketQueueDepth',\n 'outstandingHeartbeats',\n] as const satisfies readonly (keyof AgentStats)[];\n\nfunction formatStatValue(value: AgentStatValue | undefined): string {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return value.toString();\n}\n\nfunction buildChannelStatsRows(\n entries: Record<string, AgentChannelStats> | undefined\n): Record<string, number | string>[] {\n if (!entries) {\n return [];\n }\n return Object.entries(entries)\n .filter(([, value]) => value?.rtt)\n .map(([name, value]) => ({\n name,\n count: value.rtt.count,\n pending: value.rtt.pendingCount,\n 'min (ms)': value.rtt.min,\n 'avg (ms)': value.rtt.average,\n 'max (ms)': value.rtt.max,\n 'p50 (ms)': value.rtt.p50,\n 'p95 (ms)': value.rtt.p95,\n 'p99 (ms)': value.rtt.p99,\n }));\n}\n\nfunction renderAgentStats(row: { id: string; name?: string; stats: AgentStats | undefined }): void {\n const heading = row.name ? `${row.name} (${row.id})` : row.id;\n console.info(`Agent: ${heading}`);\n if (!row.stats) {\n console.info(' (stats unavailable)');\n return;\n }\n\n const summary: Record<string, string> = {};\n for (const key of SUMMARY_STAT_KEYS) {\n summary[key] = formatStatValue(row.stats[key]);\n }\n const knownKeys = new Set<string>([...SUMMARY_STAT_KEYS, 'channelStats', 'clientStats']);\n for (const [key, value] of Object.entries(row.stats)) {\n if (!knownKeys.has(key)) {\n summary[key] = formatStatValue(value);\n }\n }\n console.table(summary);\n\n const channelRows = buildChannelStatsRows(row.stats.channelStats);\n if (channelRows.length) {\n console.info('Channel Stats:');\n console.table(channelRows);\n }\n\n const clientRows = buildChannelStatsRows(row.stats.clientStats);\n if (clientRows.length) {\n console.info('Client Stats:');\n console.table(clientRows);\n }\n}\n\nexport async function callAgentBulkOperation<\n T extends Record<string, unknown>,\n R extends Parameters | OperationOutcome,\n>({\n operation,\n agentIds,\n options,\n params = {},\n parseSuccessfulResponse,\n renderSuccessfulRows,\n}: CallAgentBulkOperationArgs<T, R>): Promise<void> {\n const normalized = parseEitherIdsOrCriteria(agentIds, options);\n const medplum = await createMedplumClient(options);\n const usedCriteria = normalized.type === 'criteria' ? normalized.criteria : `Agent?_id=${normalized.ids.join(',')}`;\n const searchParams = new URLSearchParams(usedCriteria.split('?')[1]);\n for (const [paramName, paramVal] of Object.entries(params)) {\n searchParams.append(paramName, paramVal.toString());\n }\n\n let result: Bundle<Parameters> | Parameters | OperationOutcome;\n try {\n const url = medplum.fhirUrl('Agent', operation);\n url.search = searchParams.toString();\n result = await medplum.get(url, {\n cache: 'reload',\n });\n } catch (err) {\n throw new Error(`Operation '${operation}' failed`, { cause: err });\n }\n\n if (options.output === 'json') {\n console.info(JSON.stringify(result, null, 2));\n return;\n }\n\n const successfulResponses = [] as AgentBulkOpResponse<R>[];\n const failedResponses = [] as AgentBulkOpResponse<OperationOutcome>[];\n\n switch (result.resourceType) {\n case 'Bundle': {\n const responses = parseAgentBulkOpBundle(result);\n for (const response of responses) {\n if (response.result.resourceType === 'Parameters' || isOk(response.result)) {\n successfulResponses.push(response as AgentBulkOpResponse<R>);\n } else {\n failedResponses.push(response as AgentBulkOpResponse<OperationOutcome>);\n }\n }\n break;\n }\n case 'Parameters':\n case 'OperationOutcome': {\n const agent = await medplum.searchOne('Agent', searchParams, { cache: 'reload' });\n if (!agent) {\n throw new Error('Agent not found');\n }\n if (result.resourceType === 'Parameters') {\n successfulResponses.push({ agent, result } as AgentBulkOpResponse<R>);\n } else {\n failedResponses.push({ agent, result });\n }\n break;\n }\n default:\n throw new Error(`Invalid result received for '${operation}' operation: ${JSON.stringify(result)}`);\n }\n\n const successfulRows = [] as T[];\n for (const response of successfulResponses) {\n const row = parseSuccessfulResponse(response);\n successfulRows.push(row);\n }\n\n const failedRows = [] as FailedRow[];\n for (const response of failedResponses) {\n const outcome = response.result;\n const issue = outcome.issue?.[0];\n const row = {\n id: response.agent.id,\n name: response.agent.name,\n severity: issue.severity,\n code: issue.code,\n details: issue.details?.text ?? 'No details to show',\n } satisfies FailedRow;\n failedRows.push(row);\n }\n\n console.info(`\\n${successfulRows.length} successful response(s):\\n`);\n if (renderSuccessfulRows) {\n if (successfulRows.length) {\n renderSuccessfulRows(successfulRows);\n } else {\n console.info('No successful responses received');\n }\n } else {\n console.table(successfulRows.length ? successfulRows : 'No successful responses received');\n }\n console.info();\n\n if (failedRows.length) {\n console.info(`${failedRows.length} failed response(s):`);\n console.info();\n console.table(failedRows);\n }\n}\n\nexport async function resolveAgentReference(\n medplum: MedplumClient,\n agentId: string | undefined,\n options: Record<string, string>\n): Promise<Reference<Agent>> {\n if (!(agentId || options.criteria)) {\n throw new Error('This command requires either an [agentId] or a --criteria <criteria> flag');\n }\n if (agentId && options.criteria) {\n throw new Error(\n 'Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive'\n );\n }\n\n let usedId: string;\n if (agentId) {\n usedId = agentId;\n } else {\n assertValidAgentCriteria(options.criteria);\n const result = await medplum.search('Agent', `${options.criteria.split('?')[1]}&_count=2`);\n if (!result?.entry?.length) {\n throw new Error('Could not find an agent matching the provided criteria');\n }\n if (result.entry.length !== 1) {\n throw new Error(\n 'Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent'\n );\n }\n usedId = result.entry[0].resource?.id as string;\n }\n\n return { reference: `Agent/${usedId}` };\n}\n\nexport function parseAgentBulkOpBundle(bundle: Bundle<Parameters>): AgentBulkOpResponse[] {\n const responses = [];\n for (const entry of bundle.entry ?? EMPTY) {\n if (!entry.resource) {\n throw new Error('No Parameter resource found in entry');\n }\n responses.push(parseAgentBulkOpParameters(entry.resource));\n }\n return responses;\n}\n\nexport function parseAgentBulkOpParameters(params: Parameters): AgentBulkOpResponse {\n const agent = params.parameter?.find((p) => p.name === 'agent')?.resource as WithId<Agent>;\n if (!agent) {\n throw new Error(\"Agent bulk operation response missing 'agent'\");\n }\n if (agent.resourceType !== 'Agent') {\n throw new Error(`Agent bulk operation returned 'agent' with type '${agent.resourceType}'`);\n }\n const result = params.parameter?.find((p) => p.name === 'result')?.resource;\n if (!result) {\n throw new Error(\"Agent bulk operation response missing result'\");\n }\n if (!(result.resourceType === 'Parameters' || result.resourceType === 'OperationOutcome')) {\n throw new Error(`Agent bulk operation returned 'result' with type '${result.resourceType}'`);\n }\n return { agent, result };\n}\n\nexport function parseParameterValues<const R extends string[], const O extends string[] = []>(\n params: Parameters,\n paramNames: ParamNames<R, O>\n): ParsedParametersMap<R, O> {\n const map = {} as ParsedParametersMap<R, O>;\n const requiredParams = paramNames.required;\n const optionalParams = paramNames.optional;\n\n for (const paramName of requiredParams) {\n const paramsParam = params.parameter?.find((p) => p.name === paramName);\n if (!paramsParam) {\n throw new Error(`Failed to find parameter '${paramName}'`);\n }\n let valueProp: string | undefined;\n for (const prop in paramsParam) {\n // This technically could lead to parsing invalid values (ie. valueAbc123) but for now we can pretend this always works\n if (prop.startsWith('value')) {\n if (valueProp) {\n throw new Error(`Found multiple values for parameter '${paramName}'`);\n }\n valueProp = prop;\n }\n }\n if (!valueProp) {\n throw new Error(`Failed to find a value for parameter '${paramName}'`);\n }\n\n // @ts-expect-error ParsedParameterMap expects key to be T[number], which it is, but unable to be inferred in for-of loop\n map[paramName] = paramsParam[valueProp] as string;\n }\n\n if (optionalParams?.length) {\n for (const paramName of optionalParams) {\n const paramsParam = params.parameter?.find((p) => p.name === paramName);\n if (!paramsParam) {\n continue;\n }\n const value = extractValueFromParametersParameter(paramName, paramsParam);\n // @ts-expect-error ParsedParameterMap expects key to be T[number], which it is, but unable to be inferred in for-of loop\n map[paramName] = value;\n }\n }\n\n return map;\n}\n\nexport function extractValueFromParametersParameter(paramName: string, paramsParam: ParametersParameter): string {\n let valueProp: string | undefined;\n for (const prop in paramsParam) {\n // This technically could lead to parsing invalid values (ie. valueAbc123) but for now we can pretend this always works\n if (prop.startsWith('value')) {\n if (valueProp) {\n throw new Error(`Found multiple values for parameter '${paramName}'`);\n }\n valueProp = prop;\n }\n }\n if (!valueProp) {\n throw new Error(`Failed to find a value for parameter '${paramName}'`);\n }\n // @ts-expect-error valueProp is any string but it should only be choice-of-type `value[x]`\n return paramsParam[valueProp] as string;\n}\n\nexport function parseEitherIdsOrCriteria(agentIds: string[], options: { criteria: string }): ValidIdsOrCriteria {\n if (!Array.isArray(agentIds)) {\n throw new Error('Invalid agent IDs array');\n }\n if (agentIds.length) {\n // Check that options.criteria is not defined\n if (options.criteria) {\n throw new Error(\n 'Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive'\n );\n }\n for (const id of agentIds) {\n if (!isUUID(id)) {\n throw new Error(`Input '${id}' is not a valid agentId`);\n }\n }\n return { type: 'ids', ids: agentIds };\n }\n if (options.criteria) {\n assertValidAgentCriteria(options.criteria);\n return { type: 'criteria', criteria: options.criteria };\n }\n\n throw new Error('Either an [agentId...] arg or a --criteria <criteria> flag is required');\n}\n\nfunction assertValidAgentCriteria(criteria: string): void {\n const invalidCriteriaMsg =\n \"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`\";\n if (typeof criteria !== 'string') {\n throw new Error(invalidCriteriaMsg);\n }\n const [resourceType, queryStr] = criteria.split('?');\n if (resourceType !== 'Agent' || !queryStr) {\n throw new Error(invalidCriteriaMsg);\n }\n try {\n // eslint-disable-next-line no-new\n new URLSearchParams(queryStr);\n } catch (err) {\n throw new Error(invalidCriteriaMsg, { cause: err });\n }\n if (!queryStr.includes('=')) {\n throw new Error(invalidCriteriaMsg, { cause: new Error('Query string lacks at least one `=`') });\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClientOptions } from '@medplum/core';\nimport { MedplumClient } from '@medplum/core';\nimport { FileSystemStorage } from '../storage';\nimport type { Profile } from '../utils';\n\nexport async function createMedplumClient(\n options: MedplumClientOptions & { profile?: string },\n setupCredentials = true\n): Promise<MedplumClient> {\n const profileName = options.profile ?? 'default';\n\n const storage = new FileSystemStorage(profileName);\n const profile = storage.getObject('options') as Profile;\n if (profileName !== 'default' && !profile) {\n throw new Error(`Profile \"${profileName}\" does not exist`);\n }\n\n const { baseUrl, fhirUrlPath, accessToken, tokenUrl, authorizeUrl, clientId, clientSecret } = getClientValues(\n options,\n storage\n );\n const fetchApi = options.fetch ?? fetch;\n\n // Validate base URL if non-default is specified\n if (options.baseUrl && options.baseUrl !== 'https://api.medplum.com/') {\n await validateBaseUrl(options.baseUrl, fetchApi);\n }\n\n const medplumClient = new MedplumClient({\n fetch: fetchApi,\n baseUrl,\n tokenUrl,\n fhirUrlPath,\n authorizeUrl,\n storage,\n onUnauthenticated,\n verbose: options.verbose,\n });\n\n // In most commands, we want to automatically set up credentials.\n // However, in some cases such as \"login\", we don't want to do that.\n // Setup credentials if the user does not explicitly disable it.\n if (setupCredentials) {\n if (accessToken) {\n // If the access token is provided, use it.\n medplumClient.setAccessToken(accessToken);\n } else if (clientId && clientSecret) {\n // If the client ID and secret are provided, use them.\n medplumClient.setBasicAuth(clientId, clientSecret);\n if (profile?.authType !== 'basic') {\n // Unless the user explicitly specified basic auth, start the client login.\n await medplumClient.startClientLogin(clientId, clientSecret);\n }\n }\n }\n\n return medplumClient;\n}\n\nfunction getClientValues(options: MedplumClientOptions, storage: FileSystemStorage): MedplumClientOptions {\n const storageOptions = storage.getObject('options') as MedplumClientOptions;\n const baseUrl =\n options.baseUrl ?? storageOptions?.baseUrl ?? process.env['MEDPLUM_BASE_URL'] ?? 'https://api.medplum.com/';\n const fhirUrlPath = options.fhirUrlPath ?? storageOptions?.fhirUrlPath ?? process.env['MEDPLUM_FHIR_URL_PATH'];\n const accessToken = options.accessToken ?? storageOptions?.accessToken ?? process.env['MEDPLUM_CLIENT_ACCESS_TOKEN'];\n const tokenUrl = options.tokenUrl ?? storageOptions?.tokenUrl ?? process.env['MEDPLUM_TOKEN_URL'];\n const authorizeUrl = options.authorizeUrl ?? storageOptions?.authorizeUrl ?? process.env['MEDPLUM_AUTHORIZE_URL'];\n\n const clientId = options.clientId ?? storageOptions?.clientId ?? process.env['MEDPLUM_CLIENT_ID'];\n const clientSecret = options.clientSecret ?? storageOptions?.clientSecret ?? process.env['MEDPLUM_CLIENT_SECRET'];\n\n return { baseUrl, fhirUrlPath, accessToken, tokenUrl, authorizeUrl, clientId, clientSecret };\n}\n\nasync function validateBaseUrl(\n baseUrl: string,\n fetchApi: (input: string, init?: RequestInit) => Promise<Response>\n): Promise<void> {\n try {\n const url = new URL('healthcheck', baseUrl).toString();\n const response = await fetchApi(url);\n if (!response.ok) {\n throw new Error(`Healthcheck returned status ${response.status}`);\n }\n const data = (await response.json()) as { ok?: unknown };\n if (data.ok === true) {\n return;\n }\n throw new Error('Healthcheck response does not have \"ok\": true');\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(`Failed to validate base URL \"${baseUrl}\": ${message}`);\n }\n}\n\nexport function onUnauthenticated(): void {\n console.log('Unauthenticated: run `npx medplum login` to sign in');\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ClientStorage } from '@medplum/core';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\n\nexport class FileSystemStorage extends ClientStorage {\n private readonly dirName: string;\n private readonly fileName: string;\n\n constructor(profile: string) {\n super();\n this.dirName = resolve(homedir(), '.medplum');\n this.fileName = resolve(this.dirName, profile + '.json');\n }\n\n clear(): void {\n this.writeFile({});\n }\n\n getString(key: string): string | undefined {\n return this.readFile()?.[key];\n }\n\n setString(key: string, value: string | undefined): void {\n const data = this.readFile() ?? {};\n if (value) {\n data[key] = value;\n } else {\n delete data[key];\n }\n this.writeFile(data);\n }\n\n getObject<T>(key: string): T | undefined {\n const str = this.getString(key);\n return str ? (JSON.parse(str) as T) : undefined;\n }\n\n setObject<T>(key: string, value: T): void {\n this.setString(key, value ? JSON.stringify(value) : undefined);\n }\n\n private readFile(): Record<string, string> | undefined {\n if (existsSync(this.fileName)) {\n return JSON.parse(readFileSync(this.fileName, 'utf8'));\n }\n return undefined;\n }\n\n private writeFile(data: Record<string, string>): void {\n if (!existsSync(this.dirName)) {\n mkdirSync(this.dirName);\n }\n writeFileSync(this.fileName, JSON.stringify(data, null, 2), 'utf8');\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, WithId } from '@medplum/core';\nimport { ContentType, encodeBase64, isOk, normalizeErrorString, OAuthSigningAlgorithm } from '@medplum/core';\nimport type { Bot, Extension, OperationOutcome } from '@medplum/fhirtypes';\nimport { Command } from 'commander';\nimport { SignJWT } from 'jose';\nimport { createHmac, createPrivateKey, randomBytes } from 'node:crypto';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, extname, resolve } from 'node:path';\nimport { isPromise } from 'node:util/types';\nimport { extract } from 'tar';\nimport { FileSystemStorage } from './storage';\n\nexport interface MedplumConfig {\n baseUrl?: string;\n clientId?: string;\n googleClientId?: string;\n recaptchaSiteKey?: string;\n registerEnabled?: boolean;\n bots?: MedplumBotConfig[];\n}\n\nexport interface MedplumBotConfig {\n readonly name: string;\n readonly id: string;\n readonly source: string;\n readonly dist?: string;\n}\n\nexport interface Profile {\n readonly name?: string;\n readonly authType?: string;\n readonly baseUrl?: string;\n readonly clientId?: string;\n readonly clientSecret?: string;\n readonly tokenUrl?: string;\n readonly authorizeUrl?: string;\n readonly fhirUrlPath?: string;\n readonly scope?: string;\n readonly accessToken?: string;\n readonly callbackUrl?: string;\n readonly subject?: string;\n readonly audience?: string;\n readonly issuer?: string;\n readonly privateKeyPath?: string;\n}\n\nexport function prettyPrint(input: unknown): void {\n console.log(JSON.stringify(input, null, 2));\n}\n\nexport async function saveBot(medplum: MedplumClient, botConfig: MedplumBotConfig, bot: Bot): Promise<void> {\n const codePath = botConfig.source;\n const code = readFileContents(codePath);\n if (!code) {\n return;\n }\n\n console.log('Saving source code...');\n const sourceCode = await medplum.createAttachment({\n data: code,\n filename: basename(codePath),\n contentType: getCodeContentType(codePath),\n });\n\n console.log('Updating bot...');\n const updateResult = await medplum.updateResource({\n ...bot,\n sourceCode,\n });\n console.log('Success! New bot version: ' + updateResult.meta?.versionId);\n}\n\nexport async function deployBot(medplum: MedplumClient, botConfig: MedplumBotConfig, bot: WithId<Bot>): Promise<void> {\n const codePath = botConfig.dist ?? botConfig.source;\n const code = readFileContents(codePath);\n if (!code) {\n return;\n }\n\n console.log('Deploying bot...');\n const deployResult = await medplum.post<OperationOutcome>(medplum.fhirUrl('Bot', bot.id, '$deploy'), {\n code,\n filename: basename(codePath),\n });\n console.log('Deploy result: ' + deployResult.issue?.[0]?.details?.text);\n if (!isOk(deployResult)) {\n throw new Error(`Bot deploy failed: ${normalizeErrorString(deployResult)}`);\n }\n}\n\nexport async function createBot(\n medplum: MedplumClient,\n botName: string,\n projectId: string,\n sourceFile: string,\n distFile: string,\n runtimeVersion?: string,\n writeConfig?: boolean\n): Promise<void> {\n const body = {\n name: botName,\n description: '',\n runtimeVersion,\n };\n const newBot = await medplum.post<WithId<Bot>>('admin/projects/' + projectId + '/bot', body);\n const bot = await medplum.readResource('Bot', newBot.id);\n\n const botConfig = {\n name: botName,\n id: newBot.id,\n source: sourceFile,\n dist: distFile,\n };\n\n await saveBot(medplum, botConfig, bot);\n await deployBot(medplum, botConfig, bot);\n console.log(`Success! Bot created: ${bot.id}`);\n\n if (writeConfig) {\n addBotToConfig(botConfig);\n }\n}\n\nexport function readBotConfigs(botName: string): MedplumBotConfig[] {\n const regExBotName = new RegExp('^' + escapeRegex(botName).replaceAll(String.raw`\\*`, '.*') + '$');\n const botConfigs = readConfig()?.bots?.filter((b) => regExBotName.test(b.name));\n if (!botConfigs) {\n return [];\n }\n return botConfigs;\n}\n\n/**\n * Returns the config file name.\n * @param tagName - Optional environment tag name.\n * @param options - Optional command line options.\n * @returns The config file name.\n */\nexport function getConfigFileName(tagName?: string, options?: Record<string, any>): string {\n if (options?.file) {\n return options.file;\n }\n const parts = ['medplum'];\n if (tagName) {\n parts.push(tagName);\n }\n parts.push('config');\n if (options?.server) {\n parts.push('server');\n }\n parts.push('json');\n return parts.join('.');\n}\n\n/**\n * Writes a config file to disk.\n * @param configFileName - The config file name.\n * @param config - The config file contents.\n */\nexport function writeConfig(configFileName: string, config: Record<string, any>): void {\n writeFileSync(resolve(configFileName), JSON.stringify(config, undefined, 2), 'utf-8');\n}\n\nexport function readConfig(tagName?: string, options?: { file?: string }): MedplumConfig | undefined {\n const fileName = getConfigFileName(tagName, options);\n const content = readFileContents(fileName);\n if (!content) {\n return undefined;\n }\n return JSON.parse(content);\n}\n\nexport function readServerConfig(tagName?: string): Record<string, string | number> | undefined {\n const content = readFileContents(getConfigFileName(tagName, { server: true }));\n if (!content) {\n return undefined;\n }\n return JSON.parse(content);\n}\n\nfunction readFileContents(fileName: string): string {\n const path = resolve(fileName);\n if (!existsSync(path)) {\n return '';\n }\n return readFileSync(path, 'utf8');\n}\n\nfunction addBotToConfig(botConfig: MedplumBotConfig): void {\n const config = readConfig() ?? {};\n if (!config.bots) {\n config.bots = [];\n }\n config.bots.push(botConfig);\n writeFileSync('medplum.config.json', JSON.stringify(config, null, 2), 'utf8');\n console.log(`Bot added to config: ${botConfig.id}`);\n}\n\nfunction escapeRegex(str: string): string {\n return str.replaceAll(/[/\\-\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n}\n\n/**\n * Creates a safe tar extractor that limits the number of files and total size.\n *\n * Expanding archive files without controlling resource consumption is security-sensitive\n *\n * See: https://sonarcloud.io/organizations/medplum/rules?open=typescript%3AS5042&rule_key=typescript%3AS5042\n * @param destinationDir - The destination directory where all files will be extracted.\n * @returns A tar file extractor.\n */\nexport function safeTarExtractor(destinationDir: string): NodeJS.WritableStream {\n const MAX_FILES = 100;\n const MAX_SIZE = 10 * 1024 * 1024; // 10 MB\n\n let fileCount = 0;\n let totalSize = 0;\n\n return extract({\n cwd: destinationDir,\n filter: (_path, entry) => {\n fileCount++;\n if (fileCount > MAX_FILES) {\n throw new Error('Tar extractor reached max number of files');\n }\n\n totalSize += entry.size;\n if (totalSize > MAX_SIZE) {\n throw new Error('Tar extractor reached max size');\n }\n\n return true;\n },\n });\n}\n\nexport function getUnsupportedExtension(): Extension {\n return {\n url: 'http://hl7.org/fhir/StructureDefinition/data-absent-reason',\n valueCode: 'unsupported',\n };\n}\n\nexport function getCodeContentType(filename: string): string {\n const ext = extname(filename).toLowerCase();\n if (['.cjs', '.mjs', '.js'].includes(ext)) {\n return ContentType.JAVASCRIPT;\n }\n if (['.cts', '.mts', '.ts'].includes(ext)) {\n return ContentType.TYPESCRIPT;\n }\n return ContentType.TEXT;\n}\n\nexport function saveProfile(profileName: string, options: Profile): Profile {\n const storage = new FileSystemStorage(profileName);\n const optionsObject = { name: profileName, ...options };\n storage.setObject('options', optionsObject);\n return optionsObject;\n}\n\nexport function loadProfile(profileName: string): Profile {\n const storage = new FileSystemStorage(profileName);\n return storage.getObject('options') as Profile;\n}\n\nexport function profileExists(storage: FileSystemStorage, profile: string): boolean {\n if (profile === 'default') {\n return true;\n }\n const optionsObject = storage.getObject('options');\n if (!optionsObject) {\n return false;\n }\n return true;\n}\n\nexport async function jwtBearerLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n const header = {\n typ: 'JWT',\n alg: OAuthSigningAlgorithm.HS256,\n };\n\n const currentTimestamp = Math.floor(Date.now() / 1000);\n const data = {\n aud: `${profile.baseUrl}${profile.audience}`,\n iss: profile.issuer,\n sub: profile.subject,\n nbf: currentTimestamp,\n iat: currentTimestamp,\n exp: currentTimestamp + 604800, // expiry time is 7 days from time of creation\n };\n const encodedHeader = encodeBase64(JSON.stringify(header));\n const encodedData = encodeBase64(JSON.stringify(data));\n const token = `${encodedHeader}.${encodedData}`;\n const signature = createHmac('sha256', profile.clientSecret as string)\n .update(token)\n .digest('base64url');\n const signedToken = `${token}.${signature}`;\n await medplum.startJwtBearerLogin(profile.clientId as string, signedToken, profile.scope ?? '');\n}\n\nexport async function jwtAssertionLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n const privateKey = createPrivateKey(readFileSync(resolve(profile.privateKeyPath as string)));\n const jwt = await new SignJWT({})\n .setProtectedHeader({ typ: 'JWT', alg: OAuthSigningAlgorithm.RS384 })\n .setIssuer(profile.clientId as string)\n .setSubject(profile.clientId as string)\n .setAudience(`${profile.baseUrl}${profile.audience}`)\n .setJti(randomBytes(16).toString('hex'))\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(privateKey);\n await medplum.startJwtAssertionLogin(jwt);\n}\n\n/**\n * Attaches the provided subcommand to the provided parent command.\n *\n * We use this rather than directly calling the `addCommand` method on the parent command because we need\n * to modify some additional settings on each command before adding them to the parent.\n *\n * @param command - The parent command.\n * @param subcommand - The command to attach to the provided parent command.\n */\nexport function addSubcommand(command: Command, subcommand: Command): void {\n subcommand.configureHelp({ showGlobalOptions: true });\n command.addCommand(subcommand);\n}\n\nexport class MedplumCommand extends Command {\n action(fn: (...args: any[]) => void | Promise<void>): this {\n // This is the only way to get both global and local options propagated to all subcommands automatically\n // Otherwise you have to call `command.optsWithGlobals()` within every function to get merged global and local options\n const wrappedFn = withMergedOptions(this, fn);\n // @ts-expect-error Access to hidden member\n // This is the function that gets called when a command is executed\n // We overwrite it with the wrapped version\n super._actionHandler = wrappedFn;\n return this;\n }\n\n /**\n * We use this method to reset the option state\n * Which is not cleared between executions of the main function during tests\n *\n * This is because all of our subcommands are declared in the global scope\n *\n * Rather than re-architect the entire CLI package, I added this to make sure all options are reset between executions of main\n */\n resetOptionDefaults(): void {\n // @ts-expect-error Overriding private field\n this._optionValues = {};\n for (const option of this.options) {\n // So we also set options that default to false\n // We explicitly check strict equality to undefined\n if (option.defaultValue !== undefined) {\n // We use the attributeName since that's the camelCase'd name that is used to access options\n // @ts-expect-error Overriding private field\n this._optionValues[option.attributeName()] = option.defaultValue;\n }\n }\n }\n}\n\nexport function withMergedOptions(\n command: MedplumCommand,\n fn: ((...args: any[]) => Promise<void>) | ((...args: any[]) => void)\n): (args: any[]) => Promise<void> {\n // The .action callback takes an extra parameter which is the command or options.\n return async (args: any[]): Promise<void> => {\n const expectedArgsCount = command.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n actionArgs[expectedArgsCount] = command.optsWithGlobals();\n try {\n const result: Promise<void> | void = fn(...actionArgs);\n if (isPromise(result)) {\n await result;\n }\n } finally {\n // We want to always make sure to reset the options to default at the end of each execution,\n // We do it in a finally block in case the command errors\n command.resetOptionDefaults();\n }\n };\n}\n", "const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder(\"utf-8\", { fatal: !0 }), MAX_INT32 = 2 ** 32;\nfunction concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers)\n buf.set(buffer, i), i += buffer.length;\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32)\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);\n}\nfunction uint64be(value) {\n const high = Math.floor(value / MAX_INT32), low = value % MAX_INT32, buf = new Uint8Array(8);\n return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf;\n}\nfunction uint32be(value) {\n const buf = new Uint8Array(4);\n return writeUInt32BE(buf, value), buf;\n}\nconst NON_ASCII = /[^\\x00-\\x7f]/;\nfunction encode(string) {\n if (typeof string == \"string\" && string.length >= 128) {\n if (NON_ASCII.test(string))\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n return encoder.encode(string);\n }\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127)\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n bytes[i] = code;\n }\n return bytes;\n}\nfunction encodeBase64(input, url = !1) {\n if (Uint8Array.prototype.toBase64)\n return input.toBase64({ alphabet: url ? \"base64url\" : \"base64\", omitPadding: url });\n const CHUNK_SIZE = 32768, arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE)\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n const encoded = btoa(arr.join(\"\"));\n return url ? encoded.replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\") : encoded;\n}\nfunction decodeBase64(encoded, url = !1) {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(encoded, { alphabet: url ? \"base64url\" : \"base64\" });\n if (url) {\n if (encoded.includes(\"+\") || encoded.includes(\"/\"))\n throw new TypeError(\"Invalid base64url\");\n encoded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n }\n const binary = atob(encoded), bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\nasync function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\nexport {\n concat,\n decodeBase64,\n decoder,\n digest,\n encode,\n encodeBase64,\n encoder,\n strictDecoder,\n uint32be,\n uint64be\n};\n", "class JOSEError extends Error {\n static code = \"ERR_JOSE_GENERIC\";\n code = \"ERR_JOSE_GENERIC\";\n constructor(message, options) {\n super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);\n }\n}\nclass JWTClaimValidationFailed extends JOSEError {\n static code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JWTExpired extends JOSEError {\n static code = \"ERR_JWT_EXPIRED\";\n code = \"ERR_JWT_EXPIRED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JOSEAlgNotAllowed extends JOSEError {\n static code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n}\nclass JOSENotSupported extends JOSEError {\n static code = \"ERR_JOSE_NOT_SUPPORTED\";\n code = \"ERR_JOSE_NOT_SUPPORTED\";\n}\nclass JWEDecryptionFailed extends JOSEError {\n static code = \"ERR_JWE_DECRYPTION_FAILED\";\n code = \"ERR_JWE_DECRYPTION_FAILED\";\n constructor(message = \"decryption operation failed\", options) {\n super(message, options);\n }\n}\nclass JWEInvalid extends JOSEError {\n static code = \"ERR_JWE_INVALID\";\n code = \"ERR_JWE_INVALID\";\n}\nclass JWSInvalid extends JOSEError {\n static code = \"ERR_JWS_INVALID\";\n code = \"ERR_JWS_INVALID\";\n}\nclass JWTInvalid extends JOSEError {\n static code = \"ERR_JWT_INVALID\";\n code = \"ERR_JWT_INVALID\";\n}\nclass JWKInvalid extends JOSEError {\n static code = \"ERR_JWK_INVALID\";\n code = \"ERR_JWK_INVALID\";\n}\nclass JWKSInvalid extends JOSEError {\n static code = \"ERR_JWKS_INVALID\";\n code = \"ERR_JWKS_INVALID\";\n}\nclass JWKSNoMatchingKey extends JOSEError {\n static code = \"ERR_JWKS_NO_MATCHING_KEY\";\n code = \"ERR_JWKS_NO_MATCHING_KEY\";\n constructor(message = \"no applicable key found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator] = async function* () {\n };\n static code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n constructor(message = \"multiple matching keys found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSTimeout extends JOSEError {\n static code = \"ERR_JWKS_TIMEOUT\";\n code = \"ERR_JWKS_TIMEOUT\";\n constructor(message = \"request timed out\", options) {\n super(message, options);\n }\n}\nclass JWSSignatureVerificationFailed extends JOSEError {\n static code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n constructor(message = \"signature verification failed\", options) {\n super(message, options);\n }\n}\nexport {\n JOSEAlgNotAllowed,\n JOSEError,\n JOSENotSupported,\n JWEDecryptionFailed,\n JWEInvalid,\n JWKInvalid,\n JWKSInvalid,\n JWKSMultipleMatchingKeys,\n JWKSNoMatchingKey,\n JWKSTimeout,\n JWSInvalid,\n JWSSignatureVerificationFailed,\n JWTClaimValidationFailed,\n JWTExpired,\n JWTInvalid\n};\n", "import { encoder, decoder, encodeBase64, decodeBase64 } from \"../lib/buffer_utils.js\";\nconst invalid = \"The input to be decoded is not correctly encoded.\";\nfunction decode(input) {\n try {\n return decodeBase64(typeof input == \"string\" ? input : decoder.decode(input), !0);\n } catch (cause) {\n throw new TypeError(invalid, { cause });\n }\n}\nfunction encode(input) {\n return encodeBase64(typeof input == \"string\" ? encoder.encode(input) : input, !0);\n}\nexport {\n decode,\n encode\n};\n", "import { JOSENotSupported, JWSInvalid } from \"../util/errors.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { encode, strictDecoder } from \"./buffer_utils.js\";\nfunction assertUint8Array(input, label) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`${label} must be an instance of Uint8Array`);\n}\nfunction isObject(input) {\n if (typeof input != \"object\" || input === null || Object.prototype.toString.call(input) !== \"[object Object]\")\n return !1;\n const prototype = Object.getPrototypeOf(input);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\nfunction isJwkSet(input) {\n return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);\n}\nfunction isDisjoint(...headers) {\n const parameters = /* @__PURE__ */ new Set();\n for (const header of headers)\n if (header)\n for (const parameter of Object.keys(header)) {\n if (parameters.has(parameter))\n return !1;\n parameters.add(parameter);\n }\n return !0;\n}\nfunction assertNotSet(value, name) {\n if (value !== void 0)\n throw new TypeError(`${name} can only be called once`);\n}\nfunction decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n } catch {\n throw new ErrorClass(`Failed to base64url decode the ${label}`);\n }\n}\nfunction encodeBase64url(value, label, ErrorClass) {\n try {\n return encode(value);\n } catch {\n throw new ErrorClass(`The ${label} is not a valid base64url string`);\n }\n}\nfunction parseJoseHeader(b64, ErrorClass, message) {\n let parsed;\n try {\n parsed = JSON.parse(strictDecoder.decode(decode(b64)));\n } catch {\n throw new ErrorClass(message);\n }\n if (!isObject(parsed))\n throw new ErrorClass(message);\n return parsed;\n}\nconst JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null };\nfunction validateAlgorithms(option, algorithms) {\n if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != \"string\")))\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n return algorithms === void 0 ? void 0 : new Set(algorithms);\n}\nfunction validateCritDuplicates(Err, protectedHeader) {\n const { crit } = protectedHeader ?? {};\n if (Array.isArray(crit) && new Set(crit).size !== crit.length)\n throw new Err('\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values');\n}\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n if (!protectedHeader || protectedHeader.crit === void 0)\n return [];\n if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != \"string\" || input.length === 0))\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };\n for (const parameter of protectedHeader.crit) {\n if (!(parameter in recognized))\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n return protectedHeader.crit;\n}\nfunction validateB64(protectedHeader, extensions) {\n if (extensions.includes(\"b64\")) {\n const b64 = protectedHeader.b64;\n if (typeof b64 != \"boolean\")\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n return b64;\n }\n return !0;\n}\nfunction serializeJoseHeader(Err, header) {\n let serialized, parsed;\n try {\n serialized = JSON.stringify(header), parsed = JSON.parse(serialized);\n } catch (cause) {\n throw new Err(\"JOSE Header is not valid JSON\", { cause });\n }\n if (!isObject(parsed))\n throw new Err(\"JOSE Header is not a JSON object\");\n return [parsed, serialized];\n}\nexport {\n JWE_RECOGNIZED,\n JWS_RECOGNIZED,\n assertNotSet,\n assertUint8Array,\n decodeBase64url,\n encodeBase64url,\n isDisjoint,\n isJwkSet,\n isObject,\n parseJoseHeader,\n serializeJoseHeader,\n validateAlgorithms,\n validateB64,\n validateCrit,\n validateCritDuplicates\n};\n", "import { isObject } from \"./validate.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nconst tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {\n const { alg } = entry;\n if (key.use !== void 0) {\n const expected = usage === \"sign\" || usage === \"verify\" ? \"sig\" : \"enc\";\n if (key.use !== expected)\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n if (key.alg !== void 0 && key.alg !== alg)\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n if (Array.isArray(key.key_ops)) {\n const expectedKeyOp = usage === \"encrypt\" || usage === \"decrypt\" ? entry.ops?.[usage === \"encrypt\" ? 0 : 1] : usage;\n if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n};\nasync function prepareKey(entry, key, usage) {\n const { alg, secret } = entry, privateKey = usage === \"decrypt\" || usage === \"sign\";\n if (secret && key instanceof Uint8Array)\n return key;\n let normalized, keyObject;\n if (isObject(key)) {\n if (normalized = normalizeJwk(key), typeof normalized.kty != \"string\")\n throw invalidKeyType(alg, key, secret);\n if (!(secret ? normalized.kty === \"oct\" && typeof normalized.k == \"string\" : normalized.kty !== \"oct\" && (privateKey ? normalized.kty === \"AKP\" && typeof normalized.priv == \"string\" || typeof normalized.d == \"string\" : normalized.d === void 0 && normalized.priv === void 0)))\n throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present' : `JSON Web Key for this operation must be a ${privateKey ? \"private\" : \"public\"} JWK`);\n if (jwkMatchesOp(entry, normalized, usage), normalized.kty === \"oct\")\n return decode(normalized.k);\n if (!Object.isFrozen(key)) {\n const { key_ops } = key;\n Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);\n }\n } else {\n if (!isKeyLike(key))\n throw invalidKeyType(alg, key, secret);\n const expectedType = secret ? \"secret\" : privateKey ? \"private\" : \"public\";\n if (key.type !== expectedType && (secret || [\"secret\", \"public\", \"private\"].includes(key.type)))\n throw new TypeError(`${tag(key)} instances must be of type \"${expectedType}\" for the ${alg} algorithm`);\n if (isCryptoKey(key))\n return key;\n if (keyObject = key, keyObject.type === \"secret\")\n return keyObject.export();\n }\n cache ||= /* @__PURE__ */ new WeakMap();\n const cacheKey = key;\n let cached = cache.get(cacheKey);\n if (cached?.[alg])\n return cached[alg];\n if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == \"function\") {\n const isPublic = keyObject.type === \"public\", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;\n return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);\n }\n return normalized ??= keyObject.export({ format: \"jwk\" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);\n}\nlet cache;\nconst nist = {\n __proto__: null,\n prime256v1: \"P-256\",\n secp384r1: \"P-384\",\n secp521r1: \"P-521\"\n};\nfunction assertCryptoKey(key) {\n if (!isCryptoKey(key))\n throw new Error(\"CryptoKey instance expected\");\n}\nconst isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === \"CryptoKey\")\n return !0;\n try {\n return key instanceof CryptoKey;\n } catch {\n return !1;\n }\n}, isKeyObject = (key) => key?.[Symbol.toStringTag] === \"KeyObject\", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\nfunction message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}.`;\n } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;\n return actual == null ? msg += ` Received ${actual}` : typeof actual == \"function\" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == \"object\" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;\n}\nconst invalidKeyInput = (actual, ...types) => message(\"Key must be \", actual, ...types);\nfunction invalidKeyType(alg, actual, secret) {\n const types = [\"CryptoKey\", \"KeyObject\", \"JSON Web Key\"];\n return secret && types.push(\"Uint8Array\"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));\n}\nconst unusable = (name, prop = \"algorithm.name\") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage))\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n}\nfunction checkModulusLength(alg, key) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength != \"number\" || modulusLength < 2048)\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n}\nfunction checkCryptoKey(key, expected, usage) {\n const algorithm = key.algorithm;\n if (algorithm.name !== expected.name)\n throw unusable(expected.name);\n if (expected.hash && algorithm.hash?.name !== expected.hash)\n throw unusable(expected.hash, \"algorithm.hash\");\n if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)\n throw unusable(expected.namedCurve, \"algorithm.namedCurve\");\n if (expected.length !== void 0 && algorithm.length !== expected.length)\n throw unusable(expected.length, \"algorithm.length\");\n checkUsage(key, usage);\n}\nfunction snapshotJwk(jwk) {\n return { __proto__: null, ...jwk };\n}\nfunction normalizeJwk(jwk) {\n const normalized = snapshotJwk(jwk);\n if (normalized.ext !== void 0 && typeof normalized.ext != \"boolean\")\n throw new TypeError('\"ext\" (Extractable) Parameter must be a boolean');\n if (normalized.key_ops !== void 0) {\n const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;\n if (!keyOps || keyOps.some((operation) => typeof operation != \"string\") || new Set(keyOps).size !== keyOps.length)\n throw new TypeError('\"key_ops\" (Key Operations) Parameter must be an array of unique strings');\n normalized.key_ops = keyOps;\n }\n return normalized;\n}\nfunction validateExtractableOption(extractable) {\n if (extractable !== void 0 && typeof extractable != \"boolean\")\n throw new TypeError('\"extractable\" option must be a boolean');\n return extractable;\n}\nasync function jwkToKey(entry, jwk, extractable) {\n if (!entry.kty.includes(jwk.kty))\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };\n return keyData.kty !== \"AKP\" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey(\"jwk\", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);\n}\nasync function rawKey(key, expected, usage, extractable = !1) {\n return key instanceof Uint8Array && (key = await crypto.subtle.importKey(\"raw\", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;\n}\nexport {\n assertCryptoKey,\n checkCryptoKey,\n checkModulusLength,\n checkUsage,\n invalidKeyInput,\n isCryptoKey,\n isKeyLike,\n isKeyObject,\n jwkToKey,\n normalizeJwk,\n prepareKey,\n rawKey,\n snapshotJwk,\n validateExtractableOption\n};\n", "function table(entries) {\n const out = { __proto__: null };\n for (const alg in entries)\n out[alg] = { ...entries[alg], alg };\n return out;\n}\nexport {\n table\n};\n", "import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst sig = [[\"verify\"], [\"sign\"]];\nfunction hmac(bits) {\n const subtle = { name: \"HMAC\", hash: `SHA-${bits}` };\n return { kty: [\"oct\"], secret: !0, subtle, signing: subtle, usages: sig };\n}\nfunction rsa(bits, saltLength) {\n const subtle = { name: saltLength ? \"RSA-PSS\" : \"RSASSA-PKCS1-v1_5\", hash: `SHA-${bits}` };\n return {\n kty: [\"RSA\"],\n subtle,\n signing: saltLength ? { ...subtle, saltLength } : subtle,\n usages: sig,\n minRsaBits: 2048\n };\n}\nfunction ecdsa(crv, bits) {\n return {\n kty: [\"EC\"],\n crv,\n subtle: { name: \"ECDSA\", namedCurve: crv },\n signing: { name: \"ECDSA\", hash: `SHA-${bits}` },\n usages: sig\n };\n}\nfunction eddsa() {\n const subtle = { name: \"Ed25519\" };\n return {\n kty: [\"OKP\"],\n crv: \"Ed25519\",\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nfunction mldsa(bits) {\n const subtle = { name: `ML-DSA-${bits}` };\n return {\n kty: [\"AKP\"],\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nconst JWS = table({\n HS256: hmac(256),\n HS384: hmac(384),\n HS512: hmac(512),\n RS256: rsa(256),\n RS384: rsa(384),\n RS512: rsa(512),\n PS256: rsa(256, 32),\n PS384: rsa(384, 48),\n PS512: rsa(512, 64),\n ES256: ecdsa(\"P-256\", 256),\n ES384: ecdsa(\"P-384\", 384),\n ES512: ecdsa(\"P-521\", 512),\n EdDSA: eddsa(),\n Ed25519: eddsa(),\n \"ML-DSA-44\": mldsa(44),\n \"ML-DSA-65\": mldsa(65),\n \"ML-DSA-87\": mldsa(87)\n});\nfunction jwsAlgorithm(alg) {\n const entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry)\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n return entry;\n}\nexport {\n JWS,\n jwsAlgorithm\n};\n", "import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from \"../util/errors.js\";\nimport { encoder, strictDecoder } from \"./buffer_utils.js\";\nimport { isObject } from \"./validate.js\";\nconst epoch = (date) => Math.floor(date.getTime() / 1e3), multipliers = {\n s: 1,\n m: 60,\n h: 3600,\n d: 86400,\n w: 604800,\n y: 31557600\n}, REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, checkFailed = \"check_failed\";\nfunction invalidDuration() {\n throw new TypeError(\"Invalid time period format\");\n}\nfunction secs(str) {\n typeof str != \"string\" && invalidDuration();\n const matched = REGEX.exec(str);\n (!matched || matched[4] && matched[1]) && invalidDuration();\n const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);\n return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === \"-\" || matched[4] === \"ago\" ? -numericDate2 : numericDate2;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input))\n throw new TypeError(`Invalid ${label} input`);\n return input;\n}\nfunction validateStringClaim(claim, value) {\n if (typeof value != \"string\")\n throw new TypeError(`\"${claim}\" claim must be a string`);\n}\nfunction validateAudienceClaim(value) {\n if (typeof value != \"string\" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != \"string\")))\n throw new TypeError('\"aud\" claim must be a string or an array of strings');\n}\nfunction numericDate(value, label) {\n return typeof value == \"number\" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);\n}\nconst normalizeTyp = (value) => {\n const normalized = value.toLowerCase();\n return value.includes(\"/\") ? normalized : `application/${normalized}`;\n}, checkAudiencePresence = (audPayload, audOption) => typeof audPayload == \"string\" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;\nfunction validateNumericDate(payload, claim, required = !1) {\n const value = payload[claim];\n if (!(value === void 0 && !required)) {\n if (typeof value != \"number\")\n throw new JWTClaimValidationFailed(`\"${claim}\" claim must be a number`, payload, claim, \"invalid\");\n return value;\n }\n}\nfunction unexpectedClaim(payload, claim) {\n throw new JWTClaimValidationFailed(`unexpected \"${claim}\" claim value`, payload, claim, checkFailed);\n}\nfunction validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(strictDecoder.decode(encodedPayload));\n } catch {\n }\n if (!isObject(payload))\n throw new JWTInvalid(\"JWT Claims Set must be a top-level JSON object\");\n const { typ } = options;\n if (typ !== void 0 && (typeof protectedHeader.typ != \"string\" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, \"typ\", checkFailed);\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];\n maxTokenAge !== void 0 && presenceCheck.push(\"iat\"), audience !== void 0 && presenceCheck.push(\"aud\"), subject !== void 0 && presenceCheck.push(\"sub\"), issuer !== void 0 && presenceCheck.push(\"iss\");\n for (const claim of new Set(presenceCheck.reverse()))\n if (!Object.hasOwn(payload, claim))\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, \"missing\");\n issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, \"iss\"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, \"sub\"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == \"string\" ? [audience] : audience) && unexpectedClaim(payload, \"aud\");\n const { clockTolerance } = options;\n let tolerance = 0;\n if (typeof clockTolerance == \"string\")\n tolerance = secs(clockTolerance);\n else if (clockTolerance !== void 0) {\n if (typeof clockTolerance != \"number\")\n throw new TypeError(\"Invalid clockTolerance option type\");\n tolerance = clockTolerance;\n }\n validateInput(\"clockTolerance option\", tolerance);\n const { currentDate } = options, now = validateInput(\"currentDate option\", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, \"iat\", maxTokenAge !== void 0), nbf = validateNumericDate(payload, \"nbf\");\n if (nbf !== void 0 && nbf > now + tolerance)\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, \"nbf\", checkFailed);\n const exp = validateNumericDate(payload, \"exp\");\n if (exp !== void 0 && exp <= now - tolerance)\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, \"exp\", checkFailed);\n if (maxTokenAge !== void 0) {\n const age = now - iat, max = validateInput(\"maxTokenAge option\", typeof maxTokenAge == \"number\" ? maxTokenAge : secs(maxTokenAge));\n if (age - tolerance > max)\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, \"iat\", checkFailed);\n if (age < -tolerance)\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, \"iat\", checkFailed);\n }\n return payload;\n}\nlet producerPayloads;\nfunction producerPayload(producer) {\n return producerPayloads.get(producer);\n}\nfunction jwtData(producer) {\n const payload = producerPayload(producer);\n for (const claim of [\"iat\", \"nbf\", \"exp\"]) {\n const value = payload[claim];\n if (typeof value == \"number\" && !Number.isFinite(value))\n throw new TypeError(`\"${claim}\" claim must be a finite number`);\n }\n return encoder.encode(JSON.stringify(payload));\n}\nfunction jwtClaim(producer, claim) {\n return producerPayload(producer)[claim];\n}\nclass JWTClaimsBuilder {\n constructor(payload = {}) {\n if (!isObject(payload))\n throw new TypeError(\"JWT Claims Set MUST be an object\");\n (producerPayloads ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(payload));\n }\n setIssuer(value) {\n return validateStringClaim(\"iss\", value), producerPayload(this).iss = value, this;\n }\n setSubject(value) {\n return validateStringClaim(\"sub\", value), producerPayload(this).sub = value, this;\n }\n setAudience(value) {\n return validateAudienceClaim(value), producerPayload(this).aud = value, this;\n }\n setJti(value) {\n return validateStringClaim(\"jti\", value), producerPayload(this).jti = value, this;\n }\n setNotBefore(value) {\n return producerPayload(this).nbf = numericDate(value, \"setNotBefore\"), this;\n }\n setExpirationTime(value) {\n return producerPayload(this).exp = numericDate(value, \"setExpirationTime\"), this;\n }\n setIssuedAt(value) {\n const payload = producerPayload(this);\n return value === void 0 ? payload.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == \"string\" ? payload.iat = validateInput(\"setIssuedAt\", epoch(/* @__PURE__ */ new Date()) + secs(value)) : payload.iat = numericDate(value, \"setIssuedAt\"), this;\n }\n}\nexport {\n JWTClaimsBuilder,\n jwtClaim,\n jwtData,\n secs,\n validateClaimsSet\n};\n", "import { encode as b64u } from \"../util/base64url.js\";\nimport { jwsAlgorithm } from \"./jws_algorithms.js\";\nimport { isDisjoint, serializeJoseHeader, validateB64, validateCrit, validateCritDuplicates, JWS_RECOGNIZED } from \"./validate.js\";\nimport { JWSInvalid } from \"../util/errors.js\";\nimport { concat, encode, encoder } from \"./buffer_utils.js\";\nimport { prepareKey, rawKey, checkModulusLength } from \"./key.js\";\nasync function createSignature(input, key, rejectUnencoded) {\n let [payload, protectedHeader, unprotectedHeader, crit] = input, protectedHeaderString = \"\";\n if (protectedHeader !== void 0) {\n const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);\n protectedHeader = normalized[0], protectedHeaderString = b64u(normalized[1]);\n }\n if (unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWSInvalid, unprotectedHeader)[0]), !protectedHeader && !unprotectedHeader)\n throw new JWSInvalid(\"either setProtectedHeader or setUnprotectedHeader must be called before #sign()\");\n if (!isDisjoint(protectedHeader, unprotectedHeader))\n throw new JWSInvalid(\"JWS Protected and JWS Unprotected Header Parameter names must be disjoint\");\n const joseHeader = { ...protectedHeader, ...unprotectedHeader };\n validateCritDuplicates(JWSInvalid, protectedHeader);\n const b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));\n b64 || rejectUnencoded?.();\n const { alg } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n const entry = jwsAlgorithm(alg);\n let payloadS = \"\", payloadB = payload, data;\n if (b64) {\n const encoded = input[4];\n encoded ? (payloadS = encoded[0] ??= b64u(payload), payloadB = encoded[1] ??= encode(payloadS)) : (payloadS = b64u(payload), data = encoder.encode(`${protectedHeaderString}.${payloadS}`));\n }\n data ??= concat(encode(protectedHeaderString), encode(\".\"), payloadB);\n const k = await rawKey(await prepareKey(entry, key, \"sign\"), entry.subtle, \"sign\");\n entry.minRsaBits && checkModulusLength(entry.alg, k);\n const jws = {\n signature: b64u(new Uint8Array(await crypto.subtle.sign(entry.signing, k, data))),\n payload: payloadS\n };\n return protectedHeader && (jws.protected = protectedHeaderString), unprotectedHeader && (jws.header = unprotectedHeader), [jws, b64];\n}\nasync function createCompactSignature(payload, protectedHeader, crit, key, rejectUnencoded) {\n const [jws] = await createSignature([payload, protectedHeader, void 0, crit], key, rejectUnencoded);\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n}\nexport {\n createCompactSignature,\n createSignature\n};\n", "import { createCompactSignature } from \"../lib/jws_sign.js\";\nimport { JWTInvalid } from \"../util/errors.js\";\nimport { JWTClaimsBuilder, jwtData } from \"../lib/jwt_claims_set.js\";\nimport { assertNotSet } from \"../lib/validate.js\";\nconst SignJWT_base = JWTClaimsBuilder;\nclass SignJWT extends SignJWT_base {\n #protectedHeader;\n setProtectedHeader(protectedHeader) {\n return assertNotSet(this.#protectedHeader, \"setProtectedHeader\"), this.#protectedHeader = protectedHeader, this;\n }\n async sign(key, options) {\n return createCompactSignature(jwtData(this), this.#protectedHeader, options?.crit, key, () => {\n throw new JWTInvalid(\"JWTs MUST NOT use unencoded payload\");\n });\n }\n}\nexport {\n SignJWT\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { ContentType, getDisplayString, MEDPLUM_CLI_CLIENT_ID, normalizeErrorString } from '@medplum/core';\nimport { exec } from 'node:child_process';\nimport { createServer } from 'node:http';\nimport { platform } from 'node:os';\nimport { promisify } from 'node:util';\nimport { createMedplumClient } from './util/client';\nimport type { Profile } from './utils';\nimport { jwtAssertionLogin, jwtBearerLogin, MedplumCommand, saveProfile } from './utils';\n\nconst execAsync = promisify(exec);\n\nconst clientId = MEDPLUM_CLI_CLIENT_ID;\nconst redirectUri = 'http://localhost:9615';\n\nexport const login = new MedplumCommand('login');\nexport const whoami = new MedplumCommand('whoami');\nexport const token = new MedplumCommand('token');\n\nlogin.action(async (options) => {\n const profileName = options.profile ?? 'default';\n\n // Always save the profile to update settings\n const profile = saveProfile(profileName, options);\n\n const medplum = await createMedplumClient(options, false);\n await startLogin(medplum, profile);\n});\n\nwhoami.action(async (options) => {\n const medplum = await createMedplumClient(options);\n printMe(medplum);\n});\n\ntoken.action(async (options) => {\n const medplum = await createMedplumClient(options);\n await medplum.getProfileAsync();\n const token = medplum.getAccessToken();\n if (!token) {\n throw new Error('Not logged in');\n }\n console.log(token);\n});\n\nasync function startLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n const authType = profile?.authType ?? 'authorization-code';\n switch (authType) {\n case 'authorization-code':\n await medplumAuthorizationCodeLogin(medplum, profile);\n break;\n case 'basic':\n medplum.setBasicAuth(profile.clientId as string, profile.clientSecret as string);\n break;\n case 'client-credentials':\n medplum.setBasicAuth(profile.clientId as string, profile.clientSecret as string);\n await medplum.startClientLogin(profile.clientId as string, profile.clientSecret as string);\n break;\n case 'jwt-bearer':\n await jwtBearerLogin(medplum, profile);\n break;\n case 'jwt-assertion':\n await jwtAssertionLogin(medplum, profile);\n break;\n }\n}\n\nasync function startWebServer(medplum: MedplumClient): Promise<void> {\n const server = createServer(async (req, res) => {\n const url = new URL(req.url as string, 'http://localhost:9615');\n const code = url.searchParams.get('code');\n if (req.method === 'OPTIONS') {\n res.writeHead(200, {\n Allow: 'GET, POST',\n 'Content-Type': ContentType.TEXT,\n });\n res.end('OK');\n return;\n }\n if (url.pathname === '/' && code) {\n try {\n const profile = await medplum.processCode(code, { clientId, redirectUri });\n res.writeHead(200, { 'Content-Type': ContentType.TEXT });\n res.end(`Signed in as ${getDisplayString(profile)}. You may close this window.`);\n } catch (err) {\n res.writeHead(400, { 'Content-Type': ContentType.TEXT });\n res.end(`Error: ${normalizeErrorString(err)}`);\n } finally {\n server.close();\n process.exit(0);\n }\n } else {\n res.writeHead(404, { 'Content-Type': ContentType.TEXT });\n res.end('Not found');\n }\n }).listen(9615);\n}\n\n/**\n * Opens a web browser to the specified URL.\n * See: https://hasinthaindrajee.medium.com/browser-sso-for-cli-applications-b0be743fa656\n * @param url - The URL to open.\n */\nasync function openBrowser(url: string): Promise<void> {\n const os = platform();\n let cmd = undefined;\n switch (os) {\n case 'openbsd':\n case 'linux':\n cmd = `xdg-open '${url}'`;\n break;\n case 'darwin':\n cmd = `open '${url}'`;\n break;\n case 'win32':\n cmd = `cmd /c start \"\" \"${url}\"`;\n break;\n default:\n throw new Error('Unsupported platform: ' + os);\n }\n await execAsync(cmd);\n}\n\n/**\n * Prints the current user and project.\n * @param medplum - The Medplum client.\n */\nfunction printMe(medplum: MedplumClient): void {\n const loginState = medplum.getActiveLogin();\n if (loginState) {\n console.log(`Server: ${medplum.getBaseUrl()}`);\n console.log(`Profile: ${loginState.profile.display} (${loginState.profile.reference})`);\n console.log(`Project: ${loginState.project.display} (${loginState.project.reference})`);\n } else {\n console.log('Not logged in');\n }\n}\n\nasync function medplumAuthorizationCodeLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n await startWebServer(medplum);\n const loginUrl = new URL(medplum.getAuthorizeUrl());\n loginUrl.searchParams.set('client_id', clientId);\n loginUrl.searchParams.set('redirect_uri', redirectUri);\n loginUrl.searchParams.set('scope', profile.scope ?? 'openid offline_access');\n loginUrl.searchParams.set('response_type', 'code');\n loginUrl.searchParams.set('prompt', 'login');\n await openBrowser(loginUrl.toString());\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n// CLI color highlighting\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst RED = '\\x1b[31m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst BLUE = '\\x1b[34m';\n\nexport const color = {\n red: (text: string) => `${RED}${text}${RESET}`,\n green: (text: string) => `${GREEN}${text}${RESET}`,\n yellow: (text: string) => `${YELLOW}${text}${RESET}`,\n blue: (text: string) => `${BLUE}${text}${RESET}`,\n bold: (text: string) => `${BOLD}${text}${RESET}`,\n};\n\n// Bold text wrapped in ** **\nexport const processDescription = (desc: string): string => {\n return desc.replaceAll(/\\*\\*(.*?)\\*\\*/g, (_, text) => color.bold(text));\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Stack, StackResource, StackSummary } from '@aws-sdk/client-cloudformation';\nimport {\n CloudFormationClient,\n DescribeStackResourcesCommand,\n DescribeStacksCommand,\n paginateListStacks,\n} from '@aws-sdk/client-cloudformation';\nimport { CloudFrontClient, CreateInvalidationCommand } from '@aws-sdk/client-cloudfront';\nimport { ECSClient } from '@aws-sdk/client-ecs';\nimport { S3Client } from '@aws-sdk/client-s3';\nimport { GetParameterCommand, PutParameterCommand, SSMClient } from '@aws-sdk/client-ssm';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport { EMPTY, normalizeErrorString } from '@medplum/core';\nimport { readdirSync } from 'node:fs';\nimport * as semver from 'semver';\nimport { getConfigFileName } from '../utils';\nimport { checkOk, print } from './terminal';\n\nexport interface MedplumStackDetails {\n stack: Stack;\n tag: string;\n ecsCluster?: StackResource;\n ecsService?: StackResource;\n appBucket?: StackResource;\n appDistribution?: StackResource;\n appOriginAccessIdentity?: StackResource;\n storageBucket?: StackResource;\n storageDistribution?: StackResource;\n storageOriginAccessIdentity?: StackResource;\n}\n\nexport const cloudFormationClient = new CloudFormationClient({});\nexport const cloudFrontClient = new CloudFrontClient({ region: 'us-east-1' });\nexport const ecsClient = new ECSClient({});\nexport const s3Client = new S3Client({});\nexport const tagKey = 'medplum:environment';\n\n/**\n * Returns a list of all AWS CloudFormation stacks (both Medplum and non-Medplum).\n * @returns List of AWS CloudFormation stacks.\n */\nexport async function getAllStacks(): Promise<(StackSummary & { StackName: string })[]> {\n const listResult = [] as StackSummary[];\n const paginator = paginateListStacks(\n { client: cloudFormationClient },\n {\n StackStatusFilter: [\n 'CREATE_COMPLETE',\n 'CREATE_FAILED',\n 'CREATE_IN_PROGRESS',\n 'DELETE_FAILED',\n 'DELETE_IN_PROGRESS',\n 'IMPORT_COMPLETE',\n 'IMPORT_IN_PROGRESS',\n 'IMPORT_ROLLBACK_COMPLETE',\n 'IMPORT_ROLLBACK_FAILED',\n 'IMPORT_ROLLBACK_IN_PROGRESS',\n 'REVIEW_IN_PROGRESS',\n 'ROLLBACK_COMPLETE',\n 'ROLLBACK_FAILED',\n 'ROLLBACK_IN_PROGRESS',\n 'UPDATE_COMPLETE',\n 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_FAILED',\n 'UPDATE_IN_PROGRESS',\n 'UPDATE_ROLLBACK_COMPLETE',\n 'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_ROLLBACK_FAILED',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n ],\n }\n );\n\n for await (const page of paginator) {\n for (const stack of page.StackSummaries ?? EMPTY) {\n listResult.push(stack);\n }\n }\n\n return listResult as (StackSummary & { StackName: string })[];\n}\n\n/**\n * Returns Medplum stack details for the given tag.\n * @param tag - The Medplum stack tag.\n * @returns The Medplum stack details.\n */\nexport async function getStackByTag(tag: string): Promise<MedplumStackDetails | undefined> {\n const stackSummaries = await getAllStacks();\n for (const stackSummary of stackSummaries) {\n const stackName = stackSummary.StackName;\n const details = await getStackDetails(stackName);\n if (details?.tag === tag) {\n return details;\n }\n }\n return undefined;\n}\n\n/**\n * Returns Medplum stack details for the given stack name.\n * @param stackName - The CloudFormation stack name.\n * @returns The Medplum stack details.\n */\nexport async function getStackDetails(stackName: string): Promise<MedplumStackDetails | undefined> {\n const result = {} as Partial<MedplumStackDetails>;\n await buildStackDetails(cloudFormationClient, stackName, result);\n if ((await cloudFormationClient.config.region()) !== 'us-east-1') {\n try {\n await buildStackDetails(new CloudFormationClient({ region: 'us-east-1' }), stackName + '-us-east-1', result);\n } catch {\n // Fail gracefully\n }\n }\n return result as MedplumStackDetails;\n}\n\n/**\n * Builds the Medplum stack details for the given stack name and region.\n * @param client - The CloudFormation client.\n * @param stackName - The CloudFormation stack name.\n * @param result - The Medplum stack details builder.\n */\nasync function buildStackDetails(\n client: CloudFormationClient,\n stackName: string,\n result: Partial<MedplumStackDetails>\n): Promise<void> {\n const describeStacksCommand = new DescribeStacksCommand({ StackName: stackName });\n const stackDetails = await client.send(describeStacksCommand);\n const stack = stackDetails?.Stacks?.[0];\n const medplumTag = stack?.Tags?.find((tag) => tag.Key === tagKey);\n if (!medplumTag) {\n return;\n }\n\n const stackResources = await client.send(new DescribeStackResourcesCommand({ StackName: stackName }));\n if (!stackResources.StackResources) {\n return;\n }\n\n if (client === cloudFormationClient) {\n result.stack = stack;\n result.tag = medplumTag.Value;\n }\n\n for (const resource of stackResources.StackResources) {\n assignStackDetails(resource, result);\n }\n}\n\nfunction assignStackDetails(resource: StackResource, result: Partial<MedplumStackDetails>): void {\n if (resource.ResourceType === 'AWS::ECS::Cluster') {\n result.ecsCluster = resource;\n } else if (resource.ResourceType === 'AWS::ECS::Service') {\n result.ecsService = resource;\n } else if (\n resource.ResourceType === 'AWS::S3::Bucket' &&\n resource.LogicalResourceId?.startsWith('FrontEndAppBucket')\n ) {\n result.appBucket = resource;\n } else if (\n resource.ResourceType === 'AWS::CloudFront::Distribution' &&\n resource.LogicalResourceId?.startsWith('FrontEndAppDistribution')\n ) {\n result.appDistribution = resource;\n } else if (\n resource.ResourceType === 'AWS::CloudFront::CloudFrontOriginAccessIdentity' &&\n resource.LogicalResourceId?.startsWith('FrontEndOriginAccessIdentity')\n ) {\n result.appOriginAccessIdentity = resource;\n } else if (\n resource.ResourceType === 'AWS::S3::Bucket' &&\n resource.LogicalResourceId?.startsWith('StorageStorageBucket')\n ) {\n result.storageBucket = resource;\n } else if (\n resource.ResourceType === 'AWS::CloudFront::Distribution' &&\n resource.LogicalResourceId?.startsWith('StorageStorageDistribution')\n ) {\n result.storageDistribution = resource;\n } else if (\n resource.ResourceType === 'AWS::CloudFront::CloudFrontOriginAccessIdentity' &&\n resource.LogicalResourceId?.startsWith('StorageOriginAccessIdentity')\n ) {\n result.storageOriginAccessIdentity = resource;\n }\n}\n\n/**\n * Prints the given Medplum stack details to stdout.\n * @param details - The Medplum stack details.\n */\nexport function printStackDetails(details: MedplumStackDetails): void {\n console.log(`Medplum Tag: ${details.tag}`);\n console.log(`Stack Name: ${details.stack?.StackName}`);\n console.log(`Stack ID: ${details.stack?.StackId}`);\n console.log(`Status: ${details.stack?.StackStatus}`);\n console.log(`ECS Cluster: ${details.ecsCluster?.PhysicalResourceId}`);\n console.log(`ECS Service: ${getEcsServiceName(details.ecsService)}`);\n console.log(`App Bucket: ${details.appBucket?.PhysicalResourceId}`);\n console.log(`App Distribution: ${details.appDistribution?.PhysicalResourceId}`);\n console.log(`App OAI: ${details.appOriginAccessIdentity?.PhysicalResourceId}`);\n console.log(`Storage Bucket: ${details.storageBucket?.PhysicalResourceId}`);\n console.log(`Storage Distribution: ${details.storageDistribution?.PhysicalResourceId}`);\n console.log(`Storage OAI: ${details.storageOriginAccessIdentity?.PhysicalResourceId}`);\n}\n\n/**\n * Parses the ECS service name from the given AWS ECS service resource.\n * @param resource - The AWS ECS service resource.\n * @returns The ECS service name.\n */\nexport function getEcsServiceName(resource: StackResource | undefined): string | undefined {\n return resource?.PhysicalResourceId?.split('/')?.pop() || '';\n}\n\n/**\n * Creates a CloudFront invalidation to clear the cache for all files.\n * This is not strictly necessary, but it helps to ensure that the latest version of the app is served.\n * In a perfect world, every deploy is clean, and hashed resources should be cached forever.\n * However, we do not recalculate hashes after variable replacements.\n * So if variables change, we need to invalidate the cache.\n * @param distributionId - The CloudFront distribution ID.\n */\nexport async function createInvalidation(distributionId: string): Promise<void> {\n const response = await cloudFrontClient.send(\n new CreateInvalidationCommand({\n DistributionId: distributionId,\n InvalidationBatch: {\n CallerReference: `invalidate-all-${Date.now()}`,\n Paths: {\n Quantity: 1,\n Items: ['/*'],\n },\n },\n })\n );\n console.log(`Created invalidation with ID: ${response.Invalidation?.Id}`);\n}\n\nexport async function getServerVersions(from?: string): Promise<string[]> {\n const response = await fetch('https://api.github.com/repos/medplum/medplum/releases?per_page=100', {\n headers: {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n },\n });\n\n const json = (await response.json()) as { tag_name: string }[];\n const versions = json.map((release) =>\n release.tag_name.startsWith('v') ? release.tag_name.slice(1) : release.tag_name\n );\n\n // Sort in descending order\n versions.sort((a, b) => semver.compare(b, a));\n\n return from ? versions.slice(0, versions.indexOf(from)) : versions;\n}\n\n/**\n * Writes a collection of parameters to AWS Parameter Store.\n * @param region - The AWS region.\n * @param prefix - The AWS Parameter Store prefix.\n * @param params - The parameters to write.\n */\nexport async function writeParameters(\n region: string,\n prefix: string,\n params: Record<string, string | number | boolean | object>\n): Promise<void> {\n const client = new SSMClient({ region });\n for (const [key, value] of Object.entries(params)) {\n const name = prefix + key;\n const valueStr = typeof value === 'object' ? JSON.stringify(value) : value.toString();\n const existingValue = await readParameter(client, name);\n\n if (existingValue !== undefined && existingValue !== valueStr) {\n print(`Parameter \"${name}\" exists with different value.`);\n await checkOk(`Do you want to overwrite \"${name}\"?`);\n }\n\n await writeParameter(client, name, valueStr);\n }\n}\n\n/**\n * Reads a parameter from AWS Parameter Store.\n * @param client - The AWS SSM client.\n * @param name - The parameter name.\n * @returns The parameter value, or undefined if not found.\n */\nasync function readParameter(client: SSMClient, name: string): Promise<string | undefined> {\n const command = new GetParameterCommand({\n Name: name,\n WithDecryption: true,\n });\n try {\n const result = await client.send(command);\n return result.Parameter?.Value;\n } catch (err: any) {\n if (err.name === 'ParameterNotFound') {\n return undefined;\n }\n throw err;\n }\n}\n\n/**\n * Writes a parameter to AWS Parameter Store.\n * @param client - The AWS SSM client.\n * @param name - The parameter name.\n * @param value - The parameter value.\n */\nasync function writeParameter(client: SSMClient, name: string, value: string): Promise<void> {\n const command = new PutParameterCommand({\n Name: name,\n Value: value,\n Type: 'SecureString',\n Overwrite: true,\n });\n await client.send(command);\n}\n\n/**\n * Prints a \"config not found\" message to stdout.\n * Includes helpful debugging information such as available configs.\n * @param tagName - Medplum stack tag name.\n * @param options - Additional command line options.\n */\nexport function printConfigNotFound(tagName: string, options?: Record<string, any>): void {\n console.log(`Config not found: ${tagName} (${getConfigFileName(tagName, options)})`);\n\n if (options) {\n const entries = Object.entries(options);\n if (entries.length > 0) {\n console.log('Additional options:');\n for (const [key, value] of entries) {\n console.log(` ${key}: ${value}`);\n }\n }\n }\n\n console.log();\n\n let files: any[] = readdirSync('.', { withFileTypes: true });\n files = files\n .filter((f) => f.isFile() && f.name.startsWith('medplum.') && f.name.endsWith('.json'))\n .map((f) => f.name);\n\n if (files.length === 0) {\n console.log('No configs found');\n } else {\n console.log('Available configs:');\n for (const file of files) {\n console.log(\n ` ${file\n .replaceAll('medplum.', '')\n .replaceAll('.config', '')\n .replaceAll('.server', '')\n .replaceAll('.json', '')\n .padEnd(40, ' ')} (${file})`\n );\n }\n }\n}\n\n/**\n * Prints a \"stack not found\" message to stdout.\n * Includes helpful debugging information such as AWS account ID and region.\n * @param tagName - Medplum stack tag name.\n */\nexport async function printStackNotFound(tagName: string): Promise<void> {\n console.log(`Stack not found: ${tagName}`);\n console.log();\n\n try {\n const client = new STSClient();\n const command = new GetCallerIdentityCommand({});\n const response = await client.send(command);\n const region = await client.config.region();\n console.log('AWS Region: ', region);\n console.log('AWS Account ID: ', response.Account);\n console.log('AWS Account ARN: ', response.Arn);\n console.log('AWS User ID: ', response.UserId);\n } catch (err) {\n console.log('Warning: Unable to get AWS account ID', normalizeErrorString(err));\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport readline from 'node:readline';\n\nlet terminal: readline.Interface;\n\nexport function initTerminal(): void {\n terminal = readline.createInterface({ input: process.stdin, output: process.stdout });\n}\n\nexport function closeTerminal(): void {\n terminal.close();\n}\n\n/**\n * Prints to stdout.\n * @param text - The text to print.\n */\nexport function print(text: string): void {\n terminal.write(text + '\\n');\n}\n\n/**\n * Prints a header with extra line spacing.\n * @param text - The text to print.\n */\nexport function header(text: string): void {\n print('\\n' + text + '\\n');\n}\n\n/**\n * Prints a question and waits for user input.\n * @param text - The question text to print.\n * @param defaultValue - Optional default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport function ask(text: string, defaultValue: string | number = ''): Promise<string> {\n return new Promise((resolve) => {\n terminal.question(text + (defaultValue ? ' (' + defaultValue + ')' : '') + ' ', (answer: string) => {\n resolve(answer || defaultValue.toString());\n });\n });\n}\n\n/**\n * Prints a question and waits for user to choose one of the provided options.\n * @param text - The prompt text to print.\n * @param options - The list of options that the user can select.\n * @param defaultValue - Optional default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport async function choose(text: string, options: (string | number)[], defaultValue = ''): Promise<string> {\n const str = text + ' [' + options.map((o) => (o === defaultValue ? '(' + o + ')' : o)).join('|') + ']';\n\n while (true) {\n const answer = (await ask(str)) || defaultValue;\n if (options.includes(answer)) {\n return answer;\n }\n print('Please choose one of the following options: ' + options.join(', '));\n }\n}\n\n/**\n * Prints a question and waits for the user to choose a valid integer option.\n * @param text - The prompt text to print.\n * @param options - The list of options that the user can select.\n * @param defaultValue - Default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport async function chooseInt(text: string, options: number[], defaultValue: number): Promise<number> {\n return Number.parseInt(\n await choose(\n text,\n options.map((o) => o.toString()),\n defaultValue.toString()\n ),\n 10\n );\n}\n\n/**\n * Prints a question and waits for the user to choose yes or no.\n * @param text - The question to print.\n * @returns true on accept or false on reject.\n */\nexport async function yesOrNo(text: string): Promise<boolean> {\n return (await choose(text, ['y', 'n'])).toLowerCase() === 'y';\n}\n\n/**\n * Prints a question and waits for the user to confirm yes. Throws error on no, and exits the program.\n * @param text - The prompt text to print.\n */\nexport async function checkOk(text: string): Promise<void> {\n if (!(await yesOrNo(text))) {\n print('Exiting...');\n throw new Error('User cancelled');\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { getStackByTag, printStackDetails, printStackNotFound } from './utils';\n\n/**\n * The AWS \"describe\" command prints details about a Medplum CloudFormation stack.\n * @param tag - The Medplum stack tag.\n */\nexport async function describeStacksCommand(tag: string): Promise<void> {\n const details = await getStackByTag(tag);\n if (!details) {\n await printStackNotFound(tag);\n throw new Error(`Stack not found: ${tag}`);\n }\n printStackDetails(details);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { CertificateSummary, ValidationMethod } from '@aws-sdk/client-acm';\nimport { ACMClient, ListCertificatesCommand, RequestCertificateCommand } from '@aws-sdk/client-acm';\nimport { CloudFrontClient, CreatePublicKeyCommand } from '@aws-sdk/client-cloudfront';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport type { MedplumInfraConfig } from '@medplum/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { getConfigFileName, writeConfig } from '../utils';\nimport { ask, checkOk, choose, chooseInt, closeTerminal, header, initTerminal, print, yesOrNo } from './terminal';\nimport { getServerVersions, writeParameters } from './utils';\n\ntype MedplumDomainType = 'api' | 'app' | 'storage';\ntype MedplumDomainSetting = `${MedplumDomainType}DomainName`;\ntype MedplumDomainCertSetting = `${MedplumDomainType}SslCertArn`;\n\nconst getDomainSetting = (domain: MedplumDomainType): MedplumDomainSetting => `${domain}DomainName`;\nconst getDomainCertSetting = (domain: MedplumDomainType): MedplumDomainCertSetting => `${domain}SslCertArn`;\n\nexport async function initStackCommand(): Promise<void> {\n const config = { apiPort: 8103, region: 'us-east-1' } as MedplumInfraConfig;\n initTerminal();\n header('MEDPLUM');\n print('This tool prepares the necessary prerequisites for deploying Medplum in your AWS account.');\n print('');\n print('Most Medplum infrastructure is deployed using the AWS CDK.');\n print('However, some AWS resources must be created manually, such as email addresses and SSL certificates.');\n print('This tool will help you create those resources.');\n print('');\n print('Upon completion, this tool will:');\n print(' 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)');\n print(' 2. Optionally generate an AWS CloudFront signing key');\n print(' 3. Optionally request SSL certificates from AWS Certificate Manager');\n print(' 4. Optionally write server config settings to AWS Parameter Store');\n print('');\n print('The Medplum infra config file is an input to the Medplum CDK.');\n print('The Medplum CDK will create and manage the necessary AWS resources.');\n print('');\n print('We will ask a series of questions to generate your infra config file.');\n print('Some questions have predefined options in [square brackets].');\n print('Some questions have default values in (parentheses), which you can accept by pressing Enter.');\n print('Press Ctrl+C at any time to exit.');\n\n const currentAccountId = await getAccountId(config.region);\n if (!currentAccountId) {\n print('It appears that you do not have AWS credentials configured.');\n print('AWS credentials are not strictly required, but will enable some additional features.');\n print('If you intend to use AWS credentials, please configure them now.');\n await checkOk('Do you want to continue without AWS credentials?');\n }\n\n header('ENVIRONMENT NAME');\n print('Medplum deployments have a short environment name such as \"prod\", \"staging\", \"alice\", or \"demo\".');\n print('The environment name is used in multiple places:');\n print(' 1. As part of config file names (i.e., medplum.demo.config.json)');\n print(' 2. As the base of CloudFormation stack names (i.e., MedplumDemo)');\n print(' 3. AWS Parameter Store keys (i.e., /medplum/demo/...)');\n config.name = await ask('What is your environment name?', 'demo');\n print('Using environment name \"' + config.name + '\"...');\n\n header('CONFIG FILE');\n print('Medplum Infrastructure will create a config file in the current directory.');\n const configFileName = await ask('What is the config file name?', `medplum.${config.name}.config.json`);\n if (existsSync(configFileName)) {\n print('Config file already exists.');\n await checkOk('Do you want to overwrite the config file?');\n }\n print('Using config file \"' + configFileName + '\"...');\n writeConfig(configFileName, config);\n\n header('AWS REGION');\n print('Most Medplum resources will be created in a single AWS region.');\n config.region = await ask('Enter your AWS region:', 'us-east-1');\n writeConfig(configFileName, config);\n\n header('AWS ACCOUNT NUMBER');\n print('Medplum Infrastructure will use your AWS account number to create AWS resources.');\n if (currentAccountId) {\n print('Using the AWS CLI, your current account ID is: ' + currentAccountId);\n }\n config.accountNumber = await ask('What is your AWS account number?', currentAccountId);\n writeConfig(configFileName, config);\n\n header('STACK NAME');\n print('Medplum will create a CloudFormation stack to manage AWS resources.');\n print('AWS CloudFormation stack names ');\n const defaultStackName = 'Medplum' + config.name.charAt(0).toUpperCase() + config.name.slice(1);\n config.stackName = await ask('Enter your CloudFormation stack name?', defaultStackName);\n writeConfig(configFileName, config);\n\n header('BASE DOMAIN NAME');\n print('Please enter the base domain name for your Medplum deployment.');\n print('');\n print('Medplum deploys multiple subdomains for various services.');\n print('');\n print('For example, \"api.\" for the REST API and \"app.\" for the web application.');\n print('The base domain name is the common suffix for all subdomains.');\n print('');\n print('For example, if your base domain name is \"example.com\",');\n print('then the REST API will be \"api.example.com\".');\n print('');\n print('The base domain should include the TLD (i.e., \".com\", \".org\", \".net\").');\n print('');\n print('Note that you must own the base domain, and it must use Route53 DNS.');\n while (!config.domainName) {\n config.domainName = await ask('Enter your base domain name:');\n }\n writeConfig(configFileName, config);\n\n header('SUPPORT EMAIL');\n print('Medplum sends transactional emails to users.');\n print('For example, emails to new users or for password reset.');\n print('Medplum will use the support email address to send these emails.');\n print('Note that you must verify the support email address in SES.');\n const supportEmail = await ask('Enter your support email address:');\n\n header('API DOMAIN NAME');\n print('Medplum deploys a REST API for the backend services.');\n config.apiDomainName = await ask('Enter your REST API domain name:', 'api.' + config.domainName);\n config.baseUrl = `https://${config.apiDomainName}/`;\n writeConfig(configFileName, config);\n\n header('APP DOMAIN NAME');\n print('Medplum deploys a web application for the user interface.');\n config.appDomainName = await ask('Enter your web application domain name:', 'app.' + config.domainName);\n writeConfig(configFileName, config);\n\n header('STORAGE DOMAIN NAME');\n print('Medplum deploys a storage service for file uploads.');\n config.storageDomainName = await ask('Enter your storage domain name:', 'storage.' + config.domainName);\n writeConfig(configFileName, config);\n\n header('STORAGE BUCKET');\n print('Medplum uses an S3 bucket to store binary content such as file uploads.');\n print('Medplum will create a the S3 bucket as part of the CloudFormation stack.');\n config.storageBucketName = await ask('Enter your storage bucket name:', config.storageDomainName);\n writeConfig(configFileName, config);\n\n header('MAX AVAILABILITY ZONES');\n print('Medplum API servers can be deployed in multiple availability zones.');\n print('This provides redundancy and high availability.');\n print('However, it also increases the cost of the deployment.');\n print('If you want to use all availability zones, choose a large number such as 99.');\n print('If you want to restrict the number, for example to manage EIP limits,');\n print('then choose a small number such as 2 or 3.');\n config.maxAzs = await chooseInt('Enter the maximum number of availability zones:', [2, 3, 99], 2);\n\n header('DATABASE INSTANCES');\n print('Medplum uses a relational database to store data.');\n print('Medplum can create a new RDS database as part of the CloudFormation stack,');\n print('or can set up your own database and enter the database name, username, and password.');\n if (await yesOrNo('Do you want to create a new RDS database as part of the CloudFormation stack?')) {\n print('Medplum will create a new RDS database as part of the CloudFormation stack.');\n print('');\n print('If you need high availability, you can choose multiple instances.');\n print('Use 1 for a single instance, or 2 for a primary and a standby.');\n config.rdsInstances = await chooseInt('Enter the number of database instances:', [1, 2], 1);\n } else {\n print('Medplum will not create a new RDS database.');\n print('Please create a new RDS database and enter the database name, username, and password.');\n print('Set the AWS Secrets Manager secret ARN in the config file in the \"rdsSecretsArn\" setting.');\n config.rdsSecretsArn = 'TODO';\n }\n writeConfig(configFileName, config);\n\n header('SERVER INSTANCES');\n print('Medplum uses AWS Fargate to run the API servers.');\n print('Medplum will create a new Fargate cluster as part of the CloudFormation stack.');\n print('Fargate will automatically scale the number of servers up and down.');\n print('If you need high availability, you can choose multiple instances.');\n config.desiredServerCount = await chooseInt('Enter the number of server instances:', [1, 2, 3, 4, 6, 8], 1);\n writeConfig(configFileName, config);\n\n header('SERVER MEMORY');\n print('You can choose the amount of memory for each server instance.');\n print('The default is 512 MB, which is sufficient for getting started.');\n print('Note that only certain CPU units are compatible with memory units.');\n print('Consult AWS Fargate \"Task Definition Parameters\" for more information.');\n config.serverMemory = await chooseInt('Enter the server memory (MB):', [512, 1024, 2048, 4096, 8192, 16384], 512);\n writeConfig(configFileName, config);\n\n header('SERVER CPU');\n print('You can choose the amount of CPU for each server instance.');\n print('CPU is expressed as an integer using AWS CPU units');\n print('The default is 256, which is sufficient for getting started.');\n print('Note that only certain CPU units are compatible with memory units.');\n print('Consult AWS Fargate \"Task Definition Parameters\" for more information.');\n config.serverCpu = await chooseInt('Enter the server CPU:', [256, 512, 1024, 2048, 4096, 8192, 16384], 256);\n writeConfig(configFileName, config);\n\n header('SERVER IMAGE');\n print('Medplum uses Docker images for the API servers.');\n print('You can choose the image to use for the servers.');\n print('Docker images can be loaded from either Docker Hub or AWS ECR.');\n print('The default is the latest Medplum release.');\n const latestVersion = (await getServerVersions())[0] ?? 'latest';\n config.serverImage = await ask('Enter the server image:', `medplum/medplum-server:${latestVersion}`);\n writeConfig(configFileName, config);\n\n header('SIGNING KEY');\n print('Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.');\n const signingKey = await generateSigningKey(config.region, config.stackName + 'SigningKey');\n if (signingKey) {\n config.signingKeyId = signingKey.keyId;\n config.storagePublicKey = signingKey.publicKey;\n writeConfig(configFileName, config);\n } else {\n print('Unable to generate signing key.');\n print('Please manually create a signing key and enter the key ID and public key in the config file.');\n print('You must set the \"signingKeyId\", \"signingKey\", and \"signingKeyPassphrase\" settings.');\n }\n\n header('SSL CERTIFICATES');\n print(`Medplum will now check for existing SSL certificates for the subdomains.`);\n const allCerts = await listAllCertificates(config.region);\n print('Found ' + allCerts.length + ' certificate(s).');\n\n // Process certificates for each subdomain\n // Note: The \"api\" certificate must be created in the same region as the API\n // Note: The \"app\" and \"storage\" certificates must be created in us-east-1\n for (const { region, certName } of [\n { region: config.region, certName: 'api' },\n { region: 'us-east-1', certName: 'app' },\n { region: 'us-east-1', certName: 'storage' },\n ] as const) {\n print('');\n const arn = await processCert(config, allCerts, region, certName);\n config[getDomainCertSetting(certName)] = arn;\n writeConfig(configFileName, config);\n }\n\n header('AWS PARAMETER STORE');\n print('Medplum uses AWS Parameter Store to store sensitive configuration values.');\n print('These values will be encrypted at rest.');\n print(`The values will be stored in the \"/medplum/${config.name}\" path.`);\n\n const serverParams: Record<string, string | number> = {\n port: config.apiPort,\n baseUrl: config.baseUrl,\n appBaseUrl: `https://${config.appDomainName}/`,\n storageBaseUrl: `https://${config.storageDomainName}/binary/`,\n binaryStorage: `s3:${config.storageBucketName}`,\n supportEmail: supportEmail,\n };\n\n if (signingKey) {\n serverParams.signingKeyId = signingKey.keyId;\n serverParams.signingKey = signingKey.privateKey;\n serverParams.signingKeyPassphrase = signingKey.passphrase;\n }\n\n print(\n JSON.stringify(\n {\n ...serverParams,\n signingKey: '****',\n signingKeyPassphrase: '****',\n },\n null,\n 2\n )\n );\n\n if (await yesOrNo('Do you want to store these values in AWS Parameter Store?')) {\n await writeParameters(config.region, `/medplum/${config.name}/`, serverParams);\n } else {\n const serverConfigFileName = getConfigFileName(config.name, { server: true });\n writeConfig(serverConfigFileName, serverParams);\n print('Skipping AWS Parameter Store.');\n print(`Writing values to local config file: ${serverConfigFileName}`);\n print('Please add these values to AWS Parameter Store manually.');\n }\n\n header('DONE!');\n print('Medplum configuration complete.');\n print('You can now proceed to deploying the Medplum infrastructure with CDK.');\n print('Run:');\n print('');\n print(` npx cdk bootstrap -c config=${configFileName}`);\n print(` npx cdk synth -c config=${configFileName}`);\n if (config.region === 'us-east-1') {\n print(` npx cdk deploy -c config=${configFileName}`);\n } else {\n print(` npx cdk deploy -c config=${configFileName} --all`);\n }\n print('');\n print('See Medplum documentation for more information:');\n print('');\n print(' https://www.medplum.com/docs/self-hosting/install-on-aws');\n print('');\n closeTerminal();\n}\n\n/**\n * Returns the current AWS account ID.\n * This is used as the default value for the \"accountNumber\" config setting.\n * @param region - The AWS region.\n * @returns The AWS account ID.\n */\nasync function getAccountId(region: string): Promise<string | undefined> {\n try {\n const client = new STSClient({ region });\n const command = new GetCallerIdentityCommand({});\n const response = await client.send(command);\n return response.Account;\n } catch (err) {\n console.log('Warning: Unable to get AWS account ID', (err as Error).message);\n return undefined;\n }\n}\n\n/**\n * Returns a list of all AWS certificates.\n * This is used to find existing certificates for the subdomains.\n * If the primary region is not us-east-1, then certificates in us-east-1 will also be returned.\n * @param region - The AWS region.\n * @returns The list of AWS Certificates.\n */\nasync function listAllCertificates(region: string): Promise<CertificateSummary[]> {\n const result = await listCertificates(region);\n if (region !== 'us-east-1') {\n const usEast1Result = await listCertificates('us-east-1');\n result.push(...usEast1Result);\n }\n return result;\n}\n\n/**\n * Returns a list of AWS Certificates.\n * This is used to find existing certificates for the subdomains.\n * @param region - The AWS region.\n * @returns The list of AWS Certificates.\n */\nasync function listCertificates(region: string): Promise<CertificateSummary[]> {\n try {\n const client = new ACMClient({ region });\n const command = new ListCertificatesCommand({ MaxItems: 1000 });\n const response = await client.send(command);\n return response.CertificateSummaryList as CertificateSummary[];\n } catch (err) {\n console.log('Warning: Unable to list certificates', (err as Error).message);\n return [];\n }\n}\n\n/**\n * Processes a required certificate.\n *\n * 1. If the certificate already exists, return the ARN.\n * 2. If the certificate does not exist, and the user wants to create a new certificate, create it and return the ARN.\n * 3. If the certificate does not exist, and the user does not want to create a new certificate, return a placeholder.\n * @param config - In-progress config settings.\n * @param allCerts - List of all existing certificates.\n * @param region - The AWS region where the certificate is needed.\n * @param certName - The name of the certificate (api, app, or storage).\n * @returns The ARN of the certificate or placeholder if a new certificate is needed.\n */\nasync function processCert(\n config: MedplumInfraConfig,\n allCerts: CertificateSummary[],\n region: string,\n certName: 'api' | 'app' | 'storage'\n): Promise<string> {\n const domainName = config[getDomainSetting(certName)];\n const existingCert = allCerts.find((cert) => cert.CertificateArn?.includes(region) && cert.DomainName === domainName);\n if (existingCert) {\n print(`Found existing certificate for \"${domainName}\" in \"${region}.`);\n return existingCert.CertificateArn as string;\n }\n\n print(`No existing certificate found for \"${domainName}\" in \"${region}.`);\n if (!(await yesOrNo('Do you want to request a new certificate?'))) {\n print(`Please add your certificate ARN to the config file in the \"${getDomainCertSetting(certName)}\" setting.`);\n return 'TODO';\n }\n\n const arn = await requestCert(region, domainName);\n print('Certificate ARN: ' + arn);\n return arn;\n}\n\n/**\n * Requests an AWS Certificate.\n * @param region - The AWS region.\n * @param domain - The domain name.\n * @returns The AWS Certificate ARN on success, or undefined on failure.\n */\nasync function requestCert(region: string, domain: string): Promise<string> {\n try {\n const validationMethod = await choose(\n 'Validate certificate using DNS or email validation?',\n ['dns', 'email'],\n 'dns'\n );\n const client = new ACMClient({ region });\n const command = new RequestCertificateCommand({\n DomainName: domain,\n ValidationMethod: validationMethod.toUpperCase() as ValidationMethod,\n });\n const response = await client.send(command);\n return response.CertificateArn as string;\n } catch (err) {\n console.log('Error: Unable to request certificate', (err as Error).message);\n return 'TODO';\n }\n}\n\n/**\n * Generates an AWS CloudFront signing key.\n *\n * Requirements:\n *\n * 1. It must be an SSH-2 RSA key pair.\n * 2. It must be in base64-encoded PEM format.\n * 3. It must be a 2048-bit key pair.\n *\n * See: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html#private-content-creating-cloudfront-key-pairs\n *\n * @param region - The AWS region.\n * @param keyName - The key name.\n * @returns A new signing key.\n */\nasync function generateSigningKey(\n region: string,\n keyName: string\n): Promise<\n | {\n keyId: string;\n publicKey: string;\n privateKey: string;\n passphrase: string;\n }\n | undefined\n> {\n const passphrase = randomUUID();\n const signingKey = generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs1',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase,\n },\n });\n\n try {\n const response = await new CloudFrontClient({ region }).send(\n new CreatePublicKeyCommand({\n PublicKeyConfig: {\n Name: keyName,\n CallerReference: randomUUID(),\n EncodedKey: signingKey.publicKey,\n },\n })\n );\n\n return {\n keyId: response.PublicKey?.Id as string,\n publicKey: signingKey.publicKey,\n privateKey: signingKey.privateKey,\n passphrase,\n };\n } catch (err) {\n console.log('Error: Unable to create signing key: ', normalizeErrorString(err));\n return undefined;\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { getAllStacks, getStackDetails, printStackDetails } from './utils';\n\n/**\n * The AWS \"list\" command prints summary details about all Medplum CloudFormation stacks.\n */\nexport async function listStacksCommand(): Promise<void> {\n const stackSummaries = await getAllStacks();\n for (const stackSummary of stackSummaries) {\n const stackName = stackSummary.StackName;\n const details = await getStackDetails(stackName);\n if (!details) {\n continue;\n }\n printStackDetails(details);\n console.log('');\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { PutObjectCommand } from '@aws-sdk/client-s3';\nimport { ContentType } from '@medplum/core';\nimport fastGlob from 'fast-glob';\nimport { createReadStream, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join, sep } from 'node:path';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { readConfig, safeTarExtractor } from '../utils';\nimport { createInvalidation, getStackByTag, printConfigNotFound, printStackNotFound, s3Client } from './utils';\n\nexport interface UpdateAppOptions {\n file?: string;\n toVersion?: string;\n dryrun?: boolean;\n tarPath?: string;\n}\n\n/**\n * The AWS \"update-app\" command updates the Medplum app in a Medplum CloudFormation stack to the latest version.\n * @param tag - The Medplum stack tag.\n * @param options - The update options.\n */\nexport async function updateAppCommand(tag: string, options: UpdateAppOptions): Promise<void> {\n const config = readConfig(tag, options);\n if (!config) {\n printConfigNotFound(tag, options);\n throw new Error(`Config not found: ${tag}`);\n }\n const details = await getStackByTag(tag);\n if (!details) {\n await printStackNotFound(tag);\n throw new Error(`Stack not found: ${tag}`);\n }\n const appBucket = details.appBucket;\n if (!appBucket) {\n throw new Error(`App bucket not found for stack ${tag}`);\n }\n\n let tmpDir: string;\n\n if (options.tarPath) {\n tmpDir = options.tarPath;\n } else {\n const version = options?.toVersion ?? 'latest';\n tmpDir = await downloadNpmPackage('@medplum/app', version);\n }\n\n // Replace variables in the app\n replaceVariables(tmpDir, {\n MEDPLUM_BASE_URL: config.baseUrl as string,\n MEDPLUM_CLIENT_ID: config.clientId ?? '',\n GOOGLE_CLIENT_ID: config.googleClientId ?? '',\n RECAPTCHA_SITE_KEY: config.recaptchaSiteKey ?? '',\n MEDPLUM_REGISTER_ENABLED: config.registerEnabled ? 'true' : 'false',\n });\n\n // Upload the app to S3 with correct content-type and cache-control\n await uploadAppToS3(tmpDir, appBucket.PhysicalResourceId as string, options);\n\n // Create a CloudFront invalidation to clear any cached resources\n if (details.appDistribution?.PhysicalResourceId && !options.dryrun) {\n await createInvalidation(details.appDistribution.PhysicalResourceId);\n }\n\n console.log('Done');\n}\n\n/**\n * Returns NPM package metadata for a given package name.\n * See: https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#getpackageversion\n * @param packageName - The npm package name.\n * @param version - The npm package version string.\n * @returns The package.json metadata content.\n */\nasync function getNpmPackageMetadata(packageName: string, version: string): Promise<any> {\n const url = `https://registry.npmjs.org/${packageName}/${version}`;\n const response = await fetch(url);\n return response.json();\n}\n\n/**\n * Downloads and extracts an NPM package.\n * @param packageName - The NPM package name.\n * @param version - The NPM package version or \"latest\".\n * @returns Path to temporary directory where the package was downloaded and extracted.\n */\nasync function downloadNpmPackage(packageName: string, version: string): Promise<string> {\n const packageMetadata = await getNpmPackageMetadata(packageName, version);\n const tarballUrl = packageMetadata.dist.tarball as string;\n const tmpDir = mkdtempSync(join(tmpdir(), 'tarball-'));\n try {\n const response = await fetch(tarballUrl);\n if (!response.body) {\n throw new Error('Received empty response body');\n }\n const extractor = safeTarExtractor(tmpDir);\n await pipeline(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]), extractor);\n return join(tmpDir, 'package', 'dist');\n } catch (error) {\n rmSync(tmpDir, { recursive: true, force: true });\n throw error;\n }\n}\n\n/**\n * Replaces variables in all JS files in the given folder.\n * @param folderName - The folder name of the files.\n * @param replacements - The collection of variable placeholders and replacements.\n */\nfunction replaceVariables(folderName: string, replacements: Record<string, string>): void {\n for (const item of readdirSync(folderName, { withFileTypes: true })) {\n const itemPath = join(folderName, item.name);\n if (item.isDirectory()) {\n replaceVariables(itemPath, replacements);\n } else if (item.isFile() && itemPath.endsWith('.js')) {\n replaceVariablesInFile(itemPath, replacements);\n }\n }\n}\n\n/**\n * Replaces variables in the JS file.\n * @param fileName - The file name.\n * @param replacements - The collection of variable placeholders and replacements.\n */\nfunction replaceVariablesInFile(fileName: string, replacements: Record<string, string>): void {\n let contents = readFileSync(fileName, 'utf-8');\n for (const [placeholder, replacement] of Object.entries(replacements)) {\n contents = contents.replaceAll(`__${placeholder}__`, replacement);\n }\n writeFileSync(fileName, contents);\n}\n\n/**\n * Uploads the app to S3.\n * Ensures correct content-type and cache-control for each file.\n * @param tmpDir - The temporary directory where the app is located.\n * @param bucketName - The destination S3 bucket name.\n * @param options - The update options.\n */\nasync function uploadAppToS3(tmpDir: string, bucketName: string, options: UpdateAppOptions): Promise<void> {\n // Manually iterate and upload files\n // Automatic content-type detection is not reliable on Microsoft Windows\n // So we explicitly set content-type\n const uploadPatterns: [string, string, boolean][] = [\n // Cached\n // These files generally have a hash, so they can be cached forever\n // It is important to upload them first to avoid broken references from index.html\n ['assets/**/*.css', ContentType.CSS, true],\n ['assets/**/*.css.map', ContentType.JSON, true],\n ['assets/**/*.js', ContentType.JAVASCRIPT, true],\n ['assets/**/*.js.map', ContentType.JSON, true],\n ['assets/**/*.txt', ContentType.TEXT, true],\n ['assets/**/*.ico', ContentType.FAVICON, true],\n ['img/**/*.png', ContentType.PNG, true],\n ['img/**/*.svg', ContentType.SVG, true],\n ['robots.txt', ContentType.TEXT, true],\n\n // Not cached\n ['index.html', ContentType.HTML, false],\n ];\n for (const uploadPattern of uploadPatterns) {\n await uploadFolderToS3({\n rootDir: tmpDir,\n bucketName,\n fileNamePattern: uploadPattern[0],\n contentType: uploadPattern[1],\n cached: uploadPattern[2],\n dryrun: options.dryrun,\n });\n }\n}\n\n/**\n * Uploads a directory of files to S3.\n * @param options - The upload options such as bucket name, content type, and cache control.\n * @param options.rootDir - The root directory of the upload.\n * @param options.bucketName - The destination bucket name.\n * @param options.fileNamePattern - The glob file pattern to upload.\n * @param options.contentType - The content type MIME type.\n * @param options.cached - True to mark as public and cached forever.\n * @param options.dryrun - True to skip the upload.\n */\nasync function uploadFolderToS3(options: {\n rootDir: string;\n bucketName: string;\n fileNamePattern: string;\n contentType: string;\n cached: boolean;\n dryrun?: boolean;\n}): Promise<void> {\n const items = fastGlob.sync(options.fileNamePattern, { cwd: options.rootDir });\n for (const item of items) {\n await uploadFileToS3(join(options.rootDir, item), options);\n }\n}\n\n/**\n * Uploads a file to S3.\n * @param filePath - The file path.\n * @param options - The upload options such as bucket name, content type, and cache control.\n * @param options.rootDir - The root directory of the upload.\n * @param options.bucketName - The destination bucket name.\n * @param options.contentType - The content type MIME type.\n * @param options.cached - True to mark as public and cached forever.\n * @param options.dryrun - True to skip the upload.\n */\nasync function uploadFileToS3(\n filePath: string,\n options: {\n rootDir: string;\n bucketName: string;\n contentType: string;\n cached: boolean;\n dryrun?: boolean;\n }\n): Promise<void> {\n const fileStream = createReadStream(filePath);\n const s3Key = filePath\n .substring(options.rootDir.length + 1)\n .split(sep)\n .join('/');\n\n const putObjectParams = {\n Bucket: options.bucketName,\n Key: s3Key,\n Body: fileStream,\n ContentType: options.contentType,\n CacheControl: options.cached ? 'public, max-age=31536000' : 'no-cache, no-store, must-revalidate',\n };\n\n console.log(`Uploading ${s3Key} to ${options.bucketName}...`);\n if (!options.dryrun) {\n await s3Client.send(new PutObjectCommand(putObjectParams));\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { StackResource } from '@aws-sdk/client-cloudformation';\nimport { GetBucketPolicyCommand, PutBucketPolicyCommand } from '@aws-sdk/client-s3';\nimport { readConfig } from '../utils';\nimport { createInvalidation, getStackByTag, printConfigNotFound, printStackNotFound, s3Client } from './utils';\n\nexport interface UpdateBucketPoliciesOptions {\n file?: string;\n dryrun?: boolean;\n guarddutyMalwareProtection?: boolean;\n}\n\ninterface Policy {\n Version?: string;\n Statement?: PolicyStatement[];\n}\n\ninterface PolicyStatement {\n Sid?: string;\n Effect?: string;\n Principal?: { AWS?: string; CanonicalUser?: string };\n Action?: string | string[];\n Resource?: string | string[];\n Condition?: Record<string, Record<string, string | string[]>>;\n}\n\n/**\n * The AWS \"update-bucket-policies\" command adds necessary policy statements to S3 bucket policy documents.\n *\n * This is necessary for Medplum deployments outside of the us-east-1 region.\n *\n * @param tag - The Medplum stack tag.\n * @param options - The update options.\n */\nexport async function updateBucketPoliciesCommand(tag: string, options: UpdateBucketPoliciesOptions): Promise<void> {\n const config = readConfig(tag, options);\n if (!config) {\n printConfigNotFound(tag, options);\n throw new Error(`Config not found: ${tag}`);\n }\n\n const details = await getStackByTag(tag);\n if (!details) {\n await printStackNotFound(tag);\n throw new Error(`Stack not found: ${tag}`);\n }\n\n try {\n await updateBucketPolicy(\n 'App',\n details.appBucket,\n details.appDistribution,\n details.appOriginAccessIdentity,\n options\n );\n } catch (err) {\n console.error(`Error updating App bucket policy: ${(err as Error).message}`);\n }\n\n try {\n await updateBucketPolicy(\n 'Storage',\n details.storageBucket,\n details.storageDistribution,\n details.storageOriginAccessIdentity,\n options\n );\n } catch (err) {\n console.error(`Error updating Storage bucket policy: ${(err as Error).message}`);\n }\n\n console.log('Done');\n}\n\nexport async function updateBucketPolicy(\n friendlyName: string,\n bucketResource: StackResource | undefined,\n distributionResource: StackResource | undefined,\n oaiResource: StackResource | undefined,\n options: UpdateBucketPoliciesOptions\n): Promise<void> {\n if (!bucketResource?.PhysicalResourceId) {\n throw new Error(`${friendlyName} bucket not found`);\n }\n\n if (!distributionResource?.PhysicalResourceId) {\n throw new Error(`${friendlyName} distribution not found`);\n }\n\n if (!oaiResource?.PhysicalResourceId) {\n throw new Error(`${friendlyName} OAI not found`);\n }\n\n const bucketName = bucketResource.PhysicalResourceId;\n const oaiId = oaiResource.PhysicalResourceId;\n const bucketPolicy = await getPolicy(bucketName);\n if (policyHasAllowStatement(bucketPolicy, bucketName, oaiId)) {\n throw new Error(`${friendlyName} bucket already has policy statement`);\n }\n\n addAllowPolicyStatement(bucketPolicy, bucketName, oaiId);\n if (friendlyName === 'Storage' && options.guarddutyMalwareProtection) {\n addGuardDutyReadPolicyStatement(bucketPolicy, bucketName, oaiId);\n }\n console.log(`${friendlyName} bucket policy:`);\n console.log(JSON.stringify(bucketPolicy, undefined, 2));\n\n if (options.dryrun) {\n console.log('Dry run - skipping updates');\n } else {\n // Apply the updated policy\n console.log('Updating bucket policy...');\n await setPolicy(bucketName, bucketPolicy);\n console.log('Bucket policy updated');\n\n // Create a CloudFront invalidation to clear any cached responses\n console.log('Creating CloudFront invalidation...');\n await createInvalidation(distributionResource.PhysicalResourceId);\n console.log('CloudFront invalidation created');\n\n console.log(`${friendlyName} bucket policy updated`);\n }\n}\n\nasync function getPolicy(bucketName: string): Promise<Policy> {\n const policyResponse = await s3Client.send(\n new GetBucketPolicyCommand({\n Bucket: bucketName,\n })\n );\n return JSON.parse(policyResponse.Policy ?? '{}') as Policy;\n}\n\nasync function setPolicy(bucketName: string, policy: Policy): Promise<void> {\n await s3Client.send(\n new PutBucketPolicyCommand({\n Bucket: bucketName,\n Policy: JSON.stringify(policy),\n })\n );\n}\n\nfunction policyHasAllowStatement(policy: Policy, bucketName: string, oaiId: string): boolean {\n return !!policy?.Statement?.some((s: PolicyStatement) => {\n return (\n s?.Effect === 'Allow' &&\n s?.Principal?.AWS === `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}` &&\n Array.isArray(s?.Action) &&\n s?.Action?.includes('s3:GetObject*') &&\n s?.Action?.includes('s3:GetBucket*') &&\n s?.Action?.includes('s3:List*') &&\n Array.isArray(s?.Resource) &&\n s?.Resource?.includes(`arn:aws:s3:::${bucketName}`) &&\n s?.Resource?.includes(`arn:aws:s3:::${bucketName}/*`)\n );\n });\n}\n\nfunction addAllowPolicyStatement(policy: Policy, bucketName: string, oaiId: string): void {\n if (!policy.Version) {\n policy.Version = '2012-10-17';\n }\n\n if (!policy.Statement) {\n policy.Statement = [];\n }\n\n policy.Statement.push({\n Effect: 'Allow',\n Principal: {\n AWS: `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}`,\n },\n Action: ['s3:GetObject*', 's3:GetBucket*', 's3:List*'],\n Resource: [`arn:aws:s3:::${bucketName}`, `arn:aws:s3:::${bucketName}/*`],\n });\n}\n\nfunction addGuardDutyReadPolicyStatement(policy: Policy, bucketName: string, oaiId: string): void {\n if (\n policy.Statement?.some(\n (s) =>\n s?.Effect === 'Deny' &&\n s?.Principal?.AWS === `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}` &&\n statementHasAction(s, 's3:GetObject') &&\n statementHasAction(s, 's3:GetObjectVersion') &&\n s?.Condition?.StringNotEquals?.['s3:ExistingObjectTag/GuardDutyMalwareScanStatus'] === 'NO_THREATS_FOUND'\n )\n ) {\n return;\n }\n\n policy.Statement?.push({\n Sid: 'GuardDutyMalwareProtectionReadGate',\n Effect: 'Deny',\n Principal: {\n AWS: `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}`,\n },\n Action: ['s3:GetObject', 's3:GetObjectVersion'],\n Resource: `arn:aws:s3:::${bucketName}/*`,\n Condition: {\n StringNotEquals: {\n 's3:ExistingObjectTag/GuardDutyMalwareScanStatus': 'NO_THREATS_FOUND',\n },\n },\n });\n}\n\nfunction statementHasAction(statement: PolicyStatement, action: string): boolean {\n if (statement.Action === action) {\n return true;\n }\n return Array.isArray(statement.Action) && statement.Action.includes(action);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumInfraConfig } from '@medplum/core';\nimport { color } from '../util/color';\nimport { getConfigFileName, readConfig, readServerConfig } from '../utils';\nimport { closeTerminal, initTerminal, print, yesOrNo } from './terminal';\nimport { printConfigNotFound, writeParameters } from './utils';\n\nexport interface UpdateConfigOptions {\n file?: string;\n dryrun?: boolean;\n yes?: boolean;\n}\n\n/**\n * The AWS \"update-config\" command updates AWS Parameter Store values with values from the local config file.\n * @param tag - The Medplum stack tag.\n * @param options - Additional command line options.\n */\nexport async function updateConfigCommand(tag: string, options: UpdateConfigOptions): Promise<void> {\n try {\n initTerminal();\n\n const infraConfig = readConfig(tag, options) as MedplumInfraConfig;\n if (!infraConfig) {\n printConfigNotFound(tag, options);\n throw new Error(`Config not found: ${tag}`);\n }\n\n const serverConfig = readServerConfig(tag) ?? {};\n\n // If the server config is empty, prompt the user to proceed\n if (!options.yes && Object.keys(serverConfig).length === 0) {\n const serverConfigFileName = getConfigFileName(tag, { server: true });\n console.log(color.yellow(`Config file ${serverConfigFileName} not found!`));\n if (!(await yesOrNo('Do you want to proceed?'))) {\n console.log(color.red(`Run Aborted, please ensure ${serverConfigFileName} is present and try again.`));\n return;\n }\n }\n\n checkConfigConflicts(infraConfig, serverConfig);\n mergeConfigs(infraConfig, serverConfig);\n\n print('Medplum uses AWS Parameter Store to store sensitive configuration values.');\n print('These values will be encrypted at rest.');\n print(`The values will be stored in the \"/medplum/${infraConfig.name}\" path.`);\n\n print(\n JSON.stringify(\n {\n ...serverConfig,\n signingKey: '****',\n signingKeyPassphrase: '****',\n },\n null,\n 2\n )\n );\n\n if (options.dryrun) {\n console.log(color.yellow('Dry run - skipping updates!'));\n } else if (options.yes || (await yesOrNo('Do you want to store these values in AWS Parameter Store?'))) {\n await writeParameters(infraConfig.region, `/medplum/${infraConfig.name}/`, serverConfig);\n }\n } finally {\n closeTerminal();\n }\n}\n\nexport function checkConfigConflicts(\n infraConfig: MedplumInfraConfig,\n serverConfig: Record<string, string | number>\n): void {\n checkConflict(\n infraConfig.apiPort,\n serverConfig.port,\n `Infra \"apiPort\" (${infraConfig.apiPort}) does not match server \"port\" (${serverConfig.port})`\n );\n\n checkConflict(\n infraConfig.baseUrl,\n serverConfig.baseUrl,\n `Infra \"baseUrl\" (${infraConfig.baseUrl}) does not match server \"baseUrl\" (${serverConfig.baseUrl})`\n );\n\n checkConflict(\n infraConfig.appDomainName && `https://${infraConfig.appDomainName}/`,\n serverConfig.appBaseUrl,\n `Infra \"appDomainName\" (${infraConfig.appDomainName}) does not match server \"appBaseUrl\" (${serverConfig.appBaseUrl})`\n );\n\n checkConflict(\n infraConfig.storageDomainName && `https://${infraConfig.storageDomainName}/binary/`,\n serverConfig.storageBaseUrl,\n `Infra \"storageDomainName\" (${infraConfig.storageDomainName}) does not match server \"storageBaseUrl\" (${serverConfig.storageBaseUrl})`\n );\n}\n\nfunction checkConflict<T>(a: T, b: T, message: string): void {\n if (isConflict(a, b)) {\n throw new Error(message);\n }\n}\n\nfunction isConflict<T>(a: T, b: T): boolean {\n return a !== undefined && b !== undefined && a !== b;\n}\n\nexport function mergeConfigs(infraConfig: MedplumInfraConfig, serverConfig: Record<string, string | number>): void {\n if (infraConfig.apiPort) {\n serverConfig.port = infraConfig.apiPort;\n }\n if (infraConfig.baseUrl) {\n serverConfig.baseUrl = infraConfig.baseUrl;\n }\n if (infraConfig.appDomainName) {\n serverConfig.appBaseUrl = `https://${infraConfig.appDomainName}/`;\n }\n if (infraConfig.storageDomainName) {\n serverConfig.storageBaseUrl = `https://${infraConfig.storageDomainName}/binary/`;\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, MedplumClientOptions, MedplumInfraConfig } from '@medplum/core';\nimport { spawnSync } from 'node:child_process';\nimport * as semver from 'semver';\nimport { createMedplumClient } from '../util/client';\nimport { getConfigFileName, readConfig, writeConfig } from '../utils';\nimport { getServerVersions, printConfigNotFound } from './utils';\n\nexport interface UpdateServerOptions extends MedplumClientOptions {\n file?: string;\n toVersion?: string;\n}\n\n/**\n * The AWS \"update-server\" command updates the Medplum server in a Medplum CloudFormation stack.\n * @param tag - The Medplum stack tag.\n * @param options - Client options\n */\nexport async function updateServerCommand(tag: string, options: UpdateServerOptions): Promise<void> {\n const client = await createMedplumClient(options);\n const config = readConfig(tag, options) as MedplumInfraConfig;\n if (!config) {\n console.log(`Configuration file ${getConfigFileName(tag)} not found`);\n printConfigNotFound(tag, options);\n throw new Error(`Config not found: ${tag}`);\n }\n\n const separatorIndex = config.serverImage.lastIndexOf(':');\n const serverImagePrefix = config.serverImage.slice(0, separatorIndex);\n\n const initialVersion = await getCurrentVersion(client, config);\n\n let updateVersion = await nextUpdateVersion(initialVersion);\n while (updateVersion) {\n if (options.toVersion && semver.gt(updateVersion, options.toVersion)) {\n console.log(`Skipping update to v${updateVersion}`);\n break;\n }\n\n console.log(`Performing update to v${updateVersion}`);\n config.serverImage = `${serverImagePrefix}:${updateVersion}`;\n deployServerUpdate(tag, config);\n\n // Run data migrations\n await client.startAsyncRequest('/admin/super/migrate');\n\n updateVersion = await nextUpdateVersion(updateVersion);\n }\n}\n\nasync function getCurrentVersion(medplum: MedplumClient, config: MedplumInfraConfig): Promise<string> {\n const separatorIndex = config.serverImage.lastIndexOf(':');\n let initialVersion = config.serverImage.slice(separatorIndex + 1);\n if (initialVersion === 'latest') {\n const serverInfo = await medplum.get('/healthcheck');\n initialVersion = serverInfo.version as string;\n const sep = initialVersion.indexOf('-');\n if (sep > -1) {\n initialVersion = initialVersion.slice(0, sep);\n }\n }\n return initialVersion;\n}\n\nasync function nextUpdateVersion(currentVersion: string, targetVersion?: string): Promise<string | undefined> {\n // The list of server versions is sorted in descending order\n // The first entry is the latest version\n // The last entry is the oldest version\n // We want to find the \"next\" version after our current version\n // Filter the list to only include versions that are greater than or equal to the current minor version\n // Then pop the last entry from the list\n const allVersions = await getServerVersions(currentVersion);\n const latestVersion = allVersions[0];\n return allVersions\n .filter(\n (v) => v === latestVersion || v === targetVersion || semver.gte(v, semver.inc(currentVersion, 'minor') as string)\n )\n .pop();\n}\n\nfunction deployServerUpdate(tag: string, config: MedplumInfraConfig): void {\n const configFile = getConfigFileName(tag);\n writeConfig(configFile, config);\n\n const cmd = `npx cdk deploy -c config=${configFile}${config.region !== 'us-east-1' ? ' --all' : ''}`;\n console.log('> ' + cmd);\n const deploy = spawnSync(cmd, { stdio: 'inherit' });\n\n if (deploy.status !== 0) {\n throw new Error(`Deploy of ${config.serverImage} failed (exit code ${deploy.status}): ${deploy.stderr}`);\n }\n console.log(deploy.stdout);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { color, processDescription } from '../util/color';\nimport { addSubcommand, MedplumCommand } from '../utils';\nimport { describeStacksCommand } from './describe';\nimport { initStackCommand } from './init';\nimport { listStacksCommand } from './list';\nimport { updateAppCommand } from './update-app';\nimport { updateBucketPoliciesCommand } from './update-bucket-policies';\nimport { updateConfigCommand } from './update-config';\nimport { updateServerCommand } from './update-server';\n\nexport function buildAwsCommand(): MedplumCommand {\n const aws = new MedplumCommand('aws').description('Commands to manage AWS resources');\n\n aws.command('init').description('Initialize a new Medplum AWS CloudFormation stacks').action(initStackCommand);\n\n aws.command('list').description('List Medplum AWS CloudFormation stacks').action(listStacksCommand);\n\n aws\n .command('describe')\n .description('Describe a Medplum AWS CloudFormation stack by tag')\n .argument('<tag>', 'The Medplum stack tag')\n .action(describeStacksCommand);\n\n aws\n .command('update-config')\n .alias('deploy-config')\n .summary('Update the AWS Parameter Store config values.')\n .description(\n processDescription(\n 'Update the AWS Parameter Store config values.\\n\\nConfiguration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.\\n\\n' +\n color.yellow('**Services must be restarted to apply changes.**')\n )\n )\n .argument('<tag>', 'The Medplum stack tag')\n .option(\n '--file [file]',\n processDescription(\n 'File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.'\n )\n )\n .option(\n '--dryrun',\n 'Displays the operations that would be performed using the specified command without actually running them.'\n )\n .option('--yes', 'Automatically confirm the update')\n .action(updateConfigCommand);\n\n addSubcommand(\n aws,\n new MedplumCommand('update-server')\n .alias('deploy-server')\n .description('Update the server image')\n .argument('<tag>', 'The Medplum stack tag')\n .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n .option(\n '--to-version [version]',\n 'Specifies the version of the configuration to update. If not specified, the latest version is updated.'\n )\n .action(updateServerCommand)\n );\n\n aws\n .command('update-app')\n .alias('deploy-app')\n .description('Update the app site')\n .argument('<tag>', 'The Medplum stack tag')\n .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n .option(\n '--to-version [version]',\n 'Specifies the version of the configuration to update. If not specified, the latest version is updated.'\n )\n .option(\n '--dryrun',\n 'Displays the operations that would be performed using the specified command without actually running them.'\n )\n .option('--tar-path [tarPath]', 'Specifies the path to the extracted tarball of the @medplum/app package.')\n .action(updateAppCommand);\n\n aws\n .command('update-bucket-policies')\n .description('Update S3 bucket policies')\n .argument('<tag>', 'The Medplum stack tag')\n .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n .option(\n '--guardduty-malware-protection',\n 'Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.'\n )\n .option(\n '--dryrun',\n 'Displays the operations that would be performed using the specified command without actually running them.'\n )\n .action(updateBucketPoliciesCommand);\n\n return aws;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { createMedplumClient } from './util/client';\nimport { MedplumCommand, addSubcommand, createBot, deployBot, readBotConfigs, saveBot } from './utils';\n\nconst botSaveCommand = new MedplumCommand('save');\nconst botDeployCommand = new MedplumCommand('deploy');\nconst botCreateCommand = new MedplumCommand('create');\n\nexport const bot = new MedplumCommand('bot');\naddSubcommand(bot, botSaveCommand);\naddSubcommand(bot, botDeployCommand);\naddSubcommand(bot, botCreateCommand);\n\n// Commands to deprecate\nexport const saveBotDeprecate = new MedplumCommand('save-bot');\nexport const deployBotDeprecate = new MedplumCommand('deploy-bot');\nexport const createBotDeprecate = new MedplumCommand('create-bot');\n\nbotSaveCommand\n .description('Saving the bot')\n .argument('<botName>')\n .action(async (botName, options) => {\n const medplum = await createMedplumClient(options);\n\n await botWrapper(medplum, botName);\n });\n\nbotDeployCommand\n .description('Deploy the app to AWS')\n .argument('<botName>')\n .action(async (botName, options) => {\n const medplum = await createMedplumClient(options);\n\n await botWrapper(medplum, botName, true);\n });\n\nbotCreateCommand\n .arguments('<botName> <projectId> <sourceFile> <distFile>')\n .description('Creating a bot')\n .option('--runtime-version <runtimeVersion>', 'Runtime version (awslambda, vmcontext)')\n .option('--no-write-config', 'Do not write bot to config')\n .action(async (botName, projectId, sourceFile, distFile, options) => {\n const medplum = await createMedplumClient(options);\n\n await createBot(medplum, botName, projectId, sourceFile, distFile, options.runtimeVersion, !!options.writeConfig);\n });\n\nexport async function botWrapper(medplum: MedplumClient, botName: string, deploy = false): Promise<void> {\n const botConfigs = readBotConfigs(botName);\n const errors = [] as Error[];\n const errored = [] as string[];\n let saved = 0;\n let deployed = 0;\n\n for (const botConfig of botConfigs) {\n try {\n const bot = await medplum.readResource('Bot', botConfig.id);\n await saveBot(medplum, botConfig, bot);\n saved++;\n if (deploy) {\n await deployBot(medplum, botConfig, bot);\n deployed++;\n }\n } catch (err: unknown) {\n errors.push(err as Error);\n errored.push(`${botConfig.name} [${botConfig.id}]`);\n }\n }\n\n console.log(`Number of bots saved: ${saved}`);\n console.log(`Number of bots deployed: ${deployed}`);\n console.log(`Number of errors: ${errors.length}`);\n\n if (errors.length) {\n throw new Error(`${errors.length} bot(s) had failures. Bots with failures:\\n\\n ${errored.join('\\n ')}`, {\n cause: errors,\n });\n }\n}\n\n// Deprecate bot commands\nsaveBotDeprecate\n .description('Saves the bot')\n .argument('<botName>')\n .action(async (botName, options) => {\n const medplum = await createMedplumClient(options);\n\n await botWrapper(medplum, botName);\n });\n\ndeployBotDeprecate\n .description('Deploy the bot to AWS')\n .argument('<botName>')\n .action(async (botName, options) => {\n const medplum = await createMedplumClient(options);\n\n await botWrapper(medplum, botName, true);\n });\n\ncreateBotDeprecate\n .arguments('<botName> <projectId> <sourceFile> <distFile>')\n .description('Creates and saves the bot')\n .action(async (botName, projectId, sourceFile, distFile, options) => {\n const medplum = await createMedplumClient(options);\n\n await createBot(medplum, botName, projectId, sourceFile, distFile);\n });\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { EMPTY, getRateLimitReset, getStatus, OperationOutcomeError, sleep } from '@medplum/core';\nimport type { BundleEntry, ExplanationOfBenefit, ExplanationOfBenefitItem, Resource } from '@medplum/fhirtypes';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { createInterface } from 'node:readline';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport type { ReadableStream } from 'node:stream/web';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, getUnsupportedExtension, MedplumCommand, prettyPrint } from './utils';\n\nconst bulkExportCommand = new MedplumCommand('export');\nconst bulkImportCommand = new MedplumCommand('import');\n\nexport const bulk = new MedplumCommand('bulk');\naddSubcommand(bulk, bulkExportCommand);\naddSubcommand(bulk, bulkImportCommand);\n\nbulkExportCommand\n .option(\n '-e, --export-level <exportLevel>',\n 'Optional export level. Defaults to system level export. \"Group/:id\" - Group of Patients, \"Patient\" - All Patients.'\n )\n .option('-t, --types <types>', 'optional resource types to export')\n .option(\n '-s, --since <since>',\n '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).'\n )\n .option(\n '-d, --target-directory <targetDirectory>',\n 'optional target directory to save files from the bulk export operations.'\n )\n .action(async (options) => {\n const { exportLevel, types, since, targetDirectory } = options;\n const medplum = await createMedplumClient(options);\n const response = await medplum.bulkExport(exportLevel, types, since, { pollStatusOnAccepted: true });\n\n for (const { type, url } of response.output ?? EMPTY) {\n const fileUrl = new URL(url);\n const fileName = `${type}_${fileUrl.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g, '_') + '.ndjson';\n const path = resolve(targetDirectory ?? '', fileName);\n\n const res = await medplum.downloadResponse(url);\n if (!res.ok) {\n throw new Error(`Download failed: ${res.status} ${res.statusText}`);\n }\n if (!res.body) {\n throw new Error('Download response missing body');\n }\n\n const nodeStream = Readable.fromWeb(res.body as ReadableStream<Uint8Array>);\n await pipeline(nodeStream, createWriteStream(path));\n console.log(`${path} is created`);\n }\n });\n\nbulkImportCommand\n .argument('<filename>', 'File Name')\n .option(\n '--num-resources-per-request <numResourcesPerRequest>',\n 'optional number of resources to import per batch request. Defaults to 25.',\n '25'\n )\n .option(\n '--add-extensions-for-missing-values',\n 'optional flag to add extensions for missing values in a resource',\n false\n )\n .option('-d, --target-directory <targetDirectory>', 'optional target directory of file to be imported')\n .action(async (fileName, options) => {\n const { numResourcesPerRequest, addExtensionsForMissingValues, targetDirectory } = options;\n const path = resolve(targetDirectory ?? process.cwd(), fileName);\n const medplum = await createMedplumClient(options);\n\n await importFile(path, Number.parseInt(numResourcesPerRequest, 10), medplum, addExtensionsForMissingValues);\n });\n\nasync function importFile(\n path: string,\n numResourcesPerRequest: number,\n medplum: MedplumClient,\n addExtensionsForMissingValues: boolean\n): Promise<void> {\n let entries: BundleEntry[] = [];\n const fileStream = createReadStream(path);\n const rl = createInterface({\n input: fileStream,\n });\n\n for await (const line of rl) {\n const resource = parseResource(line, addExtensionsForMissingValues);\n entries.push({\n resource: resource,\n request: {\n method: 'POST',\n url: resource.resourceType,\n },\n });\n if (entries.length % numResourcesPerRequest === 0) {\n await sendBatchEntries(entries, medplum);\n entries = [];\n }\n }\n if (entries.length > 0) {\n await sendBatchEntries(entries, medplum);\n }\n}\n\nasync function sendBatchEntries(entries: BundleEntry[], medplum: MedplumClient): Promise<void> {\n let pendingEntries = entries;\n while (pendingEntries.length > 0) {\n let result;\n try {\n result = await medplum.executeBatch(\n {\n resourceType: 'Bundle',\n type: 'transaction',\n entry: pendingEntries,\n },\n { maxRetries: 0 }\n );\n } catch (err) {\n if (!(err instanceof OperationOutcomeError) || getStatus(err.outcome) !== 429) {\n throw err;\n }\n await sleep(getRateLimitRetryDelay(err.outcome, medplum));\n continue;\n }\n\n const retryEntries: BundleEntry[] = [];\n for (let i = 0; i < pendingEntries.length; i++) {\n const resultEntry = result.entry?.[i];\n if (resultEntry?.response?.outcome && getStatus(resultEntry.response.outcome) === 429) {\n retryEntries.push(pendingEntries[i]);\n } else {\n prettyPrint(resultEntry?.response);\n }\n }\n if (retryEntries.length > 0) {\n const rateLimitOutcome = result.entry?.find(\n (entry) => entry.response?.outcome && getStatus(entry.response.outcome) === 429\n )?.response?.outcome;\n await sleep(getRateLimitRetryDelay(rateLimitOutcome, medplum));\n }\n pendingEntries = retryEntries;\n }\n}\n\nfunction getRateLimitRetryDelay(\n outcome: NonNullable<BundleEntry['response']>['outcome'] | undefined,\n medplum: MedplumClient\n): number {\n const outcomeDelay = outcome && getRateLimitReset(outcome);\n if (outcomeDelay !== undefined) {\n return outcomeDelay;\n }\n return Math.max(\n 500,\n ...medplum\n .rateLimitStatus()\n .filter((limit) => limit.remainingUnits === 0)\n .map((limit) => limit.secondsUntilReset * 1000)\n );\n}\n\nfunction parseResource(jsonString: string, addExtensionsForMissingValues: boolean): Resource {\n const resource = JSON.parse(jsonString);\n\n if (addExtensionsForMissingValues) {\n return addExtensionsForMissingValuesResource(resource);\n }\n\n return resource;\n}\n\nfunction addExtensionsForMissingValuesResource(resource: Resource): Resource {\n if (resource.resourceType === 'ExplanationOfBenefit') {\n return addExtensionsForMissingValuesExplanationOfBenefits(resource);\n }\n return resource;\n}\n\nfunction addExtensionsForMissingValuesExplanationOfBenefits(resource: ExplanationOfBenefit): ExplanationOfBenefit {\n if (!resource.provider) {\n resource.provider = getUnsupportedExtension();\n }\n\n resource.item?.forEach((item: ExplanationOfBenefitItem) => {\n if (!item?.productOrService) {\n item.productOrService = getUnsupportedExtension();\n }\n });\n\n return resource;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport fastGlob from 'fast-glob';\nimport { once } from 'node:events';\nimport { createReadStream } from 'node:fs';\nimport { open, stat } from 'node:fs/promises';\nimport { basename, extname, resolve } from 'node:path';\nimport { PassThrough } from 'node:stream';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nconst DEFAULT_BATCH_SIZE = 25;\n\n/** Extensions unambiguously used for DICOM, to recognize raw datasets that carry no File Meta Information. */\nconst DICOM_EXTENSIONS = new Set(['.dcm', '.dicom', '.ima']);\n\n/** A DICOM Part 10 file starts with a 128 byte preamble followed by the \"DICM\" prefix. */\nconst DICOM_PREFIX = Buffer.from('DICM');\nconst DICOM_PREFIX_OFFSET = 128;\nconst DICOM_HEADER_LENGTH = DICOM_PREFIX_OFFSET + DICOM_PREFIX.length;\n\n/** The File Meta Information group, which a Part 10 file without a preamble starts with. */\nconst FILE_META_GROUP = 0x0002;\n\n/**\n * Returns true if the file appears to be a storable DICOM instance.\n *\n * Only used when expanding directories and glob patterns, where the user did not name the file\n * explicitly, so that stray files such as READMEs or JPEG previews do not get sent to the server.\n *\n * The two content checks mirror what the server's reader accepts, so that this does not reject\n * files the server would have stored. It accepts a third encoding - a raw dataset with no File\n * Meta Information - which has no distinguishing header to test for, hence the extension fallback.\n * @param filePath - The candidate file path.\n * @returns True if the file should be sent as a DICOM instance.\n */\nasync function isDicomFile(filePath: string): Promise<boolean> {\n // DICOMDIR is a media directory record rather than a storable instance\n if (basename(filePath).toUpperCase() === 'DICOMDIR') {\n return false;\n }\n\n const handle = await open(filePath, 'r');\n try {\n const buffer = Buffer.alloc(DICOM_HEADER_LENGTH);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n if (bytesRead === buffer.length && buffer.subarray(DICOM_PREFIX_OFFSET).equals(DICOM_PREFIX)) {\n return true;\n }\n // File Meta Information is always encoded little-endian, so the leading group number is too\n if (bytesRead >= 2 && buffer.readUInt16LE(0) === FILE_META_GROUP) {\n return true;\n }\n } finally {\n await handle.close();\n }\n\n return DICOM_EXTENSIONS.has(extname(filePath).toLowerCase());\n}\n\n/**\n * Expands the command line file arguments into a sorted list of DICOM file paths.\n *\n * Each input can be a file, a directory (searched recursively), or a glob pattern. Note that\n * POSIX shells expand unquoted patterns such as `*.dcm` before the CLI runs, so patterns only\n * reach here when quoted by the user or when running on a shell that does not expand them.\n * @param inputs - The file, directory, and glob pattern arguments.\n * @returns The de-duplicated and sorted list of absolute DICOM file paths.\n */\nexport async function resolveDicomFiles(inputs: string[]): Promise<string[]> {\n const results = new Set<string>();\n for (const input of inputs) {\n const stats = await stat(input).catch(() => undefined);\n if (stats?.isFile()) {\n // Explicitly named files are always sent, even if they do not look like DICOM\n results.add(resolve(input));\n continue;\n }\n\n let matches: string[];\n if (stats?.isDirectory()) {\n matches = await fastGlob('**/*', { cwd: input, onlyFiles: true, absolute: true });\n } else if (fastGlob.isDynamicPattern(input)) {\n // Matched case-insensitively because DICOM extensions are inconsistently cased in the wild,\n // and `*.dcm` silently matching none of a directory of `.DCM` files helps nobody\n matches = await fastGlob(input, { onlyFiles: true, absolute: true, caseSensitiveMatch: false });\n } else {\n throw new Error(`File not found: ${input}`);\n }\n\n let skipped = 0;\n for (const match of matches) {\n if (await isDicomFile(match)) {\n results.add(match);\n } else {\n skipped++;\n }\n }\n if (skipped > 0) {\n console.log(`Skipped ${skipped} non-DICOM file(s) in \"${input}\"`);\n }\n }\n return Array.from(results).sort((a, b) => a.localeCompare(b));\n}\n\nasync function writeBuffer(stream: PassThrough, buffer: Buffer): Promise<void> {\n if (!stream.write(buffer)) {\n await once(stream, 'drain');\n }\n}\n\nasync function pipeFileToStream(filePath: string, out: PassThrough): Promise<void> {\n const fileStream = createReadStream(filePath);\n try {\n for await (const chunk of fileStream) {\n if (!out.write(chunk as Buffer)) {\n await once(out, 'drain');\n }\n }\n } finally {\n fileStream.destroy();\n }\n}\n\nexport async function writeMultipartRelatedBody(\n out: PassThrough,\n filePaths: string[],\n boundary: string\n): Promise<void> {\n try {\n for (const filePath of filePaths) {\n await writeBuffer(out, Buffer.from(`--${boundary}\\r\\n`));\n await writeBuffer(out, Buffer.from('Content-Type: application/dicom\\r\\n'));\n await writeBuffer(out, Buffer.from('\\r\\n'));\n await pipeFileToStream(filePath, out);\n await writeBuffer(out, Buffer.from('\\r\\n'));\n }\n await writeBuffer(out, Buffer.from(`--${boundary}--\\r\\n`));\n out.end();\n } catch (err) {\n out.destroy(err as Error);\n throw err;\n }\n}\n\nconst stow = new MedplumCommand('stow')\n .description('Send DICOM instances via DICOMweb STOW-RS')\n .argument('<files...>', 'DICOM files, directories, or quoted glob patterns to send')\n .option('--batch-size <count>', 'Maximum number of instances per STOW-RS request', String(DEFAULT_BATCH_SIZE))\n .action(async (files: string[], options) => {\n const batchSize = Number.parseInt(options.batchSize, 10);\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new Error(`Invalid batch size: ${options.batchSize}`);\n }\n\n const filePaths = await resolveDicomFiles(files);\n if (filePaths.length === 0) {\n throw new Error('No DICOM files found');\n }\n console.log(`Sending ${filePaths.length} DICOM file(s)`);\n\n const medplum = await createMedplumClient(options);\n for (let i = 0; i < filePaths.length; i += batchSize) {\n const batch = filePaths.slice(i, i + batchSize);\n const boundary = `medplum-${Date.now()}`;\n const contentType = `multipart/related; type=application/dicom; boundary=${boundary}`;\n const stream = new PassThrough();\n const writePromise = writeMultipartRelatedBody(stream, batch, boundary);\n const requestPromise = medplum.post('/dicomweb/studies', stream, contentType);\n await writePromise;\n const text = await requestPromise;\n console.log('STOW-RS response received', text);\n }\n });\n\nexport const dicomweb = new MedplumCommand('dicomweb');\naddSubcommand(dicomweb, stow);\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { formatHl7DateTime, Hl7Message } from '@medplum/core';\nimport { Hl7Client, Hl7Server } from '@medplum/hl7';\nimport { readFileSync } from 'node:fs';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nconst send = new MedplumCommand('send')\n .description('Send an HL7 v2 message via MLLP')\n .argument('<host>', 'The destination host name or IP address')\n .argument('<port>', 'The destination port number')\n .argument('[body]', 'Optional HL7 message body')\n .option('--generate-example', 'Generate a sample HL7 message')\n .option('--file <file>', 'Read the HL7 message from a file')\n .option('--encoding <encoding>', 'The encoding to use')\n .action(async (host, port, body, options) => {\n if (options.generateExample) {\n body = generateSampleHl7Message();\n } else if (options.file) {\n body = readFileSync(options.file, 'utf8');\n }\n\n if (!body) {\n throw new Error('Missing HL7 message body');\n }\n\n const client = new Hl7Client({\n host,\n port: Number.parseInt(port, 10),\n encoding: options.encoding,\n });\n\n try {\n const response = await client.sendAndWait(Hl7Message.parse(body));\n console.log(response.toString().replaceAll('\\r', '\\n'));\n } finally {\n await client.close();\n }\n });\n\nconst listen = new MedplumCommand('listen')\n .description('Starts an HL7 v2 MLLP server')\n .argument('<port>')\n .option('--encoding <encoding>', 'The encoding to use')\n .action(async (port, options) => {\n const server = new Hl7Server((connection) => {\n connection.addEventListener('message', ({ message }) => {\n console.log(message.toString().replaceAll('\\r', '\\n'));\n connection.send(message.buildAck());\n });\n });\n\n await server.start(Number.parseInt(port, 10), options.encoding);\n console.log('Listening on port ' + port);\n });\n\nexport const hl7 = new MedplumCommand('hl7');\naddSubcommand(hl7, send);\naddSubcommand(hl7, listen);\n\nexport function generateSampleHl7Message(): string {\n const now = formatHl7DateTime(new Date());\n const controlId = Date.now().toString();\n return `MSH|^~\\\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${now}||ADT^A01|${controlId}|P|2.5|\nEVN|A01|${now}||\nPID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|\nPV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7CloseEvent, Hl7EnhancedAckSentEvent, Hl7ErrorEvent, Hl7MessageEvent, Hl7WarningEvent } from './events';\n\nexport interface Hl7EventMap {\n message: Hl7MessageEvent;\n error: Hl7ErrorEvent;\n warning: Hl7WarningEvent;\n close: Hl7CloseEvent;\n enhancedAckSent: Hl7EnhancedAckSentEvent;\n}\n\nexport abstract class Hl7Base extends EventTarget {\n addEventListener<K extends keyof Hl7EventMap>(\n type: K,\n listener: ((event: Hl7EventMap[K]) => void) | EventListenerObject | null,\n options?: boolean | AddEventListenerOptions\n ): void;\n\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n super.addEventListener(type, listener, options);\n }\n removeEventListener<K extends keyof Hl7EventMap>(\n type: K,\n listener: ((event: Hl7EventMap[K]) => void) | EventListenerObject | null,\n options?: boolean | AddEventListenerOptions\n ): void;\n\n removeEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n super.removeEventListener(type, listener, options);\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7Message } from '@medplum/core';\nimport assert from 'node:assert';\nimport type { Socket } from 'node:net';\nimport net from 'node:net';\nimport { Hl7Base } from './base';\nimport type { EnhancedMode, Hl7ConnectionOptions, SendAndWaitOptions } from './connection';\nimport { Hl7Connection } from './connection';\nimport { Hl7CloseEvent, Hl7ErrorEvent, Hl7WarningEvent } from './events';\n\nexport interface Hl7ClientOptions {\n host: string;\n port: number;\n encoding?: string;\n keepAlive?: boolean;\n connectTimeout?: number; // Add timeout option\n}\n\nexport interface DeferredConnectionPromise {\n promise: Promise<Hl7Connection>;\n resolve: (connection: Hl7Connection) => void;\n reject: (err: Error) => void;\n}\n\nexport class Hl7Client extends Hl7Base {\n options: Hl7ClientOptions;\n host: string;\n port: number;\n encoding?: string;\n connection?: Hl7Connection;\n keepAlive: boolean;\n private socket?: Socket;\n private connectTimeout: number;\n private deferredConnectionPromise?: DeferredConnectionPromise;\n\n constructor(options: Hl7ClientOptions) {\n super();\n this.options = options;\n this.host = this.options.host;\n this.port = this.options.port;\n this.encoding = this.options.encoding;\n this.keepAlive = this.options.keepAlive ?? false;\n this.connectTimeout = this.options.connectTimeout ?? 30000; // Default 30 seconds\n }\n\n connect(): Promise<Hl7Connection> {\n // If we are already waiting for a pending connection attempt, just return the deferred promise to that\n // In the case that the promise is already resolve, we will also return a resolved connection\n if (this.deferredConnectionPromise) {\n return this.deferredConnectionPromise.promise;\n }\n\n const deferredPromise = (this.deferredConnectionPromise = this.createDeferredConnectionPromise());\n\n // Create the socket\n this.socket = net.connect({\n host: this.host,\n port: this.port,\n keepAlive: this.keepAlive,\n });\n\n if (this.connectTimeout > 0) {\n this.socket.setTimeout(this.connectTimeout);\n this.registerSocketTimeoutListener(deferredPromise);\n }\n\n this.registerSocketConnectListener(deferredPromise);\n this.registerSocketErrorListener(deferredPromise);\n this.registerSocketCloseListener(deferredPromise);\n\n return deferredPromise.promise;\n }\n\n private registerSocketTimeoutListener(deferredPromise: DeferredConnectionPromise): void {\n assert(this.socket);\n const socket = this.socket;\n\n // Handle timeout event\n const timeoutListener = (): void => {\n this.cleanupSocket(socket);\n const error = new Error(`Connection timeout after ${this.connectTimeout}ms`);\n this.rejectDeferredPromise(deferredPromise, error);\n };\n\n socket.on('timeout', timeoutListener);\n }\n\n private registerSocketConnectListener(deferredPromise: DeferredConnectionPromise): void {\n assert(this.socket);\n const socket = this.socket;\n\n // Handle successful connection\n const connectListener = (): void => {\n if (socket !== this.socket) {\n this.cleanupSocket(socket);\n return;\n }\n\n // Create the HL7 connection via the factory method (allows subclasses to customize)\n let connection: Hl7Connection;\n this.connection = connection = this.createConnection(socket, this.encoding);\n\n // Remove the timeout listener as we're now connected\n socket.setTimeout(0);\n\n this.registerHl7ConnectionListeners(connection);\n\n deferredPromise.resolve(connection);\n };\n\n socket.on('connect', connectListener);\n }\n\n private registerSocketErrorListener(deferredPromise: DeferredConnectionPromise): void {\n assert(this.socket);\n const socket = this.socket;\n\n // Handle connection errors\n const errorListener = (err: Error | AggregateError): void => {\n this.cleanupSocket(socket);\n\n if (err.constructor.name === 'AggregateError') {\n this.rejectDeferredPromise(deferredPromise, (err as AggregateError).errors[0]);\n } else {\n this.rejectDeferredPromise(deferredPromise, err);\n }\n };\n\n socket.on('error', errorListener);\n }\n\n private registerSocketCloseListener(deferredPromise: DeferredConnectionPromise): void {\n assert(this.socket);\n const socket = this.socket;\n\n // Handle connection errors\n const closeListener = (): void => {\n this.cleanupSocket(socket);\n this.rejectDeferredPromise(deferredPromise, new Error('Socket closed before connection finished'));\n };\n socket.on('close', closeListener);\n }\n\n private registerHl7ConnectionListeners(connection: Hl7Connection): void {\n // Set up event handlers\n connection.addEventListener('close', () => {\n this.socket = undefined;\n this.connection = undefined;\n this.deferredConnectionPromise = undefined;\n this.dispatchEvent(new Hl7CloseEvent());\n });\n\n connection.addEventListener('error', (event) => {\n this.dispatchEvent(new Hl7ErrorEvent(event.error));\n });\n\n connection.addEventListener('warning', (event) => {\n this.dispatchEvent(new Hl7WarningEvent(event.error));\n });\n }\n\n private createDeferredConnectionPromise(): DeferredConnectionPromise {\n // Setup our deferred connection promise\n let resolve!: (connection: Hl7Connection) => void;\n let reject!: (err: Error) => void;\n\n const promise = new Promise<Hl7Connection>((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n\n return {\n promise,\n resolve,\n reject,\n };\n }\n\n private rejectDeferredPromise(deferredPromise: DeferredConnectionPromise, err: Error): void {\n // Reject this deferred promise with the given error\n deferredPromise.reject(err);\n\n // If the currently tracked deferred promise is this deferred promise, remove it from the client\n if (this.deferredConnectionPromise === deferredPromise) {\n this.deferredConnectionPromise = undefined;\n }\n }\n\n private cleanupSocket(socket: Socket): void {\n if (!socket.destroyed) {\n socket.destroy();\n }\n if (socket === this.socket) {\n this.socket = undefined;\n }\n }\n\n /**\n * Creates an `Hl7Connection` for the given socket.\n *\n * Subclasses may override this to return a customized connection\n * (e.g. one that delegates pending message tracking to a shared tracker).\n * @param socket - The connected socket.\n * @param encoding - The character encoding to use.\n * @param enhancedMode - Optional enhanced mode for the connection.\n * @param options - Optional connection options.\n * @returns A new `Hl7Connection`.\n */\n protected createConnection(\n socket: Socket,\n encoding?: string,\n enhancedMode?: EnhancedMode,\n options?: Hl7ConnectionOptions\n ): Hl7Connection {\n return new Hl7Connection(socket, encoding, enhancedMode, options);\n }\n\n async send(msg: Hl7Message): Promise<void> {\n return (await this.connect()).send(msg);\n }\n\n async sendAndWait(msg: Hl7Message, options?: SendAndWaitOptions): Promise<Hl7Message> {\n return (await this.connect()).sendAndWait(msg, options);\n }\n\n async close(): Promise<void> {\n if (this.deferredConnectionPromise) {\n this.rejectDeferredPromise(this.deferredConnectionPromise, new Error('Client closed while connecting'));\n }\n\n // Close established connection if it exists\n if (this.connection) {\n const connection = this.connection;\n delete this.connection;\n await connection.close();\n } else {\n // Emit close event because the connection will not be able to emit it for us\n // Since it has not connected at this point\n this.dispatchEvent(new Hl7CloseEvent());\n }\n // Close the socket if it exists\n if (this.socket) {\n this.socket.removeAllListeners();\n this.socket.destroy();\n this.socket = undefined;\n }\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Hl7Message, OperationOutcomeError, ReturnAckCategory, sleep, validationError } from '@medplum/core';\nimport iconv from 'iconv-lite';\nimport type net from 'node:net';\nimport { Hl7Base } from './base';\nimport { CR, FS, VT } from './constants';\nimport { Hl7CloseEvent, Hl7EnhancedAckSentEvent, Hl7ErrorEvent, Hl7MessageEvent, Hl7WarningEvent } from './events';\n\n// Export `ReturnAckCategory` for backwards-compat\nexport { ReturnAckCategory } from '@medplum/core';\n\n// iconv-lite docs have great examples and explanations for how to use Buffers with iconv-lite:\n// See: https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding\n\nexport type Hl7MessageQueueItem = {\n message: Hl7Message;\n resolve: (reply: Hl7Message) => void;\n reject: (err: Error) => void;\n returnAck: ReturnAckCategory;\n timer?: NodeJS.Timeout;\n};\n\nexport interface SendAndWaitOptions {\n /** The ACK-level that the Promise should resolve on. The default is `ReturnAckCategory.APPLICATION` (returns on the first application-level ACK). */\n returnAck?: ReturnAckCategory;\n /** The amount of milliseconds to wait before timing out when waiting for the response to a message. */\n timeoutMs?: number;\n}\n\nexport interface Hl7ConnectionOptions {\n messagesPerMin?: number;\n gracefulCloseTimeoutMs?: number;\n}\n\n/**\n * Enhanced mode for HL7 connections.\n * - `'standard'`: Standard enhanced mode behavior\n * - `'aaMode'`: AA mode - special enhanced mode that only accepts AA acknowledgements\n * - `undefined`: Enhanced mode is not enabled (standard behavior)\n */\nexport type EnhancedMode = 'standard' | 'aaMode' | undefined;\n\nexport const DEFAULT_ENCODING = 'utf-8';\nexport const GRACEFUL_CLOSE_TIMEOUT_MS = 5000;\nconst ONE_MINUTE = 60 * 1000;\n\nexport class Hl7Connection extends Hl7Base {\n readonly socket: net.Socket;\n encoding: string;\n enhancedMode: EnhancedMode = undefined;\n private messagesPerMin: number | undefined = undefined;\n private gracefulCloseTimeoutMs: number;\n private chunks: Buffer[] = [];\n private readonly pendingMessages: Map<string, Hl7MessageQueueItem> = new Map<string, Hl7MessageQueueItem>();\n private readonly responseQueue: Hl7MessageEvent[] = [];\n private lastMessageDispatchedTime = 0;\n private responseQueueProcessing = false;\n private closing = false;\n\n constructor(\n socket: net.Socket,\n encoding: string = DEFAULT_ENCODING,\n enhancedMode?: EnhancedMode,\n options: Hl7ConnectionOptions = {}\n ) {\n super();\n\n this.socket = socket;\n this.encoding = encoding;\n this.enhancedMode = enhancedMode;\n this.messagesPerMin = options.messagesPerMin;\n this.gracefulCloseTimeoutMs = options.gracefulCloseTimeoutMs ?? GRACEFUL_CLOSE_TIMEOUT_MS;\n\n socket.on('data', (data: Buffer) => {\n if (this.closing) {\n this.dispatchEvent(\n new Hl7WarningEvent(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'warning',\n code: 'transient',\n details: {\n text: 'Data received after close was initiated',\n },\n },\n ],\n })\n )\n );\n return;\n }\n try {\n this.appendData(data);\n const messages = this.parseMessages();\n for (const message of messages) {\n this.responseQueue.push(new Hl7MessageEvent(this, message));\n }\n this.processResponseQueue().catch((err) => {\n this.dispatchEvent(new Hl7ErrorEvent(err));\n });\n } catch (err) {\n this.dispatchEvent(new Hl7ErrorEvent(err as Error));\n }\n });\n\n socket.on('error', (err) => {\n this.resetBuffer();\n this.dispatchEvent(new Hl7ErrorEvent(err));\n });\n\n // The difference between \"end\" and \"close\", is that \"end\" is only emitted on half-close from the other side\n // If the connection from the other side does not close gracefully, but instead we destroy the socket, then the Hl7Connection will not emit close\n // if we listen only for \"end\"; \"close\" is always emitted, whether the close is graceful or forceful\n socket.on('close', () => {\n // Reject any messages that were still pending when the connection was closed externally (e.g. closed by peer)\n this.drainPendingMessages();\n this.dispatchEvent(new Hl7CloseEvent());\n });\n\n this.addEventListener('message', (event) => {\n // In standard enhanced mode, send commit ACK (CA) immediately, then later forward app-level ACKs\n // In aaMode, send application ACK (AA) immediately, then ignore any later app-level ACKs\n let response: Hl7Message | undefined;\n if (this.enhancedMode === 'standard') {\n response = event.message.buildAck({ ackCode: 'CA' });\n } else if (this.enhancedMode === 'aaMode') {\n response = event.message.buildAck({ ackCode: 'AA' });\n }\n if (response) {\n this.send(response);\n this.dispatchEvent(new Hl7EnhancedAckSentEvent(this, response));\n }\n const origMsgCtrlId = event.message.getSegment('MSA')?.getField(2)?.toString();\n // If there is no message control ID, just return\n if (!origMsgCtrlId) {\n return;\n }\n const queueItem = this.getPendingMessage(origMsgCtrlId);\n if (!queueItem) {\n this.dispatchEvent(\n new Hl7WarningEvent(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'warning',\n code: 'not-found',\n details: {\n text: 'Response received for unknown message control ID',\n },\n diagnostics: `Received ACK for message control ID '${origMsgCtrlId}' but there was no pending message with this control ID`,\n },\n ],\n })\n )\n );\n return;\n }\n // Check the ACK type we should return on\n const ackCode = event.message.getSegment('MSA')?.getField(1)?.toString()?.toUpperCase();\n if (!ackCode) {\n return;\n }\n\n // Two modes:\n // Application-level or first ACK\n\n // First should always return on any ACK message, this is the default\n // The exception is APPLICATION, which should not resolve when the ACK is a CA, but should resolve on all other ACK types\n // On CA, we return early\n if (queueItem.returnAck === ReturnAckCategory.APPLICATION && ackCode === 'CA') {\n return;\n }\n\n // Resolve the promise if there is one pending for this message and we didn't exit already because the ACK type matches\n if (queueItem.timer) {\n clearTimeout(queueItem.timer);\n }\n queueItem.resolve(event.message);\n this.deletePendingMessage(origMsgCtrlId);\n });\n }\n\n /** @returns A boolean representing whether the socket attached to this Hl7Connection has emitted the close event already or not. */\n isClosed(): boolean {\n return this.socket.closed;\n }\n\n private sendImpl(reply: Hl7Message): void {\n const replyString = reply.toString();\n const replyBuffer = iconv.encode(replyString, this.encoding);\n const outputBuffer = Buffer.alloc(replyBuffer.length + 3);\n outputBuffer.writeInt8(VT, 0);\n replyBuffer.copy(outputBuffer, 1);\n outputBuffer.writeInt8(FS, replyBuffer.length + 1);\n outputBuffer.writeInt8(CR, replyBuffer.length + 2);\n this.socket.write(outputBuffer);\n }\n\n private async processResponseQueue(): Promise<void> {\n if (this.responseQueueProcessing) {\n return;\n }\n\n this.responseQueueProcessing = true;\n while (this.responseQueue.length) {\n if (this.messagesPerMin) {\n const millisBetweenMsgs = ONE_MINUTE / this.messagesPerMin;\n const elapsedMillis = Date.now() - this.lastMessageDispatchedTime;\n if (millisBetweenMsgs > elapsedMillis) {\n await sleep(millisBetweenMsgs - elapsedMillis);\n }\n }\n const messageEvent = this.responseQueue.shift() as Hl7MessageEvent;\n if (messageEvent) {\n this.dispatchEvent(messageEvent);\n }\n this.lastMessageDispatchedTime = Date.now();\n }\n this.responseQueueProcessing = false;\n }\n\n /**\n * Parses complete HL7 messages from the accumulated buffer.\n * Continues parsing while the buffer starts with VT and contains FS+CR.\n * Keeps any incomplete message data in the buffer for the next chunk.\n * @returns An array of parsed HL7 messages.\n */\n private parseMessages(): Hl7Message[] {\n const messages: Hl7Message[] = [];\n const buffer = Buffer.concat(this.chunks);\n this.resetBuffer();\n\n // Check if buffer starts with VT (Vertical Tab)\n if (buffer.length === 0) {\n return messages;\n }\n\n let bufferIdx = 0;\n\n // Keep parsing while we have complete messages\n while (bufferIdx < buffer.length) {\n // Ignore bytes between message frames\n while (buffer[bufferIdx] !== VT && bufferIdx < buffer.length) {\n bufferIdx++;\n }\n\n // Look for FS+CR sequence to mark end of message\n let messageEndIndex = -1;\n\n for (let i = bufferIdx + 1; i < buffer.length - 1; i++) {\n if (buffer[i] === FS && buffer[i + 1] === CR) {\n messageEndIndex = i + 1; // Index of CR (end of message)\n break;\n }\n }\n\n // If we don't have a complete message yet, wait for more data\n if (messageEndIndex === -1) {\n break;\n }\n\n // Extract the complete message (including VT, FS, and CR)\n const messageBuffer = buffer.subarray(bufferIdx, messageEndIndex + 1);\n // Extract the content (without VT at start and FS+CR at end)\n const contentBuffer = messageBuffer.subarray(1, -2);\n const contentString = iconv.decode(contentBuffer, this.encoding);\n const message = Hl7Message.parse(contentString);\n\n messages.push(message);\n\n // Move past this message\n bufferIdx = messageEndIndex + 1;\n }\n\n // Keep any remaining unfinished chunk in this.chunks\n this.chunks = bufferIdx < buffer.length ? [buffer.subarray(bufferIdx)] : [];\n\n return messages;\n }\n\n send(reply: Hl7Message): void {\n this.sendImpl(reply);\n }\n\n async sendAndWait(msg: Hl7Message, options?: SendAndWaitOptions): Promise<Hl7Message> {\n return new Promise<Hl7Message>((resolve, reject) => {\n const msgCtrlId = msg.getSegment('MSH')?.getField(10)?.toString();\n if (!msgCtrlId) {\n reject(new OperationOutcomeError(validationError('Required field missing: MSH.10')));\n return;\n }\n\n let timer: NodeJS.Timeout | undefined;\n\n if (options?.timeoutMs) {\n timer = setTimeout(() => {\n this.deletePendingMessage(msgCtrlId);\n reject(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'error',\n code: 'timeout',\n details: {\n text: 'Client timeout',\n },\n diagnostics: `Request timed out after waiting ${options.timeoutMs} milliseconds for response`,\n },\n ],\n })\n );\n }, options.timeoutMs);\n }\n\n this.setPendingMessage(msgCtrlId, {\n message: msg,\n resolve,\n reject,\n returnAck: options?.returnAck ?? ReturnAckCategory.APPLICATION,\n timer,\n });\n this.sendImpl(msg);\n });\n }\n\n async close(): Promise<void> {\n // If we have already received the close event, then we can just return immediately\n if (this.isClosed()) {\n return;\n }\n this.closing = true;\n this.socket.end();\n // drainPendingMessages is also called by the socket 'close' handler, but we call it here first so\n // that rejections are delivered before the close event is dispatched when close() is called explicitly.\n // The socket 'close' handler's call will be a no-op since the map will already be empty.\n this.drainPendingMessages();\n await new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n this.socket.destroy();\n }, this.gracefulCloseTimeoutMs);\n\n this.socket.once('close', () => {\n clearTimeout(timer);\n resolve();\n });\n });\n }\n\n /**\n * Rejects all pending sendAndWait promises and clears the pending messages map.\n * Safe to call multiple times \u2014 subsequent calls are no-ops once the map is empty.\n *\n * Subclasses may override this to change the behavior when a connection closes\n * (e.g. to keep promises alive in an external tracker).\n */\n protected drainPendingMessages(): void {\n if (!this.pendingMessages.size) {\n return;\n }\n const pendingCount = this.pendingMessages.size;\n for (const queueItem of this.pendingMessages.values()) {\n if (queueItem.timer) {\n clearTimeout(queueItem.timer);\n }\n queueItem.reject(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'warning',\n code: 'incomplete',\n details: {\n text: 'Message was still pending when connection closed',\n },\n },\n ],\n })\n );\n }\n this.dispatchEvent(\n new Hl7ErrorEvent(\n new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: [\n {\n severity: 'warning',\n code: 'incomplete',\n details: {\n text: 'Messages were still pending when connection closed',\n },\n diagnostics: `Hl7Connection closed while ${pendingCount} messages were pending`,\n },\n ],\n })\n )\n );\n this.pendingMessages.clear();\n }\n\n private appendData(data: Buffer): void {\n this.chunks.push(data);\n }\n\n private resetBuffer(): void {\n this.chunks = [];\n }\n\n setEncoding(encoding: string | undefined): void {\n this.encoding = encoding ?? DEFAULT_ENCODING;\n }\n\n getEncoding(): string {\n return this.encoding;\n }\n\n setEnhancedMode(enhancedMode: EnhancedMode): void {\n this.enhancedMode = enhancedMode;\n }\n\n getEnhancedMode(): EnhancedMode {\n return this.enhancedMode;\n }\n\n setMessagesPerMin(messagesPerMin: number | undefined): void {\n this.messagesPerMin = messagesPerMin;\n }\n\n getMessagesPerMin(): number | undefined {\n return this.messagesPerMin;\n }\n\n getPendingMessageCount(): number {\n return this.pendingMessages.size;\n }\n\n /**\n * Looks up a pending message by its message control ID.\n * Subclasses may override this to use an external message store (e.g. a shared tracker).\n * @param msgCtrlId - The message control ID (MSH.10) to look up.\n * @returns The pending queue item, or undefined if not found.\n */\n protected getPendingMessage(msgCtrlId: string): Hl7MessageQueueItem | undefined {\n return this.pendingMessages.get(msgCtrlId);\n }\n\n /**\n * Stores a pending message by its message control ID.\n * Subclasses may override this to use an external message store (e.g. a shared tracker).\n * @param msgCtrlId - The message control ID (MSH.10).\n * @param item - The queue item containing the message and its resolve/reject callbacks.\n */\n protected setPendingMessage(msgCtrlId: string, item: Hl7MessageQueueItem): void {\n this.pendingMessages.set(msgCtrlId, item);\n }\n\n /**\n * Removes a pending message by its message control ID.\n * Subclasses may override this to use an external message store (e.g. a shared tracker).\n * @param msgCtrlId - The message control ID (MSH.10) to remove.\n */\n protected deletePendingMessage(msgCtrlId: string): void {\n this.pendingMessages.delete(msgCtrlId);\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * VT (Vertical Tab) character.\n *\n * In HL7 messages, this character is used to indicate the start of a message.\n */\nexport const VT = 0x0b;\n\n/**\n * CR (Carriage Return) character.\n *\n * In HL7 messages, this character is used to indicate the end of a message.\n */\nexport const CR = 0x0d;\n\n/**\n * FS (File Separator) character.\n *\n * In HL7 messages, this character is used to separate fields.\n */\nexport const FS = 0x1c;\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7Message } from '@medplum/core';\nimport type { Hl7Connection } from './connection';\n\nexport class Hl7MessageEvent extends Event {\n readonly connection: Hl7Connection;\n readonly message: Hl7Message;\n\n constructor(connection: Hl7Connection, message: Hl7Message) {\n super('message');\n this.connection = connection;\n this.message = message;\n }\n}\n\nexport class Hl7EnhancedAckSentEvent extends Event {\n readonly connection: Hl7Connection;\n readonly message: Hl7Message;\n\n constructor(connection: Hl7Connection, message: Hl7Message) {\n super('enhancedAckSent');\n this.connection = connection;\n this.message = message;\n }\n}\n\nexport class Hl7ErrorEvent extends Event {\n readonly error: Error;\n\n constructor(error: Error) {\n super('error');\n this.error = error;\n }\n}\n\nexport class Hl7WarningEvent extends Event {\n readonly error: Error;\n\n constructor(error: Error) {\n super('warning');\n this.error = error;\n }\n}\n\nexport class Hl7CloseEvent extends Event {\n constructor() {\n super('close');\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { AddressInfo } from 'node:net';\nimport { createServer } from 'node:net';\n\n// Every port ever handed out by `getFreePort`, so we never issue the same one twice\n// within a single test process \u2014 see the comment on `getFreePort` below.\nconst issuedPorts = new Set<number>();\n\n// Cap on how many ephemeral ports we probe before giving up looking for a fresh one.\nconst MAX_ATTEMPTS = 20;\n\n/**\n * Returns a TCP port number that is currently free, with *nothing* listening on it.\n *\n * Used only for tests that need a free port number. For tests that start an Hl7Server, prefer\n * `server.start(0)`, which returns the OS-assigned port and never has a release-then-rebind window.\n *\n * Because we close the probing server before returning, the port is freed immediately and the OS\n * may hand the *same* ephemeral port to a subsequent call. Callers that allocate two ports (e.g.\n * one per channel) would then collide. To avoid this, we remember every port we issue and keep any\n * probing server that lands on an already-issued port open until we find a fresh one, so the OS\n * can't reissue it in the same round.\n * @returns A promise that resolves with a free TCP port number.\n */\nexport async function getFreePort(): Promise<number> {\n const heldServers: ReturnType<typeof createServer>[] = [];\n const closeServer = async (server: ReturnType<typeof createServer>): Promise<void> =>\n new Promise((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n });\n try {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const server = createServer();\n const port = await new Promise<number>((resolve, reject) => {\n server.on('error', reject);\n server.listen(0, () => {\n resolve((server.address() as AddressInfo).port);\n });\n });\n if (issuedPorts.has(port)) {\n // Keep this server listening so the OS won't hand the same port out again this round.\n heldServers.push(server);\n continue;\n }\n issuedPorts.add(port);\n await closeServer(server);\n return port;\n }\n throw new Error(`Unable to find a free port after ${MAX_ATTEMPTS} attempts`);\n } finally {\n await Promise.all(heldServers.map((server) => closeServer(server).catch(() => undefined)));\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { sleep } from '@medplum/core';\nimport net from 'node:net';\nimport type { EnhancedMode, Hl7ConnectionOptions } from './connection';\nimport { Hl7Connection } from './connection';\n\n/**\n * Options for configuring the `Hl7Server#stop` method.\n */\nexport interface Hl7ServerStopOptions {\n /**\n * Time in milliseconds to allow client connections to gracefully close after the stop method has been called, before forcefully closing them.\n *\n * Can be set to `-1` to disable forceful draining of connections during stop.\n *\n * Defaults to `10_000`.\n */\n forceDrainTimeoutMs?: number;\n}\n\nexport const DEFAULT_FORCE_DRAIN_TIMEOUT_MS = 10_000;\n\nexport class Hl7Server {\n readonly handler: (connection: Hl7Connection) => void;\n server?: net.Server;\n private encoding: string | undefined = undefined;\n private enhancedMode: EnhancedMode = undefined;\n private messagesPerMin: number | undefined = undefined;\n private readonly connections = new Set<Hl7Connection>();\n\n constructor(handler: (connection: Hl7Connection) => void) {\n this.handler = handler;\n }\n\n async start(\n port: number,\n encoding?: string,\n enhancedMode?: EnhancedMode,\n connectionOptions?: Hl7ConnectionOptions\n ): Promise<number> {\n if (encoding) {\n this.setEncoding(encoding);\n }\n if (enhancedMode !== undefined) {\n this.setEnhancedMode(enhancedMode);\n }\n if (connectionOptions?.messagesPerMin !== undefined) {\n this.setMessagesPerMin(connectionOptions.messagesPerMin);\n }\n\n const server = net.createServer((socket) => {\n const connection = new Hl7Connection(socket, this.encoding, this.enhancedMode, {\n messagesPerMin: this.messagesPerMin,\n });\n this.handler(connection);\n this.connections.add(connection);\n connection.addEventListener('close', () => {\n this.connections.delete(connection);\n });\n });\n\n return new Promise<number>((resolve, reject) => {\n const listenOnPort = (port: number): void => {\n server.listen(port, () => {\n const boundPort = (server.address() as { port: number }).port;\n resolve(boundPort);\n });\n };\n\n const errorListener = (e: Error & { code?: string }): void => {\n if (e?.code === 'EADDRINUSE') {\n server.close(() => sleep(50).then(() => listenOnPort(port)));\n } else {\n reject(e);\n }\n };\n\n server.on('error', errorListener);\n\n server.once('listening', () => {\n server.off('error', errorListener);\n });\n\n listenOnPort(port);\n\n this.server = server;\n });\n }\n\n /**\n * Stops the HL7 server.\n *\n * By default, the server will stop accepting new connections after this method is called, and wait for current connections to close naturally.\n *\n * If all connections don't close within 10 seconds, the server will forcefully close them before shutting down.\n *\n * The default time to wait before forcefully closing connections can be changed by passing an integer value for the optional `options.forceDrainTimeoutMs`.\n *\n * Forced drain can also be disabled by passing `-1` for `options.forceDrainTimeoutMs`.\n * @param options - Optional options to configure the stopping of the server.\n * @returns Promise that resolves when the server has stopped, or rejects if an error prevents server from stopping.\n */\n async stop(options?: Hl7ServerStopOptions): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (!this.server) {\n reject(new Error('Stop was called but there is no server running'));\n return;\n }\n let forceDrainTimeout: NodeJS.Timeout | undefined;\n if (options?.forceDrainTimeoutMs !== -1) {\n forceDrainTimeout = setTimeout(() => {\n for (const connection of this.connections) {\n // Theoretically close should almost never throw as most errors are caught internal to the method and emitted as error events\n // We put a .catch here to prevent floating promises and log any errors that somehow make it through\n connection.close().catch(console.error);\n }\n }, options?.forceDrainTimeoutMs ?? DEFAULT_FORCE_DRAIN_TIMEOUT_MS);\n }\n this.server.close((err) => {\n if (err) {\n reject(err);\n return;\n }\n if (forceDrainTimeout) {\n clearTimeout(forceDrainTimeout);\n }\n this.connections.clear();\n this.server = undefined;\n resolve();\n });\n });\n }\n\n setEnhancedMode(enhancedMode: EnhancedMode): void {\n this.enhancedMode = enhancedMode;\n }\n\n getEnhancedMode(): EnhancedMode {\n return this.enhancedMode;\n }\n\n setEncoding(encoding: string | undefined): void {\n this.encoding = encoding;\n }\n\n getEncoding(): string | undefined {\n return this.encoding;\n }\n\n setMessagesPerMin(messagesPerMin: number | undefined): void {\n this.messagesPerMin = messagesPerMin;\n }\n\n getMessagesPerMin(): number | undefined {\n return this.messagesPerMin;\n }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { readdirSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\nimport { FileSystemStorage } from './storage';\nimport { MedplumCommand, addSubcommand, loadProfile, saveProfile } from './utils';\n\nconst setProfile = new MedplumCommand('set');\nconst removeProfile = new MedplumCommand('remove');\nconst listProfiles = new MedplumCommand('list');\nconst describeProfile = new MedplumCommand('describe');\n\nexport const profile = new MedplumCommand('profile');\naddSubcommand(profile, setProfile);\naddSubcommand(profile, removeProfile);\naddSubcommand(profile, listProfiles);\naddSubcommand(profile, describeProfile);\n\nsetProfile\n .argument('<profileName>', 'Name of the profile')\n .description('Create a new profile or replace it with the given name and its associated properties')\n .action(async (profileName, options) => {\n saveProfile(profileName, options);\n });\n\nremoveProfile\n .argument('<profileName>', 'Name of the profile')\n .description('Remove a profile by name')\n .action(async (profileName) => {\n const storage = new FileSystemStorage(profileName);\n storage.setObject('options', undefined);\n console.log(`${profileName} profile removed`);\n });\n\nlistProfiles.description('List all profiles saved').action(async () => {\n const dir = resolve(homedir(), '.medplum');\n const files = readdirSync(dir);\n const allProfiles: any[] = [];\n files.forEach((file) => {\n const fileName = file.split('.')[0];\n const storage = new FileSystemStorage(fileName);\n const profile = storage.getObject('options');\n if (profile) {\n allProfiles.push({ profileName: fileName, profile });\n }\n });\n console.log(allProfiles);\n});\n\ndescribeProfile\n .argument('<profileName>', 'Name of the profile')\n .description('Describes a profile')\n .action(async (profileName) => {\n const profile = loadProfile(profileName);\n console.log(profile);\n });\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { InviteRequest, LoginState, MedplumClient } from '@medplum/core';\nimport { Option } from 'commander';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nconst projectListCommand = new MedplumCommand('list');\nconst projectCurrentCommand = new MedplumCommand('current');\nconst projectSwitchCommand = new MedplumCommand('switch');\nconst projectInviteCommand = new MedplumCommand('invite');\n\nexport const project = new MedplumCommand('project');\naddSubcommand(project, projectListCommand);\naddSubcommand(project, projectCurrentCommand);\naddSubcommand(project, projectSwitchCommand);\naddSubcommand(project, projectInviteCommand);\n\nprojectListCommand.description('List of current projects').action(async (options) => {\n const medplum = await createMedplumClient(options);\n projectList(medplum);\n});\n\nfunction projectList(medplum: MedplumClient): void {\n const logins = medplum.getLogins();\n\n const projects = logins\n .map((login: LoginState) => `${login.project.display} (${login.project.reference})`)\n .join('\\n\\n');\n\n console.log(projects);\n}\n\nprojectCurrentCommand.description('Project you are currently on').action(async (options) => {\n const medplum = await createMedplumClient(options);\n const login = medplum.getActiveLogin();\n if (!login) {\n throw new Error('Unauthenticated: run `npx medplum login` to login');\n }\n console.log(`${login.project.display} (${login.project.reference})`);\n});\n\nprojectSwitchCommand\n .description('Switching to another project from the current one')\n .argument('<projectId>')\n .action(async (projectId, options) => {\n const medplum = await createMedplumClient(options);\n await switchProject(medplum, projectId);\n });\n\nprojectInviteCommand\n .description('Invite a member to your current project (run npx medplum project current to confirm)')\n .arguments('<firstName> <lastName> <email>')\n .option('--send-email', 'If you want to send the email when inviting the user')\n .option('--admin', 'If the user you are inviting is an admin')\n .addOption(\n new Option('-r, --role <role>', 'Role of user')\n .choices(['Practitioner', 'Patient', 'RelatedPerson'])\n .default('Practitioner')\n )\n .action(async (firstName, lastName, email, options) => {\n const medplum = await createMedplumClient(options);\n const login = medplum.getActiveLogin();\n if (!login) {\n throw new Error('Unauthenticated: run `npx medplum login` to login');\n }\n if (!login?.project?.reference) {\n throw new Error('No current project to invite user to');\n }\n\n const projectId = login.project.reference.split('/')[1];\n const inviteBody: InviteRequest = {\n resourceType: options.role,\n firstName,\n lastName,\n email,\n sendEmail: !!options.sendEmail,\n admin: !!options.admin,\n };\n await inviteUser(projectId, inviteBody, medplum);\n });\n\nasync function switchProject(medplum: MedplumClient, projectId: string): Promise<void> {\n const logins = medplum.getLogins();\n const login = logins.find((login: LoginState) => login.project.reference?.includes(projectId));\n if (!login) {\n throw new Error(`Project ${projectId} not found. Make sure you are added as a user to this project`);\n }\n await medplum.setActiveLogin(login);\n console.log(`Switched to project ${projectId}\\n`);\n}\n\nasync function inviteUser(projectId: string, inviteBody: InviteRequest, medplum: MedplumClient): Promise<void> {\n await medplum.invite(projectId, inviteBody);\n if (inviteBody.sendEmail) {\n console.log('Email sent');\n }\n console.log('See your users at https://app.medplum.com/admin/users');\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { convertToTransactionBundle } from '@medplum/core';\nimport { createMedplumClient } from './util/client';\nimport { MedplumCommand, prettyPrint } from './utils';\n\nexport const deleteObject = new MedplumCommand('delete');\nexport const get = new MedplumCommand('get');\nexport const patch = new MedplumCommand('patch');\nexport const post = new MedplumCommand('post');\nexport const put = new MedplumCommand('put');\n\ndeleteObject.argument('<url>', 'Resource/$id').action(async (url, options) => {\n const medplum = await createMedplumClient(options);\n prettyPrint(await medplum.delete(cleanUrl(medplum, url)));\n});\n\nget\n .argument('<url>', 'Resource/$id')\n .option('--as-transaction', 'Print out the bundle as a transaction type')\n .action(async (url, options) => {\n const medplum = await createMedplumClient(options);\n const response = await medplum.get(cleanUrl(medplum, url));\n if (options.asTransaction) {\n prettyPrint(convertToTransactionBundle(response));\n } else {\n prettyPrint(response);\n }\n });\n\npatch.arguments('<url> <body>').action(async (url, body, options) => {\n const medplum = await createMedplumClient(options);\n\n prettyPrint(await medplum.patch(cleanUrl(medplum, url), parseBody(body)));\n});\n\npost\n .arguments('<url> <body>')\n .option('--prefer-async', 'Sets the Prefer header to \"respond-async\"')\n .action(async (url, body, options) => {\n const medplum = await createMedplumClient(options);\n\n const headers = options.preferAsync ? { Prefer: 'respond-async' } : undefined;\n prettyPrint(await medplum.post(cleanUrl(medplum, url), parseBody(body), undefined, { headers }));\n });\n\nput.arguments('<url> <body>').action(async (url, body, options) => {\n const medplum = await createMedplumClient(options);\n\n prettyPrint(await medplum.put(cleanUrl(medplum, url), parseBody(body)));\n});\n\nfunction parseBody(input: string | undefined): any {\n if (!input) {\n return undefined;\n }\n try {\n return JSON.parse(input);\n } catch (_err) {\n return input;\n }\n}\n\nexport function cleanUrl(medplum: MedplumClient, input: string): string {\n const knownPrefixes = ['admin/', 'auth/', 'fhir/R4'];\n if (knownPrefixes.some((p) => input.startsWith(p))) {\n // If the URL starts with a known prefix, return it as-is\n return input;\n }\n\n // Otherwise, default to FHIR\n return medplum.fhirUrl(input).toString();\n}\n"],
5
+ "mappings": ";we8CEA,IAAAA,GAAsD,yBACtDC,GAAuC,qBACvCC,GAA2B,mBCO3BF,GAAuE,yBAEvEC,GAAuB,qBCVvBD,GAA8B,yBCD9BA,GAA8B,yBAC9BE,GAAmE,mBACnEC,GAAwB,mBACxBC,GAAwB,qBCFxBJ,EAA6F,yBAE7FC,GAAwB,qBAExBI,GAA0D,uBAC1DH,GAAwD,mBACxDE,GAA2C,qBAC3CE,GAA0B,2BAC1BC,GAAwB,eWRxBP,EAA2F,yBAC3FQ,GAAqB,8BACrBC,GAA6B,qBAC7BN,GA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AK,CACZ4qB,GAAY5qB,CAAY,CAC1B,CACF,CAEO,SAAS4qB,GAAY5qB,EAAmC,CAC7D,IAAI6qB,EAAW,EACXC,EAAc,GAUlB,GATI9qB,aAAe+qB,GAAAA,iBAIZ,QAAQ,IAAI,UACfD,EAAc,IAEhBD,EAAW7qB,EAAI,UAEb6qB,IAAa,GAAKC,EAAa,CACjCE,GAAmBhrB,EAAK,CAAC,CAAC,QAAQ,IAAI,OAAO,EAC7C,IAAMkC,EAAQlC,EAAI,MAClB,GAAI,QAAQ,IAAI,QACd,GAAI,MAAM,QAAQkC,CAAK,EACrB,QAAWlC,KAAOkC,EAChB8oB,GAAmBhrB,EAAK,EAAI,OAErBkC,aAAiB,OAC1B8oB,GAAmB9oB,EAAO,EAAI,CAGpC,CACA,QAAQ,KAAK2oB,CAAQ,CACvB,CAEA,SAASG,GAAmBhrB,EAAcirB,EAAU,GAAa,CAC/D,GAAIA,EAAS,CACX,QAAQ,MAAMjrB,CAAG,EACjB,MACF,CACIA,aAAe+qB,GAAAA,eACjB,QAAQ,OAAO,MAAM,MAAG1gB,GAAAA,sBAAqBrK,CAAG,CAAC;CAAI,EAErD,QAAQ,OAAO,MAAM,aAAUqK,GAAAA,sBAAqBrK,CAAG,CAAC;CAAI,CAEhE,CAEA,eAAsBkrB,IAAqB,IACrC1sB,GAAAA,YAAW,MAAM,GACnB,QAAQ,YAAY,EAEtB,MAAMisB,GAAK,QAAQ,IAAI,CACzB,CAGES,GAAI,EAAE,MAAOlrB,GAAQ,CACnB,QAAQ,MAAM,sBAAoBqK,GAAAA,sBAAqBrK,CAAG,CAAC,EAC3D,QAAQ,KAAK,CAAC,CAChB,CAAC",
6
+ "names": ["import_core", "import_commander", "import_node_fs", "import_node_os", "import_node_path", "import_node_crypto", "import_types", "import_tar", "import_node_child_process", "import_node_http", "import_node_util", "import_client_cloudformation", "import_client_cloudfront", "import_client_ecs", "import_client_s3", "import_client_ssm", "import_client_sts", "import_node_readline", "import_client_acm", "import_fast_glob", "import_node_stream", "import_promises", "import_node_events", "import_node_assert", "import_node_net", "import_iconv_lite", "require_constants", "__commonJSMin", "exports", "module", "SEMVER_SPEC_VERSION", "MAX_SAFE_INTEGER", "MAX_SAFE_COMPONENT_LENGTH", "MAX_SAFE_BUILD_LENGTH", "RELEASE_TYPES", "require_debug", "debug", "args", "require_re", "MAX_LENGTH", "re", "ye", "safeRe", "src", "safeSrc", "t", "R", "LETTERDASHNUMBER", "safeRegexReplacements", "makeSafeRegex", "value", "token", "max", "createToken", "name", "isGlobal", "safe", "index", "require_parse_options", "looseOption", "emptyOpts", "parseOptions", "options", "require_identifiers", "numeric", "compareIdentifiers", "a", "b", "anum", "bnum", "rcompareIdentifiers", "require_semver", "ne", "Ue", "Dt", "isPrereleaseIdentifier", "prerelease", "identifier", "identifiers", "i", "SemVer", "_SemVer", "version", "m", "id", "num", "other", "release", "identifierBase", "match", "base", "prereleaseBase", "require_parse", "T", "parse", "throwErrors", "er", "require_valid", "J", "valid", "v", "require_clean", "clean", "s", "require_inc", "inc", "require_diff", "diff", "version1", "version2", "v1", "v2", "comparison", "v1Higher", "highVersion", "lowVersion", "highHasPre", "prefix", "require_major", "major", "loose", "require_minor", "minor", "require_patch", "patch", "require_prerelease", "parsed", "require_compare", "compare", "require_rcompare", "M", "rcompare", "require_compare_loose", "compareLoose", "require_compare_build", "compareBuild", "versionA", "versionB", "require_sort", "qe", "sort", "list", "require_rsort", "rsort", "require_gt", "gt", "require_lt", "lt", "require_eq", "eq", "require_neq", "neq", "require_gte", "gte", "require_lte", "lte", "require_cmp", "Ut", "_t", "we", "Ge", "We", "Ke", "cmp", "op", "require_coerce", "coerce", "coerceRtlRegex", "next", "build", "require_truncate", "constants", "truncate", "truncation", "clonedVersion", "cloneInputVersion", "doTruncation", "versionStringToParse", "isPrerelease", "type", "require_lrucache", "LRUCache", "key", "firstKey", "require_range", "SPACE_CHARACTERS", "Range", "_Range", "range", "Comparator", "r", "c", "first", "isNullSet", "isAny", "comps", "k", "BUILDSTRIPRE", "memoKey", "FLAG_INCLUDE_PRERELEASE", "FLAG_LOOSE", "cached", "cache", "hr", "hyphenReplace", "comparatorTrimReplace", "tildeTrimReplace", "caretTrimReplace", "rangeList", "comp", "parseComparator", "replaceGTE0", "rangeMap", "comparators", "result", "thisComparators", "isSatisfiable", "rangeComparators", "thisComparator", "rangeComparator", "testSet", "LRU", "bo", "Ee", "remainingComparators", "testComparator", "otherComparator", "replaceCarets", "replaceTildes", "replaceXRanges", "replaceStars", "isX", "invalidXRangeOrder", "p", "replaceTilde", "z", "_", "pr", "ret", "replaceCaret", "replaceXRange", "gtlt", "xM", "xm", "xp", "anyX", "incPr", "$0", "from", "fM", "fm", "fp", "fpr", "fb", "to", "tM", "tm", "tp", "tpr", "set", "allowed", "require_comparator", "ANY", "_Comparator", "Ft", "L", "require_satisfies", "satisfies", "require_to_comparators", "toComparators", "require_max_satisfying", "maxSatisfying", "versions", "maxSV", "rangeObj", "require_min_satisfying", "minSatisfying", "min", "minSV", "require_min_version", "minVersion", "minver", "setMin", "comparator", "compver", "validRange", "require_outside", "Re", "outside", "hilo", "gtfn", "ltefn", "ltfn", "ecomp", "high", "low", "require_gtr", "Je", "gtr", "require_ltr", "ltr", "require_intersects", "intersects", "r1", "r2", "require_simplify", "prev", "ranges", "simplified", "original", "require_subset", "subset", "sub", "dom", "sawNonNull", "OUTER", "simpleSub", "simpleDom", "isSub", "simpleSubset", "minimumVersionWithPreRelease", "minimumVersion", "eqSet", "higherGT", "lowerLT", "gtltComp", "higher", "lower", "hasDomLT", "hasDomGT", "needDomLTPre", "needDomGTPre", "internalRe", "Dn", "Ln", "Fn", "qn", "Vn", "Jn", "zn", "eo", "ro", "io", "co", "wo", "So", "Mo", "Uo", "Fo", "qo", "Go", "zo", "Qo", "ts", "simplifyRange", "ns", "ls", "FileSystemStorage", "ClientStorage", "profile", "__publicField", "resolve", "homedir", "data", "str", "existsSync", "readFileSync", "mkdirSync", "writeFileSync", "createMedplumClient", "setupCredentials", "profileName", "storage", "baseUrl", "fhirUrlPath", "accessToken", "tokenUrl", "authorizeUrl", "clientId", "clientSecret", "getClientValues", "fetchApi", "validateBaseUrl", "medplumClient", "MedplumClient", "onUnauthenticated", "storageOptions", "url", "response", "err", "message", "encoder", "decoder", "strictDecoder", "MAX_INT32", "concat", "buffers", "size", "acc", "length", "buf", "buffer", "NON_ASCII", "encode", "string", "bytes", "code", "encodeBase64", "input", "CHUNK_SIZE", "arr", "encoded", "decodeBase64", "binary", "JOSEError", "JOSENotSupported", "JWSInvalid", "JWTInvalid", "_a", "_b", "JWKSMultipleMatchingKeys", "invalid", "decode", "cause", "isObject", "prototype", "isDisjoint", "headers", "parameters", "header", "parameter", "assertNotSet", "JWS_RECOGNIZED", "validateCritDuplicates", "Err", "protectedHeader", "crit", "validateCrit", "recognizedDefault", "recognizedOption", "joseHeader", "recognized", "validateB64", "extensions", "b64", "serializeJoseHeader", "serialized", "tag", "jwkMatchesOp", "entry", "usage", "alg", "expected", "expectedKeyOp", "prepareKey", "secret", "privateKey", "normalized", "keyObject", "normalizeJwk", "invalidKeyType", "key_ops", "isKeyLike", "expectedType", "isCryptoKey", "cacheKey", "isPublic", "crv", "nist", "params", "jwkToKey", "isKeyObject", "msg", "actual", "types", "last", "unusable", "prop", "checkUsage", "checkModulusLength", "modulusLength", "checkCryptoKey", "algorithm", "snapshotJwk", "jwk", "keyOps", "operation", "extractable", "isPrivate", "keyData", "rawKey", "table", "entries", "out", "sig", "hmac", "bits", "subtle", "rsa", "saltLength", "ecdsa", "eddsa", "mldsa", "JWS", "jwsAlgorithm", "epoch", "date", "multipliers", "REGEX", "invalidDuration", "secs", "matched", "numericDate2", "validateInput", "label", "validateStringClaim", "claim", "validateAudienceClaim", "member", "numericDate", "producerPayloads", "producerPayload", "producer", "jwtData", "payload", "JWTClaimsBuilder", "createSignature", "rejectUnencoded", "unprotectedHeader", "protectedHeaderString", "payloadS", "payloadB", "jws", "createCompactSignature", "SignJWT_base", "_protectedHeader", "SignJWT", "__privateAdd", "__privateGet", "__privateSet", "prettyPrint", "saveBot", "medplum", "botConfig", "bot", "codePath", "readFileContents", "sourceCode", "basename", "getCodeContentType", "updateResult", "deployBot", "deployResult", "isOk", "normalizeErrorString", "createBot", "botName", "projectId", "sourceFile", "distFile", "runtimeVersion", "writeConfig", "body", "newBot", "addBotToConfig", "readBotConfigs", "regExBotName", "escapeRegex", "readConfig", "getConfigFileName", "tagName", "parts", "configFileName", "config", "fileName", "content", "readServerConfig", "path", "safeTarExtractor", "destinationDir", "fileCount", "totalSize", "extract", "_path", "getUnsupportedExtension", "filename", "ext", "extname", "ContentType", "saveProfile", "optionsObject", "loadProfile", "jwtBearerLogin", "OAuthSigningAlgorithm", "currentTimestamp", "encodedHeader", "encodedData", "signature", "createHmac", "signedToken", "jwtAssertionLogin", "createPrivateKey", "jwt", "randomBytes", "addSubcommand", "command", "subcommand", "MedplumCommand", "Command", "fn", "wrappedFn", "withMergedOptions", "option", "expectedArgsCount", "actionArgs", "isPromise", "agentStatusCommand", "agentPingCommand", "agentPushCommand", "agentReloadConfigCommand", "agentUpgradeCommand", "agentStatsCommand", "agent", "Option", "agentIds", "callAgentBulkOperation", "statusEntry", "parseParameterValues", "ipOrDomain", "agentId", "agentRef", "resolveAgentReference", "count", "pingResult", "deviceId", "pushResult", "stats", "rows", "renderAgentStats", "SUMMARY_STAT_KEYS", "formatStatValue", "buildChannelStatsRows", "row", "heading", "summary", "knownKeys", "channelRows", "clientRows", "parseSuccessfulResponse", "renderSuccessfulRows", "parseEitherIdsOrCriteria", "usedCriteria", "searchParams", "paramName", "paramVal", "successfulResponses", "failedResponses", "responses", "parseAgentBulkOpBundle", "successfulRows", "failedRows", "issue", "usedId", "assertValidAgentCriteria", "bundle", "EMPTY", "parseAgentBulkOpParameters", "paramNames", "map", "requiredParams", "optionalParams", "paramsParam", "valueProp", "extractValueFromParametersParameter", "isUUID", "criteria", "invalidCriteriaMsg", "resourceType", "queryStr", "execAsync", "promisify", "exec", "MEDPLUM_CLI_CLIENT_ID", "redirectUri", "login", "whoami", "startLogin", "printMe", "medplumAuthorizationCodeLogin", "startWebServer", "server", "createServer", "req", "res", "getDisplayString", "openBrowser", "os", "platform", "cmd", "loginState", "loginUrl", "RESET", "BOLD", "RED", "GREEN", "YELLOW", "BLUE", "color", "text", "processDescription", "desc", "semver", "wr", "Qt", "terminal", "initTerminal", "readline", "closeTerminal", "print", "ask", "defaultValue", "answer", "choose", "o", "chooseInt", "yesOrNo", "checkOk", "cloudFormationClient", "CloudFormationClient", "cloudFrontClient", "CloudFrontClient", "ecsClient", "ECSClient", "s3Client", "S3Client", "tagKey", "getAllStacks", "listResult", "paginator", "paginateListStacks", "page", "stack", "getStackByTag", "stackSummaries", "stackSummary", "stackName", "details", "getStackDetails", "buildStackDetails", "client", "describeStacksCommand", "DescribeStacksCommand", "medplumTag", "stackResources", "DescribeStackResourcesCommand", "resource", "assignStackDetails", "printStackDetails", "getEcsServiceName", "createInvalidation", "distributionId", "CreateInvalidationCommand", "getServerVersions", "gs", "writeParameters", "region", "SSMClient", "valueStr", "existingValue", "readParameter", "writeParameter", "GetParameterCommand", "PutParameterCommand", "printConfigNotFound", "files", "readdirSync", "f", "file", "printStackNotFound", "STSClient", "GetCallerIdentityCommand", "getDomainSetting", "domain", "getDomainCertSetting", "initStackCommand", "currentAccountId", "getAccountId", "defaultStackName", "supportEmail", "latestVersion", "signingKey", "generateSigningKey", "allCerts", "listAllCertificates", "certName", "arn", "processCert", "serverParams", "serverConfigFileName", "listCertificates", "usEast1Result", "ACMClient", "ListCertificatesCommand", "domainName", "existingCert", "cert", "requestCert", "validationMethod", "RequestCertificateCommand", "keyName", "passphrase", "randomUUID", "generateKeyPairSync", "CreatePublicKeyCommand", "listStacksCommand", "updateAppCommand", "appBucket", "tmpDir", "downloadNpmPackage", "replaceVariables", "uploadAppToS3", "getNpmPackageMetadata", "packageName", "tarballUrl", "mkdtempSync", "join", "tmpdir", "extractor", "pipeline", "Readable", "error", "rmSync", "folderName", "replacements", "item", "itemPath", "replaceVariablesInFile", "contents", "placeholder", "replacement", "bucketName", "uploadPatterns", "uploadPattern", "uploadFolderToS3", "items", "fastGlob", "uploadFileToS3", "filePath", "fileStream", "createReadStream", "s3Key", "sep", "putObjectParams", "PutObjectCommand", "updateBucketPoliciesCommand", "updateBucketPolicy", "friendlyName", "bucketResource", "distributionResource", "oaiResource", "oaiId", "bucketPolicy", "getPolicy", "policyHasAllowStatement", "addAllowPolicyStatement", "addGuardDutyReadPolicyStatement", "setPolicy", "policyResponse", "GetBucketPolicyCommand", "policy", "PutBucketPolicyCommand", "statementHasAction", "statement", "action", "updateConfigCommand", "infraConfig", "serverConfig", "checkConfigConflicts", "mergeConfigs", "checkConflict", "isConflict", "updateServerCommand", "separatorIndex", "serverImagePrefix", "initialVersion", "getCurrentVersion", "updateVersion", "nextUpdateVersion", "ae", "deployServerUpdate", "currentVersion", "targetVersion", "allVersions", "configFile", "deploy", "spawnSync", "buildAwsCommand", "aws", "botSaveCommand", "botDeployCommand", "botCreateCommand", "saveBotDeprecate", "deployBotDeprecate", "createBotDeprecate", "botWrapper", "botConfigs", "errors", "errored", "saved", "deployed", "bulkExportCommand", "bulkImportCommand", "bulk", "exportLevel", "since", "targetDirectory", "fileUrl", "nodeStream", "createWriteStream", "numResourcesPerRequest", "addExtensionsForMissingValues", "importFile", "rl", "createInterface", "line", "parseResource", "sendBatchEntries", "pendingEntries", "OperationOutcomeError", "getStatus", "sleep", "getRateLimitRetryDelay", "retryEntries", "resultEntry", "rateLimitOutcome", "outcome", "outcomeDelay", "getRateLimitReset", "limit", "jsonString", "addExtensionsForMissingValuesResource", "addExtensionsForMissingValuesExplanationOfBenefits", "DEFAULT_BATCH_SIZE", "DICOM_EXTENSIONS", "DICOM_PREFIX", "DICOM_PREFIX_OFFSET", "DICOM_HEADER_LENGTH", "FILE_META_GROUP", "isDicomFile", "handle", "open", "bytesRead", "resolveDicomFiles", "inputs", "results", "stat", "matches", "skipped", "writeBuffer", "stream", "once", "pipeFileToStream", "chunk", "writeMultipartRelatedBody", "filePaths", "boundary", "stow", "batchSize", "batch", "contentType", "PassThrough", "writePromise", "requestPromise", "dicomweb", "Pd", "Id", "Hl7Base", "listener", "Hl7MessageEvent", "connection", "Hl7EnhancedAckSentEvent", "Hl7ErrorEvent", "Hl7WarningEvent", "Hl7CloseEvent", "DEFAULT_ENCODING", "GRACEFUL_CLOSE_TIMEOUT_MS", "ONE_MINUTE", "Hl7Connection", "socket", "encoding", "enhancedMode", "messages", "event", "origMsgCtrlId", "queueItem", "ackCode", "ReturnAckCategory", "reply", "replyString", "replyBuffer", "iconv", "outputBuffer", "millisBetweenMsgs", "elapsedMillis", "messageEvent", "bufferIdx", "messageEndIndex", "contentBuffer", "contentString", "Hl7Message", "reject", "msgCtrlId", "validationError", "timer", "pendingCount", "messagesPerMin", "Hl7Client", "deferredPromise", "net", "assert", "timeoutListener", "connectListener", "errorListener", "closeListener", "_resolve", "_reject", "DEFAULT_FORCE_DRAIN_TIMEOUT_MS", "Hl7Server", "handler", "port", "connectionOptions", "listenOnPort", "boundPort", "e", "forceDrainTimeout", "send", "host", "generateSampleHl7Message", "A", "listen", "hl7", "now", "formatHl7DateTime", "controlId", "setProfile", "removeProfile", "listProfiles", "describeProfile", "dir", "allProfiles", "projectListCommand", "projectCurrentCommand", "projectSwitchCommand", "projectInviteCommand", "project", "projectList", "projects", "switchProject", "firstName", "lastName", "email", "inviteBody", "inviteUser", "deleteObject", "get", "post", "put", "cleanUrl", "convertToTransactionBundle", "parseBody", "main", "argv", "MEDPLUM_VERSION", "handleError", "exitCode", "shouldPrint", "CommanderError", "writeErrorToStderr", "verbose", "run"]
7
7
  }