@medplum/core 0.9.6 → 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -49,9 +49,17 @@ class LRUCache {
49
49
  __classPrivateFieldSet(this, _LRUCache_max, max, "f");
50
50
  __classPrivateFieldSet(this, _LRUCache_cache, new Map(), "f");
51
51
  }
52
+ /**
53
+ * Deletes all values from the cache.
54
+ */
52
55
  clear() {
53
56
  __classPrivateFieldGet(this, _LRUCache_cache, "f").clear();
54
57
  }
58
+ /**
59
+ * Returns the value for the given key.
60
+ * @param key The key to retrieve.
61
+ * @returns The value if found; undefined otherwise.
62
+ */
55
63
  get(key) {
56
64
  const item = __classPrivateFieldGet(this, _LRUCache_cache, "f").get(key);
57
65
  if (item) {
@@ -60,6 +68,11 @@ class LRUCache {
60
68
  }
61
69
  return item;
62
70
  }
71
+ /**
72
+ * Sets the value for the given key.
73
+ * @param key The key to set.
74
+ * @param val The value to set.
75
+ */
63
76
  set(key, val) {
64
77
  if (__classPrivateFieldGet(this, _LRUCache_cache, "f").has(key)) {
65
78
  __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key);
@@ -69,9 +82,20 @@ class LRUCache {
69
82
  }
70
83
  __classPrivateFieldGet(this, _LRUCache_cache, "f").set(key, val);
71
84
  }
85
+ /**
86
+ * Deletes the value for the given key.
87
+ * @param key The key to delete.
88
+ */
72
89
  delete(key) {
73
90
  __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key);
74
91
  }
92
+ /**
93
+ * Returns the list of all keys in the cache.
94
+ * @returns The array of keys in the cache.
95
+ */
96
+ keys() {
97
+ return __classPrivateFieldGet(this, _LRUCache_cache, "f").keys();
98
+ }
75
99
  }
76
100
  _LRUCache_max = new WeakMap(), _LRUCache_cache = new WeakMap(), _LRUCache_instances = new WeakSet(), _LRUCache_first = function _LRUCache_first() {
77
101
  // This works because the Map class maintains ordered keys.
@@ -337,6 +361,30 @@ function buildQuestionnaireAnswerItems(items, result) {
337
361
  }
338
362
  }
339
363
  }
364
+ /**
365
+ * Returns the resource identifier for the given system.
366
+ *
367
+ * If multiple identifiers exist with the same system, the first one is returned.
368
+ *
369
+ * If the system is not found, then returns undefined.
370
+ *
371
+ * @param resource The resource to check.
372
+ * @param system The identifier system.
373
+ * @returns The identifier value if found; otherwise undefined.
374
+ */
375
+ function getIdentifier(resource, system) {
376
+ const identifiers = resource.identifier;
377
+ if (!identifiers) {
378
+ return undefined;
379
+ }
380
+ const array = Array.isArray(identifiers) ? identifiers : [identifiers];
381
+ for (const identifier of array) {
382
+ if (identifier.system === system) {
383
+ return identifier.value;
384
+ }
385
+ }
386
+ return undefined;
387
+ }
340
388
  /**
341
389
  * Returns an extension value by extension URLs.
342
390
  * @param resource The base resource.
@@ -402,7 +450,7 @@ function isEmpty(v) {
402
450
  * @param object2 The second object.
403
451
  * @returns True if the objects are equal.
404
452
  */
405
- function deepEquals(object1, object2, path) {
453
+ function deepEquals$1(object1, object2, path) {
406
454
  if (object1 === object2) {
407
455
  return true;
408
456
  }
@@ -418,10 +466,10 @@ function deepEquals(object1, object2, path) {
418
466
  if (Array.isArray(object1) || Array.isArray(object2)) {
419
467
  return false;
420
468
  }
421
- if (isObject(object1) && isObject(object2)) {
469
+ if (isObject$1(object1) && isObject$1(object2)) {
422
470
  return deepEqualsObject(object1, object2, path);
423
471
  }
424
- if (isObject(object1) || isObject(object2)) {
472
+ if (isObject$1(object1) || isObject$1(object2)) {
425
473
  return false;
426
474
  }
427
475
  return false;
@@ -431,7 +479,7 @@ function deepEqualsArray(array1, array2) {
431
479
  return false;
432
480
  }
433
481
  for (let i = 0; i < array1.length; i++) {
434
- if (!deepEquals(array1[i], array2[i])) {
482
+ if (!deepEquals$1(array1[i], array2[i])) {
435
483
  return false;
436
484
  }
437
485
  }
@@ -449,7 +497,7 @@ function deepEqualsObject(object1, object2, path) {
449
497
  for (const key of keySet) {
450
498
  const val1 = object1[key];
451
499
  const val2 = object2[key];
452
- if (!deepEquals(val1, val2, key)) {
500
+ if (!deepEquals$1(val1, val2, key)) {
453
501
  return false;
454
502
  }
455
503
  }
@@ -468,7 +516,7 @@ function isUUID(input) {
468
516
  * @param object The candidate object.
469
517
  * @returns True if the input is a non-null non-undefined object.
470
518
  */
471
- function isObject(obj) {
519
+ function isObject$1(obj) {
472
520
  return obj !== null && typeof obj === 'object';
473
521
  }
474
522
  /**
@@ -756,6 +804,109 @@ class OperationOutcomeError extends Error {
756
804
  }
757
805
  }
758
806
 
807
+ /*
808
+ * This file attempts a unified "generatePdf" function that works both client-side and server-side.
809
+ * On client-side, it checks for a global "pdfMake" variable.
810
+ * On server-side, it dynamically loads "pdfmake" from the node_modules.
811
+ */
812
+ function generatePdf(docDefinition, tableLayouts, fonts) {
813
+ return __awaiter(this, void 0, void 0, function* () {
814
+ // Setup sane defaults
815
+ // See: https://pdfmake.github.io/docs/0.1/document-definition-object/styling/
816
+ docDefinition.pageSize = docDefinition.pageSize || 'LETTER';
817
+ docDefinition.pageMargins = docDefinition.pageMargins || [60, 60, 60, 60];
818
+ docDefinition.pageOrientation = docDefinition.pageOrientation || 'portrait';
819
+ docDefinition.defaultStyle = docDefinition.defaultStyle || {};
820
+ docDefinition.defaultStyle.font = docDefinition.defaultStyle.font || 'Helvetica';
821
+ docDefinition.defaultStyle.fontSize = docDefinition.defaultStyle.fontSize || 11;
822
+ docDefinition.defaultStyle.lineHeight = docDefinition.defaultStyle.lineHeight || 2.0;
823
+ if (typeof pdfMake === 'undefined') {
824
+ return generatePdfServerSide(docDefinition, tableLayouts, fonts);
825
+ }
826
+ else {
827
+ return generatePdfClientSide(docDefinition, tableLayouts, fonts);
828
+ }
829
+ });
830
+ }
831
+ function generatePdfServerSide(docDefinition, tableLayouts, fonts) {
832
+ return __awaiter(this, void 0, void 0, function* () {
833
+ if (!fonts) {
834
+ fonts = {
835
+ Helvetica: {
836
+ normal: 'Helvetica',
837
+ bold: 'Helvetica-Bold',
838
+ italics: 'Helvetica-Oblique',
839
+ bolditalics: 'Helvetica-BoldOblique',
840
+ },
841
+ Roboto: {
842
+ normal: 'https://static.medplum.com/fonts/Roboto-Regular.ttf',
843
+ bold: 'https://static.medplum.com/fonts/Roboto-Medium.ttf',
844
+ italics: 'https://static.medplum.com/fonts/Roboto-Italic.ttf',
845
+ bolditalics: 'https://static.medplum.com/fonts/Roboto-MediumItalic.ttf',
846
+ },
847
+ Avenir: {
848
+ normal: 'https://static.medplum.com/fonts/avenir.ttf',
849
+ },
850
+ };
851
+ }
852
+ return new Promise((resolve, reject) => {
853
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
854
+ const PdfPrinter = require('pdfmake');
855
+ const printer = new PdfPrinter(fonts);
856
+ const pdfDoc = printer.createPdfKitDocument(docDefinition, { tableLayouts });
857
+ const chunks = [];
858
+ pdfDoc.on('data', (chunk) => chunks.push(chunk));
859
+ pdfDoc.on('end', () => resolve(concat(chunks)));
860
+ pdfDoc.on('error', reject);
861
+ pdfDoc.end();
862
+ });
863
+ });
864
+ }
865
+ function generatePdfClientSide(docDefinition, tableLayouts, fonts) {
866
+ return __awaiter(this, void 0, void 0, function* () {
867
+ if (!fonts) {
868
+ fonts = {
869
+ Helvetica: {
870
+ normal: 'https://static.medplum.com/fonts/Helvetica.ttf',
871
+ bold: 'https://static.medplum.com/fonts/Helvetica-bold.ttf',
872
+ italics: 'https://static.medplum.com/fonts/Helvetica-italic.ttf',
873
+ bolditalics: 'https://static.medplum.com/fonts/Helvetica-bold-italic.ttf',
874
+ },
875
+ Roboto: {
876
+ normal: 'https://static.medplum.com/fonts/Roboto-Regular.ttf',
877
+ bold: 'https://static.medplum.com/fonts/Roboto-Medium.ttf',
878
+ italics: 'https://static.medplum.com/fonts/Roboto-Italic.ttf',
879
+ bolditalics: 'https://static.medplum.com/fonts/Roboto-MediumItalic.ttf',
880
+ },
881
+ Avenir: {
882
+ normal: 'https://static.medplum.com/fonts/avenir.ttf',
883
+ },
884
+ };
885
+ }
886
+ return new Promise((resolve) => {
887
+ pdfMake.createPdf(docDefinition, tableLayouts, fonts).getBlob(resolve);
888
+ });
889
+ });
890
+ }
891
+ /**
892
+ * Concatenates an array of Uint8Arrays into a single Uint8Array.
893
+ * @param arrays An array of arrays of bytes.
894
+ * @returns A single array of bytes.
895
+ */
896
+ function concat(arrays) {
897
+ let len = 0;
898
+ for (const array of arrays) {
899
+ len += array.length;
900
+ }
901
+ const result = new Uint8Array(len);
902
+ let index = 0;
903
+ for (const array of arrays) {
904
+ result.set(array, index);
905
+ index += array.length;
906
+ }
907
+ return result;
908
+ }
909
+
759
910
  var _ReadablePromise_suspender, _ReadablePromise_status, _ReadablePromise_response, _ReadablePromise_error, _a;
760
911
  /**
761
912
  * The ReadablePromise class wraps a request promise suitable for React Suspense.
@@ -1012,7 +1163,7 @@ function formatSearchQuery(definition) {
1012
1163
  params.push('_count=' + definition.count);
1013
1164
  }
1014
1165
  if (definition.total !== undefined) {
1015
- params.push('_total=' + encodeURIComponent(definition.total));
1166
+ params.push('_total=' + definition.total);
1016
1167
  }
1017
1168
  if (params.length === 0) {
1018
1169
  return '';
@@ -1373,7 +1524,6 @@ const PATCH_CONTENT_TYPE = 'application/json-patch+json';
1373
1524
  * const bundle = await medplum.search('Patient?name=Alice');
1374
1525
  * console.log(bundle.total);
1375
1526
  * ```
1376
- *
1377
1527
  */
1378
1528
  class MedplumClient extends EventTarget {
1379
1529
  constructor(options) {
@@ -1422,6 +1572,15 @@ class MedplumClient extends EventTarget {
1422
1572
  }
1423
1573
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setupStorageListener).call(this);
1424
1574
  }
1575
+ /**
1576
+ * Returns the current base URL for all API requests.
1577
+ * By default, this is set to `https://api.medplum.com/`.
1578
+ * This can be overridden by setting the `baseUrl` option when creating the client.
1579
+ * @returns The current base URL for all API requests.
1580
+ */
1581
+ getBaseUrl() {
1582
+ return __classPrivateFieldGet(this, _MedplumClient_baseUrl, "f");
1583
+ }
1425
1584
  /**
1426
1585
  * Clears all auth state including local storage and session storage.
1427
1586
  */
@@ -1434,6 +1593,26 @@ class MedplumClient extends EventTarget {
1434
1593
  __classPrivateFieldSet(this, _MedplumClient_config, undefined, "f");
1435
1594
  this.dispatchEvent({ type: 'change' });
1436
1595
  }
1596
+ /**
1597
+ * Invalidates any cached values or cached requests for the given URL.
1598
+ * @param url The URL to invalidate.
1599
+ */
1600
+ invalidateUrl(url) {
1601
+ url = url.toString();
1602
+ __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1603
+ }
1604
+ /**
1605
+ * Invalidates all cached search results or cached requests for the given resourceType.
1606
+ * @param resourceType The resource type to invalidate.
1607
+ */
1608
+ invalidateSearches(resourceType) {
1609
+ const url = 'fhir/R4/' + resourceType;
1610
+ for (const key of __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").keys()) {
1611
+ if (key.endsWith(url) || key.includes(url + '?')) {
1612
+ __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(key);
1613
+ }
1614
+ }
1615
+ }
1437
1616
  /**
1438
1617
  * Makes an HTTP GET request to the specified URL.
1439
1618
  *
@@ -1446,6 +1625,7 @@ class MedplumClient extends EventTarget {
1446
1625
  * @returns Promise to the response content.
1447
1626
  */
1448
1627
  get(url, options = {}) {
1628
+ url = url.toString();
1449
1629
  if (!(options === null || options === void 0 ? void 0 : options.cache)) {
1450
1630
  const cached = __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").get(url);
1451
1631
  if (cached) {
@@ -1470,13 +1650,14 @@ class MedplumClient extends EventTarget {
1470
1650
  * @returns Promise to the response content.
1471
1651
  */
1472
1652
  post(url, body, contentType, options = {}) {
1653
+ url = url.toString();
1473
1654
  if (body) {
1474
1655
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestBody).call(this, options, body);
1475
1656
  }
1476
1657
  if (contentType) {
1477
1658
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, contentType);
1478
1659
  }
1479
- __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1660
+ this.invalidateUrl(url);
1480
1661
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'POST', url, options);
1481
1662
  }
1482
1663
  /**
@@ -1493,13 +1674,14 @@ class MedplumClient extends EventTarget {
1493
1674
  * @returns Promise to the response content.
1494
1675
  */
1495
1676
  put(url, body, contentType, options = {}) {
1677
+ url = url.toString();
1496
1678
  if (body) {
1497
1679
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestBody).call(this, options, body);
1498
1680
  }
1499
1681
  if (contentType) {
1500
1682
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, contentType);
1501
1683
  }
1502
- __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1684
+ this.invalidateUrl(url);
1503
1685
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'PUT', url, options);
1504
1686
  }
1505
1687
  /**
@@ -1515,9 +1697,10 @@ class MedplumClient extends EventTarget {
1515
1697
  * @returns Promise to the response content.
1516
1698
  */
1517
1699
  patch(url, operations, options = {}) {
1700
+ url = url.toString();
1518
1701
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestBody).call(this, options, operations);
1519
1702
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, PATCH_CONTENT_TYPE);
1520
- __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1703
+ this.invalidateUrl(url);
1521
1704
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'PATCH', url, options);
1522
1705
  }
1523
1706
  /**
@@ -1532,7 +1715,8 @@ class MedplumClient extends EventTarget {
1532
1715
  * @returns Promise to the response content.
1533
1716
  */
1534
1717
  delete(url, options = {}) {
1535
- __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1718
+ url = url.toString();
1719
+ this.invalidateUrl(url);
1536
1720
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'DELETE', url, options);
1537
1721
  }
1538
1722
  /**
@@ -1608,9 +1792,20 @@ class MedplumClient extends EventTarget {
1608
1792
  * @returns The well-formed FHIR URL.
1609
1793
  */
1610
1794
  fhirUrl(...path) {
1611
- const builder = [__classPrivateFieldGet(this, _MedplumClient_baseUrl, "f"), 'fhir/R4'];
1612
- path.forEach((p) => builder.push('/', encodeURIComponent(p)));
1613
- return builder.join('');
1795
+ return new URL(__classPrivateFieldGet(this, _MedplumClient_baseUrl, "f") + 'fhir/R4/' + path.join('/'));
1796
+ }
1797
+ /**
1798
+ * Builds a FHIR search URL from a search query or structured query object.
1799
+ * @param query The FHIR search query or structured query object.
1800
+ * @returns The well-formed FHIR URL.
1801
+ */
1802
+ fhirSearchUrl(query) {
1803
+ if (typeof query === 'string') {
1804
+ return this.fhirUrl(query);
1805
+ }
1806
+ const url = this.fhirUrl(query.resourceType);
1807
+ url.search = formatSearchQuery(query);
1808
+ return url;
1614
1809
  }
1615
1810
  /**
1616
1811
  * Sends a FHIR search request.
@@ -1667,7 +1862,7 @@ class MedplumClient extends EventTarget {
1667
1862
  * @returns Promise to the search result bundle.
1668
1863
  */
1669
1864
  search(query, options = {}) {
1670
- return this.get(typeof query === 'string' ? 'fhir/R4/' + query : this.fhirUrl(query.resourceType) + formatSearchQuery(query), options);
1865
+ return this.get(this.fhirSearchUrl(query), options);
1671
1866
  }
1672
1867
  /**
1673
1868
  * Sends a FHIR search request for a single resource.
@@ -1689,13 +1884,18 @@ class MedplumClient extends EventTarget {
1689
1884
  * @returns Promise to the search result bundle.
1690
1885
  */
1691
1886
  searchOne(query, options = {}) {
1692
- var _a, _b;
1693
- return __awaiter(this, void 0, void 0, function* () {
1694
- const search = typeof query === 'string' ? parseSearchDefinition(query) : query;
1695
- search.count = 1;
1696
- const bundle = yield this.search(search, options);
1697
- return (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.resource;
1698
- });
1887
+ const search = typeof query === 'string' ? parseSearchDefinition(query) : query;
1888
+ search.count = 1;
1889
+ const cacheKey = this.fhirSearchUrl(query).toString() + '-searchOne';
1890
+ if (!(options === null || options === void 0 ? void 0 : options.cache)) {
1891
+ const cached = __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").get(cacheKey);
1892
+ if (cached) {
1893
+ return cached;
1894
+ }
1895
+ }
1896
+ const promise = new ReadablePromise(this.search(search, options).then((b) => { var _a, _b; return (_b = (_a = b.entry) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.resource; }));
1897
+ __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").set(cacheKey, promise);
1898
+ return promise;
1699
1899
  }
1700
1900
  /**
1701
1901
  * Sends a FHIR search request for an array of resources.
@@ -1717,11 +1917,16 @@ class MedplumClient extends EventTarget {
1717
1917
  * @returns Promise to the search result bundle.
1718
1918
  */
1719
1919
  searchResources(query, options = {}) {
1720
- var _a, _b;
1721
- return __awaiter(this, void 0, void 0, function* () {
1722
- const bundle = yield this.search(query, options);
1723
- return (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a.map((entry) => entry.resource)) !== null && _b !== void 0 ? _b : [];
1724
- });
1920
+ const cacheKey = this.fhirSearchUrl(query).toString() + '-searchResources';
1921
+ if (!(options === null || options === void 0 ? void 0 : options.cache)) {
1922
+ const cached = __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").get(cacheKey);
1923
+ if (cached) {
1924
+ return cached;
1925
+ }
1926
+ }
1927
+ const promise = new ReadablePromise(this.search(query, options).then((b) => { var _a, _b; return (_b = (_a = b.entry) === null || _a === void 0 ? void 0 : _a.map((e) => e.resource)) !== null && _b !== void 0 ? _b : []; }));
1928
+ __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").set(cacheKey, promise);
1929
+ return promise;
1725
1930
  }
1726
1931
  /**
1727
1932
  * Searches a ValueSet resource using the "expand" operation.
@@ -1731,9 +1936,10 @@ class MedplumClient extends EventTarget {
1731
1936
  * @returns Promise to expanded ValueSet.
1732
1937
  */
1733
1938
  searchValueSet(system, filter, options = {}) {
1734
- return this.get(this.fhirUrl('ValueSet', '$expand') +
1735
- `?url=${encodeURIComponent(system)}` +
1736
- `&filter=${encodeURIComponent(filter)}`, options);
1939
+ const url = this.fhirUrl('ValueSet', '$expand');
1940
+ url.searchParams.set('url', system);
1941
+ url.searchParams.set('filter', filter);
1942
+ return this.get(url.toString(), options);
1737
1943
  }
1738
1944
  /**
1739
1945
  * Returns a cached resource if it is available.
@@ -1742,7 +1948,7 @@ class MedplumClient extends EventTarget {
1742
1948
  * @returns The resource if it is available in the cache; undefined otherwise.
1743
1949
  */
1744
1950
  getCached(resourceType, id) {
1745
- const cached = __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").get(this.fhirUrl(resourceType, id));
1951
+ const cached = __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").get(this.fhirUrl(resourceType, id).toString());
1746
1952
  return cached && !cached.isPending() ? cached.read() : undefined;
1747
1953
  }
1748
1954
  /**
@@ -1775,27 +1981,6 @@ class MedplumClient extends EventTarget {
1775
1981
  readResource(resourceType, id) {
1776
1982
  return this.get(this.fhirUrl(resourceType, id));
1777
1983
  }
1778
- /**
1779
- * Reads a resource by resource type and ID using the in-memory resource cache.
1780
- *
1781
- * If the resource is not available in the cache, it will be read from the server.
1782
- *
1783
- * Example:
1784
- *
1785
- * ```typescript
1786
- * const patient = await medplum.readCached('Patient', '123');
1787
- * console.log(patient);
1788
- * ```
1789
- *
1790
- * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
1791
- *
1792
- * @param resourceType The FHIR resource type.
1793
- * @param id The resource ID.
1794
- * @returns The resource if available; undefined otherwise.
1795
- */
1796
- readCached(resourceType, id) {
1797
- return this.get(this.fhirUrl(resourceType, id));
1798
- }
1799
1984
  /**
1800
1985
  * Reads a resource by `Reference`.
1801
1986
  *
@@ -1817,39 +2002,11 @@ class MedplumClient extends EventTarget {
1817
2002
  readReference(reference) {
1818
2003
  const refString = reference === null || reference === void 0 ? void 0 : reference.reference;
1819
2004
  if (!refString) {
1820
- return new ReadablePromise(Promise.reject('Missing reference'));
2005
+ return new ReadablePromise(Promise.reject(new Error('Missing reference')));
1821
2006
  }
1822
2007
  const [resourceType, id] = refString.split('/');
1823
2008
  return this.readResource(resourceType, id);
1824
2009
  }
1825
- /**
1826
- * Reads a resource by `Reference` using the in-memory resource cache.
1827
- *
1828
- * This is a convenience method for `readResource()` that accepts a `Reference` object.
1829
- *
1830
- * If the resource is not available in the cache, it will be read from the server.
1831
- *
1832
- * Example:
1833
- *
1834
- * ```typescript
1835
- * const serviceRequest = await medplum.readResource('ServiceRequest', '123');
1836
- * const patient = await medplum.readCachedReference(serviceRequest.subject);
1837
- * console.log(patient);
1838
- * ```
1839
- *
1840
- * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
1841
- *
1842
- * @param reference The FHIR reference object.
1843
- * @returns The resource if available; undefined otherwise.
1844
- */
1845
- readCachedReference(reference) {
1846
- const refString = reference === null || reference === void 0 ? void 0 : reference.reference;
1847
- if (!refString) {
1848
- return new ReadablePromise(Promise.reject('Missing reference'));
1849
- }
1850
- const [resourceType, id] = refString.split('/');
1851
- return this.readCached(resourceType, id);
1852
- }
1853
2010
  /**
1854
2011
  * Returns a cached schema for a resource type.
1855
2012
  * If the schema is not cached, returns undefined.
@@ -1872,7 +2029,7 @@ class MedplumClient extends EventTarget {
1872
2029
  return Promise.resolve(__classPrivateFieldGet(this, _MedplumClient_schema, "f"));
1873
2030
  }
1874
2031
  const query = `{
1875
- StructureDefinitionList(name: "${encodeURIComponent(resourceType)}") {
2032
+ StructureDefinitionList(name: "${resourceType}") {
1876
2033
  name,
1877
2034
  description,
1878
2035
  snapshot {
@@ -1892,7 +2049,7 @@ class MedplumClient extends EventTarget {
1892
2049
  }
1893
2050
  }
1894
2051
  }
1895
- SearchParameterList(base: "${encodeURIComponent(resourceType)}", _count: 100) {
2052
+ SearchParameterList(base: "${resourceType}", _count: 100) {
1896
2053
  base,
1897
2054
  code,
1898
2055
  type,
@@ -1926,7 +2083,7 @@ class MedplumClient extends EventTarget {
1926
2083
  *
1927
2084
  * @param resourceType The FHIR resource type.
1928
2085
  * @param id The resource ID.
1929
- * @returns The resource if available; undefined otherwise.
2086
+ * @returns Promise to the resource history.
1930
2087
  */
1931
2088
  readHistory(resourceType, id) {
1932
2089
  return this.get(this.fhirUrl(resourceType, id, '_history'));
@@ -1978,8 +2135,9 @@ class MedplumClient extends EventTarget {
1978
2135
  */
1979
2136
  createResource(resource) {
1980
2137
  if (!resource.resourceType) {
1981
- return Promise.reject('Missing resourceType');
2138
+ throw new Error('Missing resourceType');
1982
2139
  }
2140
+ this.invalidateSearches(resource.resourceType);
1983
2141
  return this.post(this.fhirUrl(resource.resourceType), resource);
1984
2142
  }
1985
2143
  /**
@@ -2050,9 +2208,9 @@ class MedplumClient extends EventTarget {
2050
2208
  * @returns The result of the create operation.
2051
2209
  */
2052
2210
  createBinary(data, filename, contentType) {
2053
- let url = this.fhirUrl('Binary');
2211
+ const url = this.fhirUrl('Binary');
2054
2212
  if (filename) {
2055
- url += '?_filename=' + encodeURIComponent(filename);
2213
+ url.searchParams.set('_filename', filename);
2056
2214
  }
2057
2215
  return this.post(url, data, contentType);
2058
2216
  }
@@ -2074,15 +2232,48 @@ class MedplumClient extends EventTarget {
2074
2232
  *
2075
2233
  * See the pdfmake document definition for full details: https://pdfmake.github.io/docs/0.1/document-definition-object/
2076
2234
  *
2077
- * @param docDefinition The FHIR resource to create.
2235
+ * @param docDefinition The PDF document definition.
2078
2236
  * @returns The result of the create operation.
2079
2237
  */
2080
- createPdf(docDefinition, filename) {
2081
- let url = this.fhirUrl('Binary') + '/$pdf';
2082
- if (filename) {
2083
- url += '?_filename=' + encodeURIComponent(filename);
2238
+ createPdf(docDefinition, filename, tableLayouts, fonts) {
2239
+ return __awaiter(this, void 0, void 0, function* () {
2240
+ const blob = yield generatePdf(docDefinition, tableLayouts, fonts);
2241
+ return this.createBinary(blob, filename, 'application/pdf');
2242
+ });
2243
+ }
2244
+ /**
2245
+ * Creates a FHIR `Communication` resource with the provided data content.
2246
+ *
2247
+ * This is a convenience method to handle commmon cases where a `Communication` resource is created with a `payload`.
2248
+ *
2249
+ * @param resource The FHIR resource to comment on.
2250
+ * @param text The text of the comment.
2251
+ * @returns The result of the create operation.
2252
+ */
2253
+ createComment(resource, text) {
2254
+ const profile = this.getProfile();
2255
+ let encounter = undefined;
2256
+ let subject = undefined;
2257
+ if (resource.resourceType === 'Encounter') {
2258
+ encounter = createReference(resource);
2259
+ subject = resource.subject;
2084
2260
  }
2085
- return this.post(url, docDefinition, 'application/json');
2261
+ if (resource.resourceType === 'ServiceRequest') {
2262
+ encounter = resource.encounter;
2263
+ subject = resource.subject;
2264
+ }
2265
+ if (resource.resourceType === 'Patient') {
2266
+ subject = createReference(resource);
2267
+ }
2268
+ return this.createResource({
2269
+ resourceType: 'Communication',
2270
+ basedOn: [createReference(resource)],
2271
+ encounter,
2272
+ subject,
2273
+ sender: profile ? createReference(profile) : undefined,
2274
+ sent: new Date().toISOString(),
2275
+ payload: [{ contentString: text }],
2276
+ });
2086
2277
  }
2087
2278
  /**
2088
2279
  * Updates a FHIR resource.
@@ -2110,11 +2301,12 @@ class MedplumClient extends EventTarget {
2110
2301
  */
2111
2302
  updateResource(resource) {
2112
2303
  if (!resource.resourceType) {
2113
- return Promise.reject('Missing resourceType');
2304
+ throw new Error('Missing resourceType');
2114
2305
  }
2115
2306
  if (!resource.id) {
2116
- return Promise.reject('Missing id');
2307
+ throw new Error('Missing id');
2117
2308
  }
2309
+ this.invalidateSearches(resource.resourceType);
2118
2310
  return this.put(this.fhirUrl(resource.resourceType, resource.id), resource);
2119
2311
  }
2120
2312
  /**
@@ -2141,6 +2333,7 @@ class MedplumClient extends EventTarget {
2141
2333
  * @returns The result of the patch operations.
2142
2334
  */
2143
2335
  patchResource(resourceType, id, operations) {
2336
+ this.invalidateSearches(resourceType);
2144
2337
  return this.patch(this.fhirUrl(resourceType, id), operations);
2145
2338
  }
2146
2339
  /**
@@ -2159,6 +2352,7 @@ class MedplumClient extends EventTarget {
2159
2352
  * @returns The result of the delete operation.
2160
2353
  */
2161
2354
  deleteResource(resourceType, id) {
2355
+ this.invalidateSearches(resourceType);
2162
2356
  return this.delete(this.fhirUrl(resourceType, id));
2163
2357
  }
2164
2358
  /**
@@ -2199,7 +2393,7 @@ class MedplumClient extends EventTarget {
2199
2393
  * @returns Promise to the operation outcome.
2200
2394
  */
2201
2395
  sendEmail(email) {
2202
- return this.post('email/v1/send', email);
2396
+ return this.post('email/v1/send', email, 'application/json');
2203
2397
  }
2204
2398
  graphql(query, options) {
2205
2399
  return this.post(this.fhirUrl('$graphql'), { query }, JSON_CONTENT_TYPE, options);
@@ -2220,6 +2414,9 @@ class MedplumClient extends EventTarget {
2220
2414
  yield __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_refreshProfile).call(this);
2221
2415
  });
2222
2416
  }
2417
+ getAccessToken() {
2418
+ return __classPrivateFieldGet(this, _MedplumClient_accessToken, "f");
2419
+ }
2223
2420
  setAccessToken(accessToken) {
2224
2421
  __classPrivateFieldSet(this, _MedplumClient_accessToken, accessToken, "f");
2225
2422
  __classPrivateFieldSet(this, _MedplumClient_refreshToken, undefined, "f");
@@ -2258,7 +2455,7 @@ class MedplumClient extends EventTarget {
2258
2455
  yield __classPrivateFieldGet(this, _MedplumClient_refreshPromise, "f");
2259
2456
  }
2260
2457
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_addFetchOptionsDefaults).call(this, options);
2261
- const response = yield __classPrivateFieldGet(this, _MedplumClient_fetch, "f").call(this, url, options);
2458
+ const response = yield __classPrivateFieldGet(this, _MedplumClient_fetch, "f").call(this, url.toString(), options);
2262
2459
  return response.blob();
2263
2460
  });
2264
2461
  }
@@ -2271,29 +2468,35 @@ class MedplumClient extends EventTarget {
2271
2468
  const pkceState = __classPrivateFieldGet(this, _MedplumClient_storage, "f").getString('pkceState');
2272
2469
  if (!pkceState) {
2273
2470
  this.clear();
2274
- return Promise.reject('Invalid PCKE state');
2471
+ throw new Error('Invalid PCKE state');
2275
2472
  }
2276
2473
  const codeVerifier = __classPrivateFieldGet(this, _MedplumClient_storage, "f").getString('codeVerifier');
2277
2474
  if (!codeVerifier) {
2278
2475
  this.clear();
2279
- return Promise.reject('Invalid PCKE code verifier');
2280
- }
2281
- return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_fetchTokens).call(this, 'grant_type=authorization_code' +
2282
- (__classPrivateFieldGet(this, _MedplumClient_clientId, "f") ? '&client_id=' + encodeURIComponent(__classPrivateFieldGet(this, _MedplumClient_clientId, "f")) : '') +
2283
- '&code_verifier=' +
2284
- encodeURIComponent(codeVerifier) +
2285
- '&redirect_uri=' +
2286
- encodeURIComponent(getBaseUrl()) +
2287
- '&code=' +
2288
- encodeURIComponent(code));
2289
- }
2290
- clientCredentials(clientId, clientSecret) {
2476
+ throw new Error('Invalid PCKE code verifier');
2477
+ }
2478
+ const formBody = new URLSearchParams();
2479
+ formBody.set('grant_type', 'authorization_code');
2480
+ formBody.set('client_id', __classPrivateFieldGet(this, _MedplumClient_clientId, "f"));
2481
+ formBody.set('code_verifier', codeVerifier);
2482
+ formBody.set('code', code);
2483
+ formBody.set('redirect_uri', getBaseUrl());
2484
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_fetchTokens).call(this, formBody);
2485
+ }
2486
+ /**
2487
+ * Starts a new OAuth2 client credentials flow.
2488
+ * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.4
2489
+ * @param clientId The client ID.
2490
+ * @param clientSecret The client secret.
2491
+ * @returns Promise that resolves to the client profile.
2492
+ */
2493
+ startClientLogin(clientId, clientSecret) {
2291
2494
  return __awaiter(this, void 0, void 0, function* () {
2292
- return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_fetchTokens).call(this, 'grant_type=client_credentials' +
2293
- '&client_id=' +
2294
- encodeURIComponent(clientId) +
2295
- '&client_secret=' +
2296
- encodeURIComponent(clientSecret));
2495
+ const formBody = new URLSearchParams();
2496
+ formBody.set('grant_type', 'client_credentials');
2497
+ formBody.set('client_id', clientId);
2498
+ formBody.set('client_secret', clientSecret);
2499
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_fetchTokens).call(this, formBody);
2297
2500
  });
2298
2501
  }
2299
2502
  }
