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