@medplum/mock 0.9.4 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,506 +1,507 @@
1
- import { createReference, Operator, MedplumClient, badRequest, allOk, notFound, getStatus, parseSearchDefinition } from '@medplum/core';
1
+ import { createReference, Operator, evalFhirPath, MedplumClient, badRequest, allOk, notFound, getStatus, parseSearchDefinition } from '@medplum/core';
2
2
 
3
- const ExampleAccessPolicy = {
4
- resourceType: 'AccessPolicy',
5
- id: '123',
6
- name: 'Example Access Policy',
7
- };
8
- const ExampleStatusValueSet = {
9
- resourceType: 'ValueSet',
10
- id: 'example-statuses',
11
- compose: {
12
- include: [
13
- {
14
- concept: [
15
- { code: 'ORDERED' },
16
- { code: 'SENT_TO_CUSTOMER' },
17
- { code: 'SENT_BACK_TO_LAB' },
18
- { code: 'LAB_PROCESSED' },
19
- { code: 'LAB_COMPLETE' },
20
- ],
21
- },
22
- ],
23
- },
24
- };
25
- const ExampleUserConfiguration = {
26
- resourceType: 'UserConfiguration',
27
- id: '123',
28
- name: 'Example User Configuration',
29
- option: [
30
- {
31
- id: 'statusValueSet',
32
- valueString: 'ValueSet/example-statuses',
33
- },
34
- ],
3
+ const ExampleAccessPolicy = {
4
+ resourceType: 'AccessPolicy',
5
+ id: '123',
6
+ name: 'Example Access Policy',
7
+ };
8
+ const ExampleStatusValueSet = {
9
+ resourceType: 'ValueSet',
10
+ id: 'example-statuses',
11
+ compose: {
12
+ include: [
13
+ {
14
+ concept: [
15
+ { code: 'ORDERED' },
16
+ { code: 'SENT_TO_CUSTOMER' },
17
+ { code: 'SENT_BACK_TO_LAB' },
18
+ { code: 'LAB_PROCESSED' },
19
+ { code: 'LAB_COMPLETE' },
20
+ ],
21
+ },
22
+ ],
23
+ },
24
+ };
25
+ const ExampleUserConfiguration = {
26
+ resourceType: 'UserConfiguration',
27
+ id: '123',
28
+ name: 'Example User Configuration',
29
+ option: [
30
+ {
31
+ id: 'statusValueSet',
32
+ valueString: 'ValueSet/example-statuses',
33
+ },
34
+ ],
35
35
  };
36
36
 
37
- const TestOrganization = {
38
- resourceType: 'Organization',
39
- id: '123',
40
- meta: {
41
- versionId: '1',
42
- },
43
- name: 'Test Organization',
44
- };
45
- const DifferentOrganization = {
46
- resourceType: 'Organization',
47
- id: '456',
48
- meta: {
49
- versionId: '1',
50
- },
51
- name: 'Different',
52
- };
53
- const DrAliceSmith = {
54
- resourceType: 'Practitioner',
55
- id: '123',
56
- meta: {
57
- versionId: '2',
58
- lastUpdated: '2021-01-02T12:00:00Z',
59
- author: {
60
- reference: 'Practitioner/123',
61
- },
62
- },
63
- name: [
64
- {
65
- given: ['Alice'],
66
- family: 'Smith',
67
- },
68
- ],
69
- photo: [
70
- {
71
- contentType: 'image/png',
72
- url: 'https://docs.medplum.com/img/cdc-femaledoc.png',
73
- },
74
- ],
75
- };
76
- const DrAliceSmithPreviousVersion = {
77
- resourceType: 'Practitioner',
78
- id: '123',
79
- meta: {
80
- versionId: '1',
81
- lastUpdated: '2021-01-01T12:00:00Z',
82
- author: {
83
- reference: 'Practitioner/123',
84
- },
85
- },
86
- name: [{ given: ['Medplum'], family: 'Admin' }],
87
- };
88
- const DrAliceSmithSchedule = {
89
- resourceType: 'Schedule',
90
- id: '123',
91
- actor: [
92
- {
93
- reference: 'Practitioner/123',
94
- display: 'Dr. Alice Smith',
95
- },
96
- ],
97
- };
98
- const DrAliceSmithSlots = (() => {
99
- const schedule = createReference(DrAliceSmithSchedule);
100
- const result = [];
101
- const slotDate = new Date();
102
- for (let day = 0; day < 60; day++) {
103
- for (const hour of [9, 10, 11, 13, 14, 15]) {
104
- slotDate.setHours(hour, 0, 0, 0);
105
- result.push({
106
- resourceType: 'Slot',
107
- id: `slot-${day}-${hour}`,
108
- start: slotDate.toISOString(),
109
- schedule,
110
- });
111
- }
112
- slotDate.setDate(slotDate.getDate() + 1);
113
- }
114
- return result;
37
+ const TestOrganization = {
38
+ resourceType: 'Organization',
39
+ id: '123',
40
+ meta: {
41
+ versionId: '1',
42
+ },
43
+ name: 'Test Organization',
44
+ };
45
+ const DifferentOrganization = {
46
+ resourceType: 'Organization',
47
+ id: '456',
48
+ meta: {
49
+ versionId: '1',
50
+ },
51
+ name: 'Different',
52
+ };
53
+ const DrAliceSmith = {
54
+ resourceType: 'Practitioner',
55
+ id: '123',
56
+ meta: {
57
+ versionId: '2',
58
+ lastUpdated: '2021-01-02T12:00:00Z',
59
+ author: {
60
+ reference: 'Practitioner/123',
61
+ },
62
+ },
63
+ name: [
64
+ {
65
+ given: ['Alice'],
66
+ family: 'Smith',
67
+ },
68
+ ],
69
+ photo: [
70
+ {
71
+ contentType: 'image/png',
72
+ url: 'https://docs.medplum.com/img/cdc-femaledoc.png',
73
+ },
74
+ ],
75
+ };
76
+ const DrAliceSmithPreviousVersion = {
77
+ resourceType: 'Practitioner',
78
+ id: '123',
79
+ meta: {
80
+ versionId: '1',
81
+ lastUpdated: '2021-01-01T12:00:00Z',
82
+ author: {
83
+ reference: 'Practitioner/123',
84
+ },
85
+ },
86
+ name: [{ given: ['Medplum'], family: 'Admin' }],
87
+ };
88
+ const DrAliceSmithSchedule = {
89
+ resourceType: 'Schedule',
90
+ id: '123',
91
+ actor: [
92
+ {
93
+ reference: 'Practitioner/123',
94
+ display: 'Dr. Alice Smith',
95
+ },
96
+ ],
97
+ };
98
+ const DrAliceSmithSlots = (() => {
99
+ const schedule = createReference(DrAliceSmithSchedule);
100
+ const result = [];
101
+ const slotDate = new Date();
102
+ for (let day = 0; day < 60; day++) {
103
+ for (const hour of [9, 10, 11, 13, 14, 15]) {
104
+ slotDate.setHours(hour, 0, 0, 0);
105
+ result.push({
106
+ resourceType: 'Slot',
107
+ id: `slot-${day}-${hour}`,
108
+ start: slotDate.toISOString(),
109
+ schedule,
110
+ });
111
+ }
112
+ slotDate.setDate(slotDate.getDate() + 1);
113
+ }
114
+ return result;
115
115
  })();
116
116
 
117
- const ExampleBot = {
118
- resourceType: 'Bot',
119
- id: '123',
120
- name: 'Test Bot',
121
- code: 'console.log("hello world");',
122
- };
123
- const ExampleClient = {
124
- resourceType: 'ClientApplication',
125
- id: '123',
126
- name: 'Test Client',
117
+ const ExampleBot = {
118
+ resourceType: 'Bot',
119
+ id: '123',
120
+ name: 'Test Bot',
121
+ code: 'console.log("hello world");',
122
+ };
123
+ const ExampleClient = {
124
+ resourceType: 'ClientApplication',
125
+ id: '123',
126
+ name: 'Test Client',
127
127
  };
128
128
 
129
- const ExampleQuestionnaire = {
130
- resourceType: 'Questionnaire',
131
- id: '123',
132
- name: 'Vitals',
133
- title: 'Vitals',
134
- subjectType: ['Patient'],
135
- item: [
136
- {
137
- linkId: '1',
138
- text: 'First question',
139
- type: 'string',
140
- },
141
- ],
142
- };
143
- const ExampleQuestionnaireResponse = {
144
- resourceType: 'QuestionnaireResponse',
145
- id: '123',
146
- questionnaire: 'Questionnaire/123',
147
- subject: {
148
- reference: 'Patient/123',
149
- },
150
- source: {
151
- reference: 'Practitioner/123',
152
- },
129
+ const ExampleQuestionnaire = {
130
+ resourceType: 'Questionnaire',
131
+ id: '123',
132
+ name: 'Vitals',
133
+ title: 'Vitals',
134
+ subjectType: ['Patient'],
135
+ item: [
136
+ {
137
+ linkId: '1',
138
+ text: 'First question',
139
+ type: 'string',
140
+ },
141
+ ],
142
+ };
143
+ const ExampleQuestionnaireResponse = {
144
+ resourceType: 'QuestionnaireResponse',
145
+ id: '123',
146
+ questionnaire: 'Questionnaire/123',
147
+ subject: {
148
+ reference: 'Patient/123',
149
+ },
150
+ source: {
151
+ reference: 'Practitioner/123',
152
+ },
153
153
  };
154
154
 
155
- const HomerSimpson = {
156
- resourceType: 'Patient',
157
- id: '123',
158
- meta: {
159
- versionId: '2',
160
- lastUpdated: '2020-01-02T00:00:00.000Z',
161
- author: {
162
- reference: 'Practitioner/123',
163
- },
164
- },
165
- identifier: [
166
- { system: 'abc', value: '123' },
167
- { system: 'def', value: '456' },
168
- ],
169
- active: true,
170
- birthDate: '1956-05-12',
171
- name: [
172
- {
173
- given: ['Homer'],
174
- family: 'Simpson',
175
- },
176
- ],
177
- photo: [
178
- {
179
- contentType: 'image/png',
180
- url: 'https://docs.medplum.com/img/homer-simpson.png',
181
- },
182
- ],
183
- telecom: [
184
- {
185
- system: 'phone',
186
- use: 'home',
187
- value: '555-7334',
188
- },
189
- {
190
- system: 'email',
191
- use: 'home',
192
- value: 'chunkylover53@aol.com',
193
- },
194
- ],
195
- address: [
196
- {
197
- use: 'home',
198
- line: ['742 Evergreen Terrace'],
199
- city: 'Springfield',
200
- state: 'IL',
201
- postalCode: '12345',
202
- },
203
- ],
204
- };
205
- const HomerSimpsonPreviousVersion = {
206
- resourceType: 'Patient',
207
- id: '123',
208
- meta: {
209
- versionId: '1',
210
- lastUpdated: '2020-01-01T00:00:00.000Z',
211
- author: {
212
- reference: 'Practitioner/123',
213
- },
214
- },
215
- name: [
216
- {
217
- given: ['Homer'],
218
- family: 'Simpson',
219
- },
220
- ],
221
- photo: [
222
- {
223
- contentType: 'image/png',
224
- url: 'https://docs.medplum.com/img/homer-simpson.png',
225
- },
226
- ],
227
- };
228
- const HomerEncounter = {
229
- resourceType: 'Encounter',
230
- id: '123',
231
- meta: {
232
- versionId: '456',
233
- lastUpdated: '2020-01-01T00:00:00.000Z',
234
- author: {
235
- reference: 'Practitioner/123',
236
- },
237
- },
238
- };
239
- const HomerCommunication = {
240
- resourceType: 'Communication',
241
- id: '123',
242
- meta: {
243
- lastUpdated: '2020-01-01T12:00:00Z',
244
- author: {
245
- reference: 'Practitioner/123',
246
- },
247
- },
248
- payload: [
249
- {
250
- contentString: 'Hello world',
251
- },
252
- ],
253
- };
254
- const HomerMedia = {
255
- resourceType: 'Media',
256
- id: '123',
257
- meta: {
258
- lastUpdated: '2020-01-01T12:00:00Z',
259
- author: {
260
- reference: 'Practitioner/123',
261
- },
262
- },
263
- content: {
264
- contentType: 'text/plain',
265
- url: 'https://example.com/test.txt',
266
- },
267
- };
268
- const HomerDiagnosticReport = {
269
- resourceType: 'DiagnosticReport',
270
- id: '123',
271
- meta: {
272
- versionId: '1',
273
- lastUpdated: '2020-01-02T12:00:00Z',
274
- author: {
275
- reference: 'Practitioner/123',
276
- },
277
- },
278
- subject: {
279
- reference: 'Patient/123',
280
- display: 'Homer Simpson',
281
- },
282
- resultsInterpreter: [
283
- {
284
- reference: 'Practitioner/123',
285
- display: 'Dr. Alice Smith',
286
- },
287
- ],
288
- result: [
289
- { reference: 'Observation/1' },
290
- { reference: 'Observation/2' },
291
- { reference: 'Observation/3' },
292
- { reference: 'Observation/4' },
293
- { reference: 'Observation/5' },
294
- { reference: 'Observation/6' },
295
- ],
296
- };
297
- const HomerObservation1 = {
298
- resourceType: 'Observation',
299
- id: '1',
300
- code: {
301
- text: 'Test 1',
302
- },
303
- valueString: 'test',
304
- };
305
- const HomerObservation2 = {
306
- resourceType: 'Observation',
307
- id: '2',
308
- code: {
309
- text: 'Test 2',
310
- },
311
- valueQuantity: {
312
- value: 20,
313
- unit: 'x',
314
- },
315
- referenceRange: [
316
- {
317
- low: {
318
- value: 10,
319
- },
320
- },
321
- ],
322
- };
323
- const HomerObservation3 = {
324
- resourceType: 'Observation',
325
- id: '3',
326
- code: {
327
- text: 'Test 3',
328
- },
329
- valueQuantity: {
330
- value: 30,
331
- unit: 'x',
332
- },
333
- referenceRange: [
334
- {
335
- high: {
336
- value: 50,
337
- },
338
- },
339
- ],
340
- };
341
- const HomerObservation4 = {
342
- resourceType: 'Observation',
343
- id: '4',
344
- code: {
345
- text: 'Test 4',
346
- },
347
- valueQuantity: {
348
- value: 50,
349
- unit: 'x',
350
- comparator: '>',
351
- },
352
- referenceRange: [
353
- {
354
- low: {
355
- value: 10,
356
- unit: 'x',
357
- },
358
- high: {
359
- value: 50,
360
- unit: 'x',
361
- },
362
- },
363
- ],
364
- interpretation: [
365
- {
366
- text: 'HIGH',
367
- },
368
- ],
369
- };
370
- const HomerObservation5 = {
371
- resourceType: 'Observation',
372
- id: '5',
373
- code: {
374
- text: 'Test 5',
375
- },
376
- valueQuantity: {
377
- value: 100,
378
- unit: 'x',
379
- },
380
- referenceRange: [{}],
381
- interpretation: [{}],
382
- };
383
- const HomerObservation6 = {
384
- resourceType: 'Observation',
385
- id: '6',
386
- code: {
387
- text: 'Test 6',
388
- },
389
- component: [
390
- {
391
- valueQuantity: {
392
- value: 110,
393
- unit: 'mmHg',
394
- system: 'http://unitsofmeasure.org',
395
- },
396
- },
397
- {
398
- valueQuantity: {
399
- value: 75,
400
- unit: 'mmHg',
401
- system: 'http://unitsofmeasure.org',
402
- },
403
- },
404
- ],
405
- };
406
- const HomerSimpsonSpecimen = {
407
- resourceType: 'Specimen',
408
- subject: createReference(HomerSimpson),
409
- collection: {
410
- collectedDateTime: '2020-01-01T12:00:00Z',
411
- },
412
- };
413
- const HomerServiceRequest = {
414
- resourceType: 'ServiceRequest',
415
- id: '123',
416
- meta: {
417
- versionId: '1',
418
- lastUpdated: '2020-01-01T12:00:00Z',
419
- author: {
420
- reference: 'Practitioner/123',
421
- },
422
- },
423
- identifier: [
424
- {
425
- system: 'https://example.com',
426
- value: '9001',
427
- },
428
- ],
429
- code: {
430
- coding: [
431
- {
432
- system: 'http://snomed.info/sct',
433
- code: 'SERVICE_REQUEST_CODE',
434
- },
435
- ],
436
- },
437
- subject: {
438
- reference: 'Patient/123',
439
- display: 'Homer Simpson',
440
- },
441
- status: 'active',
442
- orderDetail: [
443
- {
444
- text: 'ORDERED',
445
- },
446
- ],
447
- specimen: [createReference(HomerSimpsonSpecimen)],
448
- authoredOn: '2020-01-01T12:00:00Z',
449
- };
450
- const BartSimpson = {
451
- resourceType: 'Patient',
452
- id: '555',
453
- meta: {
454
- versionId: '1',
455
- lastUpdated: '2020-01-01T12:00:00Z',
456
- author: {
457
- reference: 'Practitioner/123',
458
- },
459
- },
460
- birthDate: '1979-12-17',
461
- name: [
462
- {
463
- given: ['Bart'],
464
- family: 'Simpson',
465
- },
466
- ],
467
- photo: [
468
- {
469
- contentType: 'image/jpeg',
470
- url: 'https://example.com/picture.jpg',
471
- },
472
- ],
473
- telecom: [
474
- {
475
- system: 'phone',
476
- use: 'home',
477
- value: '555-1239',
478
- },
479
- {
480
- system: 'email',
481
- use: 'home',
482
- value: 'bart@thesimpsons.com',
483
- },
484
- ],
155
+ const HomerSimpson = {
156
+ resourceType: 'Patient',
157
+ id: '123',
158
+ meta: {
159
+ versionId: '2',
160
+ lastUpdated: '2020-01-02T00:00:00.000Z',
161
+ author: {
162
+ reference: 'Practitioner/123',
163
+ },
164
+ },
165
+ identifier: [
166
+ { system: 'abc', value: '123' },
167
+ { system: 'def', value: '456' },
168
+ ],
169
+ active: true,
170
+ birthDate: '1956-05-12',
171
+ name: [
172
+ {
173
+ given: ['Homer'],
174
+ family: 'Simpson',
175
+ },
176
+ ],
177
+ photo: [
178
+ {
179
+ contentType: 'image/png',
180
+ url: 'https://docs.medplum.com/img/homer-simpson.png',
181
+ },
182
+ ],
183
+ telecom: [
184
+ {
185
+ system: 'phone',
186
+ use: 'home',
187
+ value: '555-7334',
188
+ },
189
+ {
190
+ system: 'email',
191
+ use: 'home',
192
+ value: 'chunkylover53@aol.com',
193
+ },
194
+ ],
195
+ address: [
196
+ {
197
+ use: 'home',
198
+ line: ['742 Evergreen Terrace'],
199
+ city: 'Springfield',
200
+ state: 'IL',
201
+ postalCode: '12345',
202
+ },
203
+ ],
204
+ };
205
+ const HomerSimpsonPreviousVersion = {
206
+ resourceType: 'Patient',
207
+ id: '123',
208
+ meta: {
209
+ versionId: '1',
210
+ lastUpdated: '2020-01-01T00:00:00.000Z',
211
+ author: {
212
+ reference: 'Practitioner/123',
213
+ },
214
+ },
215
+ name: [
216
+ {
217
+ given: ['Homer'],
218
+ family: 'Simpson',
219
+ },
220
+ ],
221
+ photo: [
222
+ {
223
+ contentType: 'image/png',
224
+ url: 'https://docs.medplum.com/img/homer-simpson.png',
225
+ },
226
+ ],
227
+ };
228
+ const HomerEncounter = {
229
+ resourceType: 'Encounter',
230
+ id: '123',
231
+ meta: {
232
+ versionId: '456',
233
+ lastUpdated: '2020-01-01T00:00:00.000Z',
234
+ author: {
235
+ reference: 'Practitioner/123',
236
+ },
237
+ },
238
+ };
239
+ const HomerCommunication = {
240
+ resourceType: 'Communication',
241
+ id: '123',
242
+ meta: {
243
+ lastUpdated: '2020-01-01T12:00:00Z',
244
+ author: {
245
+ reference: 'Practitioner/123',
246
+ },
247
+ },
248
+ payload: [
249
+ {
250
+ contentString: 'Hello world',
251
+ },
252
+ ],
253
+ };
254
+ const HomerMedia = {
255
+ resourceType: 'Media',
256
+ id: '123',
257
+ meta: {
258
+ lastUpdated: '2020-01-01T12:00:00Z',
259
+ author: {
260
+ reference: 'Practitioner/123',
261
+ },
262
+ },
263
+ content: {
264
+ contentType: 'text/plain',
265
+ url: 'https://example.com/test.txt',
266
+ },
267
+ };
268
+ const HomerDiagnosticReport = {
269
+ resourceType: 'DiagnosticReport',
270
+ id: '123',
271
+ meta: {
272
+ versionId: '1',
273
+ lastUpdated: '2020-01-02T12:00:00Z',
274
+ author: {
275
+ reference: 'Practitioner/123',
276
+ },
277
+ },
278
+ subject: {
279
+ reference: 'Patient/123',
280
+ display: 'Homer Simpson',
281
+ },
282
+ resultsInterpreter: [
283
+ {
284
+ reference: 'Practitioner/123',
285
+ display: 'Dr. Alice Smith',
286
+ },
287
+ ],
288
+ result: [
289
+ { reference: 'Observation/1' },
290
+ { reference: 'Observation/2' },
291
+ { reference: 'Observation/3' },
292
+ { reference: 'Observation/4' },
293
+ { reference: 'Observation/5' },
294
+ { reference: 'Observation/6' },
295
+ ],
296
+ };
297
+ const HomerObservation1 = {
298
+ resourceType: 'Observation',
299
+ id: '1',
300
+ code: {
301
+ text: 'Test 1',
302
+ },
303
+ valueString: 'test',
304
+ };
305
+ const HomerObservation2 = {
306
+ resourceType: 'Observation',
307
+ id: '2',
308
+ code: {
309
+ text: 'Test 2',
310
+ },
311
+ valueQuantity: {
312
+ value: 20,
313
+ unit: 'x',
314
+ },
315
+ referenceRange: [
316
+ {
317
+ low: {
318
+ value: 10,
319
+ },
320
+ },
321
+ ],
322
+ };
323
+ const HomerObservation3 = {
324
+ resourceType: 'Observation',
325
+ id: '3',
326
+ code: {
327
+ text: 'Test 3',
328
+ },
329
+ valueQuantity: {
330
+ value: 30,
331
+ unit: 'x',
332
+ },
333
+ referenceRange: [
334
+ {
335
+ high: {
336
+ value: 50,
337
+ },
338
+ },
339
+ ],
340
+ };
341
+ const HomerObservation4 = {
342
+ resourceType: 'Observation',
343
+ id: '4',
344
+ code: {
345
+ text: 'Test 4',
346
+ },
347
+ valueQuantity: {
348
+ value: 50,
349
+ unit: 'x',
350
+ comparator: '>',
351
+ },
352
+ referenceRange: [
353
+ {
354
+ low: {
355
+ value: 10,
356
+ unit: 'x',
357
+ },
358
+ high: {
359
+ value: 50,
360
+ unit: 'x',
361
+ },
362
+ },
363
+ ],
364
+ interpretation: [
365
+ {
366
+ text: 'HIGH',
367
+ },
368
+ ],
369
+ };
370
+ const HomerObservation5 = {
371
+ resourceType: 'Observation',
372
+ id: '5',
373
+ code: {
374
+ text: 'Test 5',
375
+ },
376
+ valueQuantity: {
377
+ value: 100,
378
+ unit: 'x',
379
+ },
380
+ referenceRange: [{}],
381
+ interpretation: [{}],
382
+ };
383
+ const HomerObservation6 = {
384
+ resourceType: 'Observation',
385
+ id: '6',
386
+ code: {
387
+ text: 'Test 6',
388
+ },
389
+ component: [
390
+ {
391
+ valueQuantity: {
392
+ value: 110,
393
+ unit: 'mmHg',
394
+ system: 'http://unitsofmeasure.org',
395
+ },
396
+ },
397
+ {
398
+ valueQuantity: {
399
+ value: 75,
400
+ unit: 'mmHg',
401
+ system: 'http://unitsofmeasure.org',
402
+ },
403
+ },
404
+ ],
405
+ };
406
+ const HomerSimpsonSpecimen = {
407
+ id: '123',
408
+ resourceType: 'Specimen',
409
+ subject: createReference(HomerSimpson),
410
+ collection: {
411
+ collectedDateTime: '2020-01-01T12:00:00Z',
412
+ },
413
+ };
414
+ const HomerServiceRequest = {
415
+ resourceType: 'ServiceRequest',
416
+ id: '123',
417
+ meta: {
418
+ versionId: '1',
419
+ lastUpdated: '2020-01-01T12:00:00Z',
420
+ author: {
421
+ reference: 'Practitioner/123',
422
+ },
423
+ },
424
+ identifier: [
425
+ {
426
+ system: 'https://example.com',
427
+ value: '9001',
428
+ },
429
+ ],
430
+ code: {
431
+ coding: [
432
+ {
433
+ system: 'http://snomed.info/sct',
434
+ code: 'SERVICE_REQUEST_CODE',
435
+ },
436
+ ],
437
+ },
438
+ subject: {
439
+ reference: 'Patient/123',
440
+ display: 'Homer Simpson',
441
+ },
442
+ status: 'active',
443
+ orderDetail: [
444
+ {
445
+ text: 'ORDERED',
446
+ },
447
+ ],
448
+ specimen: [createReference(HomerSimpsonSpecimen)],
449
+ authoredOn: '2020-01-01T12:00:00Z',
450
+ };
451
+ const BartSimpson = {
452
+ resourceType: 'Patient',
453
+ id: '555',
454
+ meta: {
455
+ versionId: '1',
456
+ lastUpdated: '2020-01-01T12:00:00Z',
457
+ author: {
458
+ reference: 'Practitioner/123',
459
+ },
460
+ },
461
+ birthDate: '1979-12-17',
462
+ name: [
463
+ {
464
+ given: ['Bart'],
465
+ family: 'Simpson',
466
+ },
467
+ ],
468
+ photo: [
469
+ {
470
+ contentType: 'image/jpeg',
471
+ url: 'https://example.com/picture.jpg',
472
+ },
473
+ ],
474
+ telecom: [
475
+ {
476
+ system: 'phone',
477
+ use: 'home',
478
+ value: '555-1239',
479
+ },
480
+ {
481
+ system: 'email',
482
+ use: 'home',
483
+ value: 'bart@thesimpsons.com',
484
+ },
485
+ ],
485
486
  };
486
487
 
487
- const ExampleSubscription = {
488
- resourceType: 'Subscription',
489
- id: '123',
490
- meta: {
491
- versionId: '456',
492
- },
493
- };
494
- const ExampleAuditEvent = {
495
- resourceType: 'AuditEvent',
496
- id: '123',
497
- meta: {
498
- lastUpdated: new Date().toISOString(),
499
- versionId: '456',
500
- author: {
501
- reference: 'Practitioner/123',
502
- },
503
- },
488
+ const ExampleSubscription = {
489
+ resourceType: 'Subscription',
490
+ id: '123',
491
+ meta: {
492
+ versionId: '456',
493
+ },
494
+ };
495
+ const ExampleAuditEvent = {
496
+ resourceType: 'AuditEvent',
497
+ id: '123',
498
+ meta: {
499
+ lastUpdated: new Date().toISOString(),
500
+ versionId: '456',
501
+ author: {
502
+ reference: 'Practitioner/123',
503
+ },
504
+ },
504
505
  };
505
506
 
506
507
  var StructureDefinitionList = [
@@ -6351,141 +6352,141 @@ var StructureDefinitionList = [
6351
6352
  }
6352
6353
  ];
6353
6354
 
6354
- const PatientSearchParameters = [
6355
- {
6356
- resourceType: 'SearchParameter',
6357
- id: 'Patient-name',
6358
- base: ['Patient'],
6359
- code: 'name',
6360
- name: 'name',
6361
- type: 'string',
6362
- expression: 'Patient.name',
6363
- },
6364
- {
6365
- resourceType: 'SearchParameter',
6366
- id: 'Patient-birthdate',
6367
- base: ['Patient'],
6368
- code: 'birthdate',
6369
- name: 'birthdate',
6370
- type: 'date',
6371
- expression: 'Patient.birthDate',
6372
- },
6373
- {
6374
- resourceType: 'SearchParameter',
6375
- id: 'Patient-organization',
6376
- base: ['Patient'],
6377
- code: 'organization',
6378
- name: 'organization',
6379
- type: 'reference',
6380
- expression: 'Patient.managingOrganization',
6381
- target: ['Organization'],
6382
- },
6383
- {
6384
- resourceType: 'SearchParameter',
6385
- id: 'Patient-active',
6386
- base: ['Patient'],
6387
- code: 'active',
6388
- name: 'active',
6389
- type: 'token',
6390
- expression: 'Patient.active',
6391
- },
6392
- {
6393
- resourceType: 'SearchParameter',
6394
- id: 'individual-telecom',
6395
- base: ['Patient', 'Practitioner'],
6396
- code: 'telecom',
6397
- name: 'telecom',
6398
- type: 'token',
6399
- expression: 'Patient.telecom | Practitioner.telecom',
6400
- },
6401
- {
6402
- resourceType: 'SearchParameter',
6403
- id: 'individual-email',
6404
- base: ['Patient', 'Practitioner'],
6405
- code: 'email',
6406
- name: 'email',
6407
- type: 'token',
6408
- expression: "Patient.telecom.where(system='email') | Practitioner.telecom.where(system='email')",
6409
- },
6410
- {
6411
- resourceType: 'SearchParameter',
6412
- id: 'individual-phone',
6413
- base: ['Patient', 'Practitioner'],
6414
- code: 'phone',
6415
- name: 'phone',
6416
- type: 'token',
6417
- expression: "Patient.telecom.where(system='phone') | Practitioner.telecom.where(system='phone')",
6418
- },
6419
- {
6420
- resourceType: 'SearchParameter',
6421
- id: 'individual-address-city',
6422
- base: ['Patient', 'Practitioner'],
6423
- code: 'address-city',
6424
- name: 'address-city',
6425
- type: 'token',
6426
- expression: 'Patient.address.city | Practitioner.address.city',
6427
- },
6428
- {
6429
- resourceType: 'SearchParameter',
6430
- id: 'individual-address-state',
6431
- base: ['Patient', 'Practitioner'],
6432
- code: 'address-state',
6433
- name: 'address-state',
6434
- type: 'token',
6435
- expression: 'Patient.address.state | Practitioner.address.state',
6436
- },
6437
- {
6438
- resourceType: 'SearchParameter',
6439
- id: 'ServiceRequest-subject',
6440
- code: 'subject',
6441
- base: ['ServiceRequest'],
6442
- type: 'reference',
6443
- expression: 'ServiceRequest.subject',
6444
- target: ['Group', 'Device', 'Patient', 'Location'],
6445
- },
6446
- {
6447
- resourceType: 'SearchParameter',
6448
- id: 'ServiceRequest-authored',
6449
- code: 'authored',
6450
- base: ['ServiceRequest'],
6451
- type: 'date',
6452
- expression: 'ServiceRequest.authoredOn',
6453
- },
6454
- {
6455
- resourceType: 'SearchParameter',
6456
- id: 'Observation-value-quantity',
6457
- code: 'value-quantity',
6458
- base: ['Observation'],
6459
- type: 'quantity',
6460
- expression: '(Observation.value as Quantity) | (Observation.value as SampledData)',
6461
- },
6462
- {
6463
- resourceType: 'SearchParameter',
6464
- id: 'Encounter-length',
6465
- code: 'length',
6466
- base: ['Encounter'],
6467
- type: 'quantity',
6468
- expression: 'Encounter.length',
6469
- },
6470
- ];
6471
- const GraphQLSchemaResponse = {
6472
- data: {
6473
- StructureDefinitionList,
6474
- SearchParameterList: [...PatientSearchParameters],
6475
- },
6355
+ const PatientSearchParameters = [
6356
+ {
6357
+ resourceType: 'SearchParameter',
6358
+ id: 'Patient-name',
6359
+ base: ['Patient'],
6360
+ code: 'name',
6361
+ name: 'name',
6362
+ type: 'string',
6363
+ expression: 'Patient.name',
6364
+ },
6365
+ {
6366
+ resourceType: 'SearchParameter',
6367
+ id: 'Patient-birthdate',
6368
+ base: ['Patient'],
6369
+ code: 'birthdate',
6370
+ name: 'birthdate',
6371
+ type: 'date',
6372
+ expression: 'Patient.birthDate',
6373
+ },
6374
+ {
6375
+ resourceType: 'SearchParameter',
6376
+ id: 'Patient-organization',
6377
+ base: ['Patient'],
6378
+ code: 'organization',
6379
+ name: 'organization',
6380
+ type: 'reference',
6381
+ expression: 'Patient.managingOrganization',
6382
+ target: ['Organization'],
6383
+ },
6384
+ {
6385
+ resourceType: 'SearchParameter',
6386
+ id: 'Patient-active',
6387
+ base: ['Patient'],
6388
+ code: 'active',
6389
+ name: 'active',
6390
+ type: 'token',
6391
+ expression: 'Patient.active',
6392
+ },
6393
+ {
6394
+ resourceType: 'SearchParameter',
6395
+ id: 'individual-telecom',
6396
+ base: ['Patient', 'Practitioner'],
6397
+ code: 'telecom',
6398
+ name: 'telecom',
6399
+ type: 'token',
6400
+ expression: 'Patient.telecom | Practitioner.telecom',
6401
+ },
6402
+ {
6403
+ resourceType: 'SearchParameter',
6404
+ id: 'individual-email',
6405
+ base: ['Patient', 'Practitioner'],
6406
+ code: 'email',
6407
+ name: 'email',
6408
+ type: 'token',
6409
+ expression: "Patient.telecom.where(system='email') | Practitioner.telecom.where(system='email')",
6410
+ },
6411
+ {
6412
+ resourceType: 'SearchParameter',
6413
+ id: 'individual-phone',
6414
+ base: ['Patient', 'Practitioner'],
6415
+ code: 'phone',
6416
+ name: 'phone',
6417
+ type: 'token',
6418
+ expression: "Patient.telecom.where(system='phone') | Practitioner.telecom.where(system='phone')",
6419
+ },
6420
+ {
6421
+ resourceType: 'SearchParameter',
6422
+ id: 'individual-address-city',
6423
+ base: ['Patient', 'Practitioner'],
6424
+ code: 'address-city',
6425
+ name: 'address-city',
6426
+ type: 'token',
6427
+ expression: 'Patient.address.city | Practitioner.address.city',
6428
+ },
6429
+ {
6430
+ resourceType: 'SearchParameter',
6431
+ id: 'individual-address-state',
6432
+ base: ['Patient', 'Practitioner'],
6433
+ code: 'address-state',
6434
+ name: 'address-state',
6435
+ type: 'token',
6436
+ expression: 'Patient.address.state | Practitioner.address.state',
6437
+ },
6438
+ {
6439
+ resourceType: 'SearchParameter',
6440
+ id: 'ServiceRequest-subject',
6441
+ code: 'subject',
6442
+ base: ['ServiceRequest'],
6443
+ type: 'reference',
6444
+ expression: 'ServiceRequest.subject',
6445
+ target: ['Group', 'Device', 'Patient', 'Location'],
6446
+ },
6447
+ {
6448
+ resourceType: 'SearchParameter',
6449
+ id: 'ServiceRequest-authored',
6450
+ code: 'authored',
6451
+ base: ['ServiceRequest'],
6452
+ type: 'date',
6453
+ expression: 'ServiceRequest.authoredOn',
6454
+ },
6455
+ {
6456
+ resourceType: 'SearchParameter',
6457
+ id: 'Observation-value-quantity',
6458
+ code: 'value-quantity',
6459
+ base: ['Observation'],
6460
+ type: 'quantity',
6461
+ expression: '(Observation.value as Quantity) | (Observation.value as SampledData)',
6462
+ },
6463
+ {
6464
+ resourceType: 'SearchParameter',
6465
+ id: 'Encounter-length',
6466
+ code: 'length',
6467
+ base: ['Encounter'],
6468
+ type: 'quantity',
6469
+ expression: 'Encounter.length',
6470
+ },
6471
+ ];
6472
+ const GraphQLSchemaResponse = {
6473
+ data: {
6474
+ StructureDefinitionList,
6475
+ SearchParameterList: [...PatientSearchParameters],
6476
+ },
6476
6477
  };
6477
6478
 
6478
- const exampleValueSet = {
6479
- resourceType: 'ValueSet',
6480
- expansion: {
6481
- contains: [
6482
- {
6483
- system: 'x',
6484
- code: 'test-code',
6485
- display: 'Test Display',
6486
- },
6487
- ],
6488
- },
6479
+ const exampleValueSet = {
6480
+ resourceType: 'ValueSet',
6481
+ expansion: {
6482
+ contains: [
6483
+ {
6484
+ system: 'x',
6485
+ code: 'test-code',
6486
+ display: 'Test Display',
6487
+ },
6488
+ ],
6489
+ },
6489
6490
  };
6490
6491
 
6491
6492
  /******************************************************************************
@@ -6503,34 +6504,6 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
6503
6504
  PERFORMANCE OF THIS SOFTWARE.
6504
6505
  ***************************************************************************** */
6505
6506
 
6506
- function __classPrivateFieldGet$1(receiver, state, kind, f) {
6507
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6508
- 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");
6509
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6510
- }
6511
-
6512
- function __classPrivateFieldSet$1(receiver, state, value, kind, f) {
6513
- if (kind === "m") throw new TypeError("Private method is not writable");
6514
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
6515
- 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");
6516
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6517
- }
6518
-
6519
- /******************************************************************************
6520
- Copyright (c) Microsoft Corporation.
6521
-
6522
- Permission to use, copy, modify, and/or distribute this software for any
6523
- purpose with or without fee is hereby granted.
6524
-
6525
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
6526
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
6527
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
6528
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
6529
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
6530
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
6531
- PERFORMANCE OF THIS SOFTWARE.
6532
- ***************************************************************************** */
6533
-
6534
6507
  function __classPrivateFieldGet(receiver, state, kind, f) {
6535
6508
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6536
6509
  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");
@@ -6544,2963 +6517,459 @@ function __classPrivateFieldSet(receiver, state, value, kind, f) {
6544
6517
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6545
6518
  }
6546
6519
 
6547
- /**
6548
- * Ensures that the value is wrapped in an array.
6549
- * @param input The input as a an array or a value.
6550
- * @returns The input as an array.
6551
- */
6552
- function ensureArray(input) {
6553
- if (input === null || input === undefined) {
6554
- return [];
6555
- }
6556
- return Array.isArray(input) ? input : [input];
6557
- }
6558
- /**
6559
- * Applies a function to single value or an array of values.
6560
- * @param context The context which will be passed to the function.
6561
- * @param fn The function to apply.
6562
- * @returns The result of the function.
6563
- */
6564
- function applyMaybeArray(context, fn) {
6565
- if (context === undefined) {
6566
- return undefined;
6567
- }
6568
- if (Array.isArray(context)) {
6569
- return context
6570
- .map((e) => fn(e))
6571
- .filter((e) => !!e)
6572
- .flat();
6573
- }
6574
- else {
6575
- return fn(context);
6576
- }
6577
- }
6578
- /**
6579
- * Determines if the input is an empty array.
6580
- * @param obj Any value or array of values.
6581
- * @returns True if the input is an empty array.
6582
- */
6583
- function isEmptyArray(obj) {
6584
- return Array.isArray(obj) && obj.length === 0;
6585
- }
6586
- function isFalsy(obj) {
6587
- return !obj || isEmptyArray(obj);
6588
- }
6589
- /**
6590
- * Converts unknown object into a JavaScript boolean.
6591
- * Note that this is different than the FHIRPath "toBoolean",
6592
- * which has particular semantics around arrays, empty arrays, and type conversions.
6593
- * @param obj Any value or array of values.
6594
- * @returns The converted boolean value according to FHIRPath rules.
6595
- */
6596
- function toJsBoolean(obj) {
6597
- if (Array.isArray(obj)) {
6598
- return obj.length === 0 ? false : !!obj[0];
6599
- }
6600
- return !!obj;
6601
- }
6602
- /**
6603
- * Removes duplicates in array using FHIRPath equality rules.
6604
- * @param arr The input array.
6605
- * @returns The result array with duplicates removed.
6606
- */
6607
- function removeDuplicates(arr) {
6608
- const result = [];
6609
- for (const i of arr) {
6610
- let found = false;
6611
- for (const j of result) {
6612
- if (fhirPathEquals(i, j)) {
6613
- found = true;
6614
- break;
6615
- }
6616
- }
6617
- if (!found) {
6618
- result.push(i);
6619
- }
6620
- }
6621
- return result;
6622
- }
6623
- /**
6624
- * Determines if two values are equal according to FHIRPath equality rules.
6625
- * @param x The first value.
6626
- * @param y The second value.
6627
- * @returns True if equal.
6628
- */
6629
- function fhirPathEquals(x, y) {
6630
- if (isFalsy(x) && isFalsy(y)) {
6631
- return true;
6632
- }
6633
- if (isEmptyArray(x) || isEmptyArray(y)) {
6634
- return [];
6635
- }
6636
- if (typeof x === 'number' && typeof y === 'number') {
6637
- return Math.abs(x - y) < 1e-8;
6638
- }
6639
- if (isQuantity(x) && isQuantity(y)) {
6640
- return isQuantityEquivalent(x, y);
6641
- }
6642
- if (Array.isArray(x) && Array.isArray(y)) {
6643
- return x.length === y.length && x.every((val, index) => fhirPathEquals(val, y[index]));
6644
- }
6645
- if (typeof x === 'object' && typeof y === 'object') {
6646
- return deepEquals(x, y);
6647
- }
6648
- return x === y;
6649
- }
6650
- /**
6651
- * Determines if two values are equal according to FHIRPath equality rules.
6652
- * @param x The first value.
6653
- * @param y The second value.
6654
- * @returns True if equal.
6655
- */
6656
- function fhirPathEquivalent(x, y) {
6657
- if (isFalsy(x) && isFalsy(y)) {
6658
- return true;
6659
- }
6660
- if (isEmptyArray(x) || isEmptyArray(y)) {
6661
- // Note that this implies that if the collections have a different number of items to compare,
6662
- // or if one input is a value and the other is empty ({ }), the result will be false.
6663
- return false;
6664
- }
6665
- if (typeof x === 'number' && typeof y === 'number') {
6666
- // Use more generous threshold than equality
6667
- // Decimal: values must be equal, comparison is done on values rounded to the precision of the least precise operand.
6668
- // Trailing zeroes after the decimal are ignored in determining precision.
6669
- return Math.abs(x - y) < 0.01;
6670
- }
6671
- if (isQuantity(x) && isQuantity(y)) {
6672
- return isQuantityEquivalent(x, y);
6673
- }
6674
- if (Array.isArray(x) && Array.isArray(y)) {
6675
- // If both operands are collections with multiple items:
6676
- // 1) Each item must be equivalent
6677
- // 2) Comparison is not order dependent
6678
- x.sort();
6679
- y.sort();
6680
- return x.length === y.length && x.every((val, index) => fhirPathEquals(val, y[index]));
6681
- }
6682
- if (typeof x === 'object' && typeof y === 'object') {
6683
- return deepEquals(x, y);
6684
- }
6685
- if (typeof x === 'string' && typeof y === 'string') {
6686
- // String: the strings must be the same, ignoring case and locale, and normalizing whitespace
6687
- // (see String Equivalence for more details).
6688
- return x.toLowerCase() === y.toLowerCase();
6689
- }
6690
- return x === y;
6691
- }
6692
- function fhirPathIs(value, desiredType) {
6693
- if (value === undefined || value === null) {
6694
- return false;
6695
- }
6696
- switch (desiredType) {
6697
- case 'Boolean':
6698
- return typeof value === 'boolean';
6699
- case 'Decimal':
6700
- case 'Integer':
6701
- return typeof value === 'number';
6702
- case 'Date':
6703
- return typeof value === 'string' && !!value.match(/^\d{4}(-\d{2}(-\d{2})?)?/);
6704
- case 'DateTime':
6705
- return typeof value === 'string' && !!value.match(/^\d{4}(-\d{2}(-\d{2})?)?T/);
6706
- case 'Time':
6707
- return typeof value === 'string' && !!value.match(/^T\d/);
6708
- case 'Period':
6709
- return isPeriod(value);
6710
- case 'Quantity':
6711
- return isQuantity(value);
6712
- default:
6713
- return typeof value === 'object' && (value === null || value === void 0 ? void 0 : value.resourceType) === desiredType;
6714
- }
6715
- }
6716
- /**
6717
- * Determines if the input is a Period object.
6718
- * This is heuristic based, as we do not have strong typing at runtime.
6719
- * @param input The input value.
6720
- * @returns True if the input is a period.
6721
- */
6722
- function isPeriod(input) {
6723
- return !!(input && typeof input === 'object' && 'start' in input);
6724
- }
6725
- /**
6726
- * Determines if the input is a Quantity object.
6727
- * This is heuristic based, as we do not have strong typing at runtime.
6728
- * @param input The input value.
6729
- * @returns True if the input is a quantity.
6730
- */
6731
- function isQuantity(input) {
6732
- return !!(input && typeof input === 'object' && 'value' in input && typeof input.value === 'number');
6733
- }
6734
- function isQuantityEquivalent(x, y) {
6735
- return (Math.abs(x.value - y.value) < 0.01 &&
6736
- (x.unit === y.unit || x.code === y.code || x.unit === y.code || x.code === y.unit));
6737
- }
6738
- /**
6739
- * Resource equality.
6740
- * Ignores meta.versionId and meta.lastUpdated.
6741
- * See: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/#4-deep-equality
6742
- * @param object1 The first object.
6743
- * @param object2 The second object.
6744
- * @returns True if the objects are equal.
6745
- */
6746
- function deepEquals(object1, object2) {
6747
- const keys1 = Object.keys(object1);
6748
- const keys2 = Object.keys(object2);
6749
- if (keys1.length !== keys2.length) {
6750
- return false;
6751
- }
6752
- for (const key of keys1) {
6753
- const val1 = object1[key];
6754
- const val2 = object2[key];
6755
- if (isObject(val1) && isObject(val2)) {
6756
- if (!deepEquals(val1, val2)) {
6757
- return false;
6758
- }
6759
- }
6760
- else {
6761
- if (val1 !== val2) {
6762
- return false;
6763
- }
6764
- }
6765
- }
6766
- return true;
6767
- }
6768
- function isObject(object) {
6769
- return object !== null && typeof object === 'object';
6520
+ var _MemoryRepository_resources, _MemoryRepository_history;
6521
+ class MemoryRepository {
6522
+ constructor() {
6523
+ _MemoryRepository_resources.set(this, void 0);
6524
+ _MemoryRepository_history.set(this, void 0);
6525
+ __classPrivateFieldSet(this, _MemoryRepository_resources, {}, "f");
6526
+ __classPrivateFieldSet(this, _MemoryRepository_history, {}, "f");
6527
+ }
6528
+ createResource(resource) {
6529
+ var _a;
6530
+ const result = resource;
6531
+ if (!result.id) {
6532
+ result.id = this.generateId();
6533
+ }
6534
+ if (!result.meta) {
6535
+ result.meta = {};
6536
+ }
6537
+ if (!((_a = result.meta) === null || _a === void 0 ? void 0 : _a.versionId)) {
6538
+ result.meta.versionId = this.generateId();
6539
+ }
6540
+ const { resourceType, id } = resource;
6541
+ if (!(resourceType in __classPrivateFieldGet(this, _MemoryRepository_resources, "f"))) {
6542
+ __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType] = {};
6543
+ }
6544
+ if (!(resourceType in __classPrivateFieldGet(this, _MemoryRepository_history, "f"))) {
6545
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType] = {};
6546
+ }
6547
+ if (!(id in __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType])) {
6548
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType][id] = [];
6549
+ }
6550
+ __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType][id] = resource;
6551
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType][id].push(result);
6552
+ return result;
6553
+ }
6554
+ readResource(resourceType, id) {
6555
+ var _a, _b;
6556
+ return (_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id];
6557
+ }
6558
+ readHistory(resourceType, id) {
6559
+ var _a, _b, _c;
6560
+ return {
6561
+ resourceType: 'Bundle',
6562
+ type: 'history',
6563
+ 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 : [])
6564
+ .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)); })
6565
+ .map((version) => ({ resource: version })),
6566
+ };
6567
+ }
6568
+ readVersion(resourceType, id, versionId) {
6569
+ var _a, _b, _c;
6570
+ 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; });
6571
+ }
6572
+ search(searchRequest) {
6573
+ var _a;
6574
+ const { resourceType } = searchRequest;
6575
+ const resources = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType]) !== null && _a !== void 0 ? _a : {};
6576
+ const result = Object.values(resources).filter((resource) => matchesSearchRequest(resource, searchRequest));
6577
+ return {
6578
+ resourceType: 'Bundle',
6579
+ type: 'searchset',
6580
+ entry: result.map((resource) => ({ resource })),
6581
+ total: result.length,
6582
+ };
6583
+ }
6584
+ deleteResource(resourceType, id) {
6585
+ var _a, _b;
6586
+ if ((_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) {
6587
+ delete __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType][id];
6588
+ }
6589
+ }
6590
+ generateId() {
6591
+ return Date.now().toString(36);
6592
+ }
6770
6593
  }