@@ -2365,11 +2568,14 @@ _MedplumClient_fetch = new WeakMap(), _MedplumClient_storage = new WeakMap(), _M
2365
2568
  const headers = options.headers;
2366
2569
  headers['Content-Type'] = contentType;
2367
2570
  }, _MedplumClient_setRequestBody = function _MedplumClient_setRequestBody(options, data) {
2368
- if (typeof data === 'string' || (typeof File !== 'undefined' && data instanceof File)) {
2571
+ if (typeof data === 'string' ||
2572
+ (typeof Blob !== 'undefined' && data instanceof Blob) ||
2573
+ (typeof File !== 'undefined' && data instanceof File) ||
2574
+ (typeof Uint8Array !== 'undefined' && data instanceof Uint8Array)) {
2369
2575
  options.body = data;
2370
2576
  }
2371
2577
  else if (data) {
2372
- options.body = stringify(data);
2578
+ options.body = JSON.stringify(data);
2373
2579
  }
2374
2580
  }, _MedplumClient_handleUnauthenticated = function _MedplumClient_handleUnauthenticated(method, url, options) {
2375
2581
  return __awaiter(this, void 0, void 0, function* () {
@@ -2394,25 +2600,16 @@ _MedplumClient_fetch = new WeakMap(), _MedplumClient_storage = new WeakMap(), _M
2394
2600
  __classPrivateFieldGet(this, _MedplumClient_storage, "f").setString('codeChallenge', codeChallenge);
2395
2601
  });
2396
2602
  }, _MedplumClient_requestAuthorization = function _MedplumClient_requestAuthorization() {
2397
- return __awaiter(this, void 0, void 0, function* () {
2398
- if (!__classPrivateFieldGet(this, _MedplumClient_authorizeUrl, "f")) {
2399
- return Promise.reject('Missing authorize URL');
2400
- }
2401
- __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_startPkce).call(this);
2402
- window.location.assign(__classPrivateFieldGet(this, _MedplumClient_authorizeUrl, "f") +
2403
- '?response_type=code' +
2404
- '&state=' +
2405
- encodeURIComponent(__classPrivateFieldGet(this, _MedplumClient_storage, "f").getString('pkceState')) +
2406
- '&client_id=' +
2407
- encodeURIComponent(__classPrivateFieldGet(this, _MedplumClient_clientId, "f")) +
2408
- '&redirect_uri=' +
2409
- encodeURIComponent(getBaseUrl()) +
2410
- '&scope=' +
2411
- encodeURIComponent(DEFAULT_SCOPE) +
2412
- '&code_challenge_method=S256' +
2413
- '&code_challenge=' +
2414
- encodeURIComponent(__classPrivateFieldGet(this, _MedplumClient_storage, "f").getString('codeChallenge')));
2415
- });
2603
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_startPkce).call(this);
2604
+ const url = new URL(__classPrivateFieldGet(this, _MedplumClient_authorizeUrl, "f"));
2605
+ url.searchParams.set('response_type', 'code');
2606
+ url.searchParams.set('state', __classPrivateFieldGet(this, _MedplumClient_storage, "f").getString('pkceState'));
2607
+ url.searchParams.set('client_id', __classPrivateFieldGet(this, _MedplumClient_clientId, "f"));
2608
+ url.searchParams.set('redirect_uri', getBaseUrl());
2609
+ url.searchParams.set('scope', DEFAULT_SCOPE);
2610
+ url.searchParams.set('code_challenge_method', 'S256');
2611
+ url.searchParams.set('code_challenge', __classPrivateFieldGet(this, _MedplumClient_storage, "f").getString('codeChallenge'));
2612
+ window.location.assign(url.toString());
2416
2613
  }, _MedplumClient_refresh = function _MedplumClient_refresh() {
2417
2614
  return __awaiter(this, void 0, void 0, function* () {
2418
2615
  if (__classPrivateFieldGet(this, _MedplumClient_refreshPromise, "f")) {
@@ -2420,20 +2617,17 @@ _MedplumClient_fetch = new WeakMap(), _MedplumClient_storage = new WeakMap(), _M
2420
2617
  }
2421
2618
  if (!__classPrivateFieldGet(this, _MedplumClient_refreshToken, "f")) {
2422
2619
  this.clear();
2423
- return Promise.reject('Invalid refresh token');
2620
+ throw new Error('Invalid refresh token');
2424
2621
  }
2425
- __classPrivateFieldSet(this, _MedplumClient_refreshPromise, __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_fetchTokens).call(this, 'grant_type=refresh_token' +
2426
- '&client_id=' +
2427
- encodeURIComponent(__classPrivateFieldGet(this, _MedplumClient_clientId, "f")) +
2428
- '&refresh_token=' +
2429
- encodeURIComponent(__classPrivateFieldGet(this, _MedplumClient_refreshToken, "f"))), "f");
2622
+ const formBody = new URLSearchParams();
2623
+ formBody.set('grant_type', 'refresh_token');
2624
+ formBody.set('client_id', __classPrivateFieldGet(this, _MedplumClient_clientId, "f"));
2625
+ formBody.set('refresh_token', __classPrivateFieldGet(this, _MedplumClient_refreshToken, "f"));
2626
+ __classPrivateFieldSet(this, _MedplumClient_refreshPromise, __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_fetchTokens).call(this, formBody), "f");
2430
2627
  yield __classPrivateFieldGet(this, _MedplumClient_refreshPromise, "f");
2431
2628
  });
