@medplum/mock 0.9.5 → 0.9.8

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
@@ -408,6 +408,7 @@
408
408
  ],
409
409
  };
410
410
  const HomerSimpsonSpecimen = {
411
+ id: '123',
411
412
  resourceType: 'Specimen',
412
413
  subject: core.createReference(HomerSimpson),
413
414
  collection: {
@@ -6507,34 +6508,6 @@
6507
6508
  PERFORMANCE OF THIS SOFTWARE.
6508
6509
  ***************************************************************************** */
6509
6510
 
6510
- function __classPrivateFieldGet$1(receiver, state, kind, f) {
6511
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6512
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
6513
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6514
- }
6515
-
6516
- function __classPrivateFieldSet$1(receiver, state, value, kind, f) {
6517
- if (kind === "m") throw new TypeError("Private method is not writable");
6518
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
6519
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6520
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6521
- }
6522
-
6523
- /******************************************************************************
6524
- Copyright (c) Microsoft Corporation.
6525
-
6526
- Permission to use, copy, modify, and/or distribute this software for any
6527
- purpose with or without fee is hereby granted.
6528
-
6529
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
6530
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
6531
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
6532
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
6533
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
6534
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
6535
- PERFORMANCE OF THIS SOFTWARE.
6536
- ***************************************************************************** */
6537
-
6538
6511
  function __classPrivateFieldGet(receiver, state, kind, f) {
6539
6512
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6540
6513
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
@@ -6548,2722 +6521,215 @@
6548
6521
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6549
6522
  }
6550
6523
 
6551
- /**
6552
- * Ensures that the value is wrapped in an array.
6553
- * @param input The input as a an array or a value.
6554
- * @returns The input as an array.
6555
- */
6556
- function ensureArray(input) {
6557
- if (input === null || input === undefined) {
6558
- return [];
6559
- }
6560
- return Array.isArray(input) ? input : [input];
6561
- }
6562
- /**
6563
- * Applies a function to single value or an array of values.
6564
- * @param context The context which will be passed to the function.
6565
- * @param fn The function to apply.
6566
- * @returns The result of the function.
6567
- */
6568
- function applyMaybeArray(context, fn) {
6569
- if (context === undefined) {
6570
- return undefined;
6571
- }
6572
- if (Array.isArray(context)) {
6573
- return context
6574
- .map((e) => fn(e))
6575
- .filter((e) => !!e)
6576
- .flat();
6577
- }
6578
- else {
6579
- return fn(context);
6580
- }
6581
- }
6582
- /**
6583
- * Determines if the input is an empty array.
6584
- * @param obj Any value or array of values.
6585
- * @returns True if the input is an empty array.
6586
- */
6587
- function isEmptyArray(obj) {
6588
- return Array.isArray(obj) && obj.length === 0;
6589
- }
6590
- function isFalsy(obj) {
6591
- return !obj || isEmptyArray(obj);
6592
- }
6593
- /**
6594
- * Converts unknown object into a JavaScript boolean.
6595
- * Note that this is different than the FHIRPath "toBoolean",
6596
- * which has particular semantics around arrays, empty arrays, and type conversions.
6597
- * @param obj Any value or array of values.
6598
- * @returns The converted boolean value according to FHIRPath rules.
6599
- */
6600
- function toJsBoolean(obj) {
6601
- if (Array.isArray(obj)) {
6602
- return obj.length === 0 ? false : !!obj[0];
6524
+ var _MemoryRepository_resources, _MemoryRepository_history;
6525
+ class MemoryRepository {
6526
+ constructor() {
6527
+ _MemoryRepository_resources.set(this, void 0);
6528
+ _MemoryRepository_history.set(this, void 0);
6529
+ __classPrivateFieldSet(this, _MemoryRepository_resources, {}, "f");
6530
+ __classPrivateFieldSet(this, _MemoryRepository_history, {}, "f");
6603
6531
  }
6604
- return !!obj;
6605
- }
6606
- /**
6607
- * Removes duplicates in array using FHIRPath equality rules.
6608
- * @param arr The input array.
6609
- * @returns The result array with duplicates removed.
6610
- */
6611
- function removeDuplicates(arr) {
6612
- const result = [];
6613
- for (const i of arr) {
6614
- let found = false;
6615
- for (const j of result) {
6616
- if (fhirPathEquals(i, j)) {
6617
- found = true;
6618
- break;
6619
- }
6532
+ createResource(resource) {
6533
+ var _a;
6534
+ const result = resource;
6535
+ if (!result.id) {
6536
+ result.id = this.generateId();
6620
6537
  }
6621
- if (!found) {
6622
- result.push(i);
6538
+ if (!result.meta) {
6539
+ result.meta = {};
6623
6540
  }
6541
+ if (!((_a = result.meta) === null || _a === void 0 ? void 0 : _a.versionId)) {
6542
+ result.meta.versionId = this.generateId();
6543
+ }
6544
+ const { resourceType, id } = resource;
6545
+ if (!(resourceType in __classPrivateFieldGet(this, _MemoryRepository_resources, "f"))) {
6546
+ __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType] = {};
6547
+ }
6548
+ if (!(resourceType in __classPrivateFieldGet(this, _MemoryRepository_history, "f"))) {
6549
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType] = {};
6550
+ }
6551
+ if (!(id in __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType])) {
6552
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType][id] = [];
6553
+ }
6554
+ __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType][id] = resource;
6555
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType][id].push(result);
6556
+ return result;
6624
6557
  }
6625
- return result;
6626
- }
6627
- /**
6628
- * Determines if two values are equal according to FHIRPath equality rules.
6629
- * @param x The first value.
6630
- * @param y The second value.
6631
- * @returns True if equal.
6632
- */
6633
- function fhirPathEquals(x, y) {
6634
- if (isFalsy(x) && isFalsy(y)) {
6635
- return true;
6636
- }
6637
- if (isEmptyArray(x) || isEmptyArray(y)) {
6638
- return [];
6639
- }
6640
- if (typeof x === 'number' && typeof y === 'number') {
6641
- return Math.abs(x - y) < 1e-8;
6642
- }
6643
- if (isQuantity(x) && isQuantity(y)) {
6644
- return isQuantityEquivalent(x, y);
6645
- }
6646
- if (Array.isArray(x) && Array.isArray(y)) {
6647
- return x.length === y.length && x.every((val, index) => fhirPathEquals(val, y[index]));
6648
- }
6649
- if (typeof x === 'object' && typeof y === 'object') {
6650
- return deepEquals(x, y);
6651
- }
6652
- return x === y;
6653
- }
6654
- /**
6655
- * Determines if two values are equal according to FHIRPath equality rules.
6656
- * @param x The first value.
6657
- * @param y The second value.
6658
- * @returns True if equal.
6659
- */
6660
- function fhirPathEquivalent(x, y) {
6661
- if (isFalsy(x) && isFalsy(y)) {
6662
- return true;
6663
- }
6664
- if (isEmptyArray(x) || isEmptyArray(y)) {
6665
- // Note that this implies that if the collections have a different number of items to compare,
6666
- // or if one input is a value and the other is empty ({ }), the result will be false.
6667
- return false;
6668
- }
6669
- if (typeof x === 'number' && typeof y === 'number') {
6670
- // Use more generous threshold than equality
6671
- // Decimal: values must be equal, comparison is done on values rounded to the precision of the least precise operand.
6672
- // Trailing zeroes after the decimal are ignored in determining precision.
6673
- return Math.abs(x - y) < 0.01;
6674
- }
6675
- if (isQuantity(x) && isQuantity(y)) {
6676
- return isQuantityEquivalent(x, y);
6558
+ readResource(resourceType, id) {
6559
+ var _a, _b;
6560
+ return (_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id];
6677
6561
  }
6678
- if (Array.isArray(x) && Array.isArray(y)) {
6679
- // If both operands are collections with multiple items:
6680
- // 1) Each item must be equivalent
6681
- // 2) Comparison is not order dependent
6682
- x.sort();
6683
- y.sort();
6684
- return x.length === y.length && x.every((val, index) => fhirPathEquals(val, y[index]));
6562
+ readHistory(resourceType, id) {
6563
+ var _a, _b, _c;
6564
+ return {
6565
+ resourceType: 'Bundle',
6566
+ type: 'history',
6567
+ entry: ((_c = (_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_history, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) !== null && _c !== void 0 ? _c : [])
6568
+ .sort((version1, version2) => { var _a, _b, _c; return -((_b = (_a = version1.meta) === null || _a === void 0 ? void 0 : _a.lastUpdated) === null || _b === void 0 ? void 0 : _b.localeCompare((_c = version2.meta) === null || _c === void 0 ? void 0 : _c.lastUpdated)); })
6569
+ .map((version) => ({ resource: version })),
6570
+ };
6685
6571
  }
6686
- if (typeof x === 'object' && typeof y === 'object') {
6687
- return deepEquals(x, y);
6572
+ readVersion(resourceType, id, versionId) {
6573
+ var _a, _b, _c;
6574
+ return (_c = (_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_history, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) === null || _c === void 0 ? void 0 : _c.find((v) => { var _a; return ((_a = v.meta) === null || _a === void 0 ? void 0 : _a.versionId) === versionId; });
6688
6575
  }
6689
- if (typeof x === 'string' && typeof y === 'string') {
6690
- // String: the strings must be the same, ignoring case and locale, and normalizing whitespace
6691
- // (see String Equivalence for more details).
6692
- return x.toLowerCase() === y.toLowerCase();
6576
+ search(searchRequest) {
6577
+ var _a;
6578
+ const { resourceType } = searchRequest;
6579
+ const resources = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType]) !== null && _a !== void 0 ? _a : {};
6580
+ const result = Object.values(resources).filter((resource) => matchesSearchRequest(resource, searchRequest));
6581
+ return {
6582
+ resourceType: 'Bundle',
6583
+ type: 'searchset',
6584
+ entry: result.map((resource) => ({ resource })),
6585
+ total: result.length,
6586
+ };
6693
6587
  }
6694
- return x === y;
6695
- }
6696
- function fhirPathIs(value, desiredType) {
6697
- if (value === undefined || value === null) {
6698
- return false;
6588
+ deleteResource(resourceType, id) {
6589
+ var _a, _b;
6590
+ if ((_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) {
6591
+ delete __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType][id];
6592
+ }
6699
6593
  }
6700
- switch (desiredType) {
6701
- case 'Boolean':
6702
- return typeof value === 'boolean';
6703
- case 'Decimal':
6704
- case 'Integer':
6705
- return typeof value === 'number';
6706
- case 'Date':
6707
- return typeof value === 'string' && !!value.match(/^\d{4}(-\d{2}(-\d{2})?)?/);
6708
- case 'DateTime':
6709
- return typeof value === 'string' && !!value.match(/^\d{4}(-\d{2}(-\d{2})?)?T/);
6710
- case 'Time':
6711
- return typeof value === 'string' && !!value.match(/^T\d/);
6712
- case 'Period':
6713
- return isPeriod(value);
6714
- case 'Quantity':
6715
- return isQuantity(value);
6716
- default:
6717
- return typeof value === 'object' && (value === null || value === void 0 ? void 0 : value.resourceType) === desiredType;
6594
+ generateId() {
6595
+ return Date.now().toString(36);
6718
6596
  }
6719
6597
  }
6598
+ _MemoryRepository_resources = new WeakMap(), _MemoryRepository_history = new WeakMap();
6720
6599
  /**
6721
- * Determines if the input is a Period object.
6722
- * This is heuristic based, as we do not have strong typing at runtime.
6723
- * @param input The input value.
6724
- * @returns True if the input is a period.
6725
- */
6726
- function isPeriod(input) {
6727
- return !!(input && typeof input === 'object' && 'start' in input);
6728
- }
6729
- /**
6730
- * Determines if the input is a Quantity object.
6731
- * This is heuristic based, as we do not have strong typing at runtime.
6732
- * @param input The input value.
6733
- * @returns True if the input is a quantity.
6734
- */
6735
- function isQuantity(input) {
6736
- return !!(input && typeof input === 'object' && 'value' in input && typeof input.value === 'number');
6737
- }
6738
- function isQuantityEquivalent(x, y) {
6739
- return (Math.abs(x.value - y.value) < 0.01 &&
6740
- (x.unit === y.unit || x.code === y.code || x.unit === y.code || x.code === y.unit));
6741
- }
6742
- /**
6743
- * Resource equality.
6744
- * Ignores meta.versionId and meta.lastUpdated.
6745
- * See: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/#4-deep-equality
6746
- * @param object1 The first object.
6747
- * @param object2 The second object.
6748
- * @returns True if the objects are equal.
6600
+ * Determines if the resource matches the search request.
6601
+ * @param resource The resource that was created or updated.
6602
+ * @param searchRequest The subscription criteria as a search request.
6603
+ * @returns True if the resource satisfies the search request.
6749
6604
  */
6750
- function deepEquals(object1, object2) {
6751
- const keys1 = Object.keys(object1);
6752
- const keys2 = Object.keys(object2);
6753
- if (keys1.length !== keys2.length) {
6605
+ function matchesSearchRequest(resource, searchRequest) {
6606
+ if (searchRequest.resourceType !== resource.resourceType) {
6754
6607
  return false;
6755
6608
  }
6756
- for (const key of keys1) {
6757
- const val1 = object1[key];
6758
- const val2 = object2[key];
6759
- if (isObject(val1) && isObject(val2)) {
6760
- if (!deepEquals(val1, val2)) {
6761
- return false;
6762
- }
6763
- }
6764
- else {
6765
- if (val1 !== val2) {
6609
+ if (searchRequest.filters) {
6610
+ for (const filter of searchRequest.filters) {
6611
+ if (!matchesSearchFilter(resource, filter)) {
6766
6612
  return false;
6767
6613
  }
6768
6614
  }
6769
6615
  }
6770
6616
  return true;
6771
6617
  }
6772
- function isObject(object) {
6773
- return object !== null && typeof object === 'object';
6774
- }
6775
-
6776
- class FhirPathAtom {
6777
- constructor(original, child) {
6778
- this.original = original;
6779
- this.child = child;
6780
- }
6781
- eval(context) {
6782
- try {
6783
- const result = applyMaybeArray(context, (e) => this.child.eval(e));
6784
- if (Array.isArray(result)) {
6785
- return result.flat();
6786
- }
6787
- else if (result === undefined || result === null) {
6788
- return [];
6789
- }
6790
- else {
6791
- return [result];
6792
- }
6793
- }
6794
- catch (error) {
6795
- throw new Error(`FhirPathError on "${this.original}": ${error}`);
6618
+ /**
6619
+ * Determines if the resource matches the search filter.
6620
+ * @param resource The resource that was created or updated.
6621
+ * @param filter One of the filters of a subscription criteria.
6622
+ * @returns True if the resource satisfies the search filter.
6623
+ */
6624
+ function matchesSearchFilter(resource, filter) {
6625
+ for (const filterValue of filter.value.split(',')) {
6626
+ if (matchesSearchFilterValue(resource, filter, filterValue)) {
6627
+ return true;
6796
6628
  }
6797
6629
  }
6630
+ return false;
6798
6631
  }
6799
- class LiteralAtom {
6800
- constructor(value) {
6801
- this.value = value;
6802
- }
6803
- eval() {
6804
- return this.value;
6805
- }
6632
+ function matchesSearchFilterValue(resource, filter, filterValue) {
6633
+ const expression = filter.code.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
6634
+ const values = core.evalFhirPath(expression, resource);
6635
+ const result = values.some((value) => JSON.stringify(value).toLowerCase().includes(filterValue.toLowerCase()));
6636
+ return filter.operator === core.Operator.NOT_EQUALS ? !result : result;
6806
6637
  }
6807
- class SymbolAtom {
6808
- constructor(name) {
6809
- this.name = name;
6810
- }
6811
- eval(context) {
6812
- if (this.name === '$this') {
6813
- return context;
6814
- }
6815
- return applyMaybeArray(context, (e) => {
6816
- if (e && typeof e === 'object') {
6817
- if ('resourceType' in e && e.resourceType === this.name) {
6818
- return e;
6638
+
6639
+ class MockClient extends core.MedplumClient {
6640
+ constructor(clientOptions) {
6641
+ super({
6642
+ baseUrl: 'https://example.com/',
6643
+ clientId: 'my-client-id',
6644
+ fetch: (url, options) => {
6645
+ const method = options.method || 'GET';
6646
+ const path = url.replace('https://example.com/', '');
6647
+ if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
6648
+ console.log('MockClient', method, path);
6819
6649
  }
6820
- if (this.name in e) {
6821
- return e[this.name];
6650
+ const response = mockHandler(method, path, options);
6651
+ if ((clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) && !response) {
6652
+ console.log('MockClient: not found', method, path);
6822
6653
  }
6823
- const propertyName = Object.keys(e).find((k) => k.startsWith(this.name));
6824
- if (propertyName) {
6825
- return e[propertyName];
6654
+ if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
6655
+ console.log('MockClient', JSON.stringify(response, null, 2));
6826
6656
  }
6827
- }
6828
- return undefined;
6657
+ return Promise.resolve({
6658
+ blob: () => Promise.resolve(response),
6659
+ json: () => Promise.resolve(response),
6660
+ });
6661
+ },
6829
6662
  });
6830
6663
  }
6831
- }
6832
- class EmptySetAtom {
6833
- eval() {
6834
- return [];
6835
- }
6836
- }
6837
- class UnaryOperatorAtom {
6838
- constructor(child, impl) {
6839
- this.child = child;
6840
- this.impl = impl;
6841
- }
6842
- eval(context) {
6843
- return this.impl(this.child.eval(context));
6844
- }
6845
- }
6846
- class AsAtom {
6847
- constructor(left, right) {
6848
- this.left = left;
6849
- this.right = right;
6664
+ clear() {
6665
+ super.clear();
6666
+ this.activeLoginOverride = undefined;
6850
6667
  }
6851
- eval(context) {
6852
- return this.left.eval(context);
6668
+ getProfile() {
6669
+ return {
6670
+ resourceType: 'Practitioner',
6671
+ id: '123',
6672
+ meta: {
6673
+ versionId: '456',
6674
+ },
6675
+ };
6853
6676
  }
6854
- }
6855
- class ArithemticOperatorAtom {
6856
- constructor(left, right, impl) {
6857
- this.left = left;
6858
- this.right = right;
6859
- this.impl = impl;
6677
+ setActiveLoginOverride(activeLoginOverride) {
6678
+ this.activeLoginOverride = activeLoginOverride;
6860
6679
  }
6861
- eval(context) {
6862
- const leftValue = this.left.eval(context);
6863
- const rightValue = this.right.eval(context);
6864
- if (isQuantity(leftValue) && isQuantity(rightValue)) {
6865
- return Object.assign(Object.assign({}, leftValue), { value: this.impl(leftValue.value, rightValue.value) });
6866
- }
6867
- else {
6868
- return this.impl(leftValue, rightValue);
6680
+ getActiveLogin() {
6681
+ if (this.activeLoginOverride !== undefined) {
6682
+ return this.activeLoginOverride;
6869
6683
  }
6684
+ return super.getActiveLogin();
6870
6685
  }
6871
- }
6872
- class ComparisonOperatorAtom {
6873
- constructor(left, right, impl) {
6874
- this.left = left;
6875
- this.right = right;
6876
- this.impl = impl;
6877
- }
6878
- eval(context) {
6879
- const leftValue = this.left.eval(context);
6880
- const rightValue = this.right.eval(context);
6881
- if (isQuantity(leftValue) && isQuantity(rightValue)) {
6882
- return this.impl(leftValue.value, rightValue.value);
6883
- }
6884
- else {
6885
- return this.impl(leftValue, rightValue);
6686
+ createBinary(_data, filename, contentType) {
6687
+ if (filename.endsWith('.exe')) {
6688
+ return Promise.reject(core.badRequest('Invalid file type'));
6886
6689
  }
6690
+ return Promise.resolve({
6691
+ resourceType: 'Binary',
6692
+ title: filename,
6693
+ contentType,
6694
+ url: 'https://example.com/binary/123',
6695
+ });
6887
6696
  }
6888
6697
  }
6889
- class ConcatAtom {
6890
- constructor(left, right) {
6891
- this.left = left;
6892
- this.right = right;
6698
+ function mockHandler(method, path, options) {
6699
+ if (path.startsWith('admin/')) {
6700
+ return mockAdminHandler(method, path);
6893
6701
  }
6894
- eval(context) {
6895
- const leftValue = this.left.eval(context);
6896
- const rightValue = this.right.eval(context);
6897
- const result = [];
6898
- function add(value) {
6899
- if (value) {
6900
- if (Array.isArray(value)) {
6901
- result.push(...value);
6902
- }
6903
- else {
6904
- result.push(value);
6905
- }
6906
- }
6907
- }
6908
- add(leftValue);
6909
- add(rightValue);
6910
- if (result.length > 0 && result.every((e) => typeof e === 'string')) {
6911
- return result.join('');
6912
- }
6913
- return result;
6702
+ else if (path.startsWith('auth/')) {
6703
+ return mockAuthHandler(method, path, options);
6914
6704
  }
6915
- }
6916
- class ContainsAtom {
6917
- constructor(left, right) {
6918
- this.left = left;
6919
- this.right = right;
6705
+ else if (path.startsWith('fhir/R4')) {
6706
+ return mockFhirHandler(method, path, options);
6920
6707
  }
6921
- eval(context) {
6922
- const leftValue = this.left.eval(context);
6923
- const rightValue = this.right.eval(context);
6924
- return ensureArray(leftValue).includes(rightValue);
6708
+ else {
6709
+ return null;
6925
6710
  }
6926
6711
  }
6927
- class InAtom {
6928
- constructor(left, right) {
6929
- this.left = left;
6930
- this.right = right;
6931
- }
6932
- eval(context) {
6933
- const leftValue = this.left.eval(context);
6934
- const rightValue = this.right.eval(context);
6935
- return ensureArray(rightValue).includes(leftValue);
6712
+ function mockAdminHandler(_method, path) {
6713
+ if (path.startsWith('admin/projects/123')) {
6714
+ return {
6715
+ project: { id: '123', name: 'Project 123' },
6716
+ members: [
6717
+ { id: '123', profile: { reference: 'Practitioner/123', display: 'Alice Smith' }, role: 'owner' },
6718
+ { id: '888', profile: { reference: 'ClientApplication/123', display: 'Test Client' }, role: 'client' },
6719
+ { id: '999', profile: { reference: 'Bot/123', display: 'Test Bot' }, role: 'bot' },
6720
+ ],
6721
+ };
6936
6722
  }
6723
+ return {
6724
+ ok: true,
6725
+ };
6937
6726
  }
6938
- class DotAtom {
6939
- constructor(left, right) {
6940
- this.left = left;
6941
- this.right = right;
6727
+ function mockAuthHandler(method, path, options) {
6728
+ if (path.startsWith('auth/changepassword')) {
6729
+ return mockChangePasswordHandler(method, path, options);
6942
6730
  }
6943
- eval(context) {
6944
- return this.right.eval(this.left.eval(context));
6945
- }
6946
- }
6947
- class UnionAtom {
6948
- constructor(left, right) {
6949
- this.left = left;
6950
- this.right = right;
6951
- }
6952
- eval(context) {
6953
- const leftResult = this.left.eval(context);
6954
- const rightResult = this.right.eval(context);
6955
- let resultArray;
6956
- if (leftResult !== undefined && rightResult !== undefined) {
6957
- resultArray = [leftResult, rightResult].flat();
6958
- }
6959
- else if (leftResult !== undefined) {
6960
- resultArray = ensureArray(leftResult);
6961
- }
6962
- else if (rightResult !== undefined) {
6963
- resultArray = ensureArray(rightResult);
6964
- }
6965
- else {
6966
- resultArray = [];
6967
- }
6968
- return removeDuplicates(resultArray);
6969
- }
6970
- }
6971
- class EqualsAtom {
6972
- constructor(left, right) {
6973
- this.left = left;
6974
- this.right = right;
6975
- }
6976
- eval(context) {
6977
- const leftValue = this.left.eval(context);
6978
- const rightValue = this.right.eval(context);
6979
- if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
6980
- return fhirPathEquals(leftValue.flat(), rightValue);
6981
- }
6982
- return applyMaybeArray(leftValue, (e) => fhirPathEquals(e, rightValue));
6983
- }
6984
- }
6985
- class NotEqualsAtom {
6986
- constructor(left, right) {
6987
- this.left = left;
6988
- this.right = right;
6989
- }
6990
- eval(context) {
6991
- const leftValue = this.left.eval(context);
6992
- const rightValue = this.right.eval(context);
6993
- let result;
6994
- if (Array.isArray(rightValue)) {
6995
- result = fhirPathEquals(leftValue, rightValue);
6996
- }
6997
- else {
6998
- result = applyMaybeArray(leftValue, (e) => fhirPathEquals(e, rightValue));
6999
- }
7000
- return !toJsBoolean(result);
7001
- }
7002
- }
7003
- class EquivalentAtom {
7004
- constructor(left, right) {
7005
- this.left = left;
7006
- this.right = right;
7007
- }
7008
- eval(context) {
7009
- const leftValue = this.left.eval(context);
7010
- const rightValue = this.right.eval(context);
7011
- if (Array.isArray(rightValue)) {
7012
- return fhirPathEquivalent(leftValue, rightValue);
7013
- }
7014
- return applyMaybeArray(leftValue, (e) => fhirPathEquivalent(e, rightValue));
7015
- }
7016
- }
7017
- class NotEquivalentAtom {
7018
- constructor(left, right) {
7019
- this.left = left;
7020
- this.right = right;
7021
- }
7022
- eval(context) {
7023
- const leftValue = this.left.eval(context);
7024
- const rightValue = this.right.eval(context);
7025
- let result;
7026
- if (Array.isArray(rightValue)) {
7027
- result = fhirPathEquivalent(leftValue, rightValue);
7028
- }
7029
- else {
7030
- result = applyMaybeArray(leftValue, (e) => fhirPathEquivalent(e, rightValue));
7031
- }
7032
- return !toJsBoolean(result);
7033
- }
7034
- }
7035
- class IsAtom {
7036
- constructor(left, right) {
7037
- this.left = left;
7038
- this.right = right;
7039
- }
7040
- eval(context) {
7041
- const typeName = this.right.name;
7042
- return applyMaybeArray(this.left.eval(context), (e) => fhirPathIs(e, typeName));
7043
- }
7044
- }
7045
- /**
7046
- * 6.5.1. and
7047
- * Returns true if both operands evaluate to true, false if either operand evaluates to false, and the empty collection ({ }) otherwise.
7048
- */
7049
- class AndAtom {
7050
- constructor(left, right) {
7051
- this.left = left;
7052
- this.right = right;
7053
- }
7054
- eval(context) {
7055
- const leftValue = this.left.eval(context);
7056
- const rightValue = this.right.eval(context);
7057
- if (leftValue === true && rightValue === true) {
7058
- return true;
7059
- }
7060
- if (leftValue === false || rightValue === false) {
7061
- return false;
7062
- }
7063
- return [];
7064
- }
7065
- }
7066
- class OrAtom {
7067
- constructor(left, right) {
7068
- this.left = left;
7069
- this.right = right;
7070
- }
7071
- eval(context) {
7072
- const leftValue = this.left.eval(context);
7073
- if (toJsBoolean(leftValue)) {
7074
- return leftValue;
7075
- }
7076
- const rightValue = this.right.eval(context);
7077
- if (toJsBoolean(rightValue)) {
7078
- return rightValue;
7079
- }
7080
- return [];
7081
- }
7082
- }
7083
- /**
7084
- * 6.5.4. xor
7085
- * Returns true if exactly one of the operands evaluates to true,
7086
- * false if either both operands evaluate to true or both operands evaluate to false,
7087
- * and the empty collection ({ }) otherwise:
7088
- */
7089
- class XorAtom {
7090
- constructor(left, right) {
7091
- this.left = left;
7092
- this.right = right;
7093
- }
7094
- eval(context) {
7095
- const leftValue = this.left.eval(context);
7096
- const rightValue = this.right.eval(context);
7097
- if ((leftValue === true && rightValue !== true) || (leftValue !== true && rightValue === true)) {
7098
- return true;
7099
- }
7100
- if ((leftValue === true && rightValue === true) || (leftValue === false && rightValue === false)) {
7101
- return false;
7102
- }
7103
- return [];
7104
- }
7105
- }
7106
- class FunctionAtom {
7107
- constructor(name, args, impl) {
7108
- this.name = name;
7109
- this.args = args;
7110
- this.impl = impl;
7111
- }
7112
- eval(context) {
7113
- return this.impl(ensureArray(context), ...this.args);
7114
- }
7115
- }
7116
- class IndexerAtom {
7117
- constructor(left, expr) {
7118
- this.left = left;
7119
- this.expr = expr;
7120
- }
7121
- eval(context) {
7122
- const index = this.expr.eval(context);
7123
- if (typeof index !== 'number') {
7124
- throw new Error(`Invalid indexer expression: should return integer}`);
7125
- }
7126
- const leftResult = this.left.eval(context);
7127
- if (!(index in leftResult)) {
7128
- return [];
7129
- }
7130
- return leftResult[index];
7131
- }
7132
- }
7133
-
7134
- function parseDateString(str) {
7135
- if (str.startsWith('T')) {
7136
- // If a time string,
7137
- // then normalize to full length.
7138
- return str + 'T00:00:00.000Z'.substring(str.length);
7139
- }
7140
- if (str.length <= 10) {
7141
- // If a local date (i.e., "2021-01-01"),
7142
- // then return as-is.
7143
- return str;
7144
- }
7145
- try {
7146
- // Try to normalize to UTC
7147
- return new Date(str).toISOString();
7148
- }
7149
- catch (e) {
7150
- // Fallback to original input
7151
- // This happens on unsupported time formats such as "2021-01-01T12"
7152
- return str;
7153
- }
7154
- }
7155
-
7156
- /*
7157
- * Collection of FHIRPath
7158
- * See: https://hl7.org/fhirpath/#functions
7159
- */
7160
- /**
7161
- * Temporary placholder for unimplemented methods.
7162
- */
7163
- const stub = () => [];
7164
- /*
7165
- * 5.1 Existence
7166
- * See: https://hl7.org/fhirpath/#existence
7167
- */
7168
- /**
7169
- * Returns true if the input collection is empty ({ }) and false otherwise.
7170
- *
7171
- * See: https://hl7.org/fhirpath/#empty-boolean
7172
- *
7173
- * @param input The input collection.
7174
- * @returns True if the input collection is empty ({ }) and false otherwise.
7175
- */
7176
- function empty(input) {
7177
- return [input.length === 0];
7178
- }
7179
- /**
7180
- * Returns true if the collection has unknown elements, and false otherwise.
7181
- * This is the opposite of empty(), and as such is a shorthand for empty().not().
7182
- * If the input collection is empty ({ }), the result is false.
7183
- *
7184
- * The function can also take an optional criteria to be applied to the collection
7185
- * prior to the determination of the exists. In this case, the function is shorthand
7186
- * for where(criteria).exists().
7187
- *
7188
- * See: https://hl7.org/fhirpath/#existscriteria-expression-boolean
7189
- *
7190
- * @param input
7191
- * @param criteria
7192
- * @returns True if the collection has unknown elements, and false otherwise.
7193
- */
7194
- function exists(input, criteria) {
7195
- if (criteria) {
7196
- return [input.filter((e) => toJsBoolean(criteria.eval(e))).length > 0];
7197
- }
7198
- else {
7199
- return [input.length > 0];
7200
- }
7201
- }
7202
- /**
7203
- * Returns true if for every element in the input collection, criteria evaluates to true.
7204
- * Otherwise, the result is false.
7205
- *
7206
- * If the input collection is empty ({ }), the result is true.
7207
- *
7208
- * See: https://hl7.org/fhirpath/#allcriteria-expression-boolean
7209
- *
7210
- * @param input The input collection.
7211
- * @param criteria The evaluation criteria.
7212
- * @returns True if for every element in the input collection, criteria evaluates to true.
7213
- */
7214
- function all(input, criteria) {
7215
- return [input.every((e) => toJsBoolean(criteria.eval(e)))];
7216
- }
7217
- /**
7218
- * Takes a collection of Boolean values and returns true if all the items are true.
7219
- * If unknown items are false, the result is false.
7220
- * If the input is empty ({ }), the result is true.
7221
- *
7222
- * See: https://hl7.org/fhirpath/#alltrue-boolean
7223
- *
7224
- * @param input The input collection.
7225
- * @param criteria The evaluation criteria.
7226
- * @returns True if all the items are true.
7227
- */
7228
- function allTrue(input) {
7229
- for (const value of input) {
7230
- if (!value) {
7231
- return [false];
7232
- }
7233
- }
7234
- return [true];
7235
- }
7236
- /**
7237
- * Takes a collection of Boolean values and returns true if unknown of the items are true.
7238
- * If all the items are false, or if the input is empty ({ }), the result is false.
7239
- *
7240
- * See: https://hl7.org/fhirpath/#anytrue-boolean
7241
- *
7242
- * @param input The input collection.
7243
- * @param criteria The evaluation criteria.
7244
- * @returns True if unknown of the items are true.
7245
- */
7246
- function anyTrue(input) {
7247
- for (const value of input) {
7248
- if (value) {
7249
- return [true];
7250
- }
7251
- }
7252
- return [false];
7253
- }
7254
- /**
7255
- * Takes a collection of Boolean values and returns true if all the items are false.
7256
- * If unknown items are true, the result is false.
7257
- * If the input is empty ({ }), the result is true.
7258
- *
7259
- * See: https://hl7.org/fhirpath/#allfalse-boolean
7260
- *
7261
- * @param input The input collection.
7262
- * @param criteria The evaluation criteria.
7263
- * @returns True if all the items are false.
7264
- */
7265
- function allFalse(input) {
7266
- for (const value of input) {
7267
- if (value) {
7268
- return [false];
7269
- }
7270
- }
7271
- return [true];
7272
- }
7273
- /**
7274
- * Takes a collection of Boolean values and returns true if unknown of the items are false.
7275
- * If all the items are true, or if the input is empty ({ }), the result is false.
7276
- *
7277
- * See: https://hl7.org/fhirpath/#anyfalse-boolean
7278
- *
7279
- * @param input The input collection.
7280
- * @param criteria The evaluation criteria.
7281
- * @returns True if for every element in the input collection, criteria evaluates to true.
7282
- */
7283
- function anyFalse(input) {
7284
- for (const value of input) {
7285
- if (!value) {
7286
- return [true];
7287
- }
7288
- }
7289
- return [false];
7290
- }
7291
- /**
7292
- * Returns true if all items in the input collection are members of the collection passed
7293
- * as the other argument. Membership is determined using the = (Equals) (=) operation.
7294
- *
7295
- * Conceptually, this function is evaluated by testing each element in the input collection
7296
- * for membership in the other collection, with a default of true. This means that if the
7297
- * input collection is empty ({ }), the result is true, otherwise if the other collection
7298
- * is empty ({ }), the result is false.
7299
- *
7300
- * See: http://hl7.org/fhirpath/#subsetofother-collection-boolean
7301
- */
7302
- const subsetOf = stub;
7303
- /**
7304
- * Returns true if all items in the collection passed as the other argument are members of
7305
- * the input collection. Membership is determined using the = (Equals) (=) operation.
7306
- *
7307
- * Conceptually, this function is evaluated by testing each element in the other collection
7308
- * for membership in the input collection, with a default of true. This means that if the
7309
- * other collection is empty ({ }), the result is true, otherwise if the input collection
7310
- * is empty ({ }), the result is false.
7311
- *
7312
- * See: http://hl7.org/fhirpath/#supersetofother-collection-boolean
7313
- */
7314
- const supersetOf = stub;
7315
- /**
7316
- * Returns the integer count of the number of items in the input collection.
7317
- * Returns 0 when the input collection is empty.
7318
- *
7319
- * See: https://hl7.org/fhirpath/#count-integer
7320
- *
7321
- * @param input The input collection.
7322
- * @returns The integer count of the number of items in the input collection.
7323
- */
7324
- function count(input) {
7325
- return [input.length];
7326
- }
7327
- /**
7328
- * Returns a collection containing only the unique items in the input collection.
7329
- * To determine whether two items are the same, the = (Equals) (=) operator is used,
7330
- * as defined below.
7331
- *
7332
- * If the input collection is empty ({ }), the result is empty.
7333
- *
7334
- * Note that the order of elements in the input collection is not guaranteed to be
7335
- * preserved in the result.
7336
- *
7337
- * See: https://hl7.org/fhirpath/#distinct-collection
7338
- *
7339
- * @param input The input collection.
7340
- * @returns The integer count of the number of items in the input collection.
7341
- */
7342
- function distinct(input) {
7343
- return Array.from(new Set(input));
7344
- }
7345
- /**
7346
- * Returns true if all the items in the input collection are distinct.
7347
- * To determine whether two items are distinct, the = (Equals) (=) operator is used,
7348
- * as defined below.
7349
- *
7350
- * See: https://hl7.org/fhirpath/#isdistinct-boolean
7351
- *
7352
- * @param input The input collection.
7353
- * @returns The integer count of the number of items in the input collection.
7354
- */
7355
- function isDistinct(input) {
7356
- return [input.length === new Set(input).size];
7357
- }
7358
- /*
7359
- * 5.2 Filtering and projection
7360
- */
7361
- /**
7362
- * Returns a collection containing only those elements in the input collection
7363
- * for which the stated criteria expression evaluates to true.
7364
- * Elements for which the expression evaluates to false or empty ({ }) are not
7365
- * included in the result.
7366
- *
7367
- * If the input collection is empty ({ }), the result is empty.
7368
- *
7369
- * If the result of evaluating the condition is other than a single boolean value,
7370
- * the evaluation will end and signal an error to the calling environment,
7371
- * consistent with singleton evaluation of collections behavior.
7372
- *
7373
- * See: https://hl7.org/fhirpath/#wherecriteria-expression-collection
7374
- *
7375
- * @param input The input collection.
7376
- * @param condition The condition atom.
7377
- * @returns A collection containing only those elements in the input collection for which the stated criteria expression evaluates to true.
7378
- */
7379
- function where(input, criteria) {
7380
- return input.filter((e) => toJsBoolean(criteria.eval(e)));
7381
- }
7382
- /**
7383
- * Evaluates the projection expression for each item in the input collection.
7384
- * The result of each evaluation is added to the output collection. If the
7385
- * evaluation results in a collection with multiple items, all items are added
7386
- * to the output collection (collections resulting from evaluation of projection
7387
- * are flattened). This means that if the evaluation for an element results in
7388
- * the empty collection ({ }), no element is added to the result, and that if
7389
- * the input collection is empty ({ }), the result is empty as well.
7390
- *
7391
- * See: http://hl7.org/fhirpath/#selectprojection-expression-collection
7392
- */
7393
- function select(input, criteria) {
7394
- return ensureArray(input.map((e) => criteria.eval(e)).flat());
7395
- }
7396
- /**
7397
- * A version of select that will repeat the projection and add it to the output
7398
- * collection, as long as the projection yields new items (as determined by
7399
- * the = (Equals) (=) operator).
7400
- *
7401
- * See: http://hl7.org/fhirpath/#repeatprojection-expression-collection
7402
- */
7403
- const repeat = stub;
7404
- /**
7405
- * Returns a collection that contains all items in the input collection that
7406
- * are of the given type or a subclass thereof. If the input collection is
7407
- * empty ({ }), the result is empty. The type argument is an identifier that
7408
- * must resolve to the name of a type in a model
7409
- *
7410
- * See: http://hl7.org/fhirpath/#oftypetype-type-specifier-collection
7411
- */
7412
- const ofType = stub;
7413
- /*
7414
- * 5.3 Subsetting
7415
- */
7416
- /**
7417
- * Will return the single item in the input if there is just one item.
7418
- * If the input collection is empty ({ }), the result is empty.
7419
- * If there are multiple items, an error is signaled to the evaluation environment.
7420
- * This function is useful for ensuring that an error is returned if an assumption
7421
- * about cardinality is violated at run-time.
7422
- *
7423
- * See: https://hl7.org/fhirpath/#single-collection
7424
- *
7425
- * @param input The input collection.
7426
- * @returns The single item in the input if there is just one item.
7427
- */
7428
- function single(input) {
7429
- if (input.length > 1) {
7430
- throw new Error('Expected input length one for single()');
7431
- }
7432
- return input.length === 0 ? [] : input.slice(0, 1);
7433
- }
7434
- /**
7435
- * Returns a collection containing only the first item in the input collection.
7436
- * This function is equivalent to item[0], so it will return an empty collection if the input collection has no items.
7437
- *
7438
- * See: https://hl7.org/fhirpath/#first-collection
7439
- *
7440
- * @param input The input collection.
7441
- * @returns A collection containing only the first item in the input collection.
7442
- */
7443
- function first(input) {
7444
- return input.length === 0 ? [] : [input[0]];
7445
- }
7446
- /**
7447
- * Returns a collection containing only the last item in the input collection.
7448
- * Will return an empty collection if the input collection has no items.
7449
- *
7450
- * See: https://hl7.org/fhirpath/#last-collection
7451
- *
7452
- * @param input The input collection.
7453
- * @returns A collection containing only the last item in the input collection.
7454
- */
7455
- function last(input) {
7456
- return input.length === 0 ? [] : [input[input.length - 1]];
7457
- }
7458
- /**
7459
- * Returns a collection containing all but the first item in the input collection.
7460
- * Will return an empty collection if the input collection has no items, or only one item.
7461
- *
7462
- * See: https://hl7.org/fhirpath/#tail-collection
7463
- *
7464
- * @param input The input collection.
7465
- * @returns A collection containing all but the first item in the input collection.
7466
- */
7467
- function tail(input) {
7468
- return input.length === 0 ? [] : input.slice(1, input.length);
7469
- }
7470
- /**
7471
- * Returns a collection containing all but the first num items in the input collection.
7472
- * Will return an empty collection if there are no items remaining after the
7473
- * indicated number of items have been skipped, or if the input collection is empty.
7474
- * If num is less than or equal to zero, the input collection is simply returned.
7475
- *
7476
- * See: https://hl7.org/fhirpath/#skipnum-integer-collection
7477
- *
7478
- * @param input The input collection.
7479
- * @returns A collection containing all but the first item in the input collection.
7480
- */
7481
- function skip(input, num) {
7482
- const numValue = num.eval(0);
7483
- if (typeof numValue !== 'number') {
7484
- throw new Error('Expected a number for skip(num)');
7485
- }
7486
- if (numValue >= input.length) {
7487
- return [];
7488
- }
7489
- if (numValue <= 0) {
7490
- return input;
7491
- }
7492
- return input.slice(numValue, input.length);
7493
- }
7494
- /**
7495
- * Returns a collection containing the first num items in the input collection,
7496
- * or less if there are less than num items.
7497
- * If num is less than or equal to 0, or if the input collection is empty ({ }),
7498
- * take returns an empty collection.
7499
- *
7500
- * See: https://hl7.org/fhirpath/#takenum-integer-collection
7501
- *
7502
- * @param input The input collection.
7503
- * @returns A collection containing the first num items in the input collection.
7504
- */
7505
- function take(input, num) {
7506
- const numValue = num.eval(0);
7507
- if (typeof numValue !== 'number') {
7508
- throw new Error('Expected a number for take(num)');
7509
- }
7510
- if (numValue >= input.length) {
7511
- return input;
7512
- }
7513
- if (numValue <= 0) {
7514
- return [];
7515
- }
7516
- return input.slice(0, numValue);
7517
- }
7518
- /**
7519
- * Returns the set of elements that are in both collections.
7520
- * Duplicate items will be eliminated by this function.
7521
- * Order of items is not guaranteed to be preserved in the result of this function.
7522
- *
7523
- * See: http://hl7.org/fhirpath/#intersectother-collection-collection
7524
- */
7525
- function intersect(input, other) {
7526
- if (!other) {
7527
- return input;
7528
- }
7529
- const otherArray = ensureArray(other.eval(0));
7530
- return removeDuplicates(input.filter((e) => otherArray.includes(e)));
7531
- }
7532
- /**
7533
- * Returns the set of elements that are not in the other collection.
7534
- * Duplicate items will not be eliminated by this function, and order will be preserved.
7535
- *
7536
- * e.g. (1 | 2 | 3).exclude(2) returns (1 | 3).
7537
- *
7538
- * See: http://hl7.org/fhirpath/#excludeother-collection-collection
7539
- */
7540
- function exclude(input, other) {
7541
- if (!other) {
7542
- return input;
7543
- }
7544
- const otherArray = ensureArray(other.eval(0));
7545
- return input.filter((e) => !otherArray.includes(e));
7546
- }
7547
- /*
7548
- * 5.4. Combining
7549
- *
7550
- * See: https://hl7.org/fhirpath/#combining
7551
- */
7552
- /**
7553
- * Merge the two collections into a single collection,
7554
- * eliminating unknown duplicate values (using = (Equals) (=) to determine equality).
7555
- * There is no expectation of order in the resulting collection.
7556
- *
7557
- * In other words, this function returns the distinct list of elements from both inputs.
7558
- *
7559
- * See: http://hl7.org/fhirpath/#unionother-collection
7560
- */
7561
- function union(input, other) {
7562
- if (!other) {
7563
- return input;
7564
- }
7565
- return removeDuplicates([input, other.eval(0)].flat());
7566
- }
7567
- /**
7568
- * Merge the input and other collections into a single collection
7569
- * without eliminating duplicate values. Combining an empty collection
7570
- * with a non-empty collection will return the non-empty collection.
7571
- *
7572
- * There is no expectation of order in the resulting collection.
7573
- *
7574
- * See: http://hl7.org/fhirpath/#combineother-collection-collection
7575
- */
7576
- function combine(input, other) {
7577
- if (!other) {
7578
- return input;
7579
- }
7580
- return [input, other.eval(0)].flat();
7581
- }
7582
- /*
7583
- * 5.5. Conversion
7584
- *
7585
- * See: https://hl7.org/fhirpath/#conversion
7586
- */
7587
- /**
7588
- * The iif function in FHIRPath is an immediate if,
7589
- * also known as a conditional operator (such as C’s ? : operator).
7590
- *
7591
- * The criterion expression is expected to evaluate to a Boolean.
7592
- *
7593
- * If criterion is true, the function returns the value of the true-result argument.
7594
- *
7595
- * If criterion is false or an empty collection, the function returns otherwise-result,
7596
- * unless the optional otherwise-result is not given, in which case the function returns an empty collection.
7597
- *
7598
- * Note that short-circuit behavior is expected in this function. In other words,
7599
- * true-result should only be evaluated if the criterion evaluates to true,
7600
- * and otherwise-result should only be evaluated otherwise. For implementations,
7601
- * this means delaying evaluation of the arguments.
7602
- *
7603
- * @param input
7604
- * @param criterion
7605
- * @param trueResult
7606
- * @param otherwiseResult
7607
- * @returns
7608
- */
7609
- function iif(input, criterion, trueResult, otherwiseResult) {
7610
- const evalResult = ensureArray(criterion.eval(input));
7611
- if (evalResult.length > 1 || (evalResult.length === 1 && typeof evalResult[0] !== 'boolean')) {
7612
- throw new Error('Expected criterion to evaluate to a Boolean');
7613
- }
7614
- if (toJsBoolean(evalResult)) {
7615
- return ensureArray(trueResult.eval(input));
7616
- }
7617
- if (otherwiseResult) {
7618
- return ensureArray(otherwiseResult.eval(input));
7619
- }
7620
- return [];
7621
- }
7622
- /**
7623
- * Converts an input collection to a boolean.
7624
- *
7625
- * If the input collection contains a single item, this function will return a single boolean if:
7626
- * 1) the item is a Boolean
7627
- * 2) the item is an Integer and is equal to one of the possible integer representations of Boolean values
7628
- * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
7629
- * 4) the item is a String that is equal to one of the possible string representations of Boolean values
7630
- *
7631
- * 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.
7632
- *
7633
- * See: https://hl7.org/fhirpath/#toboolean-boolean
7634
- *
7635
- * @param input
7636
- * @returns
7637
- */
7638
- function toBoolean(input) {
7639
- if (input.length === 0) {
7640
- return [];
7641
- }
7642
- const [value] = validateInput(input, 1);
7643
- if (typeof value === 'boolean') {
7644
- return [value];
7645
- }
7646
- if (typeof value === 'number') {
7647
- if (value === 0 || value === 1) {
7648
- return [!!value];
7649
- }
7650
- }
7651
- if (typeof value === 'string') {
7652
- const lowerStr = value.toLowerCase();
7653
- if (['true', 't', 'yes', 'y', '1', '1.0'].includes(lowerStr)) {
7654
- return [true];
7655
- }
7656
- if (['false', 'f', 'no', 'n', '0', '0.0'].includes(lowerStr)) {
7657
- return [false];
7658
- }
7659
- }
7660
- return [];
7661
- }
7662
- /**
7663
- * If the input collection contains a single item, this function will return true if:
7664
- * 1) the item is a Boolean
7665
- * 2) the item is an Integer that is equal to one of the possible integer representations of Boolean values
7666
- * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
7667
- * 4) the item is a String that is equal to one of the possible string representations of Boolean values
7668
- *
7669
- * 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.
7670
- *
7671
- * Possible values for Integer, Decimal, and String are described in the toBoolean() function.
7672
- *
7673
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7674
- *
7675
- * If the input collection is empty, the result is empty.
7676
- *
7677
- * See: http://hl7.org/fhirpath/#convertstoboolean-boolean
7678
- *
7679
- * @param input
7680
- * @returns
7681
- */
7682
- function convertsToBoolean(input) {
7683
- if (input.length === 0) {
7684
- return [];
7685
- }
7686
- return [toBoolean(input).length === 1];
7687
- }
7688
- /**
7689
- * Returns the integer representation of the input.
7690
- *
7691
- * If the input collection contains a single item, this function will return a single integer if:
7692
- * 1) the item is an Integer
7693
- * 2) the item is a String and is convertible to an integer
7694
- * 3) the item is a Boolean, where true results in a 1 and false results in a 0.
7695
- *
7696
- * If the item is not one the above types, the result is empty.
7697
- *
7698
- * If the item is a String, but the string is not convertible to an integer (using the regex format (\\+|-)?\d+), the result is empty.
7699
- *
7700
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7701
- *
7702
- * If the input collection is empty, the result is empty.
7703
- *
7704
- * See: https://hl7.org/fhirpath/#tointeger-integer
7705
- *
7706
- * @param input The input collection.
7707
- * @returns The string representation of the input.
7708
- */
7709
- function toInteger(input) {
7710
- if (input.length === 0) {
7711
- return [];
7712
- }
7713
- const [value] = validateInput(input, 1);
7714
- if (typeof value === 'number') {
7715
- return [value];
7716
- }
7717
- if (typeof value === 'string' && value.match(/^[+-]?\d+$/)) {
7718
- return [parseInt(value, 10)];
7719
- }
7720
- if (typeof value === 'boolean') {
7721
- return [value ? 1 : 0];
7722
- }
7723
- return [];
7724
- }
7725
- /**
7726
- * Returns true if the input can be converted to string.
7727
- *
7728
- * If the input collection contains a single item, this function will return true if:
7729
- * 1) the item is an Integer
7730
- * 2) the item is a String and is convertible to an Integer
7731
- * 3) the item is a Boolean
7732
- * 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.
7733
- *
7734
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7735
- *
7736
- * If the input collection is empty, the result is empty.
7737
- *
7738
- * See: https://hl7.org/fhirpath/#convertstointeger-boolean
7739
- *
7740
- * @param input The input collection.
7741
- * @returns
7742
- */
7743
- function convertsToInteger(input) {
7744
- if (input.length === 0) {
7745
- return [];
7746
- }
7747
- return [toInteger(input).length === 1];
7748
- }
7749
- /**
7750
- * If the input collection contains a single item, this function will return a single date if:
7751
- * 1) the item is a Date
7752
- * 2) the item is a DateTime
7753
- * 3) the item is a String and is convertible to a Date
7754
- *
7755
- * If the item is not one of the above types, the result is empty.
7756
- *
7757
- * 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.
7758
- *
7759
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7760
- *
7761
- * If the input collection is empty, the result is empty.
7762
- *
7763
- * See: https://hl7.org/fhirpath/#todate-date
7764
- */
7765
- function toDate(input) {
7766
- if (input.length === 0) {
7767
- return [];
7768
- }
7769
- const [value] = validateInput(input, 1);
7770
- if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
7771
- return [parseDateString(value)];
7772
- }
7773
- return [];
7774
- }
7775
- /**
7776
- * If the input collection contains a single item, this function will return true if:
7777
- * 1) the item is a Date
7778
- * 2) the item is a DateTime
7779
- * 3) the item is a String and is convertible to a Date
7780
- *
7781
- * 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.
7782
- *
7783
- * If the item contains a partial date (e.g. '2012-01'), the result is a partial date.
7784
- *
7785
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7786
- *
7787
- * If the input collection is empty, the result is empty.
7788
- *
7789
- * See: https://hl7.org/fhirpath/#convertstodate-boolean
7790
- */
7791
- function convertsToDate(input) {
7792
- if (input.length === 0) {
7793
- return [];
7794
- }
7795
- return [toDate(input).length === 1];
7796
- }
7797
- /**
7798
- * If the input collection contains a single item, this function will return a single datetime if:
7799
- * 1) the item is a DateTime
7800
- * 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)
7801
- * 3) the item is a String and is convertible to a DateTime
7802
- *
7803
- * If the item is not one of the above types, the result is empty.
7804
- *
7805
- * 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.
7806
- *
7807
- * If the item contains a partial datetime (e.g. '2012-01-01T10:00'), the result is a partial datetime.
7808
- *
7809
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7810
- *
7811
- * If the input collection is empty, the result is empty.
7812
-
7813
- * See: https://hl7.org/fhirpath/#todatetime-datetime
7814
- *
7815
- * @param input
7816
- * @returns
7817
- */
7818
- function toDateTime(input) {
7819
- if (input.length === 0) {
7820
- return [];
7821
- }
7822
- const [value] = validateInput(input, 1);
7823
- if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
7824
- return [parseDateString(value)];
7825
- }
7826
- return [];
7827
- }
7828
- /**
7829
- * If the input collection contains a single item, this function will return true if:
7830
- * 1) the item is a DateTime
7831
- * 2) the item is a Date
7832
- * 3) the item is a String and is convertible to a DateTime
7833
- *
7834
- * 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.
7835
- *
7836
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7837
- *
7838
- * If the input collection is empty, the result is empty.
7839
- *
7840
- * See: https://hl7.org/fhirpath/#convertstodatetime-boolean
7841
- *
7842
- * @param input
7843
- * @returns
7844
- */
7845
- function convertsToDateTime(input) {
7846
- if (input.length === 0) {
7847
- return [];
7848
- }
7849
- return [toDateTime(input).length === 1];
7850
- }
7851
- /**
7852
- * If the input collection contains a single item, this function will return a single decimal if:
7853
- * 1) the item is an Integer or Decimal
7854
- * 2) the item is a String and is convertible to a Decimal
7855
- * 3) the item is a Boolean, where true results in a 1.0 and false results in a 0.0.
7856
- * 4) If the item is not one of the above types, the result is empty.
7857
- *
7858
- * 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.
7859
- *
7860
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7861
- *
7862
- * If the input collection is empty, the result is empty.
7863
- *
7864
- * See: https://hl7.org/fhirpath/#decimal-conversion-functions
7865
- *
7866
- * @param input The input collection.
7867
- * @returns
7868
- */
7869
- function toDecimal(input) {
7870
- if (input.length === 0) {
7871
- return [];
7872
- }
7873
- const [value] = validateInput(input, 1);
7874
- if (typeof value === 'number') {
7875
- return [value];
7876
- }
7877
- if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?$/)) {
7878
- return [parseFloat(value)];
7879
- }
7880
- if (typeof value === 'boolean') {
7881
- return [value ? 1 : 0];
7882
- }
7883
- return [];
7884
- }
7885
- /**
7886
- * If the input collection contains a single item, this function will true if:
7887
- * 1) the item is an Integer or Decimal
7888
- * 2) the item is a String and is convertible to a Decimal
7889
- * 3) the item is a Boolean
7890
- *
7891
- * 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.
7892
- *
7893
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7894
- *
7895
- * If the input collection is empty, the result is empty.
7896
-
7897
- * See: https://hl7.org/fhirpath/#convertstodecimal-boolean
7898
- *
7899
- * @param input The input collection.
7900
- * @returns
7901
- */
7902
- function convertsToDecimal(input) {
7903
- if (input.length === 0) {
7904
- return [];
7905
- }
7906
- return [toDecimal(input).length === 1];
7907
- }
7908
- /**
7909
- * If the input collection contains a single item, this function will return a single quantity if:
7910
- * 1) the item is an Integer, or Decimal, where the resulting quantity will have the default unit ('1')
7911
- * 2) the item is a Quantity
7912
- * 3) the item is a String and is convertible to a Quantity
7913
- * 4) the item is a Boolean, where true results in the quantity 1.0 '1', and false results in the quantity 0.0 '1'
7914
- *
7915
- * If the item is not one of the above types, the result is empty.
7916
- *
7917
- * See: https://hl7.org/fhirpath/#quantity-conversion-functions
7918
- *
7919
- * @param input The input collection.
7920
- * @returns
7921
- */
7922
- function toQuantity(input) {
7923
- if (input.length === 0) {
7924
- return [];
7925
- }
7926
- const [value] = validateInput(input, 1);
7927
- if (isQuantity(value)) {
7928
- return [value];
7929
- }
7930
- if (typeof value === 'number') {
7931
- return [{ value, unit: '1' }];
7932
- }
7933
- if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?/)) {
7934
- return [{ value: parseFloat(value), unit: '1' }];
7935
- }
7936
- if (typeof value === 'boolean') {
7937
- return [{ value: value ? 1 : 0, unit: '1' }];
7938
- }
7939
- return [];
7940
- }
7941
- /**
7942
- * If the input collection contains a single item, this function will return true if:
7943
- * 1) the item is an Integer, Decimal, or Quantity
7944
- * 2) the item is a String that is convertible to a Quantity
7945
- * 3) the item is a Boolean
7946
- *
7947
- * If the item is not one of the above types, or is not convertible to a Quantity using the following regex format:
7948
- *
7949
- * (?'value'(\+|-)?\d+(\.\d+)?)\s*('(?'unit'[^']+)'|(?'time'[a-zA-Z]+))?
7950
- *
7951
- * then the result is false.
7952
- *
7953
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7954
- *
7955
- * If the input collection is empty, the result is empty.
7956
- *
7957
- * 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.
7958
- *
7959
- * See: https://hl7.org/fhirpath/#convertstoquantityunit-string-boolean
7960
- *
7961
- * @param input The input collection.
7962
- * @returns
7963
- */
7964
- function convertsToQuantity(input) {
7965
- if (input.length === 0) {
7966
- return [];
7967
- }
7968
- return [toQuantity(input).length === 1];
7969
- }
7970
- /**
7971
- * Returns the string representation of the input.
7972
- *
7973
- * If the input collection contains a single item, this function will return a single String if:
7974
- *
7975
- * 1) the item in the input collection is a String
7976
- * 2) the item in the input collection is an Integer, Decimal, Date, Time, DateTime, or Quantity the output will contain its String representation
7977
- * 3) the item is a Boolean, where true results in 'true' and false in 'false'.
7978
- *
7979
- * If the item is not one of the above types, the result is false.
7980
- *
7981
- * See: https://hl7.org/fhirpath/#tostring-string
7982
- *
7983
- * @param input The input collection.
7984
- * @returns The string representation of the input.
7985
- */
7986
- function toString(input) {
7987
- if (input.length === 0) {
7988
- return [];
7989
- }
7990
- const [value] = validateInput(input, 1);
7991
- if (value === null || value === undefined) {
7992
- return [];
7993
- }
7994
- if (isQuantity(value)) {
7995
- return [`${value.value} '${value.unit}'`];
7996
- }
7997
- return [value.toString()];
7998
- }
7999
- /**
8000
- * Returns true if the input can be converted to string.
8001
- *
8002
- * If the input collection contains a single item, this function will return true if:
8003
- * 1) the item is a String
8004
- * 2) the item is an Integer, Decimal, Date, Time, or DateTime
8005
- * 3) the item is a Boolean
8006
- * 4) the item is a Quantity
8007
- *
8008
- * If the item is not one of the above types, the result is false.
8009
- *
8010
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8011
- *
8012
- * If the input collection is empty, the result is empty.
8013
- *
8014
- * See: https://hl7.org/fhirpath/#tostring-string
8015
- *
8016
- * @param input The input collection.
8017
- * @returns
8018
- */
8019
- function convertsToString(input) {
8020
- if (input.length === 0) {
8021
- return [];
8022
- }
8023
- return [toString(input).length === 1];
8024
- }
8025
- /**
8026
- * If the input collection contains a single item, this function will return a single time if:
8027
- * 1) the item is a Time
8028
- * 2) the item is a String and is convertible to a Time
8029
- *
8030
- * If the item is not one of the above types, the result is empty.
8031
- *
8032
- * 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.
8033
- *
8034
- * If the item contains a partial time (e.g. '10:00'), the result is a partial time.
8035
- *
8036
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8037
- *
8038
- * If the input collection is empty, the result is empty.
8039
- *
8040
- * See: https://hl7.org/fhirpath/#totime-time
8041
- *
8042
- * @param input
8043
- * @returns
8044
- */
8045
- function toTime(input) {
8046
- if (input.length === 0) {
8047
- return [];
8048
- }
8049
- const [value] = validateInput(input, 1);
8050
- if (typeof value === 'string') {
8051
- const match = value.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);
8052
- if (match) {
8053
- return [parseDateString('T' + match[1])];
8054
- }
8055
- }
8056
- return [];
8057
- }
8058
- /**
8059
- * If the input collection contains a single item, this function will return true if:
8060
- * 1) the item is a Time
8061
- * 2) the item is a String and is convertible to a Time
8062
- *
8063
- * 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.
8064
- *
8065
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8066
- *
8067
- * If the input collection is empty, the result is empty.
8068
- *
8069
- * See: https://hl7.org/fhirpath/#convertstotime-boolean
8070
- *
8071
- * @param input
8072
- * @returns
8073
- */
8074
- function convertsToTime(input) {
8075
- if (input.length === 0) {
8076
- return [];
8077
- }
8078
- return [toTime(input).length === 1];
8079
- }
8080
- /*
8081
- * 5.6. String Manipulation.
8082
- *
8083
- * See: https://hl7.org/fhirpath/#string-manipulation
8084
- */
8085
- /**
8086
- * Returns the 0-based index of the first position substring is found in the input string, or -1 if it is not found.
8087
- *
8088
- * If substring is an empty string (''), the function returns 0.
8089
- *
8090
- * If the input or substring is empty ({ }), the result is empty ({ }).
8091
- *
8092
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8093
- *
8094
- * See: https://hl7.org/fhirpath/#indexofsubstring-string-integer
8095
- *
8096
- * @param input The input collection.
8097
- * @returns The index of the substring.
8098
- */
8099
- function indexOf(input, substringAtom) {
8100
- return applyStringFunc((str, substring) => str.indexOf(substring), input, substringAtom);
8101
- }
8102
- /**
8103
- * 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.
8104
- *
8105
- * 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.
8106
- *
8107
- * If the input or start is empty, the result is empty.
8108
- *
8109
- * If an empty length is provided, the behavior is the same as if length had not been provided.
8110
- *
8111
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8112
- *
8113
- * @param input The input collection.
8114
- * @returns The index of the substring.
8115
- */
8116
- function substring(input, startAtom, lengthAtom) {
8117
- return applyStringFunc((str, start, length) => {
8118
- const startIndex = start;
8119
- const endIndex = length ? startIndex + length : str.length;
8120
- return startIndex < 0 || startIndex >= str.length ? undefined : str.substring(startIndex, endIndex);
8121
- }, input, startAtom, lengthAtom);
8122
- }
8123
- /**
8124
- *
8125
- * @param input The input collection.
8126
- * @returns The index of the substring.
8127
- */
8128
- function startsWith(input, prefixAtom) {
8129
- return applyStringFunc((str, prefix) => str.startsWith(prefix), input, prefixAtom);
8130
- }
8131
- /**
8132
- *
8133
- * @param input The input collection.
8134
- * @returns The index of the substring.
8135
- */
8136
- function endsWith(input, suffixAtom) {
8137
- return applyStringFunc((str, suffix) => str.endsWith(suffix), input, suffixAtom);
8138
- }
8139
- /**
8140
- *
8141
- * @param input The input collection.
8142
- * @returns The index of the substring.
8143
- */
8144
- function contains(input, substringAtom) {
8145
- return applyStringFunc((str, substring) => str.includes(substring), input, substringAtom);
8146
- }
8147
- /**
8148
- *
8149
- * @param input The input collection.
8150
- * @returns The index of the substring.
8151
- */
8152
- function upper(input) {
8153
- return applyStringFunc((str) => str.toUpperCase(), input);
8154
- }
8155
- /**
8156
- *
8157
- * @param input The input collection.
8158
- * @returns The index of the substring.
8159
- */
8160
- function lower(input) {
8161
- return applyStringFunc((str) => str.toLowerCase(), input);
8162
- }
8163
- /**
8164
- *
8165
- * @param input The input collection.
8166
- * @returns The index of the substring.
8167
- */
8168
- function replace(input, patternAtom, substitionAtom) {
8169
- return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, patternAtom, substitionAtom);
8170
- }
8171
- /**
8172
- *
8173
- * @param input The input collection.
8174
- * @returns The index of the substring.
8175
- */
8176
- function matches(input, regexAtom) {
8177
- return applyStringFunc((str, regex) => !!str.match(regex), input, regexAtom);
8178
- }
8179
- /**
8180
- *
8181
- * @param input The input collection.
8182
- * @returns The index of the substring.
8183
- */
8184
- function replaceMatches(input, regexAtom, substitionAtom) {
8185
- return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, regexAtom, substitionAtom);
8186
- }
8187
- /**
8188
- *
8189
- * @param input The input collection.
8190
- * @returns The index of the substring.
8191
- */
8192
- function length(input) {
8193
- return applyStringFunc((str) => str.length, input);
8194
- }
8195
- /**
8196
- * Returns the list of characters in the input string. If the input collection is empty ({ }), the result is empty.
8197
- *
8198
- * See: https://hl7.org/fhirpath/#tochars-collection
8199
- *
8200
- * @param input The input collection.
8201
- */
8202
- function toChars(input) {
8203
- return applyStringFunc((str) => (str ? str.split('') : undefined), input);
8204
- }
8205
- /*
8206
- * 5.7. Math
8207
- */
8208
- /**
8209
- * Returns the absolute value of the input. When taking the absolute value of a quantity, the unit is unchanged.
8210
- *
8211
- * If the input collection is empty, the result is empty.
8212
- *
8213
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8214
- *
8215
- * See: https://hl7.org/fhirpath/#abs-integer-decimal-quantity
8216
- *
8217
- * @param input The input collection.
8218
- * @returns A collection containing the result.
8219
- */
8220
- function abs(input) {
8221
- return applyMathFunc(Math.abs, input);
8222
- }
8223
- /**
8224
- * Returns the first integer greater than or equal to the input.
8225
- *
8226
- * If the input collection is empty, the result is empty.
8227
- *
8228
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8229
- *
8230
- * See: https://hl7.org/fhirpath/#ceiling-integer
8231
- *
8232
- * @param input The input collection.
8233
- * @returns A collection containing the result.
8234
- */
8235
- function ceiling(input) {
8236
- return applyMathFunc(Math.ceil, input);
8237
- }
8238
- /**
8239
- * Returns e raised to the power of the input.
8240
- *
8241
- * If the input collection contains an Integer, it will be implicitly converted to a Decimal and the result will be a Decimal.
8242
- *
8243
- * If the input collection is empty, the result is empty.
8244
- *
8245
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8246
- *
8247
- * See: https://hl7.org/fhirpath/#exp-decimal
8248
- *
8249
- * @param input The input collection.
8250
- * @returns A collection containing the result.
8251
- */
8252
- function exp(input) {
8253
- return applyMathFunc(Math.exp, input);
8254
- }
8255
- /**
8256
- * Returns the first integer less than or equal to the input.
8257
- *
8258
- * If the input collection is empty, the result is empty.
8259
- *
8260
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8261
- *
8262
- * See: https://hl7.org/fhirpath/#floor-integer
8263
- *
8264
- * @param input The input collection.
8265
- * @returns A collection containing the result.
8266
- */
8267
- function floor(input) {
8268
- return applyMathFunc(Math.floor, input);
8269
- }
8270
- /**
8271
- * Returns the natural logarithm of the input (i.e. the logarithm base e).
8272
- *
8273
- * When used with an Integer, it will be implicitly converted to a Decimal.
8274
- *
8275
- * If the input collection is empty, the result is empty.
8276
- *
8277
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8278
- *
8279
- * See: https://hl7.org/fhirpath/#ln-decimal
8280
- *
8281
- * @param input The input collection.
8282
- * @returns A collection containing the result.
8283
- */
8284
- function ln(input) {
8285
- return applyMathFunc(Math.log, input);
8286
- }
8287
- /**
8288
- * Returns the logarithm base base of the input number.
8289
- *
8290
- * When used with Integers, the arguments will be implicitly converted to Decimal.
8291
- *
8292
- * If base is empty, the result is empty.
8293
- *
8294
- * If the input collection is empty, the result is empty.
8295
- *
8296
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8297
- *
8298
- * See: https://hl7.org/fhirpath/#logbase-decimal-decimal
8299
- *
8300
- * @param input The input collection.
8301
- * @returns A collection containing the result.
8302
- */
8303
- function log(input, baseAtom) {
8304
- return applyMathFunc((value, base) => Math.log(value) / Math.log(base), input, baseAtom);
8305
- }
8306
- /**
8307
- * 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.
8308
- *
8309
- * If the power cannot be represented (such as the -1 raised to the 0.5), the result is empty.
8310
- *
8311
- * If the input is empty, or exponent is empty, the result is empty.
8312
- *
8313
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8314
- *
8315
- * See: https://hl7.org/fhirpath/#powerexponent-integer-decimal-integer-decimal
8316
- *
8317
- * @param input The input collection.
8318
- * @returns A collection containing the result.
8319
- */
8320
- function power(input, expAtom) {
8321
- return applyMathFunc(Math.pow, input, expAtom);
8322
- }
8323
- /**
8324
- * 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.
8325
- *
8326
- * If specified, the number of digits of precision must be >= 0 or the evaluation will end and signal an error to the calling environment.
8327
- *
8328
- * If the input collection contains a single item of type Integer, it will be implicitly converted to a Decimal.
8329
- *
8330
- * If the input collection is empty, the result is empty.
8331
- *
8332
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8333
- *
8334
- * See: https://hl7.org/fhirpath/#roundprecision-integer-decimal
8335
- *
8336
- * @param input The input collection.
8337
- * @returns A collection containing the result.
8338
- */
8339
- function round(input) {
8340
- return applyMathFunc(Math.round, input);
8341
- }
8342
- /**
8343
- * Returns the square root of the input number as a Decimal.
8344
- *
8345
- * If the square root cannot be represented (such as the square root of -1), the result is empty.
8346
- *
8347
- * If the input collection is empty, the result is empty.
8348
- *
8349
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8350
- *
8351
- * Note that this function is equivalent to raising a number of the power of 0.5 using the power() function.
8352
- *
8353
- * See: https://hl7.org/fhirpath/#sqrt-decimal
8354
- *
8355
- * @param input The input collection.
8356
- * @returns A collection containing the result.
8357
- */
8358
- function sqrt(input) {
8359
- return applyMathFunc(Math.sqrt, input);
8360
- }
8361
- /**
8362
- * Returns the integer portion of the input.
8363
- *
8364
- * If the input collection is empty, the result is empty.
8365
- *
8366
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8367
- *
8368
- * See: https://hl7.org/fhirpath/#truncate-integer
8369
- *
8370
- * @param input The input collection.
8371
- * @returns A collection containing the result.
8372
- */
8373
- function truncate(input) {
8374
- return applyMathFunc((x) => x | 0, input);
8375
- }
8376
- /*
8377
- * 5.8. Tree navigation
8378
- */
8379
- const children = stub;
8380
- const descendants = stub;
8381
- /*
8382
- * 5.9. Utility functions
8383
- */
8384
- /**
8385
- * Adds a String representation of the input collection to the diagnostic log,
8386
- * using the name argument as the name in the log. This log should be made available
8387
- * to the user in some appropriate fashion. Does not change the input, so returns
8388
- * the input collection as output.
8389
- *
8390
- * If the projection argument is used, the trace would log the result of evaluating
8391
- * the project expression on the input, but still return the input to the trace
8392
- * function unchanged.
8393
- *
8394
- * See: https://hl7.org/fhirpath/#tracename-string-projection-expression-collection
8395
- *
8396
- * @param input The input collection.
8397
- * @param nameAtom The log name.
8398
- */
8399
- function trace(input, nameAtom) {
8400
- console.log('trace', input, nameAtom);
8401
- return input;
8402
- }
8403
- /**
8404
- * Returns the current date and time, including timezone offset.
8405
- *
8406
- * See: https://hl7.org/fhirpath/#now-datetime
8407
- */
8408
- function now() {
8409
- return [new Date().toISOString()];
8410
- }
8411
- /**
8412
- * Returns the current time.
8413
- *
8414
- * See: https://hl7.org/fhirpath/#timeofday-time
8415
- */
8416
- function timeOfDay() {
8417
- return [new Date().toISOString().substring(11)];
8418
- }
8419
- /**
8420
- * Returns the current date.
8421
- *
8422
- * See: https://hl7.org/fhirpath/#today-date
8423
- */
8424
- function today() {
8425
- return [new Date().toISOString().substring(0, 10)];
8426
- }
8427
- /*
8428
- * 6.3 Types
8429
- */
8430
- /**
8431
- * The is() function is supported for backwards compatibility with previous
8432
- * implementations of FHIRPath. Just as with the is keyword, the type argument
8433
- * is an identifier that must resolve to the name of a type in a model.
8434
- *
8435
- * For implementations with compile-time typing, this requires special-case
8436
- * handling when processing the argument to treat it as a type specifier rather
8437
- * than an identifier expression:
8438
- *
8439
- * @param input
8440
- * @param typeAtom
8441
- * @returns
8442
- */
8443
- function is(input, typeAtom) {
8444
- const typeName = typeAtom.name;
8445
- return input.map((value) => fhirPathIs(value, typeName));
8446
- }
8447
- /*
8448
- * 6.5 Boolean logic
8449
- */
8450
- /**
8451
- * 6.5.3. not() : Boolean
8452
- *
8453
- * Returns true if the input collection evaluates to false, and false if it evaluates to true. Otherwise, the result is empty ({ }):
8454
- *
8455
- * @param input
8456
- * @returns
8457
- */
8458
- function not(input) {
8459
- return toBoolean(input).map((value) => !value);
8460
- }
8461
- /*
8462
- * Additional functions
8463
- * See: https://hl7.org/fhir/fhirpath.html#functions
8464
- */
8465
- /**
8466
- * 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.
8467
- * The items in the collection may also represent a Reference, in which case the Reference.reference is resolved.
8468
- * @param input The input collection.
8469
- * @returns
8470
- */
8471
- function resolve(input) {
8472
- return input
8473
- .map((e) => {
8474
- let refStr;
8475
- if (typeof e === 'string') {
8476
- refStr = e;
8477
- }
8478
- else if (typeof e === 'object') {
8479
- const ref = e;
8480
- if (ref.resource) {
8481
- return ref.resource;
8482
- }
8483
- refStr = ref.reference;
8484
- }
8485
- if (!refStr) {
8486
- return undefined;
8487
- }
8488
- const [resourceType, id] = refStr.split('/');
8489
- return { resourceType, id };
8490
- })
8491
- .filter((e) => !!e);
8492
- }
8493
- /**
8494
- * The as operator can be used to treat a value as a specific type.
8495
- * @param context The context value.
8496
- * @returns The value as the specific type.
8497
- */
8498
- function as(context) {
8499
- return context;
8500
- }
8501
- /*
8502
- * 12. Formal Specifications
8503
- */
8504
- /**
8505
- * Returns the type of the input.
8506
- *
8507
- * 12.2. Model Information
8508
- *
8509
- * The model information returned by the reflection function type() is specified as an
8510
- * XML Schema document (xsd) and included in this specification at the following link:
8511
- * https://hl7.org/fhirpath/modelinfo.xsd
8512
- *
8513
- * See: https://hl7.org/fhirpath/#model-information
8514
- *
8515
- * @param input The input collection.
8516
- * @returns
8517
- */
8518
- function type(input) {
8519
- return input.map((value) => {
8520
- if (typeof value === 'boolean') {
8521
- return { namespace: 'System', name: 'Boolean' };
8522
- }
8523
- if (typeof value === 'number') {
8524
- return { namespace: 'System', name: 'Integer' };
8525
- }
8526
- if (value && typeof value === 'object' && 'resourceType' in value) {
8527
- return { namespace: 'FHIR', name: value.resourceType };
8528
- }
8529
- return null;
8530
- });
8531
- }
8532
- function conformsTo(input, systemAtom) {
8533
- const system = systemAtom.eval(undefined);
8534
- if (!system.startsWith('http://hl7.org/fhir/StructureDefinition/')) {
8535
- throw new Error('Expected a StructureDefinition URL');
8536
- }
8537
- const expectedResourceType = system.replace('http://hl7.org/fhir/StructureDefinition/', '');
8538
- return input.map((resource) => (resource === null || resource === void 0 ? void 0 : resource.resourceType) === expectedResourceType);
8539
- }
8540
- /*
8541
- * Helper utilities
8542
- */
8543
- function applyStringFunc(func, input, ...argsAtoms) {
8544
- if (input.length === 0) {
8545
- return [];
8546
- }
8547
- const [value] = validateInput(input, 1);
8548
- if (typeof value !== 'string') {
8549
- throw new Error('String function cannot be called with non-string');
8550
- }
8551
- const result = func(value, ...argsAtoms.map((atom) => atom && atom.eval(value)));
8552
- return result === undefined ? [] : [result];
8553
- }
8554
- function applyMathFunc(func, input, ...argsAtoms) {
8555
- if (input.length === 0) {
8556
- return [];
8557
- }
8558
- const [value] = validateInput(input, 1);
8559
- const quantity = isQuantity(value);
8560
- const numberInput = quantity ? value.value : value;
8561
- if (typeof numberInput !== 'number') {
8562
- throw new Error('Math function cannot be called with non-number');
8563
- }
8564
- const result = func(numberInput, ...argsAtoms.map((atom) => atom.eval(undefined)));
8565
- return quantity ? [Object.assign(Object.assign({}, value), { value: result })] : [result];
8566
- }
8567
- function validateInput(input, count) {
8568
- if (input.length !== count) {
8569
- throw new Error(`Expected ${count} arguments`);
8570
- }
8571
- return input;
8572
- }
8573
-
8574
- var functions = /*#__PURE__*/Object.freeze({
8575
- __proto__: null,
8576
- empty: empty,
8577
- exists: exists,
8578
- all: all,
8579
- allTrue: allTrue,
8580
- anyTrue: anyTrue,
8581
- allFalse: allFalse,
8582
- anyFalse: anyFalse,
8583
- subsetOf: subsetOf,
8584
- supersetOf: supersetOf,
8585
- count: count,
8586
- distinct: distinct,
8587
- isDistinct: isDistinct,
8588
- where: where,
8589
- select: select,
8590
- repeat: repeat,
8591
- ofType: ofType,
8592
- single: single,
8593
- first: first,
8594
- last: last,
8595
- tail: tail,
8596
- skip: skip,
8597
- take: take,
8598
- intersect: intersect,
8599
- exclude: exclude,
8600
- union: union,
8601
- combine: combine,
8602
- iif: iif,
8603
- toBoolean: toBoolean,
8604
- convertsToBoolean: convertsToBoolean,
8605
- toInteger: toInteger,
8606
- convertsToInteger: convertsToInteger,
8607
- toDate: toDate,
8608
- convertsToDate: convertsToDate,
8609
- toDateTime: toDateTime,
8610
- convertsToDateTime: convertsToDateTime,
8611
- toDecimal: toDecimal,
8612
- convertsToDecimal: convertsToDecimal,
8613
- toQuantity: toQuantity,
8614
- convertsToQuantity: convertsToQuantity,
8615
- toString: toString,
8616
- convertsToString: convertsToString,
8617
- toTime: toTime,
8618
- convertsToTime: convertsToTime,
8619
- indexOf: indexOf,
8620
- substring: substring,
8621
- startsWith: startsWith,
8622
- endsWith: endsWith,
8623
- contains: contains,
8624
- upper: upper,
8625
- lower: lower,
8626
- replace: replace,
8627
- matches: matches,
8628
- replaceMatches: replaceMatches,
8629
- length: length,
8630
- toChars: toChars,
8631
- abs: abs,
8632
- ceiling: ceiling,
8633
- exp: exp,
8634
- floor: floor,
8635
- ln: ln,
8636
- log: log,
8637
- power: power,
8638
- round: round,
8639
- sqrt: sqrt,
8640
- truncate: truncate,
8641
- children: children,
8642
- descendants: descendants,
8643
- trace: trace,
8644
- now: now,
8645
- timeOfDay: timeOfDay,
8646
- today: today,
8647
- is: is,
8648
- not: not,
8649
- resolve: resolve,
8650
- as: as,
8651
- type: type,
8652
- conformsTo: conformsTo
8653
- });
8654
-
8655
- 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;
8656
- function tokenize(str) {
8657
- return new Tokenizer(str).tokenize();
8658
- }
8659
- const STANDARD_UNITS = [
8660
- 'year',
8661
- 'years',
8662
- 'month',
8663
- 'months',
8664
- 'week',
8665
- 'weeks',
8666
- 'day',
8667
- 'days',
8668
- 'hour',
8669
- 'hours',
8670
- 'minute',
8671
- 'minutes',
8672
- 'second',
8673
- 'seconds',
8674
- 'millisecond',
8675
- 'milliseconds',
8676
- ];
8677
- const TWO_CHAR_OPERATORS = ['!=', '!~', '<=', '>=', '{}'];
8678
- class Tokenizer {
8679
- constructor(str) {
8680
- _Tokenizer_instances.add(this);
8681
- _Tokenizer_str.set(this, void 0);
8682
- _Tokenizer_pos.set(this, void 0);
8683
- __classPrivateFieldSet(this, _Tokenizer_str, str, "f");
8684
- __classPrivateFieldSet(this, _Tokenizer_pos, 0, "f");
8685
- }
8686
- tokenize() {
8687
- const result = [];
8688
- while (__classPrivateFieldGet(this, _Tokenizer_pos, "f") < __classPrivateFieldGet(this, _Tokenizer_str, "f").length) {
8689
- const token = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8690
- if (token) {
8691
- result.push(token);
8692
- }
8693
- }
8694
- return result;
8695
- }
8696
- }
8697
- _Tokenizer_str = new WeakMap(), _Tokenizer_pos = new WeakMap(), _Tokenizer_instances = new WeakSet(), _Tokenizer_peekToken = function _Tokenizer_peekToken() {
8698
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8699
- const token = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8700
- __classPrivateFieldSet(this, _Tokenizer_pos, start, "f");
8701
- return token;
8702
- }, _Tokenizer_consumeToken = function _Tokenizer_consumeToken() {
8703
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhitespace).call(this);
8704
- const c = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this);
8705
- if (!c) {
8706
- return undefined;
8707
- }
8708
- const next = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this);
8709
- if (c === '/' && next === '*') {
8710
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeMultiLineComment).call(this);
8711
- }
8712
- if (c === '/' && next === '/') {
8713
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSingleLineComment).call(this);
8714
- }
8715
- if (c === "'") {
8716
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeString).call(this);
8717
- }
8718
- if (c === '`') {
8719
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeBacktickSymbol).call(this);
8720
- }
8721
- if (c === '@') {
8722
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeDateTime).call(this);
8723
- }
8724
- if (c.match(/\d/)) {
8725
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeNumber).call(this);
8726
- }
8727
- if (c.match(/\w/)) {
8728
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSymbol).call(this);
8729
- }
8730
- if (c === '$' && next.match(/\w/)) {
8731
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSymbol).call(this);
8732
- }
8733
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeOperator).call(this);
8734
- }, _Tokenizer_consumeWhitespace = function _Tokenizer_consumeWhitespace() {
8735
- return buildToken('Whitespace', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\s/)));
8736
- }, _Tokenizer_consumeMultiLineComment = function _Tokenizer_consumeMultiLineComment() {
8737
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8738
- __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) !== '/');
8739
- __classPrivateFieldSet(this, _Tokenizer_pos, __classPrivateFieldGet(this, _Tokenizer_pos, "f") + 2, "f");
8740
- return buildToken('Comment', __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8741
- }, _Tokenizer_consumeSingleLineComment = function _Tokenizer_consumeSingleLineComment() {
8742
- return buildToken('Comment', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '\n'));
8743
- }, _Tokenizer_consumeString = function _Tokenizer_consumeString() {
8744
- var _a, _b;
8745
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8746
- 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) !== "'"));
8747
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8748
- return result;
8749
- }, _Tokenizer_consumeBacktickSymbol = function _Tokenizer_consumeBacktickSymbol() {
8750
- var _a, _b;
8751
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8752
- const result = buildToken('Symbol', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '`'));
8753
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8754
- return result;
8755
- }, _Tokenizer_consumeDateTime = function _Tokenizer_consumeDateTime() {
8756
- var _a, _b, _c, _d, _e;
8757
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8758
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8759
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d-]/));
8760
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === 'T') {
8761
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8762
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d:]/));
8763
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '.' && __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this).match(/\d/)) {
8764
- __classPrivateFieldSet(this, _Tokenizer_pos, (_c = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _c++, _c), "f");
8765
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d]/));
8766
- }
8767
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === 'Z') {
8768
- __classPrivateFieldSet(this, _Tokenizer_pos, (_d = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _d++, _d), "f");
8769
- }
8770
- else if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '+' || __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '-') {
8771
- __classPrivateFieldSet(this, _Tokenizer_pos, (_e = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _e++, _e), "f");
8772
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d:]/));
8773
- }
8774
- }
8775
- return buildToken('DateTime', __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start + 1, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8776
- }, _Tokenizer_consumeNumber = function _Tokenizer_consumeNumber() {
8777
- var _a;
8778
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8779
- let id = 'Number';
8780
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\d/));
8781
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '.' && __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this).match(/\d/)) {
8782
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8783
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\d/));
8784
- }
8785
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === ' ') {
8786
- if (isUnitToken(__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peekToken).call(this))) {
8787
- id = 'Quantity';
8788
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8789
- }
8790
- }
8791
- return buildToken(id, __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8792
- }, _Tokenizer_consumeSymbol = function _Tokenizer_consumeSymbol() {
8793
- return buildToken('Symbol', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[$\w]/)));
8794
- }, _Tokenizer_consumeOperator = function _Tokenizer_consumeOperator() {
8795
- var _a;
8796
- const c = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this);
8797
- const next = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this);
8798
- const twoCharOp = c + next;
8799
- if (TWO_CHAR_OPERATORS.includes(twoCharOp)) {
8800
- __classPrivateFieldSet(this, _Tokenizer_pos, __classPrivateFieldGet(this, _Tokenizer_pos, "f") + 2, "f");
8801
- return buildToken(twoCharOp, twoCharOp);
8802
- }
8803
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8804
- return buildToken(c, c);
8805
- }, _Tokenizer_consumeWhile = function _Tokenizer_consumeWhile(condition) {
8806
- var _a;
8807
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8808
- while (__classPrivateFieldGet(this, _Tokenizer_pos, "f") < __classPrivateFieldGet(this, _Tokenizer_str, "f").length && condition()) {
8809
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8810
- }
8811
- return __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f"));
8812
- }, _Tokenizer_curr = function _Tokenizer_curr() {
8813
- return __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f")];
8814
- }, _Tokenizer_prev = function _Tokenizer_prev() {
8815
- var _a;
8816
- return (_a = __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f") - 1]) !== null && _a !== void 0 ? _a : '';
8817
- }, _Tokenizer_peek = function _Tokenizer_peek() {
8818
- var _a;
8819
- return (_a = __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f") + 1]) !== null && _a !== void 0 ? _a : '';
8820
- };
8821
- function buildToken(id, value) {
8822
- return { id, value };
8823
- }
8824
- function isUnitToken(token) {
8825
- if (token) {
8826
- if (token.id === 'String') {
8827
- return true;
8828
- }
8829
- if (token.id === 'Symbol' && STANDARD_UNITS.includes(token.value)) {
8830
- return true;
8831
- }
8832
- }
8833
- return false;
8834
- }
8835
-
8836
- var _ParserBuilder_prefixParselets, _ParserBuilder_infixParselets, _Parser_instances, _Parser_tokens, _Parser_prefixParselets, _Parser_infixParselets, _Parser_getPrecedence, _Parser_consume, _Parser_look;
8837
- class ParserBuilder {
8838
- constructor() {
8839
- _ParserBuilder_prefixParselets.set(this, {});
8840
- _ParserBuilder_infixParselets.set(this, {});
8841
- }
8842
- registerInfix(tokenType, parselet) {
8843
- __classPrivateFieldGet(this, _ParserBuilder_infixParselets, "f")[tokenType] = parselet;
8844
- return this;
8845
- }
8846
- registerPrefix(tokenType, parselet) {
8847
- __classPrivateFieldGet(this, _ParserBuilder_prefixParselets, "f")[tokenType] = parselet;
8848
- return this;
8849
- }
8850
- prefix(tokenType, precedence, builder) {
8851
- return this.registerPrefix(tokenType, {
8852
- parse(parser, token) {
8853
- const right = parser.consumeAndParse(precedence);
8854
- return builder(token, right);
8855
- },
8856
- });
8857
- }
8858
- infixLeft(tokenType, precedence, builder) {
8859
- return this.registerInfix(tokenType, {
8860
- parse(parser, left, token) {
8861
- const right = parser.consumeAndParse(precedence);
8862
- return builder(left, token, right);
8863
- },
8864
- precedence,
8865
- });
8866
- }
8867
- construct(input) {
8868
- return new Parser(tokenize(input), __classPrivateFieldGet(this, _ParserBuilder_prefixParselets, "f"), __classPrivateFieldGet(this, _ParserBuilder_infixParselets, "f"));
8869
- }
8870
- }
8871
- _ParserBuilder_prefixParselets = new WeakMap(), _ParserBuilder_infixParselets = new WeakMap();
8872
- class Parser {
8873
- constructor(tokens, prefixParselets, infixParselets) {
8874
- _Parser_instances.add(this);
8875
- _Parser_tokens.set(this, void 0);
8876
- _Parser_prefixParselets.set(this, void 0);
8877
- _Parser_infixParselets.set(this, void 0);
8878
- __classPrivateFieldSet(this, _Parser_tokens, tokens, "f");
8879
- __classPrivateFieldSet(this, _Parser_prefixParselets, prefixParselets, "f");
8880
- __classPrivateFieldSet(this, _Parser_infixParselets, infixParselets, "f");
8881
- }
8882
- match(expected) {
8883
- const token = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_look).call(this);
8884
- if ((token === null || token === void 0 ? void 0 : token.id) !== expected) {
8885
- return false;
8886
- }
8887
- __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8888
- return true;
8889
- }
8890
- consumeAndParse(precedence = 100 /* MaximumPrecedence */) {
8891
- const token = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8892
- const prefix = __classPrivateFieldGet(this, _Parser_prefixParselets, "f")[token.id];
8893
- if (!prefix) {
8894
- throw Error(`Parse error at ${token.value}. No matching prefix parselet.`);
8895
- }
8896
- let left = prefix.parse(this, token);
8897
- while (precedence > __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_getPrecedence).call(this)) {
8898
- const next = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8899
- const infix = __classPrivateFieldGet(this, _Parser_infixParselets, "f")[next.id];
8900
- left = infix.parse(this, left, next);
8901
- }
8902
- return left;
8903
- }
8904
- }
8905
- _Parser_tokens = new WeakMap(), _Parser_prefixParselets = new WeakMap(), _Parser_infixParselets = new WeakMap(), _Parser_instances = new WeakSet(), _Parser_getPrecedence = function _Parser_getPrecedence() {
8906
- const nextToken = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_look).call(this);
8907
- if (!nextToken) {
8908
- return 100 /* MaximumPrecedence */;
8909
- }
8910
- const parser = __classPrivateFieldGet(this, _Parser_infixParselets, "f")[nextToken.id];
8911
- if (parser) {
8912
- return parser.precedence;
8913
- }
8914
- return 100 /* MaximumPrecedence */;
8915
- }, _Parser_consume = function _Parser_consume() {
8916
- if (!__classPrivateFieldGet(this, _Parser_tokens, "f").length) {
8917
- throw Error('Cant consume unknown more tokens.');
8918
- }
8919
- return __classPrivateFieldGet(this, _Parser_tokens, "f").shift();
8920
- }, _Parser_look = function _Parser_look() {
8921
- return __classPrivateFieldGet(this, _Parser_tokens, "f").length > 0 ? __classPrivateFieldGet(this, _Parser_tokens, "f")[0] : undefined;
8922
- };
8923
- const PARENTHESES_PARSELET = {
8924
- parse(parser) {
8925
- const expr = parser.consumeAndParse();
8926
- if (!parser.match(')')) {
8927
- throw new Error('Parse error: expected `)`');
8928
- }
8929
- return expr;
8930
- },
8931
- };
8932
- const INDEXER_PARSELET = {
8933
- parse(parser, left) {
8934
- const expr = parser.consumeAndParse();
8935
- if (!parser.match(']')) {
8936
- throw new Error('Parse error: expected `]`');
8937
- }
8938
- return new IndexerAtom(left, expr);
8939
- },
8940
- precedence: 2 /* Indexer */,
8941
- };
8942
- const FUNCTION_CALL_PARSELET = {
8943
- parse(parser, left) {
8944
- if (!(left instanceof SymbolAtom)) {
8945
- throw new Error('Unexpected parentheses');
8946
- }
8947
- if (!(left.name in functions)) {
8948
- throw new Error('Unrecognized function: ' + left.name);
8949
- }
8950
- const args = [];
8951
- while (!parser.match(')')) {
8952
- args.push(parser.consumeAndParse());
8953
- parser.match(',');
8954
- }
8955
- return new FunctionAtom(left.name, args, functions[left.name]);
8956
- },
8957
- precedence: 0 /* FunctionCall */,
8958
- };
8959
- function parseQuantity(str) {
8960
- const parts = str.split(' ');
8961
- const value = parseFloat(parts[0]);
8962
- let unit = parts[1];
8963
- if (unit && unit.startsWith("'") && unit.endsWith("'")) {
8964
- unit = unit.substring(1, unit.length - 1);
8965
- }
8966
- else {
8967
- unit = '{' + unit + '}';
8968
- }
8969
- return { value, unit };
8970
- }
8971
- const parserBuilder = new ParserBuilder()
8972
- .registerPrefix('String', {
8973
- parse: (_, token) => new LiteralAtom(token.value),
8974
- })
8975
- .registerPrefix('DateTime', {
8976
- parse: (_, token) => new LiteralAtom(parseDateString(token.value)),
8977
- })
8978
- .registerPrefix('Quantity', {
8979
- parse: (_, token) => new LiteralAtom(parseQuantity(token.value)),
8980
- })
8981
- .registerPrefix('Number', {
8982
- parse: (_, token) => new LiteralAtom(parseFloat(token.value)),
8983
- })
8984
- .registerPrefix('Symbol', {
8985
- parse: (_, token) => {
8986
- if (token.value === 'false') {
8987
- return new LiteralAtom(false);
8988
- }
8989
- if (token.value === 'true') {
8990
- return new LiteralAtom(true);
8991
- }
8992
- return new SymbolAtom(token.value);
8993
- },
8994
- })
8995
- .registerPrefix('{}', { parse: () => new EmptySetAtom() })
8996
- .registerPrefix('(', PARENTHESES_PARSELET)
8997
- .registerInfix('[', INDEXER_PARSELET)
8998
- .registerInfix('(', FUNCTION_CALL_PARSELET)
8999
- .prefix('+', 3 /* UnaryAdd */, (_, right) => new UnaryOperatorAtom(right, (x) => x))
9000
- .prefix('-', 3 /* UnarySubtract */, (_, right) => new ArithemticOperatorAtom(right, right, (_, y) => -y))
9001
- .infixLeft('.', 1 /* Dot */, (left, _, right) => new DotAtom(left, right))
9002
- .infixLeft('/', 4 /* Divide */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x / y))
9003
- .infixLeft('*', 4 /* Multiply */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x * y))
9004
- .infixLeft('+', 5 /* Add */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x + y))
9005
- .infixLeft('-', 5 /* Subtract */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x - y))
9006
- .infixLeft('|', 7 /* Union */, (left, _, right) => new UnionAtom(left, right))
9007
- .infixLeft('=', 9 /* Equals */, (left, _, right) => new EqualsAtom(left, right))
9008
- .infixLeft('!=', 9 /* Equals */, (left, _, right) => new NotEqualsAtom(left, right))
9009
- .infixLeft('~', 9 /* Equivalent */, (left, _, right) => new EquivalentAtom(left, right))
9010
- .infixLeft('!~', 9 /* NotEquivalent */, (left, _, right) => new NotEquivalentAtom(left, right))
9011
- .infixLeft('<', 8 /* LessThan */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x < y))
9012
- .infixLeft('<=', 8 /* LessThanOrEquals */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x <= y))
9013
- .infixLeft('>', 8 /* GreaterThan */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x > y))
9014
- .infixLeft('>=', 8 /* GreaterThanOrEquals */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x >= y))
9015
- .infixLeft('&', 5 /* Ampersand */, (left, _, right) => new ConcatAtom(left, right))
9016
- .infixLeft('Symbol', 6 /* Is */, (left, symbol, right) => {
9017
- switch (symbol.value) {
9018
- case 'and':
9019
- return new AndAtom(left, right);
9020
- case 'as':
9021
- return new AsAtom(left, right);
9022
- case 'contains':
9023
- return new ContainsAtom(left, right);
9024
- case 'div':
9025
- return new ArithemticOperatorAtom(left, right, (x, y) => (x / y) | 0);
9026
- case 'in':
9027
- return new InAtom(left, right);
9028
- case 'is':
9029
- return new IsAtom(left, right);
9030
- case 'mod':
9031
- return new ArithemticOperatorAtom(left, right, (x, y) => x % y);
9032
- case 'or':
9033
- return new OrAtom(left, right);
9034
- case 'xor':
9035
- return new XorAtom(left, right);
9036
- default:
9037
- throw new Error('Cannot use ' + symbol.value + ' as infix operator');
9038
- }
9039
- });
9040
- /**
9041
- * Parses a FHIRPath expression into an AST.
9042
- * The result can be used to evaluate the expression against a resource or other object.
9043
- * This method is useful if you know that you will evaluate the same expression many times
9044
- * against different resources.
9045
- * @param input The FHIRPath expression to parse.
9046
- * @returns The AST representing the expression.
9047
- */
9048
- function parseFhirPath(input) {
9049
- try {
9050
- return new FhirPathAtom(input, parserBuilder.construct(input).consumeAndParse());
9051
- }
9052
- catch (error) {
9053
- throw new Error(`FhirPathError on "${input}": ${error}`);
9054
- }
9055
- }
9056
- /**
9057
- * Evaluates a FHIRPath expression against a resource or other object.
9058
- * @param input The FHIRPath expression to parse.
9059
- * @param context The resource or object to evaluate the expression against.
9060
- * @returns The result of the FHIRPath expression against the resource or object.
9061
- */
9062
- function evalFhirPath(input, context) {
9063
- return parseFhirPath(input).eval(context);
9064
- }
9065
-
9066
- var _MemoryRepository_resources, _MemoryRepository_history;
9067
- class MemoryRepository {
9068
- constructor() {
9069
- _MemoryRepository_resources.set(this, void 0);
9070
- _MemoryRepository_history.set(this, void 0);
9071
- __classPrivateFieldSet$1(this, _MemoryRepository_resources, {}, "f");
9072
- __classPrivateFieldSet$1(this, _MemoryRepository_history, {}, "f");
9073
- }
9074
- createResource(resource) {
9075
- var _a;
9076
- const result = resource;
9077
- if (!result.id) {
9078
- result.id = this.generateId();
9079
- }
9080
- if (!result.meta) {
9081
- result.meta = {};
9082
- }
9083
- if (!((_a = result.meta) === null || _a === void 0 ? void 0 : _a.versionId)) {
9084
- result.meta.versionId = this.generateId();
9085
- }
9086
- const { resourceType, id } = resource;
9087
- if (!(resourceType in __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f"))) {
9088
- __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType] = {};
9089
- }
9090
- if (!(resourceType in __classPrivateFieldGet$1(this, _MemoryRepository_history, "f"))) {
9091
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType] = {};
9092
- }
9093
- if (!(id in __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType])) {
9094
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType][id] = [];
9095
- }
9096
- __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType][id] = resource;
9097
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType][id].push(result);
9098
- return result;
9099
- }
9100
- readResource(resourceType, id) {
9101
- var _a, _b;
9102
- return (_b = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id];
9103
- }
9104
- readHistory(resourceType, id) {
9105
- var _a, _b, _c;
9106
- return {
9107
- resourceType: 'Bundle',
9108
- type: 'history',
9109
- entry: ((_c = (_b = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) !== null && _c !== void 0 ? _c : [])
9110
- .sort((version1, version2) => { var _a, _b, _c; return -((_b = (_a = version1.meta) === null || _a === void 0 ? void 0 : _a.lastUpdated) === null || _b === void 0 ? void 0 : _b.localeCompare((_c = version2.meta) === null || _c === void 0 ? void 0 : _c.lastUpdated)); })
9111
- .map((version) => ({ resource: version })),
9112
- };
9113
- }
9114
- readVersion(resourceType, id, versionId) {
9115
- var _a, _b, _c;
9116
- return (_c = (_b = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) === null || _c === void 0 ? void 0 : _c.find((v) => { var _a; return ((_a = v.meta) === null || _a === void 0 ? void 0 : _a.versionId) === versionId; });
9117
- }
9118
- search(searchRequest) {
9119
- var _a;
9120
- const { resourceType } = searchRequest;
9121
- const resources = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType]) !== null && _a !== void 0 ? _a : {};
9122
- const result = Object.values(resources).filter((resource) => matchesSearchRequest(resource, searchRequest));
9123
- return {
9124
- resourceType: 'Bundle',
9125
- type: 'searchset',
9126
- entry: result.map((resource) => ({ resource })),
9127
- total: result.length,
9128
- };
9129
- }
9130
- deleteResource(resourceType, id) {
9131
- var _a, _b;
9132
- if ((_b = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) {
9133
- delete __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType][id];
9134
- }
9135
- }
9136
- generateId() {
9137
- return Date.now().toString(36);
9138
- }
9139
- }
9140
- _MemoryRepository_resources = new WeakMap(), _MemoryRepository_history = new WeakMap();
9141
- /**
9142
- * Determines if the resource matches the search request.
9143
- * @param resource The resource that was created or updated.
9144
- * @param searchRequest The subscription criteria as a search request.
9145
- * @returns True if the resource satisfies the search request.
9146
- */
9147
- function matchesSearchRequest(resource, searchRequest) {
9148
- if (searchRequest.resourceType !== resource.resourceType) {
9149
- return false;
9150
- }
9151
- if (searchRequest.filters) {
9152
- for (const filter of searchRequest.filters) {
9153
- if (!matchesSearchFilter(resource, filter)) {
9154
- return false;
9155
- }
9156
- }
9157
- }
9158
- return true;
9159
- }
9160
- /**
9161
- * Determines if the resource matches the search filter.
9162
- * @param resource The resource that was created or updated.
9163
- * @param filter One of the filters of a subscription criteria.
9164
- * @returns True if the resource satisfies the search filter.
9165
- */
9166
- function matchesSearchFilter(resource, filter) {
9167
- const expression = filter.code.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
9168
- const values = evalFhirPath(expression, resource);
9169
- const result = values.some((value) => JSON.stringify(value).toLowerCase().includes(filter.value.toLowerCase()));
9170
- return filter.operator === core.Operator.NOT_EQUALS ? !result : result;
9171
- }
9172
-
9173
- class MockClient extends core.MedplumClient {
9174
- constructor(clientOptions) {
9175
- super({
9176
- baseUrl: 'https://example.com/',
9177
- clientId: 'my-client-id',
9178
- fetch: (url, options) => {
9179
- const method = options.method || 'GET';
9180
- const path = url.replace('https://example.com/', '');
9181
- if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
9182
- console.log('MockClient', method, path);
9183
- }
9184
- const response = mockHandler(method, path, options);
9185
- if ((clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) && !response) {
9186
- console.log('MockClient: not found', method, path);
9187
- }
9188
- if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
9189
- console.log('MockClient', JSON.stringify(response, null, 2));
9190
- }
9191
- return Promise.resolve({
9192
- blob: () => Promise.resolve(response),
9193
- json: () => Promise.resolve(response),
9194
- });
9195
- },
9196
- });
9197
- }
9198
- clear() {
9199
- super.clear();
9200
- this.activeLoginOverride = undefined;
9201
- }
9202
- getProfile() {
9203
- return {
9204
- resourceType: 'Practitioner',
9205
- id: '123',
9206
- meta: {
9207
- versionId: '456',
9208
- },
9209
- };
9210
- }
9211
- setActiveLoginOverride(activeLoginOverride) {
9212
- this.activeLoginOverride = activeLoginOverride;
9213
- }
9214
- getActiveLogin() {
9215
- if (this.activeLoginOverride !== undefined) {
9216
- return this.activeLoginOverride;
9217
- }
9218
- return super.getActiveLogin();
9219
- }
9220
- createBinary(_data, filename, contentType) {
9221
- if (filename.endsWith('.exe')) {
9222
- return Promise.reject(core.badRequest('Invalid file type'));
9223
- }
9224
- return Promise.resolve({
9225
- resourceType: 'Binary',
9226
- title: filename,
9227
- contentType,
9228
- url: 'https://example.com/binary/123',
9229
- });
9230
- }
9231
- }
9232
- function mockHandler(method, path, options) {
9233
- if (path.startsWith('admin/')) {
9234
- return mockAdminHandler(method, path);
9235
- }
9236
- else if (path.startsWith('auth/')) {
9237
- return mockAuthHandler(method, path, options);
9238
- }
9239
- else if (path.startsWith('fhir/R4')) {
9240
- return mockFhirHandler(method, path, options);
9241
- }
9242
- else {
9243
- return null;
9244
- }
9245
- }
9246
- function mockAdminHandler(_method, path) {
9247
- if (path.startsWith('admin/projects/123')) {
9248
- return {
9249
- project: { id: '123', name: 'Project 123' },
9250
- members: [
9251
- { id: '123', profile: { reference: 'Practitioner/123', display: 'Alice Smith' }, role: 'owner' },
9252
- { id: '888', profile: { reference: 'ClientApplication/123', display: 'Test Client' }, role: 'client' },
9253
- { id: '999', profile: { reference: 'Bot/123', display: 'Test Bot' }, role: 'bot' },
9254
- ],
9255
- };
9256
- }
9257
- return {
9258
- ok: true,
9259
- };
9260
- }
9261
- function mockAuthHandler(method, path, options) {
9262
- if (path.startsWith('auth/changepassword')) {
9263
- return mockChangePasswordHandler(method, path, options);
9264
- }
9265
- if (path.startsWith('auth/login')) {
9266
- return mockLoginHandler(method, path, options);
6731
+ if (path.startsWith('auth/login')) {
6732
+ return mockLoginHandler(method, path, options);
9267
6733
  }
9268
6734
  if (path.startsWith('auth/setpassword')) {
9269
6735
  return mockSetPasswordHandler(method, path, options);
@@ -9417,19 +6883,22 @@
9417
6883
  const match = /fhir\/R4\/?([^/]+)?\/?([^/]+)?\/?([^/]+)?\/?([^/]+)?/.exec(path);
9418
6884
  const resourceType = match === null || match === void 0 ? void 0 : match[1];
9419
6885
  const id = match === null || match === void 0 ? void 0 : match[2];
9420
- const history = match === null || match === void 0 ? void 0 : match[3];
6886
+ const operation = match === null || match === void 0 ? void 0 : match[3];
9421
6887
  const versionId = match === null || match === void 0 ? void 0 : match[4];
9422
- if (path.startsWith('fhir/R4/ValueSet/%24expand')) {
6888
+ if (path.startsWith('fhir/R4/ValueSet/$expand')) {
9423
6889
  return exampleValueSet;
9424
6890
  }
9425
- else if (path === 'fhir/R4/%24graphql') {
6891
+ else if (path === 'fhir/R4/$graphql') {
9426
6892
  return mockFhirGraphqlHandler(method, path, options);
9427
6893
  }
9428
6894
  else if (path === 'not-found' || id === 'not-found') {
9429
6895
  return core.notFound;
9430
6896
  }
9431
6897
  else if (method === 'POST') {
9432
- if (resourceType) {
6898
+ if (resourceType && id && operation) {
6899
+ return {};
6900
+ }
6901
+ else if (resourceType) {
9433
6902
  return mockRepo.createResource(JSON.parse(options.body));
9434
6903
  }
9435
6904
  else {
@@ -9440,7 +6909,7 @@
9440
6909
  if (resourceType && id && versionId) {
9441
6910
  return mockRepo.readVersion(resourceType, id, versionId);
9442
6911
  }
9443
- else if (resourceType && id && history) {
6912
+ else if (resourceType && id && operation === '_history') {
9444
6913
  return mockRepo.readHistory(resourceType, id);
9445
6914
  }
9446
6915
  else if (resourceType && id) {