6771
-
6772
- class FhirPathAtom {
6773
- constructor(original, child) {
6774
- this.original = original;
6775
- this.child = child;
6776
- }
6777
- eval(context) {
6778
- try {
6779
- const result = applyMaybeArray(context, (e) => this.child.eval(e));
6780
- if (Array.isArray(result)) {
6781
- return result.flat();
6782
- }
6783
- else if (result === undefined || result === null) {
6784
- return [];
6785
- }
6786
- else {
6787
- return [result];
6788
- }
6789
- }
6790
- catch (error) {
6791
- throw new Error(`FhirPathError on "${this.original}": ${error}`);
6792
- }
6793
- }
6794
- }
6795
- class LiteralAtom {
6796
- constructor(value) {
6797
- this.value = value;
6798
- }
6799
- eval() {
6800
- return this.value;
6801
- }
6802
- }
6803
- class SymbolAtom {
6804
- constructor(name) {
6805
- this.name = name;
6806
- }
6807
- eval(context) {
6808
- if (this.name === '$this') {
6809
- return context;
6810
- }
6811
- return applyMaybeArray(context, (e) => {
6812
- if (e && typeof e === 'object') {
6813
- if ('resourceType' in e && e.resourceType === this.name) {
6814
- return e;
6815
- }
6816
- if (this.name in e) {
6817
- return e[this.name];
6818
- }
6819
- const propertyName = Object.keys(e).find((k) => k.startsWith(this.name));
6820
- if (propertyName) {
6821
- return e[propertyName];
6822
- }
6823
- }
6824
- return undefined;
6825
- });
6826
- }
6827
- }
6828
- class EmptySetAtom {
6829
- eval() {
6830
- return [];
6831
- }
6832
- }
6833
- class UnaryOperatorAtom {
6834
- constructor(child, impl) {
6835
- this.child = child;
6836
- this.impl = impl;
6837
- }
6838
- eval(context) {
6839
- return this.impl(this.child.eval(context));
6840
- }
6841
- }
6842
- class AsAtom {
6843
- constructor(left, right) {
6844
- this.left = left;
6845
- this.right = right;
6846
- }
6847
- eval(context) {
6848
- return this.left.eval(context);
6849
- }
6850
- }
6851
- class ArithemticOperatorAtom {
6852
- constructor(left, right, impl) {
6853
- this.left = left;
6854
- this.right = right;
6855
- this.impl = impl;
6856
- }
6857
- eval(context) {
6858
- const leftValue = this.left.eval(context);
6859
- const rightValue = this.right.eval(context);
6860
- if (isQuantity(leftValue) && isQuantity(rightValue)) {
6861
- return Object.assign(Object.assign({}, leftValue), { value: this.impl(leftValue.value, rightValue.value) });
6862
- }
6863
- else {
6864
- return this.impl(leftValue, rightValue);
6865
- }
6866
- }
6867
- }
6868
- class ComparisonOperatorAtom {
6869
- constructor(left, right, impl) {
6870
- this.left = left;
6871
- this.right = right;
6872
- this.impl = impl;
6873
- }
6874
- eval(context) {
6875
- const leftValue = this.left.eval(context);
6876
- const rightValue = this.right.eval(context);
6877
- if (isQuantity(leftValue) && isQuantity(rightValue)) {
6878
- return this.impl(leftValue.value, rightValue.value);
6879
- }
6880
- else {
6881
- return this.impl(leftValue, rightValue);
6882
- }
6883
- }
6884
- }
6885
- class ConcatAtom {
6886
- constructor(left, right) {
6887
- this.left = left;
6888
- this.right = right;
6889
- }
6890
- eval(context) {
6891
- const leftValue = this.left.eval(context);
6892
- const rightValue = this.right.eval(context);
6893
- const result = [];
6894
- function add(value) {
6895
- if (value) {
6896
- if (Array.isArray(value)) {
6897
- result.push(...value);
6898
- }
6899
- else {
6900
- result.push(value);
6901
- }
6902
- }
6903
- }
6904
- add(leftValue);
6905
- add(rightValue);
6906
- if (result.length > 0 && result.every((e) => typeof e === 'string')) {
6907
- return result.join('');
6908
- }
6909
- return result;
6910
- }
6911
- }
6912
- class ContainsAtom {
6913
- constructor(left, right) {
6914
- this.left = left;
6915
- this.right = right;
6916
- }
6917
- eval(context) {
6918
- const leftValue = this.left.eval(context);
6919
- const rightValue = this.right.eval(context);
6920
- return ensureArray(leftValue).includes(rightValue);
6921
- }
6922
- }
6923
- class InAtom {
6924
- constructor(left, right) {
6925
- this.left = left;
6926
- this.right = right;
6927
- }
6928
- eval(context) {
6929
- const leftValue = this.left.eval(context);
6930
- const rightValue = this.right.eval(context);
6931
- return ensureArray(rightValue).includes(leftValue);
6932
- }
6933
- }
6934
- class DotAtom {
6935
- constructor(left, right) {
6936
- this.left = left;
6937
- this.right = right;
6938
- }
6939
- eval(context) {
6940
- return this.right.eval(this.left.eval(context));
6941
- }
6942
- }
6943
- class UnionAtom {
6944
- constructor(left, right) {
6945
- this.left = left;
6946
- this.right = right;
6947
- }
6948
- eval(context) {
6949
- const leftResult = this.left.eval(context);
6950
- const rightResult = this.right.eval(context);
6951
- let resultArray;
6952
- if (leftResult !== undefined && rightResult !== undefined) {
6953
- resultArray = [leftResult, rightResult].flat();
6954
- }
6955
- else if (leftResult !== undefined) {
6956
- resultArray = ensureArray(leftResult);
6957
- }
6958
- else if (rightResult !== undefined) {
6959
- resultArray = ensureArray(rightResult);
6960
- }
6961
- else {
6962
- resultArray = [];
6963
- }
6964
- return removeDuplicates(resultArray);
6965
- }
6966
- }
6967
- class EqualsAtom {
6968
- constructor(left, right) {
6969
- this.left = left;
6970
- this.right = right;
6971
- }
6972
- eval(context) {
6973
- const leftValue = this.left.eval(context);
6974
- const rightValue = this.right.eval(context);
6975
- if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
6976
- return fhirPathEquals(leftValue.flat(), rightValue);
6977
- }
6978
- return applyMaybeArray(leftValue, (e) => fhirPathEquals(e, rightValue));
6979
- }
6980
- }
6981
- class NotEqualsAtom {
6982
- constructor(left, right) {
6983
- this.left = left;
6984
- this.right = right;
6985
- }
6986
- eval(context) {
6987
- const leftValue = this.left.eval(context);
6988
- const rightValue = this.right.eval(context);
6989
- let result;
6990
- if (Array.isArray(rightValue)) {
6991
- result = fhirPathEquals(leftValue, rightValue);
6992
- }
6993
- else {
6994
- result = applyMaybeArray(leftValue, (e) => fhirPathEquals(e, rightValue));
6995
- }
6996
- return !toJsBoolean(result);
6997
- }
6998
- }
6999
- class EquivalentAtom {
7000
- constructor(left, right) {
7001
- this.left = left;
7002
- this.right = right;
7003
- }
7004
- eval(context) {
7005
- const leftValue = this.left.eval(context);
7006
- const rightValue = this.right.eval(context);
7007
- if (Array.isArray(rightValue)) {
7008
- return fhirPathEquivalent(leftValue, rightValue);
7009
- }
7010
- return applyMaybeArray(leftValue, (e) => fhirPathEquivalent(e, rightValue));
7011
- }
7012
- }
7013
- class NotEquivalentAtom {
7014
- constructor(left, right) {
7015
- this.left = left;
7016
- this.right = right;
7017
- }
7018
- eval(context) {
7019
- const leftValue = this.left.eval(context);
7020
- const rightValue = this.right.eval(context);
7021
- let result;
7022
- if (Array.isArray(rightValue)) {
7023
- result = fhirPathEquivalent(leftValue, rightValue);
7024
- }
7025
- else {
7026
- result = applyMaybeArray(leftValue, (e) => fhirPathEquivalent(e, rightValue));
7027
- }
7028
- return !toJsBoolean(result);
7029
- }
7030
- }
7031
- class IsAtom {
7032
- constructor(left, right) {
7033
- this.left = left;
7034
- this.right = right;
7035
- }
7036
- eval(context) {
7037
- const typeName = this.right.name;
7038
- return applyMaybeArray(this.left.eval(context), (e) => fhirPathIs(e, typeName));
7039
- }
7040
- }
7041
- /**
7042
- * 6.5.1. and
7043
- * Returns true if both operands evaluate to true, false if either operand evaluates to false, and the empty collection ({ }) otherwise.
7044
- */
7045
- class AndAtom {
7046
- constructor(left, right) {
7047
- this.left = left;
7048
- this.right = right;
7049
- }
7050
- eval(context) {
7051
- const leftValue = this.left.eval(context);
7052
- const rightValue = this.right.eval(context);
7053
- if (leftValue === true && rightValue === true) {
7054
- return true;
7055
- }
7056
- if (leftValue === false || rightValue === false) {
7057
- return false;
7058
- }
7059
- return [];
7060
- }
7061
- }
7062
- class OrAtom {
7063
- constructor(left, right) {
7064
- this.left = left;
7065
- this.right = right;
7066
- }
7067
- eval(context) {
7068
- const leftValue = this.left.eval(context);
7069
- if (toJsBoolean(leftValue)) {
7070
- return leftValue;
7071
- }
7072
- const rightValue = this.right.eval(context);
7073
- if (toJsBoolean(rightValue)) {
7074
- return rightValue;
7075
- }
7076
- return [];
7077
- }
7078
- }
7079
- /**
7080
- * 6.5.4. xor
7081
- * Returns true if exactly one of the operands evaluates to true,
7082
- * false if either both operands evaluate to true or both operands evaluate to false,
7083
- * and the empty collection ({ }) otherwise:
7084
- */
7085
- class XorAtom {
7086
- constructor(left, right) {
7087
- this.left = left;
7088
- this.right = right;
7089
- }
7090
- eval(context) {
7091
- const leftValue = this.left.eval(context);
7092
- const rightValue = this.right.eval(context);
7093
- if ((leftValue === true && rightValue !== true) || (leftValue !== true && rightValue === true)) {
7094
- return true;
7095
- }
7096
- if ((leftValue === true && rightValue === true) || (leftValue === false && rightValue === false)) {
7097
- return false;
7098
- }
7099
- return [];
7100
- }
7101
- }
7102
- class FunctionAtom {
7103
- constructor(name, args, impl) {
7104
- this.name = name;
7105
- this.args = args;
7106
- this.impl = impl;
7107
- }
7108
- eval(context) {
7109
- return this.impl(ensureArray(context), ...this.args);
7110
- }
7111
- }
7112
- class IndexerAtom {
7113
- constructor(left, expr) {
7114
- this.left = left;
7115
- this.expr = expr;
7116
- }
7117
- eval(context) {
7118
- const index = this.expr.eval(context);
7119
- if (typeof index !== 'number') {
7120
- throw new Error(`Invalid indexer expression: should return integer}`);
7121
- }
7122
- const leftResult = this.left.eval(context);
7123
- if (!(index in leftResult)) {
7124
- return [];
7125
- }
7126
- return leftResult[index];
7127
- }
6594
+ _MemoryRepository_resources = new WeakMap(), _MemoryRepository_history = new WeakMap();
6595
+ /**
6596
+ * Determines if the resource matches the search request.
6597
+ * @param resource The resource that was created or updated.
6598
+ * @param searchRequest The subscription criteria as a search request.
6599
+ * @returns True if the resource satisfies the search request.
6600
+ */
6601
+ function matchesSearchRequest(resource, searchRequest) {
6602
+ if (searchRequest.resourceType !== resource.resourceType) {
6603
+ return false;
6604
+ }
6605
+ if (searchRequest.filters) {
6606
+ for (const filter of searchRequest.filters) {
6607
+ if (!matchesSearchFilter(resource, filter)) {
6608
+ return false;
6609
+ }
6610
+ }
6611
+ }
6612
+ return true;
7128
6613
  }
7129
-
7130
- function parseDateString(str) {
7131
- if (str.startsWith('T')) {
7132
- // If a time string,
7133
- // then normalize to full length.
7134
- return str + 'T00:00:00.000Z'.substring(str.length);
7135
- }
7136
- if (str.length <= 10) {
7137
- // If a local date (i.e., "2021-01-01"),
7138
- // then return as-is.
7139
- return str;
7140
- }
7141
- try {
7142
- // Try to normalize to UTC
7143
- return new Date(str).toISOString();
7144
- }
7145
- catch (e) {
7146
- // Fallback to original input
7147
- // This happens on unsupported time formats such as "2021-01-01T12"
7148
- return str;
7149
- }
6614
+ /**
6615
+ * Determines if the resource matches the search filter.
6616
+ * @param resource The resource that was created or updated.
6617
+ * @param filter One of the filters of a subscription criteria.
6618
+ * @returns True if the resource satisfies the search filter.
6619
+ */
6620
+ function matchesSearchFilter(resource, filter) {
6621
+ for (const filterValue of filter.value.split(',')) {
6622
+ if (matchesSearchFilterValue(resource, filter, filterValue)) {
6623
+ return true;
6624
+ }
6625
+ }
6626
+ return false;
7150
6627
  }
7151
-
7152
- /*
7153
- * Collection of FHIRPath
7154
- * See: https://hl7.org/fhirpath/#functions
7155
- */
7156
- /**
7157
- * Temporary placholder for unimplemented methods.
7158
- */
7159
- const stub = () => [];
7160
- /*
7161
- * 5.1 Existence
7162
- * See: https://hl7.org/fhirpath/#existence
7163
- */
7164
- /**
7165
- * Returns true if the input collection is empty ({ }) and false otherwise.
7166
- *
7167
- * See: https://hl7.org/fhirpath/#empty-boolean
7168
- *
7169
- * @param input The input collection.
7170
- * @returns True if the input collection is empty ({ }) and false otherwise.
7171
- */
7172
- function empty(input) {
7173
- return [input.length === 0];
7174
- }
7175
- /**
7176
- * Returns true if the collection has unknown elements, and false otherwise.
7177
- * This is the opposite of empty(), and as such is a shorthand for empty().not().
7178
- * If the input collection is empty ({ }), the result is false.
7179
- *
7180
- * The function can also take an optional criteria to be applied to the collection
7181
- * prior to the determination of the exists. In this case, the function is shorthand
7182
- * for where(criteria).exists().
7183
- *
7184
- * See: https://hl7.org/fhirpath/#existscriteria-expression-boolean
7185
- *
7186
- * @param input
7187
- * @param criteria
7188
- * @returns True if the collection has unknown elements, and false otherwise.
7189
- */
7190
- function exists(input, criteria) {
7191
- if (criteria) {
7192
- return [input.filter((e) => toJsBoolean(criteria.eval(e))).length > 0];
7193
- }
7194
- else {
7195
- return [input.length > 0];
7196
- }
7197
- }
7198
- /**
7199
- * Returns true if for every element in the input collection, criteria evaluates to true.
7200
- * Otherwise, the result is false.
7201
- *
7202
- * If the input collection is empty ({ }), the result is true.
7203
- *
7204
- * See: https://hl7.org/fhirpath/#allcriteria-expression-boolean
7205
- *
7206
- * @param input The input collection.
7207
- * @param criteria The evaluation criteria.
7208
- * @returns True if for every element in the input collection, criteria evaluates to true.
7209
- */
7210
- function all(input, criteria) {
7211
- return [input.every((e) => toJsBoolean(criteria.eval(e)))];
7212
- }
7213
- /**
7214
- * Takes a collection of Boolean values and returns true if all the items are true.
7215
- * If unknown items are false, the result is false.
7216
- * If the input is empty ({ }), the result is true.
7217
- *
7218
- * See: https://hl7.org/fhirpath/#alltrue-boolean
7219
- *
7220
- * @param input The input collection.
7221
- * @param criteria The evaluation criteria.
7222
- * @returns True if all the items are true.
7223
- */
7224
- function allTrue(input) {
7225
- for (const value of input) {
7226
- if (!value) {
7227
- return [false];
7228
- }
7229
- }
7230
- return [true];
7231
- }
7232
- /**
7233
- * Takes a collection of Boolean values and returns true if unknown of the items are true.
7234
- * If all the items are false, or if the input is empty ({ }), the result is false.
7235
- *
7236
- * See: https://hl7.org/fhirpath/#anytrue-boolean
7237
- *
7238
- * @param input The input collection.
7239
- * @param criteria The evaluation criteria.
7240
- * @returns True if unknown of the items are true.
7241
- */
7242
- function anyTrue(input) {
7243
- for (const value of input) {
7244
- if (value) {
7245
- return [true];
7246
- }
7247
- }
7248
- return [false];
7249
- }
7250
- /**
7251
- * Takes a collection of Boolean values and returns true if all the items are false.
7252
- * If unknown items are true, the result is false.
7253
- * If the input is empty ({ }), the result is true.
7254
- *
7255
- * See: https://hl7.org/fhirpath/#allfalse-boolean
7256
- *
7257
- * @param input The input collection.
7258
- * @param criteria The evaluation criteria.
7259
- * @returns True if all the items are false.
7260
- */
7261
- function allFalse(input) {
7262
- for (const value of input) {
7263
- if (value) {
7264
- return [false];
7265
- }
7266
- }
7267
- return [true];
7268
- }
7269
- /**
7270
- * Takes a collection of Boolean values and returns true if unknown of the items are false.
7271
- * If all the items are true, or if the input is empty ({ }), the result is false.
7272
- *
7273
- * See: https://hl7.org/fhirpath/#anyfalse-boolean
7274
- *
7275
- * @param input The input collection.
7276
- * @param criteria The evaluation criteria.
7277
- * @returns True if for every element in the input collection, criteria evaluates to true.
7278
- */
7279
- function anyFalse(input) {
7280
- for (const value of input) {
7281
- if (!value) {
7282
- return [true];
7283
- }
7284
- }
7285
- return [false];
7286
- }
7287
- /**
7288
- * Returns true if all items in the input collection are members of the collection passed
7289
- * as the other argument. Membership is determined using the = (Equals) (=) operation.
7290
- *
7291
- * Conceptually, this function is evaluated by testing each element in the input collection
7292
- * for membership in the other collection, with a default of true. This means that if the
7293
- * input collection is empty ({ }), the result is true, otherwise if the other collection
7294
- * is empty ({ }), the result is false.
7295
- *
7296
- * See: http://hl7.org/fhirpath/#subsetofother-collection-boolean
7297
- */
7298
- const subsetOf = stub;
7299
- /**
7300
- * Returns true if all items in the collection passed as the other argument are members of
7301
- * the input collection. Membership is determined using the = (Equals) (=) operation.
7302
- *
7303
- * Conceptually, this function is evaluated by testing each element in the other collection
7304
- * for membership in the input collection, with a default of true. This means that if the
7305
- * other collection is empty ({ }), the result is true, otherwise if the input collection
7306
- * is empty ({ }), the result is false.
7307
- *
7308
- * See: http://hl7.org/fhirpath/#supersetofother-collection-boolean
7309
- */
7310
- const supersetOf = stub;
7311
- /**
7312
- * Returns the integer count of the number of items in the input collection.
7313
- * Returns 0 when the input collection is empty.
7314
- *
7315
- * See: https://hl7.org/fhirpath/#count-integer
7316
- *
7317
- * @param input The input collection.
7318
- * @returns The integer count of the number of items in the input collection.
7319
- */
7320
- function count(input) {
7321
- return [input.length];
7322
- }
7323
- /**
7324
- * Returns a collection containing only the unique items in the input collection.
7325
- * To determine whether two items are the same, the = (Equals) (=) operator is used,
7326
- * as defined below.
7327
- *
7328
- * If the input collection is empty ({ }), the result is empty.
7329
- *
7330
- * Note that the order of elements in the input collection is not guaranteed to be
7331
- * preserved in the result.
7332
- *
7333
- * See: https://hl7.org/fhirpath/#distinct-collection
7334
- *
7335
- * @param input The input collection.
7336
- * @returns The integer count of the number of items in the input collection.
7337
- */
7338
- function distinct(input) {
7339
- return Array.from(new Set(input));
7340
- }
7341
- /**
7342
- * Returns true if all the items in the input collection are distinct.
7343
- * To determine whether two items are distinct, the = (Equals) (=) operator is used,
7344
- * as defined below.
7345
- *
7346
- * See: https://hl7.org/fhirpath/#isdistinct-boolean
7347
- *
7348
- * @param input The input collection.
7349
- * @returns The integer count of the number of items in the input collection.
7350
- */
7351
- function isDistinct(input) {
7352
- return [input.length === new Set(input).size];
7353
- }
7354
- /*
7355
- * 5.2 Filtering and projection
7356
- */
7357
- /**
7358
- * Returns a collection containing only those elements in the input collection
7359
- * for which the stated criteria expression evaluates to true.
7360
- * Elements for which the expression evaluates to false or empty ({ }) are not
7361
- * included in the result.
7362
- *
7363
- * If the input collection is empty ({ }), the result is empty.
7364
- *
7365
- * If the result of evaluating the condition is other than a single boolean value,
7366
- * the evaluation will end and signal an error to the calling environment,
7367
- * consistent with singleton evaluation of collections behavior.
7368
- *
7369
- * See: https://hl7.org/fhirpath/#wherecriteria-expression-collection
7370
- *
7371
- * @param input The input collection.
7372
- * @param condition The condition atom.
7373
- * @returns A collection containing only those elements in the input collection for which the stated criteria expression evaluates to true.
7374
- */
7375
- function where(input, criteria) {
7376
- return input.filter((e) => toJsBoolean(criteria.eval(e)));
7377
- }
7378
- /**
7379
- * Evaluates the projection expression for each item in the input collection.
7380
- * The result of each evaluation is added to the output collection. If the
7381
- * evaluation results in a collection with multiple items, all items are added
7382
- * to the output collection (collections resulting from evaluation of projection
7383
- * are flattened). This means that if the evaluation for an element results in
7384
- * the empty collection ({ }), no element is added to the result, and that if
7385
- * the input collection is empty ({ }), the result is empty as well.
7386
- *
7387
- * See: http://hl7.org/fhirpath/#selectprojection-expression-collection
7388
- */
7389
- function select(input, criteria) {
7390
- return ensureArray(input.map((e) => criteria.eval(e)).flat());
7391
- }
7392
- /**
7393
- * A version of select that will repeat the projection and add it to the output
7394
- * collection, as long as the projection yields new items (as determined by
7395
- * the = (Equals) (=) operator).
7396
- *
7397
- * See: http://hl7.org/fhirpath/#repeatprojection-expression-collection
7398
- */
7399
- const repeat = stub;
7400
- /**
7401
- * Returns a collection that contains all items in the input collection that
7402
- * are of the given type or a subclass thereof. If the input collection is
7403
- * empty ({ }), the result is empty. The type argument is an identifier that
7404
- * must resolve to the name of a type in a model
7405
- *
7406
- * See: http://hl7.org/fhirpath/#oftypetype-type-specifier-collection
7407
- */
7408
- const ofType = stub;
7409
- /*
7410
- * 5.3 Subsetting
7411
- */
7412
- /**
7413
- * Will return the single item in the input if there is just one item.
7414
- * If the input collection is empty ({ }), the result is empty.
7415
- * If there are multiple items, an error is signaled to the evaluation environment.
7416
- * This function is useful for ensuring that an error is returned if an assumption
7417
- * about cardinality is violated at run-time.
7418
- *
7419
- * See: https://hl7.org/fhirpath/#single-collection
7420
- *
7421
- * @param input The input collection.
7422
- * @returns The single item in the input if there is just one item.
7423
- */
7424
- function single(input) {
7425
- if (input.length > 1) {
7426
- throw new Error('Expected input length one for single()');
7427
- }
7428
- return input.length === 0 ? [] : input.slice(0, 1);
7429
- }
7430
- /**
7431
- * Returns a collection containing only the first item in the input collection.
7432
- * This function is equivalent to item[0], so it will return an empty collection if the input collection has no items.
7433
- *
7434
- * See: https://hl7.org/fhirpath/#first-collection
7435
- *
7436
- * @param input The input collection.
7437
- * @returns A collection containing only the first item in the input collection.
7438
- */
7439
- function first(input) {
7440
- return input.length === 0 ? [] : [input[0]];
7441
- }
7442
- /**
7443
- * Returns a collection containing only the last item in the input collection.
7444
- * Will return an empty collection if the input collection has no items.
7445
- *
7446
- * See: https://hl7.org/fhirpath/#last-collection
7447
- *
7448
- * @param input The input collection.
7449
- * @returns A collection containing only the last item in the input collection.
7450
- */
7451
- function last(input) {
7452
- return input.length === 0 ? [] : [input[input.length - 1]];
7453
- }
7454
- /**
7455
- * Returns a collection containing all but the first item in the input collection.
7456
- * Will return an empty collection if the input collection has no items, or only one item.
7457
- *
7458
- * See: https://hl7.org/fhirpath/#tail-collection
7459
- *
7460
- * @param input The input collection.
7461
- * @returns A collection containing all but the first item in the input collection.
7462
- */
7463
- function tail(input) {
7464
- return input.length === 0 ? [] : input.slice(1, input.length);
7465
- }
7466
- /**
7467
- * Returns a collection containing all but the first num items in the input collection.
7468
- * Will return an empty collection if there are no items remaining after the
7469
- * indicated number of items have been skipped, or if the input collection is empty.
7470
- * If num is less than or equal to zero, the input collection is simply returned.
7471
- *
7472
- * See: https://hl7.org/fhirpath/#skipnum-integer-collection
7473
- *
7474
- * @param input The input collection.
7475
- * @returns A collection containing all but the first item in the input collection.
7476
- */
7477
- function skip(input, num) {
7478
- const numValue = num.eval(0);
7479
- if (typeof numValue !== 'number') {
7480
- throw new Error('Expected a number for skip(num)');
7481
- }
7482
- if (numValue >= input.length) {
7483
- return [];
7484
- }
7485
- if (numValue <= 0) {
7486
- return input;
7487
- }
7488
- return input.slice(numValue, input.length);
7489
- }
7490
- /**
7491
- * Returns a collection containing the first num items in the input collection,
7492
- * or less if there are less than num items.
7493
- * If num is less than or equal to 0, or if the input collection is empty ({ }),
7494
- * take returns an empty collection.
7495
- *
7496
- * See: https://hl7.org/fhirpath/#takenum-integer-collection
7497
- *
7498
- * @param input The input collection.
7499
- * @returns A collection containing the first num items in the input collection.
7500
- */
7501
- function take(input, num) {
7502
- const numValue = num.eval(0);
7503
- if (typeof numValue !== 'number') {
7504
- throw new Error('Expected a number for take(num)');
7505
- }
7506
- if (numValue >= input.length) {
7507
- return input;
7508
- }
7509
- if (numValue <= 0) {
7510
- return [];
7511
- }
7512
- return input.slice(0, numValue);
7513
- }
7514
- /**
7515
- * Returns the set of elements that are in both collections.
7516
- * Duplicate items will be eliminated by this function.
7517
- * Order of items is not guaranteed to be preserved in the result of this function.
7518
- *
7519
- * See: http://hl7.org/fhirpath/#intersectother-collection-collection
7520
- */
7521
- function intersect(input, other) {
7522
- if (!other) {
7523
- return input;
7524
- }
7525
- const otherArray = ensureArray(other.eval(0));
7526
- return removeDuplicates(input.filter((e) => otherArray.includes(e)));
7527
- }
7528
- /**
7529
- * Returns the set of elements that are not in the other collection.
7530
- * Duplicate items will not be eliminated by this function, and order will be preserved.
7531
- *
7532
- * e.g. (1 | 2 | 3).exclude(2) returns (1 | 3).
7533
- *
7534
- * See: http://hl7.org/fhirpath/#excludeother-collection-collection
7535
- */
7536
- function exclude(input, other) {
7537
- if (!other) {
7538
- return input;
7539
- }
7540
- const otherArray = ensureArray(other.eval(0));
7541
- return input.filter((e) => !otherArray.includes(e));
7542
- }
7543
- /*
7544
- * 5.4. Combining
7545
- *
7546
- * See: https://hl7.org/fhirpath/#combining
7547
- */
7548
- /**
7549
- * Merge the two collections into a single collection,
7550
- * eliminating unknown duplicate values (using = (Equals) (=) to determine equality).
7551
- * There is no expectation of order in the resulting collection.
7552
- *
7553
- * In other words, this function returns the distinct list of elements from both inputs.
7554
- *
7555
- * See: http://hl7.org/fhirpath/#unionother-collection
7556
- */
7557
- function union(input, other) {
7558
- if (!other) {
7559
- return input;
7560
- }
7561
- return removeDuplicates([input, other.eval(0)].flat());
7562
- }
7563
- /**
7564
- * Merge the input and other collections into a single collection
7565
- * without eliminating duplicate values. Combining an empty collection
7566
- * with a non-empty collection will return the non-empty collection.
7567
- *
7568
- * There is no expectation of order in the resulting collection.
7569
- *
7570
- * See: http://hl7.org/fhirpath/#combineother-collection-collection
7571
- */
7572
- function combine(input, other) {
7573
- if (!other) {
7574
- return input;
7575
- }
7576
- return [input, other.eval(0)].flat();
7577
- }
7578
- /*
7579
- * 5.5. Conversion
7580
- *
7581
- * See: https://hl7.org/fhirpath/#conversion
7582
- */
7583
- /**
7584
- * The iif function in FHIRPath is an immediate if,
7585
- * also known as a conditional operator (such as C’s ? : operator).
7586
- *
7587
- * The criterion expression is expected to evaluate to a Boolean.
7588
- *
7589
- * If criterion is true, the function returns the value of the true-result argument.
7590
- *
7591
- * If criterion is false or an empty collection, the function returns otherwise-result,
7592
- * unless the optional otherwise-result is not given, in which case the function returns an empty collection.
7593
- *
7594
- * Note that short-circuit behavior is expected in this function. In other words,
7595
- * true-result should only be evaluated if the criterion evaluates to true,
7596
- * and otherwise-result should only be evaluated otherwise. For implementations,
7597
- * this means delaying evaluation of the arguments.
7598
- *
7599
- * @param input
7600
- * @param criterion
7601
- * @param trueResult
7602
- * @param otherwiseResult
7603
- * @returns
7604
- */
7605
- function iif(input, criterion, trueResult, otherwiseResult) {
7606
- const evalResult = ensureArray(criterion.eval(input));
7607
- if (evalResult.length > 1 || (evalResult.length === 1 && typeof evalResult[0] !== 'boolean')) {
7608
- throw new Error('Expected criterion to evaluate to a Boolean');
7609
- }
7610
- if (toJsBoolean(evalResult)) {
7611
- return ensureArray(trueResult.eval(input));
7612
- }
7613
- if (otherwiseResult) {
7614
- return ensureArray(otherwiseResult.eval(input));
7615
- }
7616
- return [];
7617
- }
7618
- /**
7619
- * Converts an input collection to a boolean.
7620
- *
7621
- * If the input collection contains a single item, this function will return a single boolean if:
7622
- * 1) the item is a Boolean
7623
- * 2) the item is an Integer and is equal to one of the possible integer representations of Boolean values
7624
- * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
7625
- * 4) the item is a String that is equal to one of the possible string representations of Boolean values
7626
- *
7627
- * 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.
7628
- *
7629
- * See: https://hl7.org/fhirpath/#toboolean-boolean
7630
- *
7631
- * @param input
7632
- * @returns
7633
- */
7634
- function toBoolean(input) {
7635
- if (input.length === 0) {
7636
- return [];
7637
- }
7638
- const [value] = validateInput(input, 1);
7639
- if (typeof value === 'boolean') {
7640
- return [value];
7641
- }
7642
- if (typeof value === 'number') {
7643
- if (value === 0 || value === 1) {
7644
- return [!!value];
7645
- }
7646
- }
7647
- if (typeof value === 'string') {
7648
- const lowerStr = value.toLowerCase();
7649
- if (['true', 't', 'yes', 'y', '1', '1.0'].includes(lowerStr)) {
7650
- return [true];
7651
- }
7652
- if (['false', 'f', 'no', 'n', '0', '0.0'].includes(lowerStr)) {
7653
- return [false];
7654
- }
7655
- }
7656
- return [];
7657
- }
7658
- /**
7659
- * If the input collection contains a single item, this function will return true if:
7660
- * 1) the item is a Boolean
7661
- * 2) the item is an Integer that is equal to one of the possible integer representations of Boolean values
7662
- * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
7663
- * 4) the item is a String that is equal to one of the possible string representations of Boolean values
7664
- *
7665
- * 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.
7666
- *
7667
- * Possible values for Integer, Decimal, and String are described in the toBoolean() function.
7668
- *
7669
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7670
- *
7671
- * If the input collection is empty, the result is empty.
7672
- *
7673
- * See: http://hl7.org/fhirpath/#convertstoboolean-boolean
7674
- *
7675
- * @param input
7676
- * @returns
7677
- */
7678
- function convertsToBoolean(input) {
7679
- if (input.length === 0) {
7680
- return [];
7681
- }
7682
- return [toBoolean(input).length === 1];
7683
- }
7684
- /**
7685
- * Returns the integer representation of the input.
7686
- *
7687
- * If the input collection contains a single item, this function will return a single integer if:
7688
- * 1) the item is an Integer
7689
- * 2) the item is a String and is convertible to an integer
7690
- * 3) the item is a Boolean, where true results in a 1 and false results in a 0.
7691
- *
7692
- * If the item is not one the above types, the result is empty.
7693
- *
7694
- * If the item is a String, but the string is not convertible to an integer (using the regex format (\\+|-)?\d+), the result is empty.
7695
- *
7696
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7697
- *
7698
- * If the input collection is empty, the result is empty.
7699
- *
7700
- * See: https://hl7.org/fhirpath/#tointeger-integer
7701
- *
7702
- * @param input The input collection.
7703
- * @returns The string representation of the input.
7704
- */
7705
- function toInteger(input) {
7706
- if (input.length === 0) {
7707
- return [];
7708
- }
7709
- const [value] = validateInput(input, 1);
7710
- if (typeof value === 'number') {
7711
- return [value];
7712
- }
7713
- if (typeof value === 'string' && value.match(/^[+-]?\d+$/)) {
7714
- return [parseInt(value, 10)];
7715
- }
7716
- if (typeof value === 'boolean') {
7717
- return [value ? 1 : 0];
7718
- }
7719
- return [];
7720
- }
7721
- /**
7722
- * Returns true if the input can be converted to string.
7723
- *
7724
- * If the input collection contains a single item, this function will return true if:
7725
- * 1) the item is an Integer
7726
- * 2) the item is a String and is convertible to an Integer
7727
- * 3) the item is a Boolean
7728
- * 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.
7729
- *
7730
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7731
- *
7732
- * If the input collection is empty, the result is empty.
7733
- *
7734
- * See: https://hl7.org/fhirpath/#convertstointeger-boolean
7735
- *
7736
- * @param input The input collection.
7737
- * @returns
7738
- */
7739
- function convertsToInteger(input) {
7740
- if (input.length === 0) {
7741
- return [];
7742
- }
7743
- return [toInteger(input).length === 1];
7744
- }
7745
- /**
7746
- * If the input collection contains a single item, this function will return a single date if:
7747
- * 1) the item is a Date
7748
- * 2) the item is a DateTime
7749
- * 3) the item is a String and is convertible to a Date
7750
- *
7751
- * If the item is not one of the above types, the result is empty.
7752
- *
7753
- * 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.
7754
- *
7755
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7756
- *
7757
- * If the input collection is empty, the result is empty.
7758
- *
7759
- * See: https://hl7.org/fhirpath/#todate-date
7760
- */
7761
- function toDate(input) {
7762
- if (input.length === 0) {
7763
- return [];
7764
- }
7765
- const [value] = validateInput(input, 1);
7766
- if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
7767
- return [parseDateString(value)];
7768
- }
7769
- return [];
7770
- }
7771
- /**
7772
- * If the input collection contains a single item, this function will return true if:
7773
- * 1) the item is a Date
7774
- * 2) the item is a DateTime
7775
- * 3) the item is a String and is convertible to a Date
7776
- *
7777
- * 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.
7778
- *
7779
- * If the item contains a partial date (e.g. '2012-01'), the result is a partial date.
7780
- *
7781
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7782
- *
7783
- * If the input collection is empty, the result is empty.
7784
- *
7785
- * See: https://hl7.org/fhirpath/#convertstodate-boolean
7786
- */
7787
- function convertsToDate(input) {
7788
- if (input.length === 0) {
7789
- return [];
7790
- }
7791
- return [toDate(input).length === 1];
7792
- }
7793
- /**
7794
- * If the input collection contains a single item, this function will return a single datetime if:
7795
- * 1) the item is a DateTime
7796
- * 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)
7797
- * 3) the item is a String and is convertible to a DateTime
7798
- *
7799
- * If the item is not one of the above types, the result is empty.
7800
- *
7801
- * 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.
7802
- *
7803
- * If the item contains a partial datetime (e.g. '2012-01-01T10:00'), the result is a partial datetime.
7804
- *
7805
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7806
- *
7807
- * If the input collection is empty, the result is empty.
7808
-
7809
- * See: https://hl7.org/fhirpath/#todatetime-datetime
7810
- *
7811
- * @param input
7812
- * @returns
7813
- */
7814
- function toDateTime(input) {
7815
- if (input.length === 0) {
7816
- return [];
7817
- }
7818
- const [value] = validateInput(input, 1);
7819
- if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
7820
- return [parseDateString(value)];
7821
- }
7822
- return [];
7823
- }
7824
- /**
7825
- * If the input collection contains a single item, this function will return true if:
7826
- * 1) the item is a DateTime
7827
- * 2) the item is a Date
7828
- * 3) the item is a String and is convertible to a DateTime
7829
- *
7830
- * 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.
7831
- *
7832
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7833
- *
7834
- * If the input collection is empty, the result is empty.
7835
- *
7836
- * See: https://hl7.org/fhirpath/#convertstodatetime-boolean
7837
- *
7838
- * @param input
7839
- * @returns
7840
- */
7841
- function convertsToDateTime(input) {
7842
- if (input.length === 0) {
7843
- return [];
7844
- }
7845
- return [toDateTime(input).length === 1];
7846
- }
7847
- /**
7848
- * If the input collection contains a single item, this function will return a single decimal if:
7849
- * 1) the item is an Integer or Decimal
7850
- * 2) the item is a String and is convertible to a Decimal
7851
- * 3) the item is a Boolean, where true results in a 1.0 and false results in a 0.0.
7852
- * 4) If the item is not one of the above types, the result is empty.
7853
- *
7854
- * 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.
7855
- *
7856
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7857
- *
7858
- * If the input collection is empty, the result is empty.
7859
- *
7860
- * See: https://hl7.org/fhirpath/#decimal-conversion-functions
7861
- *
7862
- * @param input The input collection.
7863
- * @returns
7864
- */
7865
- function toDecimal(input) {
7866
- if (input.length === 0) {
7867
- return [];
7868
- }
7869
- const [value] = validateInput(input, 1);
7870
- if (typeof value === 'number') {
7871
- return [value];
7872
- }
7873
- if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?$/)) {
7874
- return [parseFloat(value)];
7875
- }
7876
- if (typeof value === 'boolean') {
7877
- return [value ? 1 : 0];
7878
- }
7879
- return [];
7880
- }
7881
- /**
7882
- * If the input collection contains a single item, this function will true if:
7883
- * 1) the item is an Integer or Decimal
7884
- * 2) the item is a String and is convertible to a Decimal
7885
- * 3) the item is a Boolean
7886
- *
7887
- * 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.
7888
- *
7889
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7890
- *
7891
- * If the input collection is empty, the result is empty.
7892
-
7893
- * See: https://hl7.org/fhirpath/#convertstodecimal-boolean
7894
- *
7895
- * @param input The input collection.
7896
- * @returns
7897
- */
7898
- function convertsToDecimal(input) {
7899
- if (input.length === 0) {
7900
- return [];
7901
- }
7902
- return [toDecimal(input).length === 1];
7903
- }
7904
- /**
7905
- * If the input collection contains a single item, this function will return a single quantity if:
7906
- * 1) the item is an Integer, or Decimal, where the resulting quantity will have the default unit ('1')
7907
- * 2) the item is a Quantity
7908
- * 3) the item is a String and is convertible to a Quantity
7909
- * 4) the item is a Boolean, where true results in the quantity 1.0 '1', and false results in the quantity 0.0 '1'
7910
- *
7911
- * If the item is not one of the above types, the result is empty.
7912
- *
7913
- * See: https://hl7.org/fhirpath/#quantity-conversion-functions
7914
- *
7915
- * @param input The input collection.
7916
- * @returns
7917
- */
7918
- function toQuantity(input) {
7919
- if (input.length === 0) {
7920
- return [];
7921
- }
7922
- const [value] = validateInput(input, 1);
7923
- if (isQuantity(value)) {
7924
- return [value];
7925
- }
7926
- if (typeof value === 'number') {
7927
- return [{ value, unit: '1' }];
7928
- }
7929
- if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?/)) {
7930
- return [{ value: parseFloat(value), unit: '1' }];
7931
- }
7932
- if (typeof value === 'boolean') {
7933
- return [{ value: value ? 1 : 0, unit: '1' }];
7934
- }
7935
- return [];
7936
- }
7937
- /**
7938
- * If the input collection contains a single item, this function will return true if:
7939
- * 1) the item is an Integer, Decimal, or Quantity
7940
- * 2) the item is a String that is convertible to a Quantity
7941
- * 3) the item is a Boolean
7942
- *
7943
- * If the item is not one of the above types, or is not convertible to a Quantity using the following regex format:
7944
- *
7945
- * (?'value'(\+|-)?\d+(\.\d+)?)\s*('(?'unit'[^']+)'|(?'time'[a-zA-Z]+))?
7946
- *
7947
- * then the result is false.
7948
- *
7949
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7950
- *
7951
- * If the input collection is empty, the result is empty.
7952
- *
7953
- * 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.
7954
- *
7955
- * See: https://hl7.org/fhirpath/#convertstoquantityunit-string-boolean
7956
- *
7957
- * @param input The input collection.
7958
- * @returns
7959
- */
7960
- function convertsToQuantity(input) {
7961
- if (input.length === 0) {
7962
- return [];
7963
- }
7964
- return [toQuantity(input).length === 1];
7965
- }
7966
- /**
7967
- * Returns the string representation of the input.
7968
- *
7969
- * If the input collection contains a single item, this function will return a single String if:
7970
- *
7971
- * 1) the item in the input collection is a String
7972
- * 2) the item in the input collection is an Integer, Decimal, Date, Time, DateTime, or Quantity the output will contain its String representation
7973
- * 3) the item is a Boolean, where true results in 'true' and false in 'false'.
7974
- *
7975
- * If the item is not one of the above types, the result is false.
7976
- *
7977
- * See: https://hl7.org/fhirpath/#tostring-string
7978
- *
7979
- * @param input The input collection.
7980
- * @returns The string representation of the input.
7981
- */
7982
- function toString(input) {
7983
- if (input.length === 0) {
7984
- return [];
7985
- }
7986
- const [value] = validateInput(input, 1);
7987
- if (value === null || value === undefined) {
7988
- return [];
7989
- }
7990
- if (isQuantity(value)) {
7991
- return [`${value.value} '${value.unit}'`];
7992
- }
7993
- return [value.toString()];
7994
- }
7995
- /**
7996
- * Returns true if the input can be converted to string.
7997
- *
7998
- * If the input collection contains a single item, this function will return true if:
7999
- * 1) the item is a String
8000
- * 2) the item is an Integer, Decimal, Date, Time, or DateTime
8001
- * 3) the item is a Boolean
8002
- * 4) the item is a Quantity
8003
- *
8004
- * If the item is not one of the above types, the result is false.
8005
- *
8006
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8007
- *
8008
- * If the input collection is empty, the result is empty.
8009
- *
8010
- * See: https://hl7.org/fhirpath/#tostring-string
8011
- *
8012
- * @param input The input collection.
8013
- * @returns
8014
- */
8015
- function convertsToString(input) {
8016
- if (input.length === 0) {
8017
- return [];
8018
- }
8019
- return [toString(input).length === 1];
8020
- }
8021
- /**
8022
- * If the input collection contains a single item, this function will return a single time if:
8023
- * 1) the item is a Time
8024
- * 2) the item is a String and is convertible to a Time
8025
- *
8026
- * If the item is not one of the above types, the result is empty.
8027
- *
8028
- * 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.
8029
- *
8030
- * If the item contains a partial time (e.g. '10:00'), the result is a partial time.
8031
- *
8032
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8033
- *
8034
- * If the input collection is empty, the result is empty.
8035
- *
8036
- * See: https://hl7.org/fhirpath/#totime-time
8037
- *
8038
- * @param input
8039
- * @returns
8040
- */
8041
- function toTime(input) {
8042
- if (input.length === 0) {
8043
- return [];
8044
- }
8045
- const [value] = validateInput(input, 1);
8046
- if (typeof value === 'string') {
8047
- const match = value.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);
8048
- if (match) {
8049
- return [parseDateString('T' + match[1])];
8050
- }
8051
- }
8052
- return [];
8053
- }
8054
- /**
8055
- * If the input collection contains a single item, this function will return true if:
8056
- * 1) the item is a Time
8057
- * 2) the item is a String and is convertible to a Time
8058
- *
8059
- * 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.
8060
- *
8061
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8062
- *
8063
- * If the input collection is empty, the result is empty.
8064
- *
8065
- * See: https://hl7.org/fhirpath/#convertstotime-boolean
8066
- *
8067
- * @param input
8068
- * @returns
8069
- */
8070
- function convertsToTime(input) {
8071
- if (input.length === 0) {
8072
- return [];
8073
- }
8074
- return [toTime(input).length === 1];
8075
- }
8076
- /*
8077
- * 5.6. String Manipulation.
8078
- *
8079
- * See: https://hl7.org/fhirpath/#string-manipulation
8080
- */
8081
- /**
8082
- * Returns the 0-based index of the first position substring is found in the input string, or -1 if it is not found.
8083
- *
8084
- * If substring is an empty string (''), the function returns 0.
8085
- *
8086
- * If the input or substring is empty ({ }), the result is empty ({ }).
8087
- *
8088
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8089
- *
8090
- * See: https://hl7.org/fhirpath/#indexofsubstring-string-integer
8091
- *
8092
- * @param input The input collection.
8093
- * @returns The index of the substring.
8094
- */
8095
- function indexOf(input, substringAtom) {
8096
- return applyStringFunc((str, substring) => str.indexOf(substring), input, substringAtom);
8097
- }
8098
- /**
8099
- * 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.
8100
- *
8101
- * 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.
8102
- *
8103
- * If the input or start is empty, the result is empty.
8104
- *
8105
- * If an empty length is provided, the behavior is the same as if length had not been provided.
8106
- *
8107
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8108
- *
8109
- * @param input The input collection.
8110
- * @returns The index of the substring.
8111
- */
8112
- function substring(input, startAtom, lengthAtom) {
8113
- return applyStringFunc((str, start, length) => {
8114
- const startIndex = start;
8115
- const endIndex = length ? startIndex + length : str.length;
8116
- return startIndex < 0 || startIndex >= str.length ? undefined : str.substring(startIndex, endIndex);
8117
- }, input, startAtom, lengthAtom);
8118
- }
8119
- /**
8120
- *
8121
- * @param input The input collection.
8122
- * @returns The index of the substring.
8123
- */
8124
- function startsWith(input, prefixAtom) {
8125
- return applyStringFunc((str, prefix) => str.startsWith(prefix), input, prefixAtom);
8126
- }
8127
- /**
8128
- *
8129
- * @param input The input collection.
8130
- * @returns The index of the substring.
8131
- */
8132
- function endsWith(input, suffixAtom) {
8133
- return applyStringFunc((str, suffix) => str.endsWith(suffix), input, suffixAtom);
8134
- }
8135
- /**
8136
- *
8137
- * @param input The input collection.
8138
- * @returns The index of the substring.
8139
- */
8140
- function contains(input, substringAtom) {
8141
- return applyStringFunc((str, substring) => str.includes(substring), input, substringAtom);
8142
- }
8143
- /**
8144
- *
8145
- * @param input The input collection.
8146
- * @returns The index of the substring.
8147
- */
8148
- function upper(input) {
8149
- return applyStringFunc((str) => str.toUpperCase(), input);
8150
- }
8151
- /**
8152
- *
8153
- * @param input The input collection.
8154
- * @returns The index of the substring.
8155
- */
8156
- function lower(input) {
8157
- return applyStringFunc((str) => str.toLowerCase(), input);
8158
- }
8159
- /**
8160
- *
8161
- * @param input The input collection.
8162
- * @returns The index of the substring.
8163
- */
8164
- function replace(input, patternAtom, substitionAtom) {
8165
- return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, patternAtom, substitionAtom);
8166
- }
8167
- /**
8168
- *
8169
- * @param input The input collection.
8170
- * @returns The index of the substring.
8171
- */
8172
- function matches(input, regexAtom) {
8173
- return applyStringFunc((str, regex) => !!str.match(regex), input, regexAtom);
8174
- }
8175
- /**
8176
- *
8177
- * @param input The input collection.
8178
- * @returns The index of the substring.
8179
- */
8180
- function replaceMatches(input, regexAtom, substitionAtom) {
8181
- return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, regexAtom, substitionAtom);
8182
- }
8183
- /**
8184
- *
8185
- * @param input The input collection.
8186
- * @returns The index of the substring.
8187
- */
8188
- function length(input) {
8189
- return applyStringFunc((str) => str.length, input);
8190
- }
8191
- /**
8192
- * Returns the list of characters in the input string. If the input collection is empty ({ }), the result is empty.
8193
- *
8194
- * See: https://hl7.org/fhirpath/#tochars-collection
8195
- *
8196
- * @param input The input collection.
8197
- */
8198
- function toChars(input) {
8199
- return applyStringFunc((str) => (str ? str.split('') : undefined), input);
8200
- }
8201
- /*
8202
- * 5.7. Math
8203
- */
8204
- /**
8205
- * Returns the absolute value of the input. When taking the absolute value of a quantity, the unit is unchanged.
8206
- *
8207
- * If the input collection is empty, the result is empty.
8208
- *
8209
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8210
- *
8211
- * See: https://hl7.org/fhirpath/#abs-integer-decimal-quantity
8212
- *
8213
- * @param input The input collection.
8214
- * @returns A collection containing the result.
8215
- */
8216
- function abs(input) {
8217
- return applyMathFunc(Math.abs, input);
8218
- }
8219
- /**
8220
- * Returns the first integer greater than or equal to the input.
8221
- *
8222
- * If the input collection is empty, the result is empty.
8223
- *
8224
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8225
- *
8226
- * See: https://hl7.org/fhirpath/#ceiling-integer
8227
- *
8228
- * @param input The input collection.
8229
- * @returns A collection containing the result.
8230
- */
8231
- function ceiling(input) {
8232
- return applyMathFunc(Math.ceil, input);
8233
- }
8234
- /**
8235
- * Returns e raised to the power of the input.
8236
- *
8237
- * If the input collection contains an Integer, it will be implicitly converted to a Decimal and the result will be a Decimal.
8238
- *
8239
- * If the input collection is empty, the result is empty.
8240
- *
8241
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8242
- *
8243
- * See: https://hl7.org/fhirpath/#exp-decimal
8244
- *
8245
- * @param input The input collection.
8246
- * @returns A collection containing the result.
8247
- */
8248
- function exp(input) {
8249
- return applyMathFunc(Math.exp, input);
8250
- }
8251
- /**
8252
- * Returns the first integer less than or equal to the input.
8253
- *
8254
- * If the input collection is empty, the result is empty.
8255
- *
8256
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8257
- *
8258
- * See: https://hl7.org/fhirpath/#floor-integer
8259
- *
8260
- * @param input The input collection.
8261
- * @returns A collection containing the result.
8262
- */
8263
- function floor(input) {
8264
- return applyMathFunc(Math.floor, input);
8265
- }
8266
- /**
8267
- * Returns the natural logarithm of the input (i.e. the logarithm base e).
8268
- *
8269
- * When used with an Integer, it will be implicitly converted to a Decimal.
8270
- *
8271
- * If the input collection is empty, the result is empty.
8272
- *
8273
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8274
- *
8275
- * See: https://hl7.org/fhirpath/#ln-decimal
8276
- *
8277
- * @param input The input collection.
8278
- * @returns A collection containing the result.
8279
- */
8280
- function ln(input) {
8281
- return applyMathFunc(Math.log, input);
8282
- }
8283
- /**
8284
- * Returns the logarithm base base of the input number.
8285
- *
8286
- * When used with Integers, the arguments will be implicitly converted to Decimal.
8287
- *
8288
- * If base is empty, the result is empty.
8289
- *
8290
- * If the input collection is empty, the result is empty.
8291
- *
8292
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8293
- *
8294
- * See: https://hl7.org/fhirpath/#logbase-decimal-decimal
8295
- *
8296
- * @param input The input collection.
8297
- * @returns A collection containing the result.
8298
- */
8299
- function log(input, baseAtom) {
8300
- return applyMathFunc((value, base) => Math.log(value) / Math.log(base), input, baseAtom);
8301
- }
8302
- /**
8303
- * 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.
8304
- *
8305
- * If the power cannot be represented (such as the -1 raised to the 0.5), the result is empty.
8306
- *
8307
- * If the input is empty, or exponent is empty, the result is empty.
8308
- *
8309
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8310
- *
8311
- * See: https://hl7.org/fhirpath/#powerexponent-integer-decimal-integer-decimal
8312
- *
8313
- * @param input The input collection.
8314
- * @returns A collection containing the result.
8315
- */
8316
- function power(input, expAtom) {
8317
- return applyMathFunc(Math.pow, input, expAtom);
8318
- }
8319
- /**
8320
- * 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.
8321
- *
8322
- * If specified, the number of digits of precision must be >= 0 or the evaluation will end and signal an error to the calling environment.
8323
- *
8324
- * If the input collection contains a single item of type Integer, it will be implicitly converted to a Decimal.
8325
- *
8326
- * If the input collection is empty, the result is empty.
8327
- *
8328
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8329
- *
8330
- * See: https://hl7.org/fhirpath/#roundprecision-integer-decimal
8331
- *
8332
- * @param input The input collection.
8333
- * @returns A collection containing the result.
8334
- */
8335
- function round(input) {
8336
- return applyMathFunc(Math.round, input);
8337
- }
8338
- /**
8339
- * Returns the square root of the input number as a Decimal.
8340
- *
8341
- * If the square root cannot be represented (such as the square root of -1), the result is empty.
8342
- *
8343
- * If the input collection is empty, the result is empty.
8344
- *
8345
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8346
- *
8347
- * Note that this function is equivalent to raising a number of the power of 0.5 using the power() function.
8348
- *
8349
- * See: https://hl7.org/fhirpath/#sqrt-decimal
8350
- *
8351
- * @param input The input collection.
8352
- * @returns A collection containing the result.
8353
- */
8354
- function sqrt(input) {
8355
- return applyMathFunc(Math.sqrt, input);
8356
- }
8357
- /**
8358
- * Returns the integer portion of the input.
8359
- *
8360
- * If the input collection is empty, the result is empty.
8361
- *
8362
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8363
- *
8364
- * See: https://hl7.org/fhirpath/#truncate-integer
8365
- *
8366
- * @param input The input collection.
8367
- * @returns A collection containing the result.
8368
- */
8369
- function truncate(input) {
8370
- return applyMathFunc((x) => x | 0, input);
8371
- }
8372
- /*
8373
- * 5.8. Tree navigation
8374
- */
8375
- const children = stub;
8376
- const descendants = stub;
8377
- /*
8378
- * 5.9. Utility functions
8379
- */
8380
- /**
8381
- * Adds a String representation of the input collection to the diagnostic log,
8382
- * using the name argument as the name in the log. This log should be made available
8383
- * to the user in some appropriate fashion. Does not change the input, so returns
8384
- * the input collection as output.
8385
- *
8386
- * If the projection argument is used, the trace would log the result of evaluating
8387
- * the project expression on the input, but still return the input to the trace
8388
- * function unchanged.
8389
- *
8390
- * See: https://hl7.org/fhirpath/#tracename-string-projection-expression-collection
8391
- *
8392
- * @param input The input collection.
8393
- * @param nameAtom The log name.
8394
- */
8395
- function trace(input, nameAtom) {
8396
- console.log('trace', input, nameAtom);
8397
- return input;
8398
- }
8399
- /**
8400
- * Returns the current date and time, including timezone offset.
8401
- *
8402
- * See: https://hl7.org/fhirpath/#now-datetime
8403
- */
8404
- function now() {
8405
- return [new Date().toISOString()];
8406
- }
8407
- /**
8408
- * Returns the current time.
8409
- *
8410
- * See: https://hl7.org/fhirpath/#timeofday-time
8411
- */
8412
- function timeOfDay() {
8413
- return [new Date().toISOString().substring(11)];
8414
- }
8415
- /**
8416
- * Returns the current date.
8417
- *
8418
- * See: https://hl7.org/fhirpath/#today-date
8419
- */
8420
- function today() {
8421
- return [new Date().toISOString().substring(0, 10)];
8422
- }
8423
- /*
8424
- * 6.3 Types
8425
- */
8426
- /**
8427
- * The is() function is supported for backwards compatibility with previous
8428
- * implementations of FHIRPath. Just as with the is keyword, the type argument
8429
- * is an identifier that must resolve to the name of a type in a model.
8430
- *
8431
- * For implementations with compile-time typing, this requires special-case
8432
- * handling when processing the argument to treat it as a type specifier rather
8433
- * than an identifier expression:
8434
- *
8435
- * @param input
8436
- * @param typeAtom
8437
- * @returns
8438
- */
8439
- function is(input, typeAtom) {
8440
- const typeName = typeAtom.name;
8441
- return input.map((value) => fhirPathIs(value, typeName));
8442
- }
8443
- /*
8444
- * 6.5 Boolean logic
8445
- */
8446
- /**
8447
- * 6.5.3. not() : Boolean
8448
- *
8449
- * Returns true if the input collection evaluates to false, and false if it evaluates to true. Otherwise, the result is empty ({ }):
8450
- *
8451
- * @param input
8452
- * @returns
8453
- */
8454
- function not(input) {
8455
- return toBoolean(input).map((value) => !value);
8456
- }
8457
- /*
8458
- * Additional functions
8459
- * See: https://hl7.org/fhir/fhirpath.html#functions
8460
- */
8461
- /**
8462
- * 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.
8463
- * The items in the collection may also represent a Reference, in which case the Reference.reference is resolved.
8464
- * @param input The input collection.
8465
- * @returns
8466
- */
8467
- function resolve(input) {
8468
- return input
8469
- .map((e) => {
8470
- let refStr;
8471
- if (typeof e === 'string') {
8472
- refStr = e;
8473
- }
8474
- else if (typeof e === 'object') {
8475
- const ref = e;
8476
- if (ref.resource) {
8477
- return ref.resource;
8478
- }
8479
- refStr = ref.reference;
8480
- }
8481
- if (!refStr) {
8482
- return undefined;
8483
- }
8484
- const [resourceType, id] = refStr.split('/');
8485
- return { resourceType, id };
8486
- })
8487
- .filter((e) => !!e);
8488
- }
8489
- /**
8490
- * The as operator can be used to treat a value as a specific type.
8491
- * @param context The context value.
8492
- * @returns The value as the specific type.
8493
- */
8494
- function as(context) {
8495
- return context;
8496
- }
8497
- /*
8498
- * 12. Formal Specifications
8499
- */
8500
- /**
8501
- * Returns the type of the input.
8502
- *
8503
- * 12.2. Model Information
8504
- *
8505
- * The model information returned by the reflection function type() is specified as an
8506
- * XML Schema document (xsd) and included in this specification at the following link:
8507
- * https://hl7.org/fhirpath/modelinfo.xsd
8508
- *
8509
- * See: https://hl7.org/fhirpath/#model-information
8510
- *
8511
- * @param input The input collection.
8512
- * @returns
8513
- */
8514
- function type(input) {
8515
- return input.map((value) => {
8516
- if (typeof value === 'boolean') {
8517
- return { namespace: 'System', name: 'Boolean' };
8518
- }
8519
- if (typeof value === 'number') {
8520
- return { namespace: 'System', name: 'Integer' };
8521
- }
8522
- if (value && typeof value === 'object' && 'resourceType' in value) {
8523
- return { namespace: 'FHIR', name: value.resourceType };
8524
- }
8525
- return null;
8526
- });
8527
- }
8528
- function conformsTo(input, systemAtom) {
8529
- const system = systemAtom.eval(undefined);
8530
- if (!system.startsWith('http://hl7.org/fhir/StructureDefinition/')) {
8531
- throw new Error('Expected a StructureDefinition URL');
8532
- }
8533
- const expectedResourceType = system.replace('http://hl7.org/fhir/StructureDefinition/', '');
8534
- return input.map((resource) => (resource === null || resource === void 0 ? void 0 : resource.resourceType) === expectedResourceType);
8535
- }
8536
- /*
8537
- * Helper utilities
8538
- */
8539
- function applyStringFunc(func, input, ...argsAtoms) {
8540
- if (input.length === 0) {
8541
- return [];
8542
- }
8543
- const [value] = validateInput(input, 1);
8544
- if (typeof value !== 'string') {
8545
- throw new Error('String function cannot be called with non-string');
8546
- }
8547
- const result = func(value, ...argsAtoms.map((atom) => atom && atom.eval(value)));
8548
- return result === undefined ? [] : [result];
8549
- }
8550
- function applyMathFunc(func, input, ...argsAtoms) {
8551
- if (input.length === 0) {
8552
- return [];
8553
- }
8554
- const [value] = validateInput(input, 1);
8555
- const quantity = isQuantity(value);
8556
- const numberInput = quantity ? value.value : value;
8557
- if (typeof numberInput !== 'number') {
8558
- throw new Error('Math function cannot be called with non-number');
8559
- }
8560
- const result = func(numberInput, ...argsAtoms.map((atom) => atom.eval(undefined)));
8561
- return quantity ? [Object.assign(Object.assign({}, value), { value: result })] : [result];
8562
- }
8563
- function validateInput(input, count) {
8564
- if (input.length !== count) {
8565
- throw new Error(`Expected ${count} arguments`);
8566
- }
8567
- return input;
6628
+ function matchesSearchFilterValue(resource, filter, filterValue) {
6629
+ const expression = filter.code.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
6630
+ const values = evalFhirPath(expression, resource);
6631
+ const result = values.some((value) => JSON.stringify(value).toLowerCase().includes(filterValue.toLowerCase()));
6632
+ return filter.operator === Operator.NOT_EQUALS ? !result : result;
8568
6633
  }
8569
6634
 
8570
- var functions = /*#__PURE__*/Object.freeze({
8571
- __proto__: null,
8572
- empty: empty,
8573
- exists: exists,
8574
- all: all,
8575
- allTrue: allTrue,
8576
- anyTrue: anyTrue,
8577
- allFalse: allFalse,
8578
- anyFalse: anyFalse,
8579
- subsetOf: subsetOf,
8580
- supersetOf: supersetOf,
8581
- count: count,
8582
- distinct: distinct,
8583
- isDistinct: isDistinct,
8584
- where: where,
8585
- select: select,
8586
- repeat: repeat,
8587
- ofType: ofType,
8588
- single: single,
8589
- first: first,
8590
- last: last,
8591
- tail: tail,
8592
- skip: skip,
8593
- take: take,
8594
- intersect: intersect,
8595
- exclude: exclude,
8596
- union: union,
8597
- combine: combine,
8598
- iif: iif,
8599
- toBoolean: toBoolean,
8600
- convertsToBoolean: convertsToBoolean,
8601
- toInteger: toInteger,
8602
- convertsToInteger: convertsToInteger,
8603
- toDate: toDate,
8604
- convertsToDate: convertsToDate,
8605
- toDateTime: toDateTime,
8606
- convertsToDateTime: convertsToDateTime,
8607
- toDecimal: toDecimal,
8608
- convertsToDecimal: convertsToDecimal,
8609
- toQuantity: toQuantity,
8610
- convertsToQuantity: convertsToQuantity,
8611
- toString: toString,
8612
- convertsToString: convertsToString,
8613
- toTime: toTime,
8614
- convertsToTime: convertsToTime,
8615
- indexOf: indexOf,
8616
- substring: substring,
8617
- startsWith: startsWith,
8618
- endsWith: endsWith,
8619
- contains: contains,
8620
- upper: upper,
8621
- lower: lower,
8622
- replace: replace,
8623
- matches: matches,
8624
- replaceMatches: replaceMatches,
8625
- length: length,
8626
- toChars: toChars,
8627
- abs: abs,
8628
- ceiling: ceiling,
8629
- exp: exp,
8630
- floor: floor,
8631
- ln: ln,
8632
- log: log,
8633
- power: power,
8634
- round: round,
8635
- sqrt: sqrt,
8636
- truncate: truncate,
8637
- children: children,
8638
- descendants: descendants,
8639
- trace: trace,
8640
- now: now,
8641
- timeOfDay: timeOfDay,
8642
- today: today,
8643
- is: is,
8644
- not: not,
8645
- resolve: resolve,
8646
- as: as,
8647
- type: type,
8648
- conformsTo: conformsTo
8649
- });
8650
-
8651
- 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;
8652
- function tokenize(str) {
8653
- return new Tokenizer(str).tokenize();
8654
- }
8655
- const STANDARD_UNITS = [
8656
- 'year',
8657
- 'years',
8658
- 'month',
8659
- 'months',
8660
- 'week',
8661
- 'weeks',
8662
- 'day',
8663
- 'days',
8664
- 'hour',
8665
- 'hours',
8666
- 'minute',
8667
- 'minutes',
8668
- 'second',
8669
- 'seconds',
8670
- 'millisecond',
8671
- 'milliseconds',
8672
- ];
8673
- const TWO_CHAR_OPERATORS = ['!=', '!~', '<=', '>=', '{}'];
8674
- class Tokenizer {
8675
- constructor(str) {
8676
- _Tokenizer_instances.add(this);
8677
- _Tokenizer_str.set(this, void 0);
8678
- _Tokenizer_pos.set(this, void 0);
8679
- __classPrivateFieldSet(this, _Tokenizer_str, str, "f");
8680
- __classPrivateFieldSet(this, _Tokenizer_pos, 0, "f");
8681
- }
8682
- tokenize() {
8683
- const result = [];
8684
- while (__classPrivateFieldGet(this, _Tokenizer_pos, "f") < __classPrivateFieldGet(this, _Tokenizer_str, "f").length) {
8685
- const token = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8686
- if (token) {
8687
- result.push(token);
8688
- }
8689
- }
8690
- return result;
8691
- }
8692
- }
8693
- _Tokenizer_str = new WeakMap(), _Tokenizer_pos = new WeakMap(), _Tokenizer_instances = new WeakSet(), _Tokenizer_peekToken = function _Tokenizer_peekToken() {
8694
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8695
- const token = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8696
- __classPrivateFieldSet(this, _Tokenizer_pos, start, "f");
8697
- return token;
8698
- }, _Tokenizer_consumeToken = function _Tokenizer_consumeToken() {
8699
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhitespace).call(this);
8700
- const c = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this);
8701
- if (!c) {
8702
- return undefined;
8703
- }
8704
- const next = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this);
8705
- if (c === '/' && next === '*') {
8706
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeMultiLineComment).call(this);
8707
- }
8708
- if (c === '/' && next === '/') {
8709
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSingleLineComment).call(this);
8710
- }
8711
- if (c === "'") {
8712
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeString).call(this);
8713
- }
8714
- if (c === '`') {
8715
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeBacktickSymbol).call(this);
8716
- }
8717
- if (c === '@') {
8718
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeDateTime).call(this);
8719
- }
8720
- if (c.match(/\d/)) {
8721
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeNumber).call(this);
8722
- }
8723
- if (c.match(/\w/)) {
8724
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSymbol).call(this);
8725
- }
8726
- if (c === '$' && next.match(/\w/)) {
8727
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSymbol).call(this);
8728
- }
8729
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeOperator).call(this);
8730
- }, _Tokenizer_consumeWhitespace = function _Tokenizer_consumeWhitespace() {
8731
- return buildToken('Whitespace', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\s/)));
8732
- }, _Tokenizer_consumeMultiLineComment = function _Tokenizer_consumeMultiLineComment() {
8733
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8734
- __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) !== '/');
8735
- __classPrivateFieldSet(this, _Tokenizer_pos, __classPrivateFieldGet(this, _Tokenizer_pos, "f") + 2, "f");
8736
- return buildToken('Comment', __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8737
- }, _Tokenizer_consumeSingleLineComment = function _Tokenizer_consumeSingleLineComment() {
8738
- return buildToken('Comment', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '\n'));
8739
- }, _Tokenizer_consumeString = function _Tokenizer_consumeString() {
8740
- var _a, _b;
8741
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8742
- 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) !== "'"));
8743
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8744
- return result;
8745
- }, _Tokenizer_consumeBacktickSymbol = function _Tokenizer_consumeBacktickSymbol() {
8746
- var _a, _b;
8747
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8748
- const result = buildToken('Symbol', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '`'));
8749
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8750
- return result;
8751
- }, _Tokenizer_consumeDateTime = function _Tokenizer_consumeDateTime() {
8752
- var _a, _b, _c, _d, _e;
8753
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8754
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8755
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d-]/));
8756
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === 'T') {
8757
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8758
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d:]/));
8759
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '.' && __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this).match(/\d/)) {
8760
- __classPrivateFieldSet(this, _Tokenizer_pos, (_c = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _c++, _c), "f");
8761
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d]/));
8762
- }
8763
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === 'Z') {
8764
- __classPrivateFieldSet(this, _Tokenizer_pos, (_d = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _d++, _d), "f");
8765
- }
8766
- else if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '+' || __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '-') {
8767
- __classPrivateFieldSet(this, _Tokenizer_pos, (_e = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _e++, _e), "f");
8768
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d:]/));
8769
- }
8770
- }
8771
- return buildToken('DateTime', __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start + 1, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8772
- }, _Tokenizer_consumeNumber = function _Tokenizer_consumeNumber() {
8773
- var _a;
8774
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8775
- let id = 'Number';
8776
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\d/));
8777
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '.' && __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this).match(/\d/)) {
8778
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8779
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\d/));
8780
- }
8781
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === ' ') {
8782
- if (isUnitToken(__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peekToken).call(this))) {
8783
- id = 'Quantity';
8784
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8785
- }
8786
- }
8787
- return buildToken(id, __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8788
- }, _Tokenizer_consumeSymbol = function _Tokenizer_consumeSymbol() {
8789
- return buildToken('Symbol', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[$\w]/)));
8790
- }, _Tokenizer_consumeOperator = function _Tokenizer_consumeOperator() {
8791
- var _a;
8792
- const c = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this);
8793
- const next = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this);
8794
- const twoCharOp = c + next;
8795
- if (TWO_CHAR_OPERATORS.includes(twoCharOp)) {
8796
- __classPrivateFieldSet(this, _Tokenizer_pos, __classPrivateFieldGet(this, _Tokenizer_pos, "f") + 2, "f");
8797
- return buildToken(twoCharOp, twoCharOp);
8798
- }
8799
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8800
- return buildToken(c, c);
8801
- }, _Tokenizer_consumeWhile = function _Tokenizer_consumeWhile(condition) {
8802
- var _a;
8803
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8804
- while (__classPrivateFieldGet(this, _Tokenizer_pos, "f") < __classPrivateFieldGet(this, _Tokenizer_str, "f").length && condition()) {
8805
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8806
- }
8807
- return __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f"));
8808
- }, _Tokenizer_curr = function _Tokenizer_curr() {
8809
- return __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f")];
8810
- }, _Tokenizer_prev = function _Tokenizer_prev() {
8811
- var _a;
8812
- return (_a = __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f") - 1]) !== null && _a !== void 0 ? _a : '';
8813
- }, _Tokenizer_peek = function _Tokenizer_peek() {
8814
- var _a;
8815
- return (_a = __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f") + 1]) !== null && _a !== void 0 ? _a : '';
8816
- };
8817
- function buildToken(id, value) {
8818
- return { id, value };
8819
- }
8820
- function isUnitToken(token) {
8821
- if (token) {
8822
- if (token.id === 'String') {
8823
- return true;
8824
- }
8825
- if (token.id === 'Symbol' && STANDARD_UNITS.includes(token.value)) {
8826
- return true;
8827
- }
8828
- }
8829
- return false;
6635
+ class MockClient extends MedplumClient {
6636
+ constructor(clientOptions) {
6637
+ super({
6638
+ baseUrl: 'https://example.com/',
6639
+ clientId: 'my-client-id',
6640
+ fetch: (url, options) => {
6641
+ const method = options.method || 'GET';
6642
+ const path = url.replace('https://example.com/', '');
6643
+ if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
6644
+ console.log('MockClient', method, path);
6645
+ }
6646
+ const response = mockHandler(method, path, options);
6647
+ if ((clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) && !response) {
6648
+ console.log('MockClient: not found', method, path);
6649
+ }
6650
+ if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
6651
+ console.log('MockClient', JSON.stringify(response, null, 2));
6652
+ }
6653
+ return Promise.resolve({
6654
+ blob: () => Promise.resolve(response),
6655
+ json: () => Promise.resolve(response),
6656
+ });
6657
+ },
6658
+ });
6659
+ }
6660
+ clear() {
6661
+ super.clear();
6662
+ this.activeLoginOverride = undefined;
6663
+ }
6664
+ getProfile() {
6665
+ return {
6666
+ resourceType: 'Practitioner',
6667
+ id: '123',
6668
+ meta: {
6669
+ versionId: '456',
6670
+ },
6671
+ };
6672
+ }
6673
+ setActiveLoginOverride(activeLoginOverride) {
6674
+ this.activeLoginOverride = activeLoginOverride;
6675
+ }
6676
+ getActiveLogin() {
6677
+ if (this.activeLoginOverride !== undefined) {
6678
+ return this.activeLoginOverride;
6679
+ }
6680
+ return super.getActiveLogin();
6681
+ }
6682
+ createBinary(_data, filename, contentType) {
6683
+ if (filename.endsWith('.exe')) {
6684
+ return Promise.reject(badRequest('Invalid file type'));
6685
+ }
6686
+ return Promise.resolve({
6687
+ resourceType: 'Binary',
6688
+ title: filename,
6689
+ contentType,
6690
+ url: 'https://example.com/binary/123',
6691
+ });
6692
+ }
8830
6693
  }
8831
-
8832
- var _ParserBuilder_prefixParselets, _ParserBuilder_infixParselets, _Parser_instances, _Parser_tokens, _Parser_prefixParselets, _Parser_infixParselets, _Parser_getPrecedence, _Parser_consume, _Parser_look;
8833
- class ParserBuilder {
8834
- constructor() {
8835
- _ParserBuilder_prefixParselets.set(this, {});
8836
- _ParserBuilder_infixParselets.set(this, {});
8837
- }
8838
- registerInfix(tokenType, parselet) {
8839
- __classPrivateFieldGet(this, _ParserBuilder_infixParselets, "f")[tokenType] = parselet;
8840
- return this;
8841
- }
8842
- registerPrefix(tokenType, parselet) {
8843
- __classPrivateFieldGet(this, _ParserBuilder_prefixParselets, "f")[tokenType] = parselet;
8844
- return this;
8845
- }
8846
- prefix(tokenType, precedence, builder) {
8847
- return this.registerPrefix(tokenType, {
8848
- parse(parser, token) {
8849
- const right = parser.consumeAndParse(precedence);
8850
- return builder(token, right);
8851
- },
8852
- });
8853
- }
8854
- infixLeft(tokenType, precedence, builder) {
8855
- return this.registerInfix(tokenType, {
8856
- parse(parser, left, token) {
8857
- const right = parser.consumeAndParse(precedence);
8858
- return builder(left, token, right);
8859
- },
8860
- precedence,
8861
- });
8862
- }
8863
- construct(input) {
8864
- return new Parser(tokenize(input), __classPrivateFieldGet(this, _ParserBuilder_prefixParselets, "f"), __classPrivateFieldGet(this, _ParserBuilder_infixParselets, "f"));
8865
- }
8866
- }
8867
- _ParserBuilder_prefixParselets = new WeakMap(), _ParserBuilder_infixParselets = new WeakMap();
8868
- class Parser {
8869
- constructor(tokens, prefixParselets, infixParselets) {
8870
- _Parser_instances.add(this);
8871
- _Parser_tokens.set(this, void 0);
8872
- _Parser_prefixParselets.set(this, void 0);
8873
- _Parser_infixParselets.set(this, void 0);
8874
- __classPrivateFieldSet(this, _Parser_tokens, tokens, "f");
8875
- __classPrivateFieldSet(this, _Parser_prefixParselets, prefixParselets, "f");
8876
- __classPrivateFieldSet(this, _Parser_infixParselets, infixParselets, "f");
8877
- }
8878
- match(expected) {
8879
- const token = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_look).call(this);
8880
- if ((token === null || token === void 0 ? void 0 : token.id) !== expected) {
8881
- return false;
8882
- }
8883
- __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8884
- return true;
8885
- }
8886
- consumeAndParse(precedence = 100 /* MaximumPrecedence */) {
8887
- const token = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8888
- const prefix = __classPrivateFieldGet(this, _Parser_prefixParselets, "f")[token.id];
8889
- if (!prefix) {
8890
- throw Error(`Parse error at ${token.value}. No matching prefix parselet.`);
8891
- }
8892
- let left = prefix.parse(this, token);
8893
- while (precedence > __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_getPrecedence).call(this)) {
8894
- const next = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8895
- const infix = __classPrivateFieldGet(this, _Parser_infixParselets, "f")[next.id];
8896
- left = infix.parse(this, left, next);
8897
- }
8898
- return left;
8899
- }
8900
- }
8901
- _Parser_tokens = new WeakMap(), _Parser_prefixParselets = new WeakMap(), _Parser_infixParselets = new WeakMap(), _Parser_instances = new WeakSet(), _Parser_getPrecedence = function _Parser_getPrecedence() {
8902
- const nextToken = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_look).call(this);
8903
- if (!nextToken) {
8904
- return 100 /* MaximumPrecedence */;
8905
- }
8906
- const parser = __classPrivateFieldGet(this, _Parser_infixParselets, "f")[nextToken.id];
8907
- if (parser) {
8908
- return parser.precedence;
8909
- }
8910
- return 100 /* MaximumPrecedence */;
8911
- }, _Parser_consume = function _Parser_consume() {
8912
- if (!__classPrivateFieldGet(this, _Parser_tokens, "f").length) {
8913
- throw Error('Cant consume unknown more tokens.');
8914
- }
8915
- return __classPrivateFieldGet(this, _Parser_tokens, "f").shift();
8916
- }, _Parser_look = function _Parser_look() {
8917
- return __classPrivateFieldGet(this, _Parser_tokens, "f").length > 0 ? __classPrivateFieldGet(this, _Parser_tokens, "f")[0] : undefined;
8918
- };
8919
- const PARENTHESES_PARSELET = {
8920
- parse(parser) {
8921
- const expr = parser.consumeAndParse();
8922
- if (!parser.match(')')) {
8923
- throw new Error('Parse error: expected `)`');
8924
- }
8925
- return expr;
8926
- },
8927
- };
8928
- const INDEXER_PARSELET = {
8929
- parse(parser, left) {
8930
- const expr = parser.consumeAndParse();
8931
- if (!parser.match(']')) {
8932
- throw new Error('Parse error: expected `]`');
8933
- }
8934
- return new IndexerAtom(left, expr);
8935
- },
8936
- precedence: 2 /* Indexer */,
8937
- };
8938
- const FUNCTION_CALL_PARSELET = {
8939
- parse(parser, left) {
8940
- if (!(left instanceof SymbolAtom)) {
8941
- throw new Error('Unexpected parentheses');
8942
- }
8943
- if (!(left.name in functions)) {
8944
- throw new Error('Unrecognized function: ' + left.name);
8945
- }
8946
- const args = [];
8947
- while (!parser.match(')')) {
8948
- args.push(parser.consumeAndParse());
8949
- parser.match(',');
8950
- }
8951
- return new FunctionAtom(left.name, args, functions[left.name]);
8952
- },
8953
- precedence: 0 /* FunctionCall */,
8954
- };
8955
- function parseQuantity(str) {
8956
- const parts = str.split(' ');
8957
- const value = parseFloat(parts[0]);
8958
- let unit = parts[1];
8959
- if (unit && unit.startsWith("'") && unit.endsWith("'")) {
8960
- unit = unit.substring(1, unit.length - 1);
8961
- }
8962
- else {
8963
- unit = '{' + unit + '}';
8964
- }
8965
- return { value, unit };
8966
- }
8967
- const parserBuilder = new ParserBuilder()
8968
- .registerPrefix('String', {
8969
- parse: (_, token) => new LiteralAtom(token.value),
8970
- })
8971
- .registerPrefix('DateTime', {
8972
- parse: (_, token) => new LiteralAtom(parseDateString(token.value)),
8973
- })
8974
- .registerPrefix('Quantity', {
8975
- parse: (_, token) => new LiteralAtom(parseQuantity(token.value)),
8976
- })
8977
- .registerPrefix('Number', {
8978
- parse: (_, token) => new LiteralAtom(parseFloat(token.value)),
8979
- })
8980
- .registerPrefix('Symbol', {
8981
- parse: (_, token) => {
8982
- if (token.value === 'false') {
8983
- return new LiteralAtom(false);
8984
- }
8985
- if (token.value === 'true') {
8986
- return new LiteralAtom(true);
8987
- }
8988
- return new SymbolAtom(token.value);
8989
- },
8990
- })
8991
- .registerPrefix('{}', { parse: () => new EmptySetAtom() })
8992
- .registerPrefix('(', PARENTHESES_PARSELET)
8993
- .registerInfix('[', INDEXER_PARSELET)
8994
- .registerInfix('(', FUNCTION_CALL_PARSELET)
8995
- .prefix('+', 3 /* UnaryAdd */, (_, right) => new UnaryOperatorAtom(right, (x) => x))
8996
- .prefix('-', 3 /* UnarySubtract */, (_, right) => new ArithemticOperatorAtom(right, right, (_, y) => -y))
8997
- .infixLeft('.', 1 /* Dot */, (left, _, right) => new DotAtom(left, right))
8998
- .infixLeft('/', 4 /* Divide */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x / y))
8999
- .infixLeft('*', 4 /* Multiply */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x * y))
9000
- .infixLeft('+', 5 /* Add */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x + y))
9001
- .infixLeft('-', 5 /* Subtract */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x - y))
9002
- .infixLeft('|', 7 /* Union */, (left, _, right) => new UnionAtom(left, right))
9003
- .infixLeft('=', 9 /* Equals */, (left, _, right) => new EqualsAtom(left, right))
9004
- .infixLeft('!=', 9 /* Equals */, (left, _, right) => new NotEqualsAtom(left, right))
9005
- .infixLeft('~', 9 /* Equivalent */, (left, _, right) => new EquivalentAtom(left, right))
9006
- .infixLeft('!~', 9 /* NotEquivalent */, (left, _, right) => new NotEquivalentAtom(left, right))
9007
- .infixLeft('<', 8 /* LessThan */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x < y))
9008
- .infixLeft('<=', 8 /* LessThanOrEquals */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x <= y))
9009
- .infixLeft('>', 8 /* GreaterThan */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x > y))
9010
- .infixLeft('>=', 8 /* GreaterThanOrEquals */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x >= y))
9011
- .infixLeft('&', 5 /* Ampersand */, (left, _, right) => new ConcatAtom(left, right))
9012
- .infixLeft('Symbol', 6 /* Is */, (left, symbol, right) => {
9013
- switch (symbol.value) {
9014
- case 'and':
9015
- return new AndAtom(left, right);
9016
- case 'as':
9017
- return new AsAtom(left, right);
9018
- case 'contains':
9019
- return new ContainsAtom(left, right);
9020
- case 'div':
9021
- return new ArithemticOperatorAtom(left, right, (x, y) => (x / y) | 0);
9022
- case 'in':
9023
- return new InAtom(left, right);
9024
- case 'is':
9025
- return new IsAtom(left, right);
9026
- case 'mod':
9027
- return new ArithemticOperatorAtom(left, right, (x, y) => x % y);
9028
- case 'or':
9029
- return new OrAtom(left, right);
9030
- case 'xor':
9031
- return new XorAtom(left, right);
9032
- default:
9033
- throw new Error('Cannot use ' + symbol.value + ' as infix operator');
9034
- }
9035
- });
9036
- /**
9037
- * Parses a FHIRPath expression into an AST.
9038
- * The result can be used to evaluate the expression against a resource or other object.
9039
- * This method is useful if you know that you will evaluate the same expression many times
9040
- * against different resources.
9041
- * @param input The FHIRPath expression to parse.
9042
- * @returns The AST representing the expression.
9043
- */
9044
- function parseFhirPath(input) {
9045
- try {
9046
- return new FhirPathAtom(input, parserBuilder.construct(input).consumeAndParse());
9047
- }
9048
- catch (error) {
9049
- throw new Error(`FhirPathError on "${input}": ${error}`);
9050
- }
9051
- }
9052
- /**
9053
- * Evaluates a FHIRPath expression against a resource or other object.
9054
- * @param input The FHIRPath expression to parse.
9055
- * @param context The resource or object to evaluate the expression against.
9056
- * @returns The result of the FHIRPath expression against the resource or object.
9057
- */
9058
- function evalFhirPath(input, context) {
9059
- return parseFhirPath(input).eval(context);
6694
+ function mockHandler(method, path, options) {
6695
+ if (path.startsWith('admin/')) {
6696
+ return mockAdminHandler(method, path);
6697
+ }
6698
+ else if (path.startsWith('auth/')) {
6699
+ return mockAuthHandler(method, path, options);
6700
+ }
6701
+ else if (path.startsWith('fhir/R4')) {
6702
+ return mockFhirHandler(method, path, options);
6703
+ }
6704
+ else {
6705
+ return null;
6706
+ }
9060
6707
  }
9061
-
9062
- var _MemoryRepository_resources, _MemoryRepository_history;
9063
- class MemoryRepository {
9064
- constructor() {
9065
- _MemoryRepository_resources.set(this, void 0);
9066
- _MemoryRepository_history.set(this, void 0);
9067
- __classPrivateFieldSet$1(this, _MemoryRepository_resources, {}, "f");
9068
- __classPrivateFieldSet$1(this, _MemoryRepository_history, {}, "f");
9069
- }
9070
- createResource(resource) {
9071
- var _a;
9072
- const result = resource;
9073
- if (!result.id) {
9074
- result.id = this.generateId();
9075
- }
9076
- if (!result.meta) {
9077
- result.meta = {};
9078
- }
9079
- if (!((_a = result.meta) === null || _a === void 0 ? void 0 : _a.versionId)) {
9080
- result.meta.versionId = this.generateId();
9081
- }
9082
- const { resourceType, id } = resource;
9083
- if (!(resourceType in __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f"))) {
9084
- __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType] = {};
9085
- }
9086
- if (!(resourceType in __classPrivateFieldGet$1(this, _MemoryRepository_history, "f"))) {
9087
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType] = {};
9088
- }
9089
- if (!(id in __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType])) {
9090
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType][id] = [];
9091
- }
9092
- __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType][id] = resource;
9093
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType][id].push(result);
9094
- return result;
9095
- }
9096
- readResource(resourceType, id) {
9097
- var _a, _b;
9098
- 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];
9099
- }
9100
- readHistory(resourceType, id) {
9101
- var _a, _b, _c;
9102
- return {
9103
- resourceType: 'Bundle',
9104
- type: 'history',
9105
- 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 : [])
9106
- .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)); })
9107
- .map((version) => ({ resource: version })),
9108
- };
9109
- }
9110
- readVersion(resourceType, id, versionId) {
9111
- var _a, _b, _c;
9112
- 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; });
9113
- }
9114
- search(searchRequest) {
9115
- var _a;
9116
- const { resourceType } = searchRequest;
9117
- const resources = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType]) !== null && _a !== void 0 ? _a : {};
9118
- const result = Object.values(resources).filter((resource) => matchesSearchRequest(resource, searchRequest));
9119
- return {
9120
- resourceType: 'Bundle',
9121
- type: 'searchset',
9122
- entry: result.map((resource) => ({ resource })),
9123
- total: result.length,
9124
- };
9125
- }
9126
- deleteResource(resourceType, id) {
9127
- var _a, _b;
9128
- 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]) {
9129
- delete __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType][id];
9130
- }
9131
- }
9132
- generateId() {
9133
- return Date.now().toString(36);
9134
- }
9135
- }
9136
- _MemoryRepository_resources = new WeakMap(), _MemoryRepository_history = new WeakMap();
9137
- /**
9138
- * Determines if the resource matches the search request.
9139
- * @param resource The resource that was created or updated.
9140
- * @param searchRequest The subscription criteria as a search request.
9141
- * @returns True if the resource satisfies the search request.
9142
- */
9143
- function matchesSearchRequest(resource, searchRequest) {
9144
- if (searchRequest.resourceType !== resource.resourceType) {
9145
- return false;
9146
- }
9147
- if (searchRequest.filters) {
9148
- for (const filter of searchRequest.filters) {
9149
- if (!matchesSearchFilter(resource, filter)) {
9150
- return false;
9151
- }
9152
- }
9153
- }
9154
- return true;
9155
- }
9156
- /**
9157
- * Determines if the resource matches the search filter.
9158
- * @param resource The resource that was created or updated.
9159
- * @param filter One of the filters of a subscription criteria.
9160
- * @returns True if the resource satisfies the search filter.
9161
- */
9162
- function matchesSearchFilter(resource, filter) {
9163
- const expression = filter.code.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
9164
- const values = evalFhirPath(expression, resource);
9165
- const result = values.some((value) => JSON.stringify(value).toLowerCase().includes(filter.value.toLowerCase()));
9166
- return filter.operator === Operator.NOT_EQUALS ? !result : result;
6708
+ function mockAdminHandler(_method, path) {
6709
+ if (path.startsWith('admin/projects/123')) {
6710
+ return {
6711
+ project: { id: '123', name: 'Project 123' },
6712
+ members: [
6713
+ { id: '123', profile: { reference: 'Practitioner/123', display: 'Alice Smith' }, role: 'owner' },
6714
+ { id: '888', profile: { reference: 'ClientApplication/123', display: 'Test Client' }, role: 'client' },
6715
+ { id: '999', profile: { reference: 'Bot/123', display: 'Test Bot' }, role: 'bot' },
6716
+ ],
6717
+ };
6718
+ }
6719
+ return {
6720
+ ok: true,
6721
+ };
9167
6722
  }
9168
-
9169
- class MockClient extends MedplumClient {
9170
- constructor(clientOptions) {
9171
- super({
9172
- baseUrl: 'https://example.com/',
9173
- clientId: 'my-client-id',
9174
- fetch: (url, options) => {
9175
- const method = options.method || 'GET';
9176
- const path = url.replace('https://example.com/', '');
9177
- if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
9178
- console.log('MockClient', method, path);
9179
- }
9180
- const response = mockHandler(method, path, options);
9181
- if ((clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) && !response) {
9182
- console.log('MockClient: not found', method, path);
9183
- }
9184
- if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
9185
- console.log('MockClient', JSON.stringify(response, null, 2));
9186
- }
9187
- return Promise.resolve({
9188
- blob: () => Promise.resolve(response),
9189
- json: () => Promise.resolve(response),
9190
- });
9191
- },
9192
- });
9193
- }
9194
- clear() {
9195
- super.clear();
9196
- this.activeLoginOverride = undefined;
9197
- }
9198
- getProfile() {
9199
- return {
9200
- resourceType: 'Practitioner',
9201
- id: '123',
9202
- meta: {
9203
- versionId: '456',
9204
- },
9205
- };
9206
- }
9207
- setActiveLoginOverride(activeLoginOverride) {
9208
- this.activeLoginOverride = activeLoginOverride;
9209
- }
9210
- getActiveLogin() {
9211
- if (this.activeLoginOverride !== undefined) {
9212
- return this.activeLoginOverride;
9213
- }
9214
- return super.getActiveLogin();
9215
- }
9216
- createBinary(_data, filename, contentType) {
9217
- if (filename.endsWith('.exe')) {
9218
- return Promise.reject(badRequest('Invalid file type'));
9219
- }
9220
- return Promise.resolve({
9221
- resourceType: 'Binary',
9222
- title: filename,
9223
- contentType,
9224
- url: 'https://example.com/binary/123',
9225
- });
9226
- }
9227
- }
9228
- function mockHandler(method, path, options) {
9229
- if (path.startsWith('admin/')) {
9230
- return mockAdminHandler(method, path);
9231
- }
9232
- else if (path.startsWith('auth/')) {
9233
- return mockAuthHandler(method, path, options);
9234
- }
9235
- else if (path.startsWith('fhir/R4')) {
9236
- return mockFhirHandler(method, path, options);
9237
- }
9238
- else {
9239
- return null;
9240
- }
9241
- }
9242
- function mockAdminHandler(_method, path) {
9243
- if (path.startsWith('admin/projects/123')) {
9244
- return {
9245
- project: { id: '123', name: 'Project 123' },
9246
- members: [
9247
- { id: '123', profile: { reference: 'Practitioner/123', display: 'Alice Smith' }, role: 'owner' },
9248
- { id: '888', profile: { reference: 'ClientApplication/123', display: 'Test Client' }, role: 'client' },
9249
- { id: '999', profile: { reference: 'Bot/123', display: 'Test Bot' }, role: 'bot' },
9250
- ],
9251
- };
9252
- }
9253
- return {
9254
- ok: true,
9255
- };
9256
- }
9257
- function mockAuthHandler(method, path, options) {
9258
- if (path.startsWith('auth/changepassword')) {
9259
- return mockChangePasswordHandler(method, path, options);
9260
- }
9261
- if (path.startsWith('auth/login')) {
9262
- return mockLoginHandler(method, path, options);
9263
- }
9264
- if (path.startsWith('auth/setpassword')) {
9265
- return mockSetPasswordHandler(method, path, options);
9266
- }
9267
- if (path.startsWith('auth/register')) {
9268
- return mockRegisterHandler(method, path, options);
9269
- }
9270
- if (path.startsWith('auth/resetpassword')) {
9271
- return mockResetPasswordHandler(method, path, options);
9272
- }
9273
- if (path.startsWith('auth/me')) {
9274
- return {
9275
- profile: { reference: 'Practitioner/123' },
9276
- };
9277
- }
9278
- return null;
9279
- }
9280
- function mockChangePasswordHandler(_method, _path, options) {
9281
- const { body } = options;
9282
- const { oldPassword } = JSON.parse(body);
9283
- if (oldPassword === 'orange') {
9284
- return allOk;
9285
- }
9286
- else {
9287
- return {
9288
- resourceType: 'OperationOutcome',
9289
- issue: [
9290
- {
9291
- expression: ['oldPassword'],
9292
- details: {
9293
- text: 'Incorrect password',
9294
- },
9295
- },
9296
- ],
9297
- };
9298
- }
9299
- }
9300
- function mockLoginHandler(_method, _path, options) {
9301
- const { body } = options;
9302
- const { password } = JSON.parse(body);
9303
- if (password === 'password') {
9304
- return {
9305
- profile: { reference: 'Practitioner/123' },
9306
- };
9307
- }
9308
- else {
9309
- return {
9310
- resourceType: 'OperationOutcome',
9311
- issue: [
9312
- {
9313
- expression: ['password'],
9314
- details: {
9315
- text: 'Invalid password',
9316
- },
9317
- },
9318
- ],
9319
- };
9320
- }
9321
- }
9322
- function mockSetPasswordHandler(_method, _path, options) {
9323
- const { body } = options;
9324
- const { password } = JSON.parse(body);
9325
- if (password === 'orange') {
9326
- return allOk;
9327
- }
9328
- else {
9329
- return {
9330
- resourceType: 'OperationOutcome',
9331
- issue: [
9332
- {
9333
- expression: ['password'],
9334
- details: {
9335
- text: 'Invalid password',
9336
- },
9337
- },
9338
- ],
9339
- };
9340
- }
9341
- }
9342
- function mockRegisterHandler(_method, _path, options) {
9343
- const { body } = options;
9344
- const { email, password } = JSON.parse(body);
9345
- if (email === 'george@example.com' && password === 'password') {
9346
- return allOk;
9347
- }
9348
- else {
9349
- return {
9350
- resourceType: 'OperationOutcome',
9351
- issue: [
9352
- {
9353
- details: {
9354
- text: 'Invalid',
9355
- },
9356
- },
9357
- ],
9358
- };
9359
- }
9360
- }
9361
- function mockResetPasswordHandler(_method, _path, options) {
9362
- const { body } = options;
9363
- const { email } = JSON.parse(body);
9364
- if (email === 'admin@example.com') {
9365
- return allOk;
9366
- }
9367
- else {
9368
- return {
9369
- resourceType: 'OperationOutcome',
9370
- issue: [
9371
- {
9372
- expression: ['email'],
9373
- details: {
9374
- text: 'Email not found',
9375
- },
9376
- },
9377
- ],
9378
- };
9379
- }
9380
- }
9381
- const mockRepo = new MemoryRepository();
9382
- mockRepo.createResource(HomerSimpsonPreviousVersion);
9383
- mockRepo.createResource(HomerSimpson);
9384
- mockRepo.createResource(ExampleAccessPolicy);
9385
- mockRepo.createResource(ExampleStatusValueSet);
9386
- mockRepo.createResource(ExampleUserConfiguration);
9387
- mockRepo.createResource(ExampleBot);
9388
- mockRepo.createResource(ExampleClient);
9389
- mockRepo.createResource(HomerDiagnosticReport);
9390
- mockRepo.createResource(HomerEncounter);
9391
- mockRepo.createResource(HomerCommunication);
9392
- mockRepo.createResource(HomerMedia);
9393
- mockRepo.createResource(HomerObservation1);
9394
- mockRepo.createResource(HomerObservation2);
9395
- mockRepo.createResource(HomerObservation3);
9396
- mockRepo.createResource(HomerObservation4);
9397
- mockRepo.createResource(HomerObservation5);
9398
- mockRepo.createResource(HomerObservation6);
9399
- mockRepo.createResource(HomerSimpsonSpecimen);
9400
- mockRepo.createResource(TestOrganization);
9401
- mockRepo.createResource(DifferentOrganization);
9402
- mockRepo.createResource(ExampleQuestionnaire);
9403
- mockRepo.createResource(ExampleQuestionnaireResponse);
9404
- mockRepo.createResource(HomerServiceRequest);
9405
- mockRepo.createResource(ExampleSubscription);
9406
- mockRepo.createResource(BartSimpson);
9407
- mockRepo.createResource(DrAliceSmithPreviousVersion);
9408
- mockRepo.createResource(DrAliceSmith);
9409
- mockRepo.createResource(DrAliceSmithSchedule);
9410
- DrAliceSmithSlots.forEach((slot) => mockRepo.createResource(slot));
9411
- function mockFhirHandler(method, url, options) {
9412
- const path = url.includes('?') ? url.substring(0, url.indexOf('?')) : url;
9413
- const match = /fhir\/R4\/?([^/]+)?\/?([^/]+)?\/?([^/]+)?\/?([^/]+)?/.exec(path);
9414
- const resourceType = match === null || match === void 0 ? void 0 : match[1];
9415
- const id = match === null || match === void 0 ? void 0 : match[2];
9416
- const history = match === null || match === void 0 ? void 0 : match[3];
9417
- const versionId = match === null || match === void 0 ? void 0 : match[4];
9418
- if (path.startsWith('fhir/R4/ValueSet/%24expand')) {
9419
- return exampleValueSet;
9420
- }
9421
- else if (path === 'fhir/R4/%24graphql') {
9422
- return mockFhirGraphqlHandler(method, path, options);
9423
- }
9424
- else if (path === 'not-found' || id === 'not-found') {
9425
- return notFound;
9426
- }
9427
- else if (method === 'POST') {
9428
- if (resourceType) {
9429
- return mockRepo.createResource(JSON.parse(options.body));
9430
- }
9431
- else {
9432
- return mockFhirBatchHandler(method, path, options);
9433
- }
9434
- }
9435
- else if (method === 'GET') {
9436
- if (resourceType && id && versionId) {
9437
- return mockRepo.readVersion(resourceType, id, versionId);
9438
- }
9439
- else if (resourceType && id && history) {
9440
- return mockRepo.readHistory(resourceType, id);
9441
- }
9442
- else if (resourceType && id) {
9443
- return mockRepo.readResource(resourceType, id);
9444
- }
9445
- else if (resourceType) {
9446
- return mockRepo.search(parseSearchDefinition(url));
9447
- }
9448
- }
9449
- else if (method === 'PUT') {
9450
- return mockRepo.createResource(JSON.parse(options.body));
9451
- }
9452
- else if (method === 'DELETE') {
9453
- if (resourceType && id) {
9454
- return mockRepo.deleteResource(resourceType, id);
9455
- }
9456
- else {
9457
- return notFound;
9458
- }
9459
- }
9460
- }
9461
- function mockFhirGraphqlHandler(_method, _path, options) {
9462
- const { body } = options;
9463
- if (body.includes('ResourceList: ServiceRequestList')) {
9464
- return {
9465
- data: {
9466
- ResourceList: [
9467
- Object.assign(Object.assign({}, HomerServiceRequest), { ObservationList: [
9468
- HomerObservation1,
9469
- HomerObservation2,
9470
- HomerObservation3,
9471
- HomerObservation4,
9472
- HomerObservation5,
9473
- HomerObservation6,
9474
- ] }),
9475
- ],
9476
- },
9477
- };
9478
- }
9479
- return GraphQLSchemaResponse;
9480
- }
9481
- function mockFhirBatchHandler(_method, _path, options) {
9482
- var _a;
9483
- const { body } = options;
9484
- const request = JSON.parse(body);
9485
- return {
9486
- resourceType: 'Bundle',
9487
- type: 'batch-response',
9488
- entry: (_a = request.entry) === null || _a === void 0 ? void 0 : _a.map((e) => {
9489
- var _a, _b;
9490
- const url = 'fhir/R4/' + ((_a = e === null || e === void 0 ? void 0 : e.request) === null || _a === void 0 ? void 0 : _a.url);
9491
- const method = (_b = e === null || e === void 0 ? void 0 : e.request) === null || _b === void 0 ? void 0 : _b.method;
9492
- const resource = mockHandler(method, url, null);
9493
- if ((resource === null || resource === void 0 ? void 0 : resource.resourceType) === 'OperationOutcome') {
9494
- return { resource, response: { status: getStatus(resource).toString() } };
9495
- }
9496
- else if (resource) {
9497
- return { resource, response: { status: '200' } };
9498
- }
9499
- else {
9500
- return { resource: notFound, response: { status: '404' } };
9501
- }
9502
- }),
9503
- };
6723
+ function mockAuthHandler(method, path, options) {
6724
+ if (path.startsWith('auth/changepassword')) {
6725
+ return mockChangePasswordHandler(method, path, options);
6726
+ }
6727
+ if (path.startsWith('auth/login')) {
6728
+ return mockLoginHandler(method, path, options);
6729
+ }
6730
+ if (path.startsWith('auth/setpassword')) {
6731
+ return mockSetPasswordHandler(method, path, options);
6732
+ }
6733
+ if (path.startsWith('auth/register')) {
6734
+ return mockRegisterHandler(method, path, options);
6735
+ }
6736
+ if (path.startsWith('auth/resetpassword')) {
6737
+ return mockResetPasswordHandler(method, path, options);
6738
+ }
6739
+ if (path.startsWith('auth/me')) {
6740
+ return {
6741
+ profile: { reference: 'Practitioner/123' },
6742
+ };
6743
+ }
6744
+ return null;
6745
+ }
6746
+ function mockChangePasswordHandler(_method, _path, options) {
6747
+ const { body } = options;
6748
+ const { oldPassword } = JSON.parse(body);
6749
+ if (oldPassword === 'orange') {
6750
+ return allOk;
6751
+ }
6752
+ else {
6753
+ return {
6754
+ resourceType: 'OperationOutcome',
6755
+ issue: [
6756
+ {
6757
+ expression: ['oldPassword'],
6758
+ details: {
6759
+ text: 'Incorrect password',
6760
+ },
6761
+ },
6762
+ ],
6763
+ };
6764
+ }
6765
+ }
6766
+ function mockLoginHandler(_method, _path, options) {
6767
+ const { body } = options;
6768
+ const { password } = JSON.parse(body);
6769
+ if (password === 'password') {
6770
+ return {
6771
+ profile: { reference: 'Practitioner/123' },
6772
+ };
6773
+ }
6774
+ else {
6775
+ return {
6776
+ resourceType: 'OperationOutcome',
6777
+ issue: [
6778
+ {
6779
+ expression: ['password'],
6780
+ details: {
6781
+ text: 'Invalid password',
6782
+ },
6783
+ },
6784
+ ],
6785
+ };
6786
+ }
6787
+ }
6788
+ function mockSetPasswordHandler(_method, _path, options) {
6789
+ const { body } = options;
6790
+ const { password } = JSON.parse(body);
6791
+ if (password === 'orange') {
6792
+ return allOk;
6793
+ }
6794
+ else {
6795
+ return {
6796
+ resourceType: 'OperationOutcome',
6797
+ issue: [
6798
+ {
6799
+ expression: ['password'],
6800
+ details: {
6801
+ text: 'Invalid password',
6802
+ },
6803
+ },
6804
+ ],
6805
+ };
6806
+ }
6807
+ }
6808
+ function mockRegisterHandler(_method, _path, options) {
6809
+ const { body } = options;
6810
+ const { email, password } = JSON.parse(body);
6811
+ if (email === 'george@example.com' && password === 'password') {
6812
+ return allOk;
6813
+ }
6814
+ else {
6815
+ return {
6816
+ resourceType: 'OperationOutcome',
6817
+ issue: [
6818
+ {
6819
+ details: {
6820
+ text: 'Invalid',
6821
+ },
6822
+ },
6823
+ ],
6824
+ };
6825
+ }
6826
+ }
6827
+ function mockResetPasswordHandler(_method, _path, options) {
6828
+ const { body } = options;
6829
+ const { email } = JSON.parse(body);
6830
+ if (email === 'admin@example.com') {
6831
+ return allOk;
6832
+ }
6833
+ else {
6834
+ return {
6835
+ resourceType: 'OperationOutcome',
6836
+ issue: [
6837
+ {
6838
+ expression: ['email'],
6839
+ details: {
6840
+ text: 'Email not found',
6841
+ },
6842
+ },
6843
+ ],
6844
+ };
6845
+ }
6846
+ }
6847
+ const mockRepo = new MemoryRepository();
6848
+ mockRepo.createResource(HomerSimpsonPreviousVersion);
6849
+ mockRepo.createResource(HomerSimpson);
6850
+ mockRepo.createResource(ExampleAccessPolicy);
6851
+ mockRepo.createResource(ExampleStatusValueSet);
6852
+ mockRepo.createResource(ExampleUserConfiguration);
6853
+ mockRepo.createResource(ExampleBot);
6854
+ mockRepo.createResource(ExampleClient);
6855
+ mockRepo.createResource(HomerDiagnosticReport);
6856
+ mockRepo.createResource(HomerEncounter);
6857
+ mockRepo.createResource(HomerCommunication);
6858
+ mockRepo.createResource(HomerMedia);
6859
+ mockRepo.createResource(HomerObservation1);
6860
+ mockRepo.createResource(HomerObservation2);
6861
+ mockRepo.createResource(HomerObservation3);
6862
+ mockRepo.createResource(HomerObservation4);
6863
+ mockRepo.createResource(HomerObservation5);
6864
+ mockRepo.createResource(HomerObservation6);
6865
+ mockRepo.createResource(HomerSimpsonSpecimen);
6866
+ mockRepo.createResource(TestOrganization);
6867
+ mockRepo.createResource(DifferentOrganization);
6868
+ mockRepo.createResource(ExampleQuestionnaire);
6869
+ mockRepo.createResource(ExampleQuestionnaireResponse);
6870
+ mockRepo.createResource(HomerServiceRequest);
6871
+ mockRepo.createResource(ExampleSubscription);
6872
+ mockRepo.createResource(BartSimpson);
6873
+ mockRepo.createResource(DrAliceSmithPreviousVersion);
6874
+ mockRepo.createResource(DrAliceSmith);
6875
+ mockRepo.createResource(DrAliceSmithSchedule);
6876
+ DrAliceSmithSlots.forEach((slot) => mockRepo.createResource(slot));
6877
+ function mockFhirHandler(method, url, options) {
6878
+ const path = url.includes('?') ? url.substring(0, url.indexOf('?')) : url;
6879
+ const match = /fhir\/R4\/?([^/]+)?\/?([^/]+)?\/?([^/]+)?\/?([^/]+)?/.exec(path);
6880
+ const resourceType = match === null || match === void 0 ? void 0 : match[1];
6881
+ const id = match === null || match === void 0 ? void 0 : match[2];
6882
+ const operation = match === null || match === void 0 ? void 0 : match[3];
6883
+ const versionId = match === null || match === void 0 ? void 0 : match[4];
6884
+ if (path.startsWith('fhir/R4/ValueSet/$expand')) {
6885
+ return exampleValueSet;
6886
+ }
6887
+ else if (path === 'fhir/R4/$graphql') {
6888
+ return mockFhirGraphqlHandler(method, path, options);
6889
+ }
6890
+ else if (path === 'not-found' || id === 'not-found') {
6891
+ return notFound;
6892
+ }
6893
+ else if (method === 'POST') {
6894
+ if (resourceType && id && operation) {
6895
+ return {};
6896
+ }
6897
+ else if (resourceType) {
6898
+ return mockRepo.createResource(JSON.parse(options.body));
6899
+ }
6900
+ else {
6901
+ return mockFhirBatchHandler(method, path, options);
6902
+ }
6903
+ }
6904
+ else if (method === 'GET') {
6905
+ if (resourceType && id && versionId) {
6906
+ return mockRepo.readVersion(resourceType, id, versionId);
6907
+ }
6908
+ else if (resourceType && id && operation === '_history') {
6909
+ return mockRepo.readHistory(resourceType, id);
6910
+ }
6911
+ else if (resourceType && id) {
6912
+ return mockRepo.readResource(resourceType, id);
6913
+ }
6914
+ else if (resourceType) {
6915
+ return mockRepo.search(parseSearchDefinition(url));
6916
+ }
6917
+ }
6918
+ else if (method === 'PUT') {
6919
+ return mockRepo.createResource(JSON.parse(options.body));
6920
+ }
6921
+ else if (method === 'DELETE') {
6922
+ if (resourceType && id) {
6923
+ return mockRepo.deleteResource(resourceType, id);
6924
+ }
6925
+ else {
6926
+ return notFound;
6927
+ }
6928
+ }
6929
+ }
6930
+ function mockFhirGraphqlHandler(_method, _path, options) {
6931
+ const { body } = options;
6932
+ if (body.includes('ResourceList: ServiceRequestList')) {
6933
+ return {
6934
+ data: {
6935
+ ResourceList: [
6936
+ Object.assign(Object.assign({}, HomerServiceRequest), { ObservationList: [
6937
+ HomerObservation1,
6938
+ HomerObservation2,
6939
+ HomerObservation3,
6940
+ HomerObservation4,
6941
+ HomerObservation5,
6942
+ HomerObservation6,
6943
+ ] }),
6944
+ ],
6945
+ },
6946
+ };
6947
+ }
6948
+ return GraphQLSchemaResponse;
6949
+ }
6950
+ function mockFhirBatchHandler(_method, _path, options) {
6951
+ var _a;
6952
+ const { body } = options;
6953
+ const request = JSON.parse(body);
6954
+ return {
6955
+ resourceType: 'Bundle',
6956
+ type: 'batch-response',
6957
+ entry: (_a = request.entry) === null || _a === void 0 ? void 0 : _a.map((e) => {
6958
+ var _a, _b;
6959
+ const url = 'fhir/R4/' + ((_a = e === null || e === void 0 ? void 0 : e.request) === null || _a === void 0 ? void 0 : _a.url);
6960
+ const method = (_b = e === null || e === void 0 ? void 0 : e.request) === null || _b === void 0 ? void 0 : _b.method;
6961
+ const resource = mockHandler(method, url, null);
6962
+ if ((resource === null || resource === void 0 ? void 0 : resource.resourceType) === 'OperationOutcome') {
6963
+ return { resource, response: { status: getStatus(resource).toString() } };
6964
+ }
6965
+ else if (resource) {
6966
+ return { resource, response: { status: '200' } };
6967
+ }
6968
+ else {
6969
+ return { resource: notFound, response: { status: '404' } };
6970
+ }
6971
+ }),
6972
+ };
9504
6973
  }
9505
6974
 
9506
6975
  export { BartSimpson, DifferentOrganization, DrAliceSmith, DrAliceSmithPreviousVersion, DrAliceSmithSchedule, DrAliceSmithSlots, ExampleAccessPolicy, ExampleAuditEvent, ExampleBot, ExampleClient, ExampleQuestionnaire, ExampleQuestionnaireResponse, ExampleStatusValueSet, ExampleSubscription, ExampleUserConfiguration, GraphQLSchemaResponse, HomerCommunication, HomerDiagnosticReport, HomerEncounter, HomerMedia, HomerObservation1, HomerObservation2, HomerObservation3, HomerObservation4, HomerObservation5, HomerObservation6, HomerServiceRequest, HomerSimpson, HomerSimpsonPreviousVersion, HomerSimpsonSpecimen, MockClient, PatientSearchParameters, TestOrganization, exampleValueSet };