2432
2629
  }, _MedplumClient_fetchTokens = function _MedplumClient_fetchTokens(formBody) {
2433
2630
  return __awaiter(this, void 0, void 0, function* () {
2434
- if (!__classPrivateFieldGet(this, _MedplumClient_tokenUrl, "f")) {
2435
- return Promise.reject('Missing token URL');
2436
- }
2437
2631
  return __classPrivateFieldGet(this, _MedplumClient_fetch, "f").call(this, __classPrivateFieldGet(this, _MedplumClient_tokenUrl, "f"), {
2438
2632
  method: 'POST',
2439
2633
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
@@ -2441,7 +2635,7 @@ _MedplumClient_fetch = new WeakMap(), _MedplumClient_storage = new WeakMap(), _M
2441
2635
  })
2442
2636
  .then((response) => {
2443
2637
  if (!response.ok) {
2444
- return Promise.reject('Failed to fetch tokens');
2638
+ throw new Error('Failed to fetch tokens');
2445
2639
  }
2446
2640
  return response.json();
2447
2641
  })
@@ -2455,12 +2649,12 @@ _MedplumClient_fetch = new WeakMap(), _MedplumClient_storage = new WeakMap(), _M
2455
2649
  const tokenPayload = parseJWTPayload(token);
2456
2650
  if (Date.now() >= tokenPayload.exp * 1000) {
2457
2651
  this.clear();
2458
- return Promise.reject('Token expired');
2652
+ throw new Error('Token expired');
2459
2653
  }
2460
2654
  // Verify app_client_id
2461
2655
  if (__classPrivateFieldGet(this, _MedplumClient_clientId, "f") && tokenPayload.client_id !== __classPrivateFieldGet(this, _MedplumClient_clientId, "f")) {
2462
2656
  this.clear();
2463
- return Promise.reject('Token was not issued for this audience');
2657
+ throw new Error('Token was not issued for this audience');
2464
2658
  }
2465
2659
  yield this.setActiveLogin({
2466
2660
  accessToken: token,
@@ -2491,115 +2685,2652 @@ function getBaseUrl() {
2491
2685
  return window.location.protocol + '//' + window.location.host + '/';
2492
2686
  }
2493
2687
 
2494
- const SEGMENT_SEPARATOR = '\r';
2495
- const FIELD_SEPARATOR = '|';
2496
- const COMPONENT_SEPARATOR = '^';
2497
2688
  /**
2498
- * The Hl7Message class represents one HL7 message.
2499
- * A message is a collection of segments.
2500
- * Note that we do not strictly parse messages, and only use default delimeters.
2689
+ * Returns a single element array with a typed boolean value.
2690
+ * @param value The primitive boolean value.
2691
+ * @returns Single element array with a typed boolean value.
2501
2692
  */
2502
- class Hl7Message {
2503
- constructor(segments) {
2504
- this.segments = segments;
2693
+ function booleanToTypedValue(value) {
2694
+ return [{ type: PropertyType.boolean, value }];
2695
+ }
2696
+ /**
2697
+ * Returns a "best guess" TypedValue for a given value.
2698
+ * @param value The unknown value to check.
2699
+ * @returns A "best guess" TypedValue for the given value.
2700
+ */
2701
+ function toTypedValue(value) {
2702
+ if (Number.isSafeInteger(value)) {
2703
+ return { type: PropertyType.integer, value };
2505
2704
  }
2506
- get(index) {
2507
- if (typeof index === 'number') {
2508
- return this.segments[index];
2509
- }
2510
- return this.segments.find((s) => s.name === index);
2705
+ else if (typeof value === 'number') {
2706
+ return { type: PropertyType.decimal, value };
2511
2707
  }
2512
- getAll(name) {
2513
- return this.segments.filter((s) => s.name === name);
2708
+ else if (typeof value === 'boolean') {
2709
+ return { type: PropertyType.boolean, value };
2514
2710
  }
2515
- toString() {
2516
- return this.segments.map((s) => s.toString()).join(SEGMENT_SEPARATOR);
2711
+ else if (typeof value === 'string') {
2712
+ return { type: PropertyType.string, value };
2517
2713
  }
2518
- buildAck() {
2519
- var _a, _b, _c, _d, _e, _f;
2520
- const now = new Date();
2521
- const msh = this.get('MSH');
2522
- const sendingApp = ((_a = msh === null || msh === void 0 ? void 0 : msh.get(2)) === null || _a === void 0 ? void 0 : _a.toString()) || '';
2523
- const sendingFacility = ((_b = msh === null || msh === void 0 ? void 0 : msh.get(3)) === null || _b === void 0 ? void 0 : _b.toString()) || '';
2524
- const receivingApp = ((_c = msh === null || msh === void 0 ? void 0 : msh.get(4)) === null || _c === void 0 ? void 0 : _c.toString()) || '';
2525
- const receivingFacility = ((_d = msh === null || msh === void 0 ? void 0 : msh.get(5)) === null || _d === void 0 ? void 0 : _d.toString()) || '';
2526
- const controlId = ((_e = msh === null || msh === void 0 ? void 0 : msh.get(9)) === null || _e === void 0 ? void 0 : _e.toString()) || '';
2527
- const versionId = ((_f = msh === null || msh === void 0 ? void 0 : msh.get(12)) === null || _f === void 0 ? void 0 : _f.toString()) || '2.5.1';
2528
- return new Hl7Message([
2529
- new Hl7Segment([
2530
- 'MSH',
2531
- '^~\\&',
2532
- receivingApp,
2533
- receivingFacility,
2534
- sendingApp,
2535
- sendingFacility,
2536
- now.toISOString(),
2537
- '',
2538
- 'ACK',
2539
- now.getTime().toString(),
2540
- 'P',
2541
- versionId,
2542
- ]),
2543
- new Hl7Segment(['MSA', 'AA', controlId, 'OK']),
2544
- ]);
2714
+ else if (isQuantity(value)) {
2715
+ return { type: PropertyType.Quantity, value };
2545
2716
  }
2546
- static parse(text) {
2547
- if (!text.startsWith('MSH|^~\\&')) {
2548
- const err = new Error('Invalid HL7 message');
2549
- err.type = 'entity.parse.failed';
2550
- throw err;
2551
- }
2552
- return new Hl7Message(text.split(/[\r\n]+/).map((line) => Hl7Segment.parse(line)));
2717
+ else {
2718
+ return { type: PropertyType.BackboneElement, value };
2553
2719
  }
2554
2720
  }
2555
2721
  /**
2556
- * The Hl7Segment class represents one HL7 segment.
2557
- * A segment is a collection of fields.
2558
- * The name field is the first field.
2559
- * Note that we do not strictly parse messages, and only use default delimeters.
2722
+ * Converts unknown object into a JavaScript boolean.
2723
+ * Note that this is different than the FHIRPath "toBoolean",
2724
+ * which has particular semantics around arrays, empty arrays, and type conversions.
2725
+ * @param obj Any value or array of values.
2726
+ * @returns The converted boolean value according to FHIRPath rules.
2560
2727
  */
2561
- class Hl7Segment {
2562
- constructor(fields) {
2563
- if (isStringArray(fields)) {
2564
- this.fields = fields.map((f) => Hl7Field.parse(f));
2728
+ function toJsBoolean(obj) {
2729
+ return obj.length === 0 ? false : !!obj[0].value;
2730
+ }
2731
+ /**
2732
+ * Removes duplicates in array using FHIRPath equality rules.
2733
+ * @param arr The input array.
2734
+ * @returns The result array with duplicates removed.
2735
+ */
2736
+ function removeDuplicates(arr) {
2737
+ const result = [];
2738
+ for (const i of arr) {
2739
+ let found = false;
2740
+ for (const j of result) {
2741
+ if (toJsBoolean(fhirPathEquals(i, j))) {
2742
+ found = true;
2743
+ break;
2744
+ }
2565
2745
  }
2566
- else {
2567
- this.fields = fields;
2746
+ if (!found) {
2747
+ result.push(i);
2568
2748
  }
2569
- this.name = this.fields[0].components[0];
2570
- }
2571
- get(index) {
2572
- return this.fields[index];
2573
2749
  }
2574
- toString() {
2575
- return this.fields.map((f) => f.toString()).join(FIELD_SEPARATOR);
2750
+ return result;
2751
+ }
2752
+ /**
2753
+ * Returns a negated FHIRPath boolean expression.
2754
+ * @param input The input array.
2755
+ * @returns The negated type value array.
2756
+ */
2757
+ function fhirPathNot(input) {
2758
+ return booleanToTypedValue(!toJsBoolean(input));
2759
+ }
2760
+ /**
2761
+ * Determines if two arrays are equal according to FHIRPath equality rules.
2762
+ * @param x The first array.
2763
+ * @param y The second array.
2764
+ * @returns FHIRPath true if the arrays are equal.
2765
+ */
2766
+ function fhirPathArrayEquals(x, y) {
2767
+ if (x.length === 0 || y.length === 0) {
2768
+ return [];
2576
2769
  }
2577
- static parse(text) {
2578
- return new Hl7Segment(text.split(FIELD_SEPARATOR).map((f) => Hl7Field.parse(f)));
2770
+ if (x.length !== y.length) {
2771
+ return booleanToTypedValue(false);
2579
2772
  }
2773
+ return booleanToTypedValue(x.every((val, index) => toJsBoolean(fhirPathEquals(val, y[index]))));
2580
2774
  }
2581
2775
  /**
2582
- * The Hl7Field class represents one HL7 field.
2583
- * A field is a collection of components.
2584
- * Note that we do not strictly parse messages, and only use default delimeters.
2776
+ * Determines if two values are equal according to FHIRPath equality rules.
2777
+ * @param x The first value.
2778
+ * @param y The second value.
2779
+ * @returns True if equal.
2585
2780
  */
2586
- class Hl7Field {
2587
- constructor(components) {
2588
- this.components = components;
2781
+ function fhirPathEquals(x, y) {
2782
+ const xValue = x.value;
2783
+ const yValue = y.value;
2784
+ if (typeof xValue === 'number' && typeof yValue === 'number') {
2785
+ return booleanToTypedValue(Math.abs(xValue - yValue) < 1e-8);
2589
2786
  }
2590
- get(index) {
2591
- return this.components[index];
2787
+ if (isQuantity(xValue) && isQuantity(yValue)) {
2788
+ return booleanToTypedValue(isQuantityEquivalent(xValue, yValue));
2592
2789
  }
2593
- toString() {
2594
- return this.components.join(COMPONENT_SEPARATOR);
2790
+ if (typeof xValue === 'object' && typeof yValue === 'object') {
2791
+ return booleanToTypedValue(deepEquals(x, y));
2595
2792
  }
2596
- static parse(text) {
2597
- return new Hl7Field(text.split(COMPONENT_SEPARATOR));
2793
+ return booleanToTypedValue(xValue === yValue);
2794
+ }
2795
+ /**
2796
+ * Determines if two arrays are equivalent according to FHIRPath equality rules.
2797
+ * @param x The first array.
2798
+ * @param y The second array.
2799
+ * @returns FHIRPath true if the arrays are equivalent.
2800
+ */
2801
+ function fhirPathArrayEquivalent(x, y) {
2802
+ if (x.length === 0 && y.length === 0) {
2803
+ return booleanToTypedValue(true);
2598
2804
  }
2805
+ if (x.length !== y.length) {
2806
+ return booleanToTypedValue(false);
2807
+ }
2808
+ x.sort(fhirPathEquivalentCompare);
2809
+ y.sort(fhirPathEquivalentCompare);
2810
+ return booleanToTypedValue(x.every((val, index) => toJsBoolean(fhirPathEquivalent(val, y[index]))));
2599
2811
  }
2600
-
2601
- var SearchParameterType;
2602
- (function (SearchParameterType) {
2812
+ /**
2813
+ * Determines if two values are equivalent according to FHIRPath equality rules.
2814
+ * @param x The first value.
2815
+ * @param y The second value.
2816
+ * @returns True if equivalent.
2817
+ */
2818
+ function fhirPathEquivalent(x, y) {
2819
+ const xValue = x.value;
2820
+ const yValue = y.value;
2821
+ if (typeof xValue === 'number' && typeof yValue === 'number') {
2822
+ // Use more generous threshold than equality
2823
+ // Decimal: values must be equal, comparison is done on values rounded to the precision of the least precise operand.
2824
+ // Trailing zeroes after the decimal are ignored in determining precision.
2825
+ return booleanToTypedValue(Math.abs(xValue - yValue) < 0.01);
2826
+ }
2827
+ if (isQuantity(xValue) && isQuantity(yValue)) {
2828
+ return booleanToTypedValue(isQuantityEquivalent(xValue, yValue));
2829
+ }
2830
+ if (typeof xValue === 'object' && typeof yValue === 'object') {
2831
+ return booleanToTypedValue(deepEquals(xValue, yValue));
2832
+ }
2833
+ if (typeof xValue === 'string' && typeof yValue === 'string') {
2834
+ // String: the strings must be the same, ignoring case and locale, and normalizing whitespace
2835
+ // (see String Equivalence for more details).
2836
+ return booleanToTypedValue(xValue.toLowerCase() === yValue.toLowerCase());
2837
+ }
2838
+ return booleanToTypedValue(xValue === yValue);
2839
+ }
2840
+ /**
2841
+ * Returns the sort order of two values for FHIRPath array equivalence.
2842
+ * @param x The first value.
2843
+ * @param y The second value.
2844
+ * @returns The sort order of the values.
2845
+ */
2846
+ function fhirPathEquivalentCompare(x, y) {
2847
+ const xValue = x.value;
2848
+ const yValue = y.value;
2849
+ if (typeof xValue === 'number' && typeof yValue === 'number') {
2850
+ return xValue - yValue;
2851
+ }
2852
+ if (typeof xValue === 'string' && typeof yValue === 'string') {
2853
+ return xValue.localeCompare(yValue);
2854
+ }
2855
+ return 0;
2856
+ }
2857
+ /**
2858
+ * Determines if the typed value is the desired type.
2859
+ * @param typedValue The typed value to check.
2860
+ * @param desiredType The desired type name.
2861
+ * @returns True if the typed value is of the desired type.
2862
+ */
2863
+ function fhirPathIs(typedValue, desiredType) {
2864
+ const { value } = typedValue;
2865
+ if (value === undefined || value === null) {
2866
+ return false;
2867
+ }
2868
+ switch (desiredType) {
2869
+ case 'Boolean':
2870
+ return typeof value === 'boolean';
2871
+ case 'Decimal':
2872
+ case 'Integer':
2873
+ return typeof value === 'number';
2874
+ case 'Date':
2875
+ return typeof value === 'string' && !!value.match(/^\d{4}(-\d{2}(-\d{2})?)?/);
2876
+ case 'DateTime':
2877
+ return typeof value === 'string' && !!value.match(/^\d{4}(-\d{2}(-\d{2})?)?T/);
2878
+ case 'Time':
2879
+ return typeof value === 'string' && !!value.match(/^T\d/);
2880
+ case 'Period':
2881
+ return isPeriod(value);
2882
+ case 'Quantity':
2883
+ return isQuantity(value);
2884
+ default:
2885
+ return typeof value === 'object' && (value === null || value === void 0 ? void 0 : value.resourceType) === desiredType;
2886
+ }
2887
+ }
2888
+ /**
2889
+ * Determines if the input is a Period object.
2890
+ * This is heuristic based, as we do not have strong typing at runtime.
2891
+ * @param input The input value.
2892
+ * @returns True if the input is a period.
2893
+ */
2894
+ function isPeriod(input) {
2895
+ return !!(input && typeof input === 'object' && 'start' in input);
2896
+ }
2897
+ /**
2898
+ * Determines if the input is a Quantity object.
2899
+ * This is heuristic based, as we do not have strong typing at runtime.
2900
+ * @param input The input value.
2901
+ * @returns True if the input is a quantity.
2902
+ */
2903
+ function isQuantity(input) {
2904
+ return !!(input && typeof input === 'object' && 'value' in input && typeof input.value === 'number');
2905
+ }
2906
+ function isQuantityEquivalent(x, y) {
2907
+ return (Math.abs(x.value - y.value) < 0.01 &&
2908
+ (x.unit === y.unit || x.code === y.code || x.unit === y.code || x.code === y.unit));
2909
+ }
2910
+ /**
2911
+ * Resource equality.
2912
+ * Ignores meta.versionId and meta.lastUpdated.
2913
+ * See: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/#4-deep-equality
2914
+ * @param object1 The first object.
2915
+ * @param object2 The second object.
2916
+ * @returns True if the objects are equal.
2917
+ */
2918
+ function deepEquals(object1, object2) {
2919
+ const keys1 = Object.keys(object1);
2920
+ const keys2 = Object.keys(object2);
2921
+ if (keys1.length !== keys2.length) {
2922
+ return false;
2923
+ }
2924
+ for (const key of keys1) {
2925
+ const val1 = object1[key];
2926
+ const val2 = object2[key];
2927
+ if (isObject(val1) && isObject(val2)) {
2928
+ if (!deepEquals(val1, val2)) {
2929
+ return false;
2930
+ }
2931
+ }
2932
+ else {
2933
+ if (val1 !== val2) {
2934
+ return false;
2935
+ }
2936
+ }
2937
+ }
2938
+ return true;
2939
+ }
2940
+ function isObject(object) {
2941
+ return object !== null && typeof object === 'object';
2942
+ }
2943
+
2944
+ var _SymbolAtom_instances, _SymbolAtom_evalValue;
2945
+ class FhirPathAtom {
2946
+ constructor(original, child) {
2947
+ this.original = original;
2948
+ this.child = child;
2949
+ }
2950
+ eval(context) {
2951
+ try {
2952
+ if (context.length > 0) {
2953
+ return context.map((e) => this.child.eval([e])).flat();
2954
+ }
2955
+ else {
2956
+ return this.child.eval(context);
2957
+ }
2958
+ }
2959
+ catch (error) {
2960
+ throw new Error(`FhirPathError on "${this.original}": ${error}`);
2961
+ }
2962
+ }
2963
+ }
2964
+ class LiteralAtom {
2965
+ constructor(value) {
2966
+ this.value = value;
2967
+ }
2968
+ eval() {
2969
+ return [this.value];
2970
+ }
2971
+ }
2972
+ class SymbolAtom {
2973
+ constructor(name) {
2974
+ this.name = name;
2975
+ _SymbolAtom_instances.add(this);
2976
+ }
2977
+ eval(context) {
2978
+ if (this.name === '$this') {
2979
+ return context;
2980
+ }
2981
+ return context
2982
+ .map((e) => __classPrivateFieldGet(this, _SymbolAtom_instances, "m", _SymbolAtom_evalValue).call(this, e))
2983
+ .flat()
2984
+ .filter((e) => (e === null || e === void 0 ? void 0 : e.value) !== undefined);
2985
+ }
2986
+ }
2987
+ _SymbolAtom_instances = new WeakSet(), _SymbolAtom_evalValue = function _SymbolAtom_evalValue(typedValue) {
2988
+ const input = typedValue.value;
2989
+ if (!input || typeof input !== 'object') {
2990
+ return undefined;
2991
+ }
2992
+ if ('resourceType' in input && input.resourceType === this.name) {
2993
+ return typedValue;
2994
+ }
2995
+ let result = undefined;
2996
+ if (this.name in input) {
2997
+ result = input[this.name];
2998
+ }
2999
+ else {
3000
+ const propertyName = Object.keys(input).find((k) => k.startsWith(this.name));
3001
+ if (propertyName) {
3002
+ result = input[propertyName];
3003
+ }
3004
+ }
3005
+ if (result === undefined) {
3006
+ return undefined;
3007
+ }
3008
+ // TODO: Get the PropertyType from the choice of type
3009
+ if (Array.isArray(result)) {
3010
+ return result.map(toTypedValue);
3011
+ }
3012
+ else {
3013
+ return [toTypedValue(result)];
3014
+ }
3015
+ };
3016
+ class EmptySetAtom {
3017
+ eval() {
3018
+ return [];
3019
+ }
3020
+ }
3021
+ class UnaryOperatorAtom {
3022
+ constructor(child, impl) {
3023
+ this.child = child;
3024
+ this.impl = impl;
3025
+ }
3026
+ eval(context) {
3027
+ return this.impl(this.child.eval(context));
3028
+ }
3029
+ }
3030
+ class AsAtom {
3031
+ constructor(left, right) {
3032
+ this.left = left;
3033
+ this.right = right;
3034
+ }
3035
+ eval(context) {
3036
+ return this.left.eval(context);
3037
+ }
3038
+ }
3039
+ class ArithemticOperatorAtom {
3040
+ constructor(left, right, impl) {
3041
+ this.left = left;
3042
+ this.right = right;
3043
+ this.impl = impl;
3044
+ }
3045
+ eval(context) {
3046
+ const leftEvalResult = this.left.eval(context);
3047
+ if (leftEvalResult.length !== 1) {
3048
+ return [];
3049
+ }
3050
+ const rightEvalResult = this.right.eval(context);
3051
+ if (rightEvalResult.length !== 1) {
3052
+ return [];
3053
+ }
3054
+ const leftValue = leftEvalResult[0].value;
3055
+ const rightValue = rightEvalResult[0].value;
3056
+ const leftNumber = isQuantity(leftValue) ? leftValue.value : leftValue;
3057
+ const rightNumber = isQuantity(rightValue) ? rightValue.value : rightValue;
3058
+ const result = this.impl(leftNumber, rightNumber);
3059
+ if (typeof result === 'boolean') {
3060
+ return booleanToTypedValue(result);
3061
+ }
3062
+ else if (isQuantity(leftValue)) {
3063
+ return [{ type: PropertyType.Quantity, value: Object.assign(Object.assign({}, leftValue), { value: result }) }];
3064
+ }
3065
+ else {
3066
+ return [toTypedValue(result)];
3067
+ }
3068
+ }
3069
+ }
3070
+ class ConcatAtom {
3071
+ constructor(left, right) {
3072
+ this.left = left;
3073
+ this.right = right;
3074
+ }
3075
+ eval(context) {
3076
+ const leftValue = this.left.eval(context);
3077
+ const rightValue = this.right.eval(context);
3078
+ const result = [...leftValue, ...rightValue];
3079
+ if (result.length > 0 && result.every((e) => typeof e.value === 'string')) {
3080
+ return [{ type: PropertyType.string, value: result.map((e) => e.value).join('') }];
3081
+ }
3082
+ return result;
3083
+ }
3084
+ }
3085
+ class ContainsAtom {
3086
+ constructor(left, right) {
3087
+ this.left = left;
3088
+ this.right = right;
3089
+ }
3090
+ eval(context) {
3091
+ const leftValue = this.left.eval(context);
3092
+ const rightValue = this.right.eval(context);
3093
+ return booleanToTypedValue(leftValue.some((e) => e.value === rightValue[0].value));
3094
+ }
3095
+ }
3096
+ class InAtom {
3097
+ constructor(left, right) {
3098
+ this.left = left;
3099
+ this.right = right;
3100
+ }
3101
+ eval(context) {
3102
+ const leftValue = this.left.eval(context);
3103
+ const rightValue = this.right.eval(context);
3104
+ return booleanToTypedValue(rightValue.some((e) => e.value === leftValue[0].value));
3105
+ }
3106
+ }
3107
+ class DotAtom {
3108
+ constructor(left, right) {
3109
+ this.left = left;
3110
+ this.right = right;
3111
+ }
3112
+ eval(context) {
3113
+ return this.right.eval(this.left.eval(context));
3114
+ }
3115
+ }
3116
+ class UnionAtom {
3117
+ constructor(left, right) {
3118
+ this.left = left;
3119
+ this.right = right;
3120
+ }
3121
+ eval(context) {
3122
+ const leftResult = this.left.eval(context);
3123
+ const rightResult = this.right.eval(context);
3124
+ return removeDuplicates([...leftResult, ...rightResult]);
3125
+ }
3126
+ }
3127
+ class EqualsAtom {
3128
+ constructor(left, right) {
3129
+ this.left = left;
3130
+ this.right = right;
3131
+ }
3132
+ eval(context) {
3133
+ const leftValue = this.left.eval(context);
3134
+ const rightValue = this.right.eval(context);
3135
+ return fhirPathArrayEquals(leftValue, rightValue);
3136
+ }
3137
+ }
3138
+ class NotEqualsAtom {
3139
+ constructor(left, right) {
3140
+ this.left = left;
3141
+ this.right = right;
3142
+ }
3143
+ eval(context) {
3144
+ const leftValue = this.left.eval(context);
3145
+ const rightValue = this.right.eval(context);
3146
+ return fhirPathNot(fhirPathArrayEquals(leftValue, rightValue));
3147
+ }
3148
+ }
3149
+ class EquivalentAtom {
3150
+ constructor(left, right) {
3151
+ this.left = left;
3152
+ this.right = right;
3153
+ }
3154
+ eval(context) {
3155
+ const leftValue = this.left.eval(context);
3156
+ const rightValue = this.right.eval(context);
3157
+ return fhirPathArrayEquivalent(leftValue, rightValue);
3158
+ }
3159
+ }
3160
+ class NotEquivalentAtom {
3161
+ constructor(left, right) {
3162
+ this.left = left;
3163
+ this.right = right;
3164
+ }
3165
+ eval(context) {
3166
+ const leftValue = this.left.eval(context);
3167
+ const rightValue = this.right.eval(context);
3168
+ return fhirPathNot(fhirPathArrayEquivalent(leftValue, rightValue));
3169
+ }
3170
+ }
3171
+ class IsAtom {
3172
+ constructor(left, right) {
3173
+ this.left = left;
3174
+ this.right = right;
3175
+ }
3176
+ eval(context) {
3177
+ const leftValue = this.left.eval(context);
3178
+ if (leftValue.length !== 1) {
3179
+ return [];
3180
+ }
3181
+ const typeName = this.right.name;
3182
+ return booleanToTypedValue(fhirPathIs(leftValue[0], typeName));
3183
+ }
3184
+ }
3185
+ /**
3186
+ * 6.5.1. and
3187
+ * Returns true if both operands evaluate to true, false if either operand evaluates to false, and the empty collection ({ }) otherwise.
3188
+ */
3189
+ class AndAtom {
3190
+ constructor(left, right) {
3191
+ this.left = left;
3192
+ this.right = right;
3193
+ }
3194
+ eval(context) {
3195
+ var _a, _b, _c, _d;
3196
+ const leftValue = this.left.eval(context);
3197
+ const rightValue = this.right.eval(context);
3198
+ if (((_a = leftValue[0]) === null || _a === void 0 ? void 0 : _a.value) === true && ((_b = rightValue[0]) === null || _b === void 0 ? void 0 : _b.value) === true) {
3199
+ return booleanToTypedValue(true);
3200
+ }
3201
+ if (((_c = leftValue[0]) === null || _c === void 0 ? void 0 : _c.value) === false || ((_d = rightValue[0]) === null || _d === void 0 ? void 0 : _d.value) === false) {
3202
+ return booleanToTypedValue(false);
3203
+ }
3204
+ return [];
3205
+ }
3206
+ }
3207
+ class OrAtom {
3208
+ constructor(left, right) {
3209
+ this.left = left;
3210
+ this.right = right;
3211
+ }
3212
+ eval(context) {
3213
+ const leftValue = this.left.eval(context);
3214
+ if (toJsBoolean(leftValue)) {
3215
+ return leftValue;
3216
+ }
3217
+ const rightValue = this.right.eval(context);
3218
+ if (toJsBoolean(rightValue)) {
3219
+ return rightValue;
3220
+ }
3221
+ return [];
3222
+ }
3223
+ }
3224
+ /**
3225
+ * 6.5.4. xor
3226
+ * Returns true if exactly one of the operands evaluates to true,
3227
+ * false if either both operands evaluate to true or both operands evaluate to false,
3228
+ * and the empty collection ({ }) otherwise:
3229
+ */
3230
+ class XorAtom {
3231
+ constructor(left, right) {
3232
+ this.left = left;
3233
+ this.right = right;
3234
+ }
3235
+ eval(context) {
3236
+ const leftResult = this.left.eval(context);
3237
+ const rightResult = this.right.eval(context);
3238
+ if (leftResult.length === 0 && rightResult.length === 0) {
3239
+ return [];
3240
+ }
3241
+ const leftValue = leftResult.length === 0 ? null : leftResult[0].value;
3242
+ const rightValue = rightResult.length === 0 ? null : rightResult[0].value;
3243
+ if ((leftValue === true && rightValue !== true) || (leftValue !== true && rightValue === true)) {
3244
+ return booleanToTypedValue(true);
3245
+ }
3246
+ if ((leftValue === true && rightValue === true) || (leftValue === false && rightValue === false)) {
3247
+ return booleanToTypedValue(false);
3248
+ }
3249
+ return [];
3250
+ }
3251
+ }
3252
+ class FunctionAtom {
3253
+ constructor(name, args, impl) {
3254
+ this.name = name;
3255
+ this.args = args;
3256
+ this.impl = impl;
3257
+ }
3258
+ eval(context) {
3259
+ return this.impl(context, ...this.args);
3260
+ }
3261
+ }
3262
+ class IndexerAtom {
3263
+ constructor(left, expr) {
3264
+ this.left = left;
3265
+ this.expr = expr;
3266
+ }
3267
+ eval(context) {
3268
+ const evalResult = this.expr.eval(context);
3269
+ if (evalResult.length !== 1) {
3270
+ return [];
3271
+ }
3272
+ const index = evalResult[0].value;
3273
+ if (typeof index !== 'number') {
3274
+ throw new Error(`Invalid indexer expression: should return integer}`);
3275
+ }
3276
+ const leftResult = this.left.eval(context);
3277
+ if (!(index in leftResult)) {
3278
+ return [];
3279
+ }
3280
+ return [leftResult[index]];
3281
+ }
3282
+ }
3283
+
3284
+ function parseDateString(str) {
3285
+ if (str.startsWith('T')) {
3286
+ // If a time string,
3287
+ // then normalize to full length.
3288
+ return str + 'T00:00:00.000Z'.substring(str.length);
3289
+ }
3290
+ if (str.length <= 10) {
3291
+ // If a local date (i.e., "2021-01-01"),
3292
+ // then return as-is.
3293
+ return str;
3294
+ }
3295
+ try {
3296
+ // Try to normalize to UTC
3297
+ return new Date(str).toISOString();
3298
+ }
3299
+ catch (e) {
3300
+ // Fallback to original input
3301
+ // This happens on unsupported time formats such as "2021-01-01T12"
3302
+ return str;
3303
+ }
3304
+ }
3305
+
3306
+ /**
3307
+ * Temporary placholder for unimplemented methods.
3308
+ */
3309
+ const stub = () => [];
3310
+ const functions = {
3311
+ /*
3312
+ * 5.1 Existence
3313
+ * See: https://hl7.org/fhirpath/#existence
3314
+ */
3315
+ /**
3316
+ * Returns true if the input collection is empty ({ }) and false otherwise.
3317
+ *
3318
+ * See: https://hl7.org/fhirpath/#empty-boolean
3319
+ *
3320
+ * @param input The input collection.
3321
+ * @returns True if the input collection is empty ({ }) and false otherwise.
3322
+ */
3323
+ empty: (input) => {
3324
+ return booleanToTypedValue(input.length === 0);
3325
+ },
3326
+ /**
3327
+ * Returns true if the collection has unknown elements, and false otherwise.
3328
+ * This is the opposite of empty(), and as such is a shorthand for empty().not().
3329
+ * If the input collection is empty ({ }), the result is false.
3330
+ *
3331
+ * The function can also take an optional criteria to be applied to the collection
3332
+ * prior to the determination of the exists. In this case, the function is shorthand
3333
+ * for where(criteria).exists().
3334
+ *
3335
+ * See: https://hl7.org/fhirpath/#existscriteria-expression-boolean
3336
+ *
3337
+ * @param input
3338
+ * @param criteria
3339
+ * @returns True if the collection has unknown elements, and false otherwise.
3340
+ */
3341
+ exists: (input, criteria) => {
3342
+ if (criteria) {
3343
+ return booleanToTypedValue(input.filter((e) => toJsBoolean(criteria.eval([e]))).length > 0);
3344
+ }
3345
+ else {
3346
+ return booleanToTypedValue(input.length > 0);
3347
+ }
3348
+ },
3349
+ /**
3350
+ * Returns true if for every element in the input collection, criteria evaluates to true.
3351
+ * Otherwise, the result is false.
3352
+ *
3353
+ * If the input collection is empty ({ }), the result is true.
3354
+ *
3355
+ * See: https://hl7.org/fhirpath/#allcriteria-expression-boolean
3356
+ *
3357
+ * @param input The input collection.
3358
+ * @param criteria The evaluation criteria.
3359
+ * @returns True if for every element in the input collection, criteria evaluates to true.
3360
+ */
3361
+ all: (input, criteria) => {
3362
+ return booleanToTypedValue(input.every((e) => toJsBoolean(criteria.eval([e]))));
3363
+ },
3364
+ /**
3365
+ * Takes a collection of Boolean values and returns true if all the items are true.
3366
+ * If unknown items are false, the result is false.
3367
+ * If the input is empty ({ }), the result is true.
3368
+ *
3369
+ * See: https://hl7.org/fhirpath/#alltrue-boolean
3370
+ *
3371
+ * @param input The input collection.
3372
+ * @param criteria The evaluation criteria.
3373
+ * @returns True if all the items are true.
3374
+ */
3375
+ allTrue: (input) => {
3376
+ for (const value of input) {
3377
+ if (!value.value) {
3378
+ return booleanToTypedValue(false);
3379
+ }
3380
+ }
3381
+ return booleanToTypedValue(true);
3382
+ },
3383
+ /**
3384
+ * Takes a collection of Boolean values and returns true if unknown of the items are true.
3385
+ * If all the items are false, or if the input is empty ({ }), the result is false.
3386
+ *
3387
+ * See: https://hl7.org/fhirpath/#anytrue-boolean
3388
+ *
3389
+ * @param input The input collection.
3390
+ * @param criteria The evaluation criteria.
3391
+ * @returns True if unknown of the items are true.
3392
+ */
3393
+ anyTrue: (input) => {
3394
+ for (const value of input) {
3395
+ if (value.value) {
3396
+ return booleanToTypedValue(true);
3397
+ }
3398
+ }
3399
+ return booleanToTypedValue(false);
3400
+ },
3401
+ /**
3402
+ * Takes a collection of Boolean values and returns true if all the items are false.
3403
+ * If unknown items are true, the result is false.
3404
+ * If the input is empty ({ }), the result is true.
3405
+ *
3406
+ * See: https://hl7.org/fhirpath/#allfalse-boolean
3407
+ *
3408
+ * @param input The input collection.
3409
+ * @param criteria The evaluation criteria.
3410
+ * @returns True if all the items are false.
3411
+ */
3412
+ allFalse: (input) => {
3413
+ for (const value of input) {
3414
+ if (value.value) {
3415
+ return booleanToTypedValue(false);
3416
+ }
3417
+ }
3418
+ return booleanToTypedValue(true);
3419
+ },
3420
+ /**
3421
+ * Takes a collection of Boolean values and returns true if unknown of the items are false.
3422
+ * If all the items are true, or if the input is empty ({ }), the result is false.
3423
+ *
3424
+ * See: https://hl7.org/fhirpath/#anyfalse-boolean
3425
+ *
3426
+ * @param input The input collection.
3427
+ * @param criteria The evaluation criteria.
3428
+ * @returns True if for every element in the input collection, criteria evaluates to true.
3429
+ */
3430
+ anyFalse: (input) => {
3431
+ for (const value of input) {
3432
+ if (!value.value) {
3433
+ return booleanToTypedValue(true);
3434
+ }
3435
+ }
3436
+ return booleanToTypedValue(false);
3437
+ },
3438
+ /**
3439
+ * Returns true if all items in the input collection are members of the collection passed
3440
+ * as the other argument. Membership is determined using the = (Equals) (=) operation.
3441
+ *
3442
+ * Conceptually, this function is evaluated by testing each element in the input collection
3443
+ * for membership in the other collection, with a default of true. This means that if the
3444
+ * input collection is empty ({ }), the result is true, otherwise if the other collection
3445
+ * is empty ({ }), the result is false.
3446
+ *
3447
+ * See: http://hl7.org/fhirpath/#subsetofother-collection-boolean
3448
+ */
3449
+ subsetOf: stub,
3450
+ /**
3451
+ * Returns true if all items in the collection passed as the other argument are members of
3452
+ * the input collection. Membership is determined using the = (Equals) (=) operation.
3453
+ *
3454
+ * Conceptually, this function is evaluated by testing each element in the other collection
3455
+ * for membership in the input collection, with a default of true. This means that if the
3456
+ * other collection is empty ({ }), the result is true, otherwise if the input collection
3457
+ * is empty ({ }), the result is false.
3458
+ *
3459
+ * See: http://hl7.org/fhirpath/#supersetofother-collection-boolean
3460
+ */
3461
+ supersetOf: stub,
3462
+ /**
3463
+ * Returns the integer count of the number of items in the input collection.
3464
+ * Returns 0 when the input collection is empty.
3465
+ *
3466
+ * See: https://hl7.org/fhirpath/#count-integer
3467
+ *
3468
+ * @param input The input collection.
3469
+ * @returns The integer count of the number of items in the input collection.
3470
+ */
3471
+ count: (input) => {
3472
+ return [{ type: PropertyType.integer, value: input.length }];
3473
+ },
3474
+ /**
3475
+ * Returns a collection containing only the unique items in the input collection.
3476
+ * To determine whether two items are the same, the = (Equals) (=) operator is used,
3477
+ * as defined below.
3478
+ *
3479
+ * If the input collection is empty ({ }), the result is empty.
3480
+ *
3481
+ * Note that the order of elements in the input collection is not guaranteed to be
3482
+ * preserved in the result.
3483
+ *
3484
+ * See: https://hl7.org/fhirpath/#distinct-collection
3485
+ *
3486
+ * @param input The input collection.
3487
+ * @returns The integer count of the number of items in the input collection.
3488
+ */
3489
+ distinct: (input) => {
3490
+ const result = [];
3491
+ for (const value of input) {
3492
+ if (!result.some((e) => e.value === value.value)) {
3493
+ result.push(value);
3494
+ }
3495
+ }
3496
+ return result;
3497
+ },
3498
+ /**
3499
+ * Returns true if all the items in the input collection are distinct.
3500
+ * To determine whether two items are distinct, the = (Equals) (=) operator is used,
3501
+ * as defined below.
3502
+ *
3503
+ * See: https://hl7.org/fhirpath/#isdistinct-boolean
3504
+ *
3505
+ * @param input The input collection.
3506
+ * @returns The integer count of the number of items in the input collection.
3507
+ */
3508
+ isDistinct: (input) => {
3509
+ return booleanToTypedValue(input.length === functions.distinct(input).length);
3510
+ },
3511
+ /*
3512
+ * 5.2 Filtering and projection
3513
+ */
3514
+ /**
3515
+ * Returns a collection containing only those elements in the input collection
3516
+ * for which the stated criteria expression evaluates to true.
3517
+ * Elements for which the expression evaluates to false or empty ({ }) are not
3518
+ * included in the result.
3519
+ *
3520
+ * If the input collection is empty ({ }), the result is empty.
3521
+ *
3522
+ * If the result of evaluating the condition is other than a single boolean value,
3523
+ * the evaluation will end and signal an error to the calling environment,
3524
+ * consistent with singleton evaluation of collections behavior.
3525
+ *
3526
+ * See: https://hl7.org/fhirpath/#wherecriteria-expression-collection
3527
+ *
3528
+ * @param input The input collection.
3529
+ * @param condition The condition atom.
3530
+ * @returns A collection containing only those elements in the input collection for which the stated criteria expression evaluates to true.
3531
+ */
3532
+ where: (input, criteria) => {
3533
+ return input.filter((e) => toJsBoolean(criteria.eval([e])));
3534
+ },
3535
+ /**
3536
+ * Evaluates the projection expression for each item in the input collection.
3537
+ * The result of each evaluation is added to the output collection. If the
3538
+ * evaluation results in a collection with multiple items, all items are added
3539
+ * to the output collection (collections resulting from evaluation of projection
3540
+ * are flattened). This means that if the evaluation for an element results in
3541
+ * the empty collection ({ }), no element is added to the result, and that if
3542
+ * the input collection is empty ({ }), the result is empty as well.
3543
+ *
3544
+ * See: http://hl7.org/fhirpath/#selectprojection-expression-collection
3545
+ */
3546
+ select: (input, criteria) => {
3547
+ return input.map((e) => criteria.eval([e])).flat();
3548
+ },
3549
+ /**
3550
+ * A version of select that will repeat the projection and add it to the output
3551
+ * collection, as long as the projection yields new items (as determined by
3552
+ * the = (Equals) (=) operator).
3553
+ *
3554
+ * See: http://hl7.org/fhirpath/#repeatprojection-expression-collection
3555
+ */
3556
+ repeat: stub,
3557
+ /**
3558
+ * Returns a collection that contains all items in the input collection that
3559
+ * are of the given type or a subclass thereof. If the input collection is
3560
+ * empty ({ }), the result is empty. The type argument is an identifier that
3561
+ * must resolve to the name of a type in a model
3562
+ *
3563
+ * See: http://hl7.org/fhirpath/#oftypetype-type-specifier-collection
3564
+ */
3565
+ ofType: stub,
3566
+ /*
3567
+ * 5.3 Subsetting
3568
+ */
3569
+ /**
3570
+ * Will return the single item in the input if there is just one item.
3571
+ * If the input collection is empty ({ }), the result is empty.
3572
+ * If there are multiple items, an error is signaled to the evaluation environment.
3573
+ * This function is useful for ensuring that an error is returned if an assumption
3574
+ * about cardinality is violated at run-time.
3575
+ *
3576
+ * See: https://hl7.org/fhirpath/#single-collection
3577
+ *
3578
+ * @param input The input collection.
3579
+ * @returns The single item in the input if there is just one item.
3580
+ */
3581
+ single: (input) => {
3582
+ if (input.length > 1) {
3583
+ throw new Error('Expected input length one for single()');
3584
+ }
3585
+ return input.length === 0 ? [] : input.slice(0, 1);
3586
+ },
3587
+ /**
3588
+ * Returns a collection containing only the first item in the input collection.
3589
+ * This function is equivalent to item[0], so it will return an empty collection if the input collection has no items.
3590
+ *
3591
+ * See: https://hl7.org/fhirpath/#first-collection
3592
+ *
3593
+ * @param input The input collection.
3594
+ * @returns A collection containing only the first item in the input collection.
3595
+ */
3596
+ first: (input) => {
3597
+ return input.length === 0 ? [] : input.slice(0, 1);
3598
+ },
3599
+ /**
3600
+ * Returns a collection containing only the last item in the input collection.
3601
+ * Will return an empty collection if the input collection has no items.
3602
+ *
3603
+ * See: https://hl7.org/fhirpath/#last-collection
3604
+ *
3605
+ * @param input The input collection.
3606
+ * @returns A collection containing only the last item in the input collection.
3607
+ */
3608
+ last: (input) => {
3609
+ return input.length === 0 ? [] : input.slice(input.length - 1, input.length);
3610
+ },
3611
+ /**
3612
+ * Returns a collection containing all but the first item in the input collection.
3613
+ * Will return an empty collection if the input collection has no items, or only one item.
3614
+ *
3615
+ * See: https://hl7.org/fhirpath/#tail-collection
3616
+ *
3617
+ * @param input The input collection.
3618
+ * @returns A collection containing all but the first item in the input collection.
3619
+ */
3620
+ tail: (input) => {
3621
+ return input.length === 0 ? [] : input.slice(1, input.length);
3622
+ },
3623
+ /**
3624
+ * Returns a collection containing all but the first num items in the input collection.
3625
+ * Will return an empty collection if there are no items remaining after the
3626
+ * indicated number of items have been skipped, or if the input collection is empty.
3627
+ * If num is less than or equal to zero, the input collection is simply returned.
3628
+ *
3629
+ * See: https://hl7.org/fhirpath/#skipnum-integer-collection
3630
+ *
3631
+ * @param input The input collection.
3632
+ * @returns A collection containing all but the first item in the input collection.
3633
+ */
3634
+ skip: (input, num) => {
3635
+ var _a;
3636
+ const numValue = (_a = num.eval([])[0]) === null || _a === void 0 ? void 0 : _a.value;
3637
+ if (typeof numValue !== 'number') {
3638
+ throw new Error('Expected a number for skip(num)');
3639
+ }
3640
+ if (numValue >= input.length) {
3641
+ return [];
3642
+ }
3643
+ if (numValue <= 0) {
3644
+ return input;
3645
+ }
3646
+ return input.slice(numValue, input.length);
3647
+ },
3648
+ /**
3649
+ * Returns a collection containing the first num items in the input collection,
3650
+ * or less if there are less than num items.
3651
+ * If num is less than or equal to 0, or if the input collection is empty ({ }),
3652
+ * take returns an empty collection.
3653
+ *
3654
+ * See: https://hl7.org/fhirpath/#takenum-integer-collection
3655
+ *
3656
+ * @param input The input collection.
3657
+ * @returns A collection containing the first num items in the input collection.
3658
+ */
3659
+ take: (input, num) => {
3660
+ var _a;
3661
+ const numValue = (_a = num.eval([])[0]) === null || _a === void 0 ? void 0 : _a.value;
3662
+ if (typeof numValue !== 'number') {
3663
+ throw new Error('Expected a number for take(num)');
3664
+ }
3665
+ if (numValue >= input.length) {
3666
+ return input;
3667
+ }
3668
+ if (numValue <= 0) {
3669
+ return [];
3670
+ }
3671
+ return input.slice(0, numValue);
3672
+ },
3673
+ /**
3674
+ * Returns the set of elements that are in both collections.
3675
+ * Duplicate items will be eliminated by this function.
3676
+ * Order of items is not guaranteed to be preserved in the result of this function.
3677
+ *
3678
+ * See: http://hl7.org/fhirpath/#intersectother-collection-collection
3679
+ */
3680
+ intersect: (input, other) => {
3681
+ if (!other) {
3682
+ return input;
3683
+ }
3684
+ const otherArray = other.eval([]);
3685
+ const result = [];
3686
+ for (const value of input) {
3687
+ if (!result.some((e) => e.value === value.value) && otherArray.some((e) => e.value === value.value)) {
3688
+ result.push(value);
3689
+ }
3690
+ }
3691
+ return result;
3692
+ },
3693
+ /**
3694
+ * Returns the set of elements that are not in the other collection.
3695
+ * Duplicate items will not be eliminated by this function, and order will be preserved.
3696
+ *
3697
+ * e.g. (1 | 2 | 3).exclude(2) returns (1 | 3).
3698
+ *
3699
+ * See: http://hl7.org/fhirpath/#excludeother-collection-collection
3700
+ */
3701
+ exclude: (input, other) => {
3702
+ if (!other) {
3703
+ return input;
3704
+ }
3705
+ const otherArray = other.eval([]);
3706
+ const result = [];
3707
+ for (const value of input) {
3708
+ if (!otherArray.some((e) => e.value === value.value)) {
3709
+ result.push(value);
3710
+ }
3711
+ }
3712
+ return result;
3713
+ },
3714
+ /*
3715
+ * 5.4. Combining
3716
+ *
3717
+ * See: https://hl7.org/fhirpath/#combining
3718
+ */
3719
+ /**
3720
+ * Merge the two collections into a single collection,
3721
+ * eliminating unknown duplicate values (using = (Equals) (=) to determine equality).
3722
+ * There is no expectation of order in the resulting collection.
3723
+ *
3724
+ * In other words, this function returns the distinct list of elements from both inputs.
3725
+ *
3726
+ * See: http://hl7.org/fhirpath/#unionother-collection
3727
+ */
3728
+ union: (input, other) => {
3729
+ if (!other) {
3730
+ return input;
3731
+ }
3732
+ const otherArray = other.eval([]);
3733
+ return removeDuplicates([...input, ...otherArray]);
3734
+ },
3735
+ /**
3736
+ * Merge the input and other collections into a single collection
3737
+ * without eliminating duplicate values. Combining an empty collection
3738
+ * with a non-empty collection will return the non-empty collection.
3739
+ *
3740
+ * There is no expectation of order in the resulting collection.
3741
+ *
3742
+ * See: http://hl7.org/fhirpath/#combineother-collection-collection
3743
+ */
3744
+ combine: (input, other) => {
3745
+ if (!other) {
3746
+ return input;
3747
+ }
3748
+ const otherArray = other.eval([]);
3749
+ return [...input, ...otherArray];
3750
+ },
3751
+ /*
3752
+ * 5.5. Conversion
3753
+ *
3754
+ * See: https://hl7.org/fhirpath/#conversion
3755
+ */
3756
+ /**
3757
+ * The iif function in FHIRPath is an immediate if,
3758
+ * also known as a conditional operator (such as C’s ? : operator).
3759
+ *
3760
+ * The criterion expression is expected to evaluate to a Boolean.
3761
+ *
3762
+ * If criterion is true, the function returns the value of the true-result argument.
3763
+ *
3764
+ * If criterion is false or an empty collection, the function returns otherwise-result,
3765
+ * unless the optional otherwise-result is not given, in which case the function returns an empty collection.
3766
+ *
3767
+ * Note that short-circuit behavior is expected in this function. In other words,
3768
+ * true-result should only be evaluated if the criterion evaluates to true,
3769
+ * and otherwise-result should only be evaluated otherwise. For implementations,
3770
+ * this means delaying evaluation of the arguments.
3771
+ *
3772
+ * @param input
3773
+ * @param criterion
3774
+ * @param trueResult
3775
+ * @param otherwiseResult
3776
+ * @returns
3777
+ */
3778
+ iif: (input, criterion, trueResult, otherwiseResult) => {
3779
+ const evalResult = criterion.eval(input);
3780
+ if (evalResult.length > 1 || (evalResult.length === 1 && typeof evalResult[0].value !== 'boolean')) {
3781
+ throw new Error('Expected criterion to evaluate to a Boolean');
3782
+ }
3783
+ if (toJsBoolean(evalResult)) {
3784
+ return trueResult.eval(input);
3785
+ }
3786
+ if (otherwiseResult) {
3787
+ return otherwiseResult.eval(input);
3788
+ }
3789
+ return [];
3790
+ },
3791
+ /**
3792
+ * Converts an input collection to a boolean.
3793
+ *
3794
+ * If the input collection contains a single item, this function will return a single boolean if:
3795
+ * 1) the item is a Boolean
3796
+ * 2) the item is an Integer and is equal to one of the possible integer representations of Boolean values
3797
+ * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
3798
+ * 4) the item is a String that is equal to one of the possible string representations of Boolean values
3799
+ *
3800
+ * If the item is not one the above types, or the item is a String, Integer, or Decimal, but is not equal to one of the possible values convertible to a Boolean, the result is empty.
3801
+ *
3802
+ * See: https://hl7.org/fhirpath/#toboolean-boolean
3803
+ *
3804
+ * @param input
3805
+ * @returns
3806
+ */
3807
+ toBoolean: (input) => {
3808
+ if (input.length === 0) {
3809
+ return [];
3810
+ }
3811
+ const [{ value }] = validateInput(input, 1);
3812
+ if (typeof value === 'boolean') {
3813
+ return [{ type: PropertyType.boolean, value }];
3814
+ }
3815
+ if (typeof value === 'number') {
3816
+ if (value === 0 || value === 1) {
3817
+ return booleanToTypedValue(!!value);
3818
+ }
3819
+ }
3820
+ if (typeof value === 'string') {
3821
+ const lowerStr = value.toLowerCase();
3822
+ if (['true', 't', 'yes', 'y', '1', '1.0'].includes(lowerStr)) {
3823
+ return booleanToTypedValue(true);
3824
+ }
3825
+ if (['false', 'f', 'no', 'n', '0', '0.0'].includes(lowerStr)) {
3826
+ return booleanToTypedValue(false);
3827
+ }
3828
+ }
3829
+ return [];
3830
+ },
3831
+ /**
3832
+ * If the input collection contains a single item, this function will return true if:
3833
+ * 1) the item is a Boolean
3834
+ * 2) the item is an Integer that is equal to one of the possible integer representations of Boolean values
3835
+ * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
3836
+ * 4) the item is a String that is equal to one of the possible string representations of Boolean values
3837
+ *
3838
+ * If the item is not one of the above types, or the item is a String, Integer, or Decimal, but is not equal to one of the possible values convertible to a Boolean, the result is false.
3839
+ *
3840
+ * Possible values for Integer, Decimal, and String are described in the toBoolean() function.
3841
+ *
3842
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3843
+ *
3844
+ * If the input collection is empty, the result is empty.
3845
+ *
3846
+ * See: http://hl7.org/fhirpath/#convertstoboolean-boolean
3847
+ *
3848
+ * @param input
3849
+ * @returns
3850
+ */
3851
+ convertsToBoolean: (input) => {
3852
+ if (input.length === 0) {
3853
+ return [];
3854
+ }
3855
+ return booleanToTypedValue(functions.toBoolean(input).length === 1);
3856
+ },
3857
+ /**
3858
+ * Returns the integer representation of the input.
3859
+ *
3860
+ * If the input collection contains a single item, this function will return a single integer if:
3861
+ * 1) the item is an Integer
3862
+ * 2) the item is a String and is convertible to an integer
3863
+ * 3) the item is a Boolean, where true results in a 1 and false results in a 0.
3864
+ *
3865
+ * If the item is not one the above types, the result is empty.
3866
+ *
3867
+ * If the item is a String, but the string is not convertible to an integer (using the regex format (\\+|-)?\d+), the result is empty.
3868
+ *
3869
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3870
+ *
3871
+ * If the input collection is empty, the result is empty.
3872
+ *
3873
+ * See: https://hl7.org/fhirpath/#tointeger-integer
3874
+ *
3875
+ * @param input The input collection.
3876
+ * @returns The string representation of the input.
3877
+ */
3878
+ toInteger: (input) => {
3879
+ if (input.length === 0) {
3880
+ return [];
3881
+ }
3882
+ const [{ value }] = validateInput(input, 1);
3883
+ if (typeof value === 'number') {
3884
+ return [{ type: PropertyType.integer, value }];
3885
+ }
3886
+ if (typeof value === 'string' && value.match(/^[+-]?\d+$/)) {
3887
+ return [{ type: PropertyType.integer, value: parseInt(value, 10) }];
3888
+ }
3889
+ if (typeof value === 'boolean') {
3890
+ return [{ type: PropertyType.integer, value: value ? 1 : 0 }];
3891
+ }
3892
+ return [];
3893
+ },
3894
+ /**
3895
+ * Returns true if the input can be converted to string.
3896
+ *
3897
+ * If the input collection contains a single item, this function will return true if:
3898
+ * 1) the item is an Integer
3899
+ * 2) the item is a String and is convertible to an Integer
3900
+ * 3) the item is a Boolean
3901
+ * 4) If the item is not one of the above types, or the item is a String, but is not convertible to an Integer (using the regex format (\\+|-)?\d+), the result is false.
3902
+ *
3903
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3904
+ *
3905
+ * If the input collection is empty, the result is empty.
3906
+ *
3907
+ * See: https://hl7.org/fhirpath/#convertstointeger-boolean
3908
+ *
3909
+ * @param input The input collection.
3910
+ * @returns
3911
+ */
3912
+ convertsToInteger: (input) => {
3913
+ if (input.length === 0) {
3914
+ return [];
3915
+ }
3916
+ return booleanToTypedValue(functions.toInteger(input).length === 1);
3917
+ },
3918
+ /**
3919
+ * If the input collection contains a single item, this function will return a single date if:
3920
+ * 1) the item is a Date
3921
+ * 2) the item is a DateTime
3922
+ * 3) the item is a String and is convertible to a Date
3923
+ *
3924
+ * If the item is not one of the above types, the result is empty.
3925
+ *
3926
+ * If the item is a String, but the string is not convertible to a Date (using the format YYYY-MM-DD), the result is empty.
3927
+ *
3928
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3929
+ *
3930
+ * If the input collection is empty, the result is empty.
3931
+ *
3932
+ * See: https://hl7.org/fhirpath/#todate-date
3933
+ */
3934
+ toDate: (input) => {
3935
+ if (input.length === 0) {
3936
+ return [];
3937
+ }
3938
+ const [{ value }] = validateInput(input, 1);
3939
+ if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
3940
+ return [{ type: PropertyType.date, value: parseDateString(value) }];
3941
+ }
3942
+ return [];
3943
+ },
3944
+ /**
3945
+ * If the input collection contains a single item, this function will return true if:
3946
+ * 1) the item is a Date
3947
+ * 2) the item is a DateTime
3948
+ * 3) the item is a String and is convertible to a Date
3949
+ *
3950
+ * If the item is not one of the above types, or is not convertible to a Date (using the format YYYY-MM-DD), the result is false.
3951
+ *
3952
+ * If the item contains a partial date (e.g. '2012-01'), the result is a partial date.
3953
+ *
3954
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3955
+ *
3956
+ * If the input collection is empty, the result is empty.
3957
+ *
3958
+ * See: https://hl7.org/fhirpath/#convertstodate-boolean
3959
+ */
3960
+ convertsToDate: (input) => {
3961
+ if (input.length === 0) {
3962
+ return [];
3963
+ }
3964
+ return booleanToTypedValue(functions.toDate(input).length === 1);
3965
+ },
3966
+ /**
3967
+ * If the input collection contains a single item, this function will return a single datetime if:
3968
+ * 1) the item is a DateTime
3969
+ * 2) the item is a Date, in which case the result is a DateTime with the year, month, and day of the Date, and the time components empty (not set to zero)
3970
+ * 3) the item is a String and is convertible to a DateTime
3971
+ *
3972
+ * If the item is not one of the above types, the result is empty.
3973
+ *
3974
+ * If the item is a String, but the string is not convertible to a DateTime (using the format YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mm), the result is empty.
3975
+ *
3976
+ * If the item contains a partial datetime (e.g. '2012-01-01T10:00'), the result is a partial datetime.
3977
+ *
3978
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3979
+ *
3980
+ * If the input collection is empty, the result is empty.
3981
+
3982
+ * See: https://hl7.org/fhirpath/#todatetime-datetime
3983
+ *
3984
+ * @param input
3985
+ * @returns
3986
+ */
3987
+ toDateTime: (input) => {
3988
+ if (input.length === 0) {
3989
+ return [];
3990
+ }
3991
+ const [{ value }] = validateInput(input, 1);
3992
+ if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
3993
+ return [{ type: PropertyType.dateTime, value: parseDateString(value) }];
3994
+ }
3995
+ return [];
3996
+ },
3997
+ /**
3998
+ * If the input collection contains a single item, this function will return true if:
3999
+ * 1) the item is a DateTime
4000
+ * 2) the item is a Date
4001
+ * 3) the item is a String and is convertible to a DateTime
4002
+ *
4003
+ * If the item is not one of the above types, or is not convertible to a DateTime (using the format YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mm), the result is false.
4004
+ *
4005
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4006
+ *
4007
+ * If the input collection is empty, the result is empty.
4008
+ *
4009
+ * See: https://hl7.org/fhirpath/#convertstodatetime-boolean
4010
+ *
4011
+ * @param input
4012
+ * @returns
4013
+ */
4014
+ convertsToDateTime: (input) => {
4015
+ if (input.length === 0) {
4016
+ return [];
4017
+ }
4018
+ return booleanToTypedValue(functions.toDateTime(input).length === 1);
4019
+ },
4020
+ /**
4021
+ * If the input collection contains a single item, this function will return a single decimal if:
4022
+ * 1) the item is an Integer or Decimal
4023
+ * 2) the item is a String and is convertible to a Decimal
4024
+ * 3) the item is a Boolean, where true results in a 1.0 and false results in a 0.0.
4025
+ * 4) If the item is not one of the above types, the result is empty.
4026
+ *
4027
+ * If the item is a String, but the string is not convertible to a Decimal (using the regex format (\\+|-)?\d+(\.\d+)?), the result is empty.
4028
+ *
4029
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4030
+ *
4031
+ * If the input collection is empty, the result is empty.
4032
+ *
4033
+ * See: https://hl7.org/fhirpath/#decimal-conversion-functions
4034
+ *
4035
+ * @param input The input collection.
4036
+ * @returns
4037
+ */
4038
+ toDecimal: (input) => {
4039
+ if (input.length === 0) {
4040
+ return [];
4041
+ }
4042
+ const [{ value }] = validateInput(input, 1);
4043
+ if (typeof value === 'number') {
4044
+ return [{ type: PropertyType.decimal, value }];
4045
+ }
4046
+ if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?$/)) {
4047
+ return [{ type: PropertyType.decimal, value: parseFloat(value) }];
4048
+ }
4049
+ if (typeof value === 'boolean') {
4050
+ return [{ type: PropertyType.decimal, value: value ? 1 : 0 }];
4051
+ }
4052
+ return [];
4053
+ },
4054
+ /**
4055
+ * If the input collection contains a single item, this function will true if:
4056
+ * 1) the item is an Integer or Decimal
4057
+ * 2) the item is a String and is convertible to a Decimal
4058
+ * 3) the item is a Boolean
4059
+ *
4060
+ * If the item is not one of the above types, or is not convertible to a Decimal (using the regex format (\\+|-)?\d+(\.\d+)?), the result is false.
4061
+ *
4062
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4063
+ *
4064
+ * If the input collection is empty, the result is empty.
4065
+
4066
+ * See: https://hl7.org/fhirpath/#convertstodecimal-boolean
4067
+ *
4068
+ * @param input The input collection.
4069
+ * @returns
4070
+ */
4071
+ convertsToDecimal: (input) => {
4072
+ if (input.length === 0) {
4073
+ return [];
4074
+ }
4075
+ return booleanToTypedValue(functions.toDecimal(input).length === 1);
4076
+ },
4077
+ /**
4078
+ * If the input collection contains a single item, this function will return a single quantity if:
4079
+ * 1) the item is an Integer, or Decimal, where the resulting quantity will have the default unit ('1')
4080
+ * 2) the item is a Quantity
4081
+ * 3) the item is a String and is convertible to a Quantity
4082
+ * 4) the item is a Boolean, where true results in the quantity 1.0 '1', and false results in the quantity 0.0 '1'
4083
+ *
4084
+ * If the item is not one of the above types, the result is empty.
4085
+ *
4086
+ * See: https://hl7.org/fhirpath/#quantity-conversion-functions
4087
+ *
4088
+ * @param input The input collection.
4089
+ * @returns
4090
+ */
4091
+ toQuantity: (input) => {
4092
+ if (input.length === 0) {
4093
+ return [];
4094
+ }
4095
+ const [{ value }] = validateInput(input, 1);
4096
+ if (isQuantity(value)) {
4097
+ return [{ type: PropertyType.Quantity, value }];
4098
+ }
4099
+ if (typeof value === 'number') {
4100
+ return [{ type: PropertyType.Quantity, value: { value, unit: '1' } }];
4101
+ }
4102
+ if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?/)) {
4103
+ return [{ type: PropertyType.Quantity, value: { value: parseFloat(value), unit: '1' } }];
4104
+ }
4105
+ if (typeof value === 'boolean') {
4106
+ return [{ type: PropertyType.Quantity, value: { value: value ? 1 : 0, unit: '1' } }];
4107
+ }
4108
+ return [];
4109
+ },
4110
+ /**
4111
+ * If the input collection contains a single item, this function will return true if:
4112
+ * 1) the item is an Integer, Decimal, or Quantity
4113
+ * 2) the item is a String that is convertible to a Quantity
4114
+ * 3) the item is a Boolean
4115
+ *
4116
+ * If the item is not one of the above types, or is not convertible to a Quantity using the following regex format:
4117
+ *
4118
+ * (?'value'(\+|-)?\d+(\.\d+)?)\s*('(?'unit'[^']+)'|(?'time'[a-zA-Z]+))?
4119
+ *
4120
+ * then the result is false.
4121
+ *
4122
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4123
+ *
4124
+ * If the input collection is empty, the result is empty.
4125
+ *
4126
+ * If the unit argument is provided, it must be the string representation of a UCUM code (or a FHIRPath calendar duration keyword), and is used to determine whether the input quantity can be converted to the given unit, according to the unit conversion rules specified by UCUM. If the input quantity can be converted, the result is true, otherwise, the result is false.
4127
+ *
4128
+ * See: https://hl7.org/fhirpath/#convertstoquantityunit-string-boolean
4129
+ *
4130
+ * @param input The input collection.
4131
+ * @returns
4132
+ */
4133
+ convertsToQuantity: (input) => {
4134
+ if (input.length === 0) {
4135
+ return [];
4136
+ }
4137
+ return booleanToTypedValue(functions.toQuantity(input).length === 1);
4138
+ },
4139
+ /**
4140
+ * Returns the string representation of the input.
4141
+ *
4142
+ * If the input collection contains a single item, this function will return a single String if:
4143
+ *
4144
+ * 1) the item in the input collection is a String
4145
+ * 2) the item in the input collection is an Integer, Decimal, Date, Time, DateTime, or Quantity the output will contain its String representation
4146
+ * 3) the item is a Boolean, where true results in 'true' and false in 'false'.
4147
+ *
4148
+ * If the item is not one of the above types, the result is false.
4149
+ *
4150
+ * See: https://hl7.org/fhirpath/#tostring-string
4151
+ *
4152
+ * @param input The input collection.
4153
+ * @returns The string representation of the input.
4154
+ */
4155
+ toString: (input) => {
4156
+ if (input.length === 0) {
4157
+ return [];
4158
+ }
4159
+ const [{ value }] = validateInput(input, 1);
4160
+ if (value === null || value === undefined) {
4161
+ return [];
4162
+ }
4163
+ if (isQuantity(value)) {
4164
+ return [{ type: PropertyType.string, value: `${value.value} '${value.unit}'` }];
4165
+ }
4166
+ return [{ type: PropertyType.string, value: value.toString() }];
4167
+ },
4168
+ /**
4169
+ * Returns true if the input can be converted to string.
4170
+ *
4171
+ * If the input collection contains a single item, this function will return true if:
4172
+ * 1) the item is a String
4173
+ * 2) the item is an Integer, Decimal, Date, Time, or DateTime
4174
+ * 3) the item is a Boolean
4175
+ * 4) the item is a Quantity
4176
+ *
4177
+ * If the item is not one of the above types, the result is false.
4178
+ *
4179
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4180
+ *
4181
+ * If the input collection is empty, the result is empty.
4182
+ *
4183
+ * See: https://hl7.org/fhirpath/#tostring-string
4184
+ *
4185
+ * @param input The input collection.
4186
+ * @returns
4187
+ */
4188
+ convertsToString: (input) => {
4189
+ if (input.length === 0) {
4190
+ return [];
4191
+ }
4192
+ return booleanToTypedValue(functions.toString(input).length === 1);
4193
+ },
4194
+ /**
4195
+ * If the input collection contains a single item, this function will return a single time if:
4196
+ * 1) the item is a Time
4197
+ * 2) the item is a String and is convertible to a Time
4198
+ *
4199
+ * If the item is not one of the above types, the result is empty.
4200
+ *
4201
+ * If the item is a String, but the string is not convertible to a Time (using the format hh:mm:ss.fff(+|-)hh:mm), the result is empty.
4202
+ *
4203
+ * If the item contains a partial time (e.g. '10:00'), the result is a partial time.
4204
+ *
4205
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4206
+ *
4207
+ * If the input collection is empty, the result is empty.
4208
+ *
4209
+ * See: https://hl7.org/fhirpath/#totime-time
4210
+ *
4211
+ * @param input
4212
+ * @returns
4213
+ */
4214
+ toTime: (input) => {
4215
+ if (input.length === 0) {
4216
+ return [];
4217
+ }
4218
+ const [{ value }] = validateInput(input, 1);
4219
+ if (typeof value === 'string') {
4220
+ const match = value.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);
4221
+ if (match) {
4222
+ return [{ type: PropertyType.time, value: parseDateString('T' + match[1]) }];
4223
+ }
4224
+ }
4225
+ return [];
4226
+ },
4227
+ /**
4228
+ * If the input collection contains a single item, this function will return true if:
4229
+ * 1) the item is a Time
4230
+ * 2) the item is a String and is convertible to a Time
4231
+ *
4232
+ * If the item is not one of the above types, or is not convertible to a Time (using the format hh:mm:ss.fff(+|-)hh:mm), the result is false.
4233
+ *
4234
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4235
+ *
4236
+ * If the input collection is empty, the result is empty.
4237
+ *
4238
+ * See: https://hl7.org/fhirpath/#convertstotime-boolean
4239
+ *
4240
+ * @param input
4241
+ * @returns
4242
+ */
4243
+ convertsToTime: (input) => {
4244
+ if (input.length === 0) {
4245
+ return [];
4246
+ }
4247
+ return booleanToTypedValue(functions.toTime(input).length === 1);
4248
+ },
4249
+ /*
4250
+ * 5.6. String Manipulation.
4251
+ *
4252
+ * See: https://hl7.org/fhirpath/#string-manipulation
4253
+ */
4254
+ /**
4255
+ * Returns the 0-based index of the first position substring is found in the input string, or -1 if it is not found.
4256
+ *
4257
+ * If substring is an empty string (''), the function returns 0.
4258
+ *
4259
+ * If the input or substring is empty ({ }), the result is empty ({ }).
4260
+ *
4261
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4262
+ *
4263
+ * See: https://hl7.org/fhirpath/#indexofsubstring-string-integer
4264
+ *
4265
+ * @param input The input collection.
4266
+ * @returns The index of the substring.
4267
+ */
4268
+ indexOf: (input, substringAtom) => {
4269
+ return applyStringFunc((str, substring) => str.indexOf(substring), input, substringAtom);
4270
+ },
4271
+ /**
4272
+ * Returns the part of the string starting at position start (zero-based). If length is given, will return at most length number of characters from the input string.
4273
+ *
4274
+ * If start lies outside the length of the string, the function returns empty ({ }). If there are less remaining characters in the string than indicated by length, the function returns just the remaining characters.
4275
+ *
4276
+ * If the input or start is empty, the result is empty.
4277
+ *
4278
+ * If an empty length is provided, the behavior is the same as if length had not been provided.
4279
+ *
4280
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4281
+ *
4282
+ * @param input The input collection.
4283
+ * @returns The index of the substring.
4284
+ */
4285
+ substring: (input, startAtom, lengthAtom) => {
4286
+ return applyStringFunc((str, start, length) => {
4287
+ const startIndex = start;
4288
+ const endIndex = length ? startIndex + length : str.length;
4289
+ return startIndex < 0 || startIndex >= str.length ? undefined : str.substring(startIndex, endIndex);
4290
+ }, input, startAtom, lengthAtom);
4291
+ },
4292
+ /**
4293
+ *
4294
+ * @param input The input collection.
4295
+ * @returns The index of the substring.
4296
+ */
4297
+ startsWith: (input, prefixAtom) => {
4298
+ return applyStringFunc((str, prefix) => str.startsWith(prefix), input, prefixAtom);
4299
+ },
4300
+ /**
4301
+ *
4302
+ * @param input The input collection.
4303
+ * @returns The index of the substring.
4304
+ */
4305
+ endsWith: (input, suffixAtom) => {
4306
+ return applyStringFunc((str, suffix) => str.endsWith(suffix), input, suffixAtom);
4307
+ },
4308
+ /**
4309
+ *
4310
+ * @param input The input collection.
4311
+ * @returns The index of the substring.
4312
+ */
4313
+ contains: (input, substringAtom) => {
4314
+ return applyStringFunc((str, substring) => str.includes(substring), input, substringAtom);
4315
+ },
4316
+ /**
4317
+ *
4318
+ * @param input The input collection.
4319
+ * @returns The index of the substring.
4320
+ */
4321
+ upper: (input) => {
4322
+ return applyStringFunc((str) => str.toUpperCase(), input);
4323
+ },
4324
+ /**
4325
+ *
4326
+ * @param input The input collection.
4327
+ * @returns The index of the substring.
4328
+ */
4329
+ lower: (input) => {
4330
+ return applyStringFunc((str) => str.toLowerCase(), input);
4331
+ },
4332
+ /**
4333
+ *
4334
+ * @param input The input collection.
4335
+ * @returns The index of the substring.
4336
+ */
4337
+ replace: (input, patternAtom, substitionAtom) => {
4338
+ return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, patternAtom, substitionAtom);
4339
+ },
4340
+ /**
4341
+ *
4342
+ * @param input The input collection.
4343
+ * @returns The index of the substring.
4344
+ */
4345
+ matches: (input, regexAtom) => {
4346
+ return applyStringFunc((str, regex) => !!str.match(regex), input, regexAtom);
4347
+ },
4348
+ /**
4349
+ *
4350
+ * @param input The input collection.
4351
+ * @returns The index of the substring.
4352
+ */
4353
+ replaceMatches: (input, regexAtom, substitionAtom) => {
4354
+ return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, regexAtom, substitionAtom);
4355
+ },
4356
+ /**
4357
+ *
4358
+ * @param input The input collection.
4359
+ * @returns The index of the substring.
4360
+ */
4361
+ length: (input) => {
4362
+ return applyStringFunc((str) => str.length, input);
4363
+ },
4364
+ /**
4365
+ * Returns the list of characters in the input string. If the input collection is empty ({ }), the result is empty.
4366
+ *
4367
+ * See: https://hl7.org/fhirpath/#tochars-collection
4368
+ *
4369
+ * @param input The input collection.
4370
+ */
4371
+ toChars: (input) => {
4372
+ return applyStringFunc((str) => (str ? str.split('') : undefined), input);
4373
+ },
4374
+ /*
4375
+ * 5.7. Math
4376
+ */
4377
+ /**
4378
+ * Returns the absolute value of the input. When taking the absolute value of a quantity, the unit is unchanged.
4379
+ *
4380
+ * If the input collection is empty, the result is empty.
4381
+ *
4382
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4383
+ *
4384
+ * See: https://hl7.org/fhirpath/#abs-integer-decimal-quantity
4385
+ *
4386
+ * @param input The input collection.
4387
+ * @returns A collection containing the result.
4388
+ */
4389
+ abs: (input) => {
4390
+ return applyMathFunc(Math.abs, input);
4391
+ },
4392
+ /**
4393
+ * Returns the first integer greater than or equal to the input.
4394
+ *
4395
+ * If the input collection is empty, the result is empty.
4396
+ *
4397
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4398
+ *
4399
+ * See: https://hl7.org/fhirpath/#ceiling-integer
4400
+ *
4401
+ * @param input The input collection.
4402
+ * @returns A collection containing the result.
4403
+ */
4404
+ ceiling: (input) => {
4405
+ return applyMathFunc(Math.ceil, input);
4406
+ },
4407
+ /**
4408
+ * Returns e raised to the power of the input.
4409
+ *
4410
+ * If the input collection contains an Integer, it will be implicitly converted to a Decimal and the result will be a Decimal.
4411
+ *
4412
+ * If the input collection is empty, the result is empty.
4413
+ *
4414
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4415
+ *
4416
+ * See: https://hl7.org/fhirpath/#exp-decimal
4417
+ *
4418
+ * @param input The input collection.
4419
+ * @returns A collection containing the result.
4420
+ */
4421
+ exp: (input) => {
4422
+ return applyMathFunc(Math.exp, input);
4423
+ },
4424
+ /**
4425
+ * Returns the first integer less than or equal to the input.
4426
+ *
4427
+ * If the input collection is empty, the result is empty.
4428
+ *
4429
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4430
+ *
4431
+ * See: https://hl7.org/fhirpath/#floor-integer
4432
+ *
4433
+ * @param input The input collection.
4434
+ * @returns A collection containing the result.
4435
+ */
4436
+ floor: (input) => {
4437
+ return applyMathFunc(Math.floor, input);
4438
+ },
4439
+ /**
4440
+ * Returns the natural logarithm of the input (i.e. the logarithm base e).
4441
+ *
4442
+ * When used with an Integer, it will be implicitly converted to a Decimal.
4443
+ *
4444
+ * If the input collection is empty, the result is empty.
4445
+ *
4446
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4447
+ *
4448
+ * See: https://hl7.org/fhirpath/#ln-decimal
4449
+ *
4450
+ * @param input The input collection.
4451
+ * @returns A collection containing the result.
4452
+ */
4453
+ ln: (input) => {
4454
+ return applyMathFunc(Math.log, input);
4455
+ },
4456
+ /**
4457
+ * Returns the logarithm base base of the input number.
4458
+ *
4459
+ * When used with Integers, the arguments will be implicitly converted to Decimal.
4460
+ *
4461
+ * If base is empty, the result is empty.
4462
+ *
4463
+ * If the input collection is empty, the result is empty.
4464
+ *
4465
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4466
+ *
4467
+ * See: https://hl7.org/fhirpath/#logbase-decimal-decimal
4468
+ *
4469
+ * @param input The input collection.
4470
+ * @returns A collection containing the result.
4471
+ */
4472
+ log: (input, baseAtom) => {
4473
+ return applyMathFunc((value, base) => Math.log(value) / Math.log(base), input, baseAtom);
4474
+ },
4475
+ /**
4476
+ * Raises a number to the exponent power. If this function is used with Integers, the result is an Integer. If the function is used with Decimals, the result is a Decimal. If the function is used with a mixture of Integer and Decimal, the Integer is implicitly converted to a Decimal and the result is a Decimal.
4477
+ *
4478
+ * If the power cannot be represented (such as the -1 raised to the 0.5), the result is empty.
4479
+ *
4480
+ * If the input is empty, or exponent is empty, the result is empty.
4481
+ *
4482
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4483
+ *
4484
+ * See: https://hl7.org/fhirpath/#powerexponent-integer-decimal-integer-decimal
4485
+ *
4486
+ * @param input The input collection.
4487
+ * @returns A collection containing the result.
4488
+ */
4489
+ power: (input, expAtom) => {
4490
+ return applyMathFunc(Math.pow, input, expAtom);
4491
+ },
4492
+ /**
4493
+ * Rounds the decimal to the nearest whole number using a traditional round (i.e. 0.5 or higher will round to 1). If specified, the precision argument determines the decimal place at which the rounding will occur. If not specified, the rounding will default to 0 decimal places.
4494
+ *
4495
+ * If specified, the number of digits of precision must be >= 0 or the evaluation will end and signal an error to the calling environment.
4496
+ *
4497
+ * If the input collection contains a single item of type Integer, it will be implicitly converted to a Decimal.
4498
+ *
4499
+ * If the input collection is empty, the result is empty.
4500
+ *
4501
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4502
+ *
4503
+ * See: https://hl7.org/fhirpath/#roundprecision-integer-decimal
4504
+ *
4505
+ * @param input The input collection.
4506
+ * @returns A collection containing the result.
4507
+ */
4508
+ round: (input) => {
4509
+ return applyMathFunc(Math.round, input);
4510
+ },
4511
+ /**
4512
+ * Returns the square root of the input number as a Decimal.
4513
+ *
4514
+ * If the square root cannot be represented (such as the square root of -1), the result is empty.
4515
+ *
4516
+ * If the input collection is empty, the result is empty.
4517
+ *
4518
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4519
+ *
4520
+ * Note that this function is equivalent to raising a number of the power of 0.5 using the power() function.
4521
+ *
4522
+ * See: https://hl7.org/fhirpath/#sqrt-decimal
4523
+ *
4524
+ * @param input The input collection.
4525
+ * @returns A collection containing the result.
4526
+ */
4527
+ sqrt: (input) => {
4528
+ return applyMathFunc(Math.sqrt, input);
4529
+ },
4530
+ /**
4531
+ * Returns the integer portion of the input.
4532
+ *
4533
+ * If the input collection is empty, the result is empty.
4534
+ *
4535
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4536
+ *
4537
+ * See: https://hl7.org/fhirpath/#truncate-integer
4538
+ *
4539
+ * @param input The input collection.
4540
+ * @returns A collection containing the result.
4541
+ */
4542
+ truncate: (input) => {
4543
+ return applyMathFunc((x) => x | 0, input);
4544
+ },
4545
+ /*
4546
+ * 5.8. Tree navigation
4547
+ */
4548
+ children: stub,
4549
+ descendants: stub,
4550
+ /*
4551
+ * 5.9. Utility functions
4552
+ */
4553
+ /**
4554
+ * Adds a String representation of the input collection to the diagnostic log,
4555
+ * using the name argument as the name in the log. This log should be made available
4556
+ * to the user in some appropriate fashion. Does not change the input, so returns
4557
+ * the input collection as output.
4558
+ *
4559
+ * If the projection argument is used, the trace would log the result of evaluating
4560
+ * the project expression on the input, but still return the input to the trace
4561
+ * function unchanged.
4562
+ *
4563
+ * See: https://hl7.org/fhirpath/#tracename-string-projection-expression-collection
4564
+ *
4565
+ * @param input The input collection.
4566
+ * @param nameAtom The log name.
4567
+ */
4568
+ trace: (input, nameAtom) => {
4569
+ console.log('trace', input, nameAtom);
4570
+ return input;
4571
+ },
4572
+ /**
4573
+ * Returns the current date and time, including timezone offset.
4574
+ *
4575
+ * See: https://hl7.org/fhirpath/#now-datetime
4576
+ */
4577
+ now: () => {
4578
+ return [{ type: PropertyType.dateTime, value: new Date().toISOString() }];
4579
+ },
4580
+ /**
4581
+ * Returns the current time.
4582
+ *
4583
+ * See: https://hl7.org/fhirpath/#timeofday-time
4584
+ */
4585
+ timeOfDay: () => {
4586
+ return [{ type: PropertyType.time, value: new Date().toISOString().substring(11) }];
4587
+ },
4588
+ /**
4589
+ * Returns the current date.
4590
+ *
4591
+ * See: https://hl7.org/fhirpath/#today-date
4592
+ */
4593
+ today: () => {
4594
+ return [{ type: PropertyType.date, value: new Date().toISOString().substring(0, 10) }];
4595
+ },
4596
+ /**
4597
+ * Calculates the difference between two dates or date/times.
4598
+ *
4599
+ * This is not part of the official FHIRPath spec.
4600
+ *
4601
+ * IBM FHIR issue: https://github.com/IBM/FHIR/issues/1014
4602
+ * IBM FHIR PR: https://github.com/IBM/FHIR/pull/1023
4603
+ */
4604
+ between: (context, startAtom, endAtom, unitsAtom) => {
4605
+ const startDate = functions.toDateTime(startAtom.eval(context));
4606
+ if (startDate.length === 0) {
4607
+ throw new Error('Invalid start date');
4608
+ }
4609
+ const endDate = functions.toDateTime(endAtom.eval(context));
4610
+ if (endDate.length === 0) {
4611
+ throw new Error('Invalid end date');
4612
+ }
4613
+ const unit = unitsAtom.eval(context)[0].value;
4614
+ if (unit !== 'years' && unit !== 'months' && unit !== 'days') {
4615
+ throw new Error('Invalid units');
4616
+ }
4617
+ const age = calculateAge(startDate[0].value, endDate[0].value);
4618
+ return [{ type: PropertyType.Quantity, value: { value: age[unit], unit } }];
4619
+ },
4620
+ /*
4621
+ * 6.3 Types
4622
+ */
4623
+ /**
4624
+ * The is() function is supported for backwards compatibility with previous
4625
+ * implementations of FHIRPath. Just as with the is keyword, the type argument
4626
+ * is an identifier that must resolve to the name of a type in a model.
4627
+ *
4628
+ * For implementations with compile-time typing, this requires special-case
4629
+ * handling when processing the argument to treat it as a type specifier rather
4630
+ * than an identifier expression:
4631
+ *
4632
+ * @param input
4633
+ * @param typeAtom
4634
+ * @returns
4635
+ */
4636
+ is: (input, typeAtom) => {
4637
+ let typeName = '';
4638
+ if (typeAtom instanceof SymbolAtom) {
4639
+ typeName = typeAtom.name;
4640
+ }
4641
+ else if (typeAtom instanceof DotAtom) {
4642
+ typeName = typeAtom.left.name + '.' + typeAtom.right.name;
4643
+ }
4644
+ if (!typeName) {
4645
+ return [];
4646
+ }
4647
+ return input.map((value) => ({ type: PropertyType.boolean, value: fhirPathIs(value, typeName) }));
4648
+ },
4649
+ /*
4650
+ * 6.5 Boolean logic
4651
+ */
4652
+ /**
4653
+ * 6.5.3. not() : Boolean
4654
+ *
4655
+ * Returns true if the input collection evaluates to false, and false if it evaluates to true. Otherwise, the result is empty ({ }):
4656
+ *
4657
+ * @param input
4658
+ * @returns
4659
+ */
4660
+ not: (input) => {
4661
+ return functions.toBoolean(input).map((value) => ({ type: PropertyType.boolean, value: !value.value }));
4662
+ },
4663
+ /*
4664
+ * Additional functions
4665
+ * See: https://hl7.org/fhir/fhirpath.html#functions
4666
+ */
4667
+ /**
4668
+ * For each item in the collection, if it is a string that is a uri (or canonical or url), locate the target of the reference, and add it to the resulting collection. If the item does not resolve to a resource, the item is ignored and nothing is added to the output collection.
4669
+ * The items in the collection may also represent a Reference, in which case the Reference.reference is resolved.
4670
+ * @param input The input collection.
4671
+ * @returns
4672
+ */
4673
+ resolve: (input) => {
4674
+ return input
4675
+ .map((e) => {
4676
+ const value = e.value;
4677
+ let refStr;
4678
+ if (typeof value === 'string') {
4679
+ refStr = value;
4680
+ }
4681
+ else if (typeof value === 'object') {
4682
+ const ref = value;
4683
+ if (ref.resource) {
4684
+ return { type: PropertyType.BackboneElement, value: ref.resource };
4685
+ }
4686
+ refStr = ref.reference;
4687
+ }
4688
+ if (!refStr) {
4689
+ return { type: PropertyType.BackboneElement, value: null };
4690
+ }
4691
+ const [resourceType, id] = refStr.split('/');
4692
+ return { type: PropertyType.BackboneElement, value: { resourceType, id } };
4693
+ })
4694
+ .filter((e) => !!e.value);
4695
+ },
4696
+ /**
4697
+ * The as operator can be used to treat a value as a specific type.
4698
+ * @param context The context value.
4699
+ * @returns The value as the specific type.
4700
+ */
4701
+ as: (context) => {
4702
+ return context;
4703
+ },
4704
+ /*
4705
+ * 12. Formal Specifications
4706
+ */
4707
+ /**
4708
+ * Returns the type of the input.
4709
+ *
4710
+ * 12.2. Model Information
4711
+ *
4712
+ * The model information returned by the reflection function type() is specified as an
4713
+ * XML Schema document (xsd) and included in this specification at the following link:
4714
+ * https://hl7.org/fhirpath/modelinfo.xsd
4715
+ *
4716
+ * See: https://hl7.org/fhirpath/#model-information
4717
+ *
4718
+ * @param input The input collection.
4719
+ * @returns
4720
+ */
4721
+ type: (input) => {
4722
+ return input.map(({ value }) => {
4723
+ if (typeof value === 'boolean') {
4724
+ return { type: PropertyType.BackboneElement, value: { namespace: 'System', name: 'Boolean' } };
4725
+ }
4726
+ if (typeof value === 'number') {
4727
+ return { type: PropertyType.BackboneElement, value: { namespace: 'System', name: 'Integer' } };
4728
+ }
4729
+ if (value && typeof value === 'object' && 'resourceType' in value) {
4730
+ return {
4731
+ type: PropertyType.BackboneElement,
4732
+ value: { namespace: 'FHIR', name: value.resourceType },
4733
+ };
4734
+ }
4735
+ return { type: PropertyType.BackboneElement, value: null };
4736
+ });
4737
+ },
4738
+ conformsTo: (input, systemAtom) => {
4739
+ const system = systemAtom.eval([])[0].value;
4740
+ if (!system.startsWith('http://hl7.org/fhir/StructureDefinition/')) {
4741
+ throw new Error('Expected a StructureDefinition URL');
4742
+ }
4743
+ const expectedResourceType = system.replace('http://hl7.org/fhir/StructureDefinition/', '');
4744
+ return input.map((value) => {
4745
+ var _a;
4746
+ return ({
4747
+ type: PropertyType.boolean,
4748
+ value: ((_a = value.value) === null || _a === void 0 ? void 0 : _a.resourceType) === expectedResourceType,
4749
+ });
4750
+ });
4751
+ },
4752
+ };
4753
+ /*
4754
+ * Helper utilities
4755
+ */
4756
+ function applyStringFunc(func, input, ...argsAtoms) {
4757
+ if (input.length === 0) {
4758
+ return [];
4759
+ }
4760
+ const [{ value }] = validateInput(input, 1);
4761
+ if (typeof value !== 'string') {
4762
+ throw new Error('String function cannot be called with non-string');
4763
+ }
4764
+ const result = func(value, ...argsAtoms.map((atom) => { var _a, _b; return atom && ((_b = (_a = atom.eval(input)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.value); }));
4765
+ if (result === undefined) {
4766
+ return [];
4767
+ }
4768
+ if (Array.isArray(result)) {
4769
+ return result.map(toTypedValue);
4770
+ }
4771
+ return [toTypedValue(result)];
4772
+ }
4773
+ function applyMathFunc(func, input, ...argsAtoms) {
4774
+ if (input.length === 0) {
4775
+ return [];
4776
+ }
4777
+ const [{ value }] = validateInput(input, 1);
4778
+ const quantity = isQuantity(value);
4779
+ const numberInput = quantity ? value.value : value;
4780
+ if (typeof numberInput !== 'number') {
4781
+ throw new Error('Math function cannot be called with non-number');
4782
+ }
4783
+ const result = func(numberInput, ...argsAtoms.map((atom) => { var _a, _b; return (_b = (_a = atom.eval([])) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.value; }));
4784
+ const type = quantity ? PropertyType.Quantity : input[0].type;
4785
+ const returnValue = quantity ? Object.assign(Object.assign({}, value), { value: result }) : result;
4786
+ return [{ type, value: returnValue }];
4787
+ }
4788
+ function validateInput(input, count) {
4789
+ if (input.length !== count) {
4790
+ throw new Error(`Expected ${count} arguments`);
4791
+ }
4792
+ for (const element of input) {
4793
+ if (element === null || element === undefined) {
4794
+ throw new Error('Expected non-null argument');
4795
+ }
4796
+ }
4797
+ return input;
4798
+ }
4799
+
4800
+ var _Tokenizer_instances, _Tokenizer_str, _Tokenizer_pos, _Tokenizer_peekToken, _Tokenizer_consumeToken, _Tokenizer_consumeWhitespace, _Tokenizer_consumeMultiLineComment, _Tokenizer_consumeSingleLineComment, _Tokenizer_consumeString, _Tokenizer_consumeBacktickSymbol, _Tokenizer_consumeDateTime, _Tokenizer_consumeNumber, _Tokenizer_consumeSymbol, _Tokenizer_consumeOperator, _Tokenizer_consumeWhile, _Tokenizer_curr, _Tokenizer_prev, _Tokenizer_peek;
4801
+ function tokenize(str) {
4802
+ return new Tokenizer(str).tokenize();
4803
+ }
4804
+ const STANDARD_UNITS = [
4805
+ 'year',
4806
+ 'years',
4807
+ 'month',
4808
+ 'months',
4809
+ 'week',
4810
+ 'weeks',
4811
+ 'day',
4812
+ 'days',
4813
+ 'hour',
4814
+ 'hours',
4815
+ 'minute',
4816
+ 'minutes',
4817
+ 'second',
4818
+ 'seconds',
4819
+ 'millisecond',
4820
+ 'milliseconds',
4821
+ ];
4822
+ const TWO_CHAR_OPERATORS = ['!=', '!~', '<=', '>=', '{}'];
4823
+ class Tokenizer {
4824
+ constructor(str) {
4825
+ _Tokenizer_instances.add(this);
4826
+ _Tokenizer_str.set(this, void 0);
4827
+ _Tokenizer_pos.set(this, void 0);
4828
+ __classPrivateFieldSet(this, _Tokenizer_str, str, "f");
4829
+ __classPrivateFieldSet(this, _Tokenizer_pos, 0, "f");
4830
+ }
4831
+ tokenize() {
4832
+ const result = [];
4833
+ while (__classPrivateFieldGet(this, _Tokenizer_pos, "f") < __classPrivateFieldGet(this, _Tokenizer_str, "f").length) {
4834
+ const token = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
4835
+ if (token) {
4836
+ result.push(token);
4837
+ }
4838
+ }
4839
+ return result;
4840
+ }
4841
+ }
4842
+ _Tokenizer_str = new WeakMap(), _Tokenizer_pos = new WeakMap(), _Tokenizer_instances = new WeakSet(), _Tokenizer_peekToken = function _Tokenizer_peekToken() {
4843
+ const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
4844
+ const token = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
4845
+ __classPrivateFieldSet(this, _Tokenizer_pos, start, "f");
4846
+ return token;
4847
+ }, _Tokenizer_consumeToken = function _Tokenizer_consumeToken() {
4848
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhitespace).call(this);
4849
+ const c = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this);
4850
+ if (!c) {
4851
+ return undefined;
4852
+ }
4853
+ const next = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this);
4854
+ if (c === '/' && next === '*') {
4855
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeMultiLineComment).call(this);
4856
+ }
4857
+ if (c === '/' && next === '/') {
4858
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSingleLineComment).call(this);
4859
+ }
4860
+ if (c === "'") {
4861
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeString).call(this);
4862
+ }
4863
+ if (c === '`') {
4864
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeBacktickSymbol).call(this);
4865
+ }
4866
+ if (c === '@') {
4867
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeDateTime).call(this);
4868
+ }
4869
+ if (c.match(/\d/)) {
4870
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeNumber).call(this);
4871
+ }
4872
+ if (c.match(/\w/)) {
4873
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSymbol).call(this);
4874
+ }
4875
+ if (c === '$' && next.match(/\w/)) {
4876
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSymbol).call(this);
4877
+ }
4878
+ return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeOperator).call(this);
4879
+ }, _Tokenizer_consumeWhitespace = function _Tokenizer_consumeWhitespace() {
4880
+ return buildToken('Whitespace', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\s/)));
4881
+ }, _Tokenizer_consumeMultiLineComment = function _Tokenizer_consumeMultiLineComment() {
4882
+ const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
4883
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '*' || __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this) !== '/');
4884
+ __classPrivateFieldSet(this, _Tokenizer_pos, __classPrivateFieldGet(this, _Tokenizer_pos, "f") + 2, "f");
4885
+ return buildToken('Comment', __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
4886
+ }, _Tokenizer_consumeSingleLineComment = function _Tokenizer_consumeSingleLineComment() {
4887
+ return buildToken('Comment', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '\n'));
4888
+ }, _Tokenizer_consumeString = function _Tokenizer_consumeString() {
4889
+ var _a, _b;
4890
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
4891
+ const result = buildToken('String', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_prev).call(this) === '\\' || __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== "'"));
4892
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
4893
+ return result;
4894
+ }, _Tokenizer_consumeBacktickSymbol = function _Tokenizer_consumeBacktickSymbol() {
4895
+ var _a, _b;
4896
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
4897
+ const result = buildToken('Symbol', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '`'));
4898
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
4899
+ return result;
4900
+ }, _Tokenizer_consumeDateTime = function _Tokenizer_consumeDateTime() {
4901
+ var _a, _b, _c, _d, _e;
4902
+ const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
4903
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
4904
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d-]/));
4905
+ if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === 'T') {
4906
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
4907
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d:]/));
4908
+ if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '.' && __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this).match(/\d/)) {
4909
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_c = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _c++, _c), "f");
4910
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d]/));
4911
+ }
4912
+ if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === 'Z') {
4913
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_d = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _d++, _d), "f");
4914
+ }
4915
+ else if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '+' || __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '-') {
4916
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_e = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _e++, _e), "f");
4917
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d:]/));
4918
+ }
4919
+ }
4920
+ return buildToken('DateTime', __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start + 1, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
4921
+ }, _Tokenizer_consumeNumber = function _Tokenizer_consumeNumber() {
4922
+ var _a;
4923
+ const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
4924
+ let id = 'Number';
4925
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\d/));
4926
+ if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '.' && __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this).match(/\d/)) {
4927
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
4928
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\d/));
4929
+ }
4930
+ if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === ' ') {
4931
+ if (isUnitToken(__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peekToken).call(this))) {
4932
+ id = 'Quantity';
4933
+ __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
4934
+ }
4935
+ }
4936
+ return buildToken(id, __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
4937
+ }, _Tokenizer_consumeSymbol = function _Tokenizer_consumeSymbol() {
4938
+ return buildToken('Symbol', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[$\w]/)));
4939
+ }, _Tokenizer_consumeOperator = function _Tokenizer_consumeOperator() {
4940
+ var _a;
4941
+ const c = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this);
4942
+ const next = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this);
4943
+ const twoCharOp = c + next;
4944
+ if (TWO_CHAR_OPERATORS.includes(twoCharOp)) {
4945
+ __classPrivateFieldSet(this, _Tokenizer_pos, __classPrivateFieldGet(this, _Tokenizer_pos, "f") + 2, "f");
4946
+ return buildToken(twoCharOp, twoCharOp);
4947
+ }
4948
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
4949
+ return buildToken(c, c);
4950
+ }, _Tokenizer_consumeWhile = function _Tokenizer_consumeWhile(condition) {
4951
+ var _a;
4952
+ const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
4953
+ while (__classPrivateFieldGet(this, _Tokenizer_pos, "f") < __classPrivateFieldGet(this, _Tokenizer_str, "f").length && condition()) {
4954
+ __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
4955
+ }
4956
+ return __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f"));
4957
+ }, _Tokenizer_curr = function _Tokenizer_curr() {
4958
+ return __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f")];
4959
+ }, _Tokenizer_prev = function _Tokenizer_prev() {
4960
+ var _a;
4961
+ return (_a = __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f") - 1]) !== null && _a !== void 0 ? _a : '';
4962
+ }, _Tokenizer_peek = function _Tokenizer_peek() {
4963
+ var _a;
4964
+ return (_a = __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f") + 1]) !== null && _a !== void 0 ? _a : '';
4965
+ };
4966
+ function buildToken(id, value) {
4967
+ return { id, value };
4968
+ }
4969
+ function isUnitToken(token) {
4970
+ if (token) {
4971
+ if (token.id === 'String') {
4972
+ return true;
4973
+ }
4974
+ if (token.id === 'Symbol' && STANDARD_UNITS.includes(token.value)) {
4975
+ return true;
4976
+ }
4977
+ }
4978
+ return false;
4979
+ }
4980
+
4981
+ var _ParserBuilder_prefixParselets, _ParserBuilder_infixParselets, _Parser_instances, _Parser_tokens, _Parser_prefixParselets, _Parser_infixParselets, _Parser_getPrecedence, _Parser_consume, _Parser_look;
4982
+ class ParserBuilder {
4983
+ constructor() {
4984
+ _ParserBuilder_prefixParselets.set(this, {});
4985
+ _ParserBuilder_infixParselets.set(this, {});
4986
+ }
4987
+ registerInfix(tokenType, parselet) {
4988
+ __classPrivateFieldGet(this, _ParserBuilder_infixParselets, "f")[tokenType] = parselet;
4989
+ return this;
4990
+ }
4991
+ registerPrefix(tokenType, parselet) {
4992
+ __classPrivateFieldGet(this, _ParserBuilder_prefixParselets, "f")[tokenType] = parselet;
4993
+ return this;
4994
+ }
4995
+ prefix(tokenType, precedence, builder) {
4996
+ return this.registerPrefix(tokenType, {
4997
+ parse(parser, token) {
4998
+ const right = parser.consumeAndParse(precedence);
4999
+ return builder(token, right);
5000
+ },
5001
+ });
5002
+ }
5003
+ infixLeft(tokenType, precedence, builder) {
5004
+ return this.registerInfix(tokenType, {
5005
+ parse(parser, left, token) {
5006
+ const right = parser.consumeAndParse(precedence);
5007
+ return builder(left, token, right);
5008
+ },
5009
+ precedence,
5010
+ });
5011
+ }
5012
+ construct(input) {
5013
+ return new Parser(tokenize(input), __classPrivateFieldGet(this, _ParserBuilder_prefixParselets, "f"), __classPrivateFieldGet(this, _ParserBuilder_infixParselets, "f"));
5014
+ }
5015
+ }
5016
+ _ParserBuilder_prefixParselets = new WeakMap(), _ParserBuilder_infixParselets = new WeakMap();
5017
+ class Parser {
5018
+ constructor(tokens, prefixParselets, infixParselets) {
5019
+ _Parser_instances.add(this);
5020
+ _Parser_tokens.set(this, void 0);
5021
+ _Parser_prefixParselets.set(this, void 0);
5022
+ _Parser_infixParselets.set(this, void 0);
5023
+ __classPrivateFieldSet(this, _Parser_tokens, tokens, "f");
5024
+ __classPrivateFieldSet(this, _Parser_prefixParselets, prefixParselets, "f");
5025
+ __classPrivateFieldSet(this, _Parser_infixParselets, infixParselets, "f");
5026
+ }
5027
+ match(expected) {
5028
+ const token = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_look).call(this);
5029
+ if ((token === null || token === void 0 ? void 0 : token.id) !== expected) {
5030
+ return false;
5031
+ }
5032
+ __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
5033
+ return true;
5034
+ }
5035
+ consumeAndParse(precedence = 100 /* Precedence.MaximumPrecedence */) {
5036
+ const token = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
5037
+ const prefix = __classPrivateFieldGet(this, _Parser_prefixParselets, "f")[token.id];
5038
+ if (!prefix) {
5039
+ throw Error(`Parse error at ${token.value}. No matching prefix parselet.`);
5040
+ }
5041
+ let left = prefix.parse(this, token);
5042
+ while (precedence > __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_getPrecedence).call(this)) {
5043
+ const next = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
5044
+ const infix = __classPrivateFieldGet(this, _Parser_infixParselets, "f")[next.id];
5045
+ left = infix.parse(this, left, next);
5046
+ }
5047
+ return left;
5048
+ }
5049
+ }
5050
+ _Parser_tokens = new WeakMap(), _Parser_prefixParselets = new WeakMap(), _Parser_infixParselets = new WeakMap(), _Parser_instances = new WeakSet(), _Parser_getPrecedence = function _Parser_getPrecedence() {
5051
+ const nextToken = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_look).call(this);
5052
+ if (!nextToken) {
5053
+ return 100 /* Precedence.MaximumPrecedence */;
5054
+ }
5055
+ const parser = __classPrivateFieldGet(this, _Parser_infixParselets, "f")[nextToken.id];
5056
+ if (parser) {
5057
+ return parser.precedence;
5058
+ }
5059
+ return 100 /* Precedence.MaximumPrecedence */;
5060
+ }, _Parser_consume = function _Parser_consume() {
5061
+ if (!__classPrivateFieldGet(this, _Parser_tokens, "f").length) {
5062
+ throw Error('Cant consume unknown more tokens.');
5063
+ }
5064
+ return __classPrivateFieldGet(this, _Parser_tokens, "f").shift();
5065
+ }, _Parser_look = function _Parser_look() {
5066
+ return __classPrivateFieldGet(this, _Parser_tokens, "f").length > 0 ? __classPrivateFieldGet(this, _Parser_tokens, "f")[0] : undefined;
5067
+ };
5068
+ const PARENTHESES_PARSELET = {
5069
+ parse(parser) {
5070
+ const expr = parser.consumeAndParse();
5071
+ if (!parser.match(')')) {
5072
+ throw new Error('Parse error: expected `)`');
5073
+ }
5074
+ return expr;
5075
+ },
5076
+ };
5077
+ const INDEXER_PARSELET = {
5078
+ parse(parser, left) {
5079
+ const expr = parser.consumeAndParse();
5080
+ if (!parser.match(']')) {
5081
+ throw new Error('Parse error: expected `]`');
5082
+ }
5083
+ return new IndexerAtom(left, expr);
5084
+ },
5085
+ precedence: 2 /* Precedence.Indexer */,
5086
+ };
5087
+ const FUNCTION_CALL_PARSELET = {
5088
+ parse(parser, left) {
5089
+ if (!(left instanceof SymbolAtom)) {
5090
+ throw new Error('Unexpected parentheses');
5091
+ }
5092
+ if (!(left.name in functions)) {
5093
+ throw new Error('Unrecognized function: ' + left.name);
5094
+ }
5095
+ const args = [];
5096
+ while (!parser.match(')')) {
5097
+ args.push(parser.consumeAndParse());
5098
+ parser.match(',');
5099
+ }
5100
+ return new FunctionAtom(left.name, args, functions[left.name]);
5101
+ },
5102
+ precedence: 0 /* Precedence.FunctionCall */,
5103
+ };
5104
+ function parseQuantity(str) {
5105
+ const parts = str.split(' ');
5106
+ const value = parseFloat(parts[0]);
5107
+ let unit = parts[1];
5108
+ if (unit && unit.startsWith("'") && unit.endsWith("'")) {
5109
+ unit = unit.substring(1, unit.length - 1);
5110
+ }
5111
+ else {
5112
+ unit = '{' + unit + '}';
5113
+ }
5114
+ return { value, unit };
5115
+ }
5116
+ const parserBuilder = new ParserBuilder()
5117
+ .registerPrefix('String', {
5118
+ parse: (_, token) => new LiteralAtom({ type: PropertyType.string, value: token.value }),
5119
+ })
5120
+ .registerPrefix('DateTime', {
5121
+ parse: (_, token) => new LiteralAtom({ type: PropertyType.dateTime, value: parseDateString(token.value) }),
5122
+ })
5123
+ .registerPrefix('Quantity', {
5124
+ parse: (_, token) => new LiteralAtom({ type: PropertyType.Quantity, value: parseQuantity(token.value) }),
5125
+ })
5126
+ .registerPrefix('Number', {
5127
+ parse: (_, token) => new LiteralAtom({ type: PropertyType.decimal, value: parseFloat(token.value) }),
5128
+ })
5129
+ .registerPrefix('Symbol', {
5130
+ parse: (_, token) => {
5131
+ if (token.value === 'false') {
5132
+ return new LiteralAtom({ type: PropertyType.boolean, value: false });
5133
+ }
5134
+ if (token.value === 'true') {
5135
+ return new LiteralAtom({ type: PropertyType.boolean, value: true });
5136
+ }
5137
+ return new SymbolAtom(token.value);
5138
+ },
5139
+ })
5140
+ .registerPrefix('{}', { parse: () => new EmptySetAtom() })
5141
+ .registerPrefix('(', PARENTHESES_PARSELET)
5142
+ .registerInfix('[', INDEXER_PARSELET)
5143
+ .registerInfix('(', FUNCTION_CALL_PARSELET)
5144
+ .prefix('+', 3 /* Precedence.UnaryAdd */, (_, right) => new UnaryOperatorAtom(right, (x) => x))
5145
+ .prefix('-', 3 /* Precedence.UnarySubtract */, (_, right) => new ArithemticOperatorAtom(right, right, (_, y) => -y))
5146
+ .infixLeft('.', 1 /* Precedence.Dot */, (left, _, right) => new DotAtom(left, right))
5147
+ .infixLeft('/', 4 /* Precedence.Divide */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x / y))
5148
+ .infixLeft('*', 4 /* Precedence.Multiply */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x * y))
5149
+ .infixLeft('+', 5 /* Precedence.Add */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x + y))
5150
+ .infixLeft('-', 5 /* Precedence.Subtract */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x - y))
5151
+ .infixLeft('|', 7 /* Precedence.Union */, (left, _, right) => new UnionAtom(left, right))
5152
+ .infixLeft('=', 9 /* Precedence.Equals */, (left, _, right) => new EqualsAtom(left, right))
5153
+ .infixLeft('!=', 9 /* Precedence.Equals */, (left, _, right) => new NotEqualsAtom(left, right))
5154
+ .infixLeft('~', 9 /* Precedence.Equivalent */, (left, _, right) => new EquivalentAtom(left, right))
5155
+ .infixLeft('!~', 9 /* Precedence.NotEquivalent */, (left, _, right) => new NotEquivalentAtom(left, right))
5156
+ .infixLeft('<', 8 /* Precedence.LessThan */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x < y))
5157
+ .infixLeft('<=', 8 /* Precedence.LessThanOrEquals */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x <= y))
5158
+ .infixLeft('>', 8 /* Precedence.GreaterThan */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x > y))
5159
+ .infixLeft('>=', 8 /* Precedence.GreaterThanOrEquals */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x >= y))
5160
+ .infixLeft('&', 5 /* Precedence.Ampersand */, (left, _, right) => new ConcatAtom(left, right))
5161
+ .infixLeft('Symbol', 6 /* Precedence.Is */, (left, symbol, right) => {
5162
+ switch (symbol.value) {
5163
+ case 'and':
5164
+ return new AndAtom(left, right);
5165
+ case 'as':
5166
+ return new AsAtom(left, right);
5167
+ case 'contains':
5168
+ return new ContainsAtom(left, right);
5169
+ case 'div':
5170
+ return new ArithemticOperatorAtom(left, right, (x, y) => (x / y) | 0);
5171
+ case 'in':
5172
+ return new InAtom(left, right);
5173
+ case 'is':
5174
+ return new IsAtom(left, right);
5175
+ case 'mod':
5176
+ return new ArithemticOperatorAtom(left, right, (x, y) => x % y);
5177
+ case 'or':
5178
+ return new OrAtom(left, right);
5179
+ case 'xor':
5180
+ return new XorAtom(left, right);
5181
+ default:
5182
+ throw new Error('Cannot use ' + symbol.value + ' as infix operator');
5183
+ }
5184
+ });
5185
+ /**
5186
+ * Parses a FHIRPath expression into an AST.
5187
+ * The result can be used to evaluate the expression against a resource or other object.
5188
+ * This method is useful if you know that you will evaluate the same expression many times
5189
+ * against different resources.
5190
+ * @param input The FHIRPath expression to parse.
5191
+ * @returns The AST representing the expression.
5192
+ */
5193
+ function parseFhirPath(input) {
5194
+ try {
5195
+ return new FhirPathAtom(input, parserBuilder.construct(input).consumeAndParse());
5196
+ }
5197
+ catch (error) {
5198
+ throw new Error(`FhirPathError on "${input}": ${error}`);
5199
+ }
5200
+ }
5201
+ /**
5202
+ * Evaluates a FHIRPath expression against a resource or other object.
5203
+ * @param input The FHIRPath expression to parse.
5204
+ * @param context The resource or object to evaluate the expression against.
5205
+ * @returns The result of the FHIRPath expression against the resource or object.
5206
+ */
5207
+ function evalFhirPath(input, context) {
5208
+ // eval requires a TypedValue array
5209
+ // As a convenience, we can accept array or non-array, and TypedValue or unknown value
5210
+ if (!Array.isArray(context)) {
5211
+ context = [context];
5212
+ }
5213
+ const array = Array.isArray(context) ? context : [context];
5214
+ for (let i = 0; i < array.length; i++) {
5215
+ const el = array[i];
5216
+ if (!(typeof el === 'object' && 'type' in el && 'value' in el)) {
5217
+ array[i] = { type: PropertyType.BackboneElement, value: el };
5218
+ }
5219
+ }
5220
+ return parseFhirPath(input)
5221
+ .eval(array)
5222
+ .map((e) => e.value);
5223
+ }
5224
+
5225
+ const SEGMENT_SEPARATOR = '\r';
5226
+ const FIELD_SEPARATOR = '|';
5227
+ const COMPONENT_SEPARATOR = '^';
5228
+ /**
5229
+ * The Hl7Message class represents one HL7 message.
5230
+ * A message is a collection of segments.
5231
+ * Note that we do not strictly parse messages, and only use default delimeters.
5232
+ */
5233
+ class Hl7Message {
5234
+ constructor(segments) {
5235
+ this.segments = segments;
5236
+ }
5237
+ get(index) {
5238
+ if (typeof index === 'number') {
5239
+ return this.segments[index];
5240
+ }
5241
+ return this.segments.find((s) => s.name === index);
5242
+ }
5243
+ getAll(name) {
5244
+ return this.segments.filter((s) => s.name === name);
5245
+ }
5246
+ toString() {
5247
+ return this.segments.map((s) => s.toString()).join(SEGMENT_SEPARATOR);
5248
+ }
5249
+ buildAck() {
5250
+ var _a, _b, _c, _d, _e, _f;
5251
+ const now = new Date();
5252
+ const msh = this.get('MSH');
5253
+ const sendingApp = ((_a = msh === null || msh === void 0 ? void 0 : msh.get(2)) === null || _a === void 0 ? void 0 : _a.toString()) || '';
5254
+ const sendingFacility = ((_b = msh === null || msh === void 0 ? void 0 : msh.get(3)) === null || _b === void 0 ? void 0 : _b.toString()) || '';
5255
+ const receivingApp = ((_c = msh === null || msh === void 0 ? void 0 : msh.get(4)) === null || _c === void 0 ? void 0 : _c.toString()) || '';
5256
+ const receivingFacility = ((_d = msh === null || msh === void 0 ? void 0 : msh.get(5)) === null || _d === void 0 ? void 0 : _d.toString()) || '';
5257
+ const controlId = ((_e = msh === null || msh === void 0 ? void 0 : msh.get(9)) === null || _e === void 0 ? void 0 : _e.toString()) || '';
5258
+ const versionId = ((_f = msh === null || msh === void 0 ? void 0 : msh.get(12)) === null || _f === void 0 ? void 0 : _f.toString()) || '2.5.1';
5259
+ return new Hl7Message([
5260
+ new Hl7Segment([
5261
+ 'MSH',
5262
+ '^~\\&',
5263
+ receivingApp,
5264
+ receivingFacility,
5265
+ sendingApp,
5266
+ sendingFacility,
5267
+ now.toISOString(),
5268
+ '',
5269
+ 'ACK',
5270
+ now.getTime().toString(),
5271
+ 'P',
5272
+ versionId,
5273
+ ]),
5274
+ new Hl7Segment(['MSA', 'AA', controlId, 'OK']),
5275
+ ]);
5276
+ }
5277
+ static parse(text) {
5278
+ if (!text.startsWith('MSH|^~\\&')) {
5279
+ const err = new Error('Invalid HL7 message');
5280
+ err.type = 'entity.parse.failed';
5281
+ throw err;
5282
+ }
5283
+ return new Hl7Message(text.split(/[\r\n]+/).map((line) => Hl7Segment.parse(line)));
5284
+ }
5285
+ }
5286
+ /**
5287
+ * The Hl7Segment class represents one HL7 segment.
5288
+ * A segment is a collection of fields.
5289
+ * The name field is the first field.
5290
+ * Note that we do not strictly parse messages, and only use default delimeters.
5291
+ */
5292
+ class Hl7Segment {
5293
+ constructor(fields) {
5294
+ if (isStringArray(fields)) {
5295
+ this.fields = fields.map((f) => Hl7Field.parse(f));
5296
+ }
5297
+ else {
5298
+ this.fields = fields;
5299
+ }
5300
+ this.name = this.fields[0].components[0];
5301
+ }
5302
+ get(index) {
5303
+ return this.fields[index];
5304
+ }
5305
+ toString() {
5306
+ return this.fields.map((f) => f.toString()).join(FIELD_SEPARATOR);
5307
+ }
5308
+ static parse(text) {
5309
+ return new Hl7Segment(text.split(FIELD_SEPARATOR).map((f) => Hl7Field.parse(f)));
5310
+ }
5311
+ }
5312
+ /**
5313
+ * The Hl7Field class represents one HL7 field.
5314
+ * A field is a collection of components.
5315
+ * Note that we do not strictly parse messages, and only use default delimeters.
5316
+ */
5317
+ class Hl7Field {
5318
+ constructor(components) {
5319
+ this.components = components;
5320
+ }
5321
+ get(index) {
5322
+ return this.components[index];
5323
+ }
5324
+ toString() {
5325
+ return this.components.join(COMPONENT_SEPARATOR);
5326
+ }
5327
+ static parse(text) {
5328
+ return new Hl7Field(text.split(COMPONENT_SEPARATOR));
5329
+ }
5330
+ }
5331
+
5332
+ var SearchParameterType;
5333
+ (function (SearchParameterType) {
2603
5334
  SearchParameterType["BOOLEAN"] = "BOOLEAN";
2604
5335
  SearchParameterType["NUMBER"] = "NUMBER";
2605
5336
  SearchParameterType["QUANTITY"] = "QUANTITY";
@@ -2681,7 +5412,12 @@ function getSearchParameterType(searchParam, propertyType) {
2681
5412
  let type = SearchParameterType.TEXT;
2682
5413
  switch (searchParam.type) {
2683
5414
  case 'date':
2684
- type = SearchParameterType.DATE;
5415
+ if (propertyType === PropertyType.dateTime || propertyType === PropertyType.instant) {
5416
+ type = SearchParameterType.DATETIME;
5417
+ }
5418
+ else {
5419
+ type = SearchParameterType.DATE;
5420
+ }
2685
5421
  break;
2686
5422
  case 'number':
2687
5423
  type = SearchParameterType.NUMBER;
@@ -2724,5 +5460,5 @@ function simplifyExpression(input) {
2724
5460
  return result;
2725
5461
  }
2726
5462
 
2727
- export { COMPONENT_SEPARATOR, DEFAULT_SEARCH_COUNT, FIELD_SEPARATOR, Hl7Field, Hl7Message, Hl7Segment, LRUCache, MedplumClient, OperationOutcomeError, Operator, PropertyType, ReadablePromise, SEGMENT_SEPARATOR, SearchParameterType, accessDenied, allOk, arrayBufferToBase64, arrayBufferToHex, assertOk, badRequest, buildTypeName, calculateAge, calculateAgeString, capitalize, createReference, createSchema, createTypeSchema, created, deepEquals, formatAddress, formatFamilyName, formatGivenName, formatHumanName, formatSearchQuery, getDateProperty, getDisplayString, getExpressionForResourceType, getExtensionValue, getImageSrc, getPropertyDisplayName, getQuestionnaireAnswers, getReferenceString, getSearchParameterDetails, getStatus, gone, indexSearchParameter, indexStructureDefinition, isGone, isLowerCase, isNotFound, isObject, isOk, isProfileResource, isStringArray, isUUID, notFound, notModified, parseSearchDefinition, resolveId, stringify };
5463
+ export { COMPONENT_SEPARATOR, DEFAULT_SEARCH_COUNT, FIELD_SEPARATOR, Hl7Field, Hl7Message, Hl7Segment, LRUCache, MedplumClient, OperationOutcomeError, Operator, PropertyType, ReadablePromise, SEGMENT_SEPARATOR, SearchParameterType, accessDenied, allOk, arrayBufferToBase64, arrayBufferToHex, assertOk, badRequest, buildTypeName, calculateAge, calculateAgeString, capitalize, createReference, createSchema, createTypeSchema, created, deepEquals$1 as deepEquals, evalFhirPath, formatAddress, formatFamilyName, formatGivenName, formatHumanName, formatSearchQuery, getDateProperty, getDisplayString, getExpressionForResourceType, getExtensionValue, getIdentifier, getImageSrc, getPropertyDisplayName, getQuestionnaireAnswers, getReferenceString, getSearchParameterDetails, getStatus, gone, indexSearchParameter, indexStructureDefinition, isGone, isLowerCase, isNotFound, isObject$1 as isObject, isOk, isProfileResource, isStringArray, isUUID, notFound, notModified, parseFhirPath, parseSearchDefinition, resolveId, stringify, tokenize };
2728
5464
  //# sourceMappingURL=index.js.map