@oystehr/sdk 4.3.9 → 4.3.11

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.
Files changed (38) hide show
  1. package/dist/cjs/client/client.cjs +12 -5
  2. package/dist/cjs/client/client.cjs.map +1 -1
  3. package/dist/cjs/client/client.d.ts +5 -0
  4. package/dist/cjs/index.min.cjs +1 -1
  5. package/dist/cjs/index.min.cjs.map +1 -1
  6. package/dist/cjs/resources/classes/fhir-ext.cjs +196 -4
  7. package/dist/cjs/resources/classes/fhir-ext.cjs.map +1 -1
  8. package/dist/cjs/resources/classes/fhir-ext.d.ts +70 -3
  9. package/dist/cjs/resources/classes/fhir.cjs +14 -3
  10. package/dist/cjs/resources/classes/fhir.cjs.map +1 -1
  11. package/dist/cjs/resources/classes/fhir.d.ts +14 -3
  12. package/dist/cjs/resources/types/FaxSendParams.d.ts +1 -1
  13. package/dist/cjs/resources/types/ZambdaCreateParams.d.ts +1 -1
  14. package/dist/cjs/resources/types/ZambdaUpdateParams.d.ts +1 -1
  15. package/dist/cjs/resources/types/fhir.d.ts +20 -0
  16. package/dist/esm/client/client.d.ts +5 -0
  17. package/dist/esm/client/client.js +12 -5
  18. package/dist/esm/client/client.js.map +1 -1
  19. package/dist/esm/index.min.js +1 -1
  20. package/dist/esm/index.min.js.map +1 -1
  21. package/dist/esm/resources/classes/fhir-ext.d.ts +70 -3
  22. package/dist/esm/resources/classes/fhir-ext.js +194 -5
  23. package/dist/esm/resources/classes/fhir-ext.js.map +1 -1
  24. package/dist/esm/resources/classes/fhir.d.ts +14 -3
  25. package/dist/esm/resources/classes/fhir.js +15 -4
  26. package/dist/esm/resources/classes/fhir.js.map +1 -1
  27. package/dist/esm/resources/types/FaxSendParams.d.ts +1 -1
  28. package/dist/esm/resources/types/ZambdaCreateParams.d.ts +1 -1
  29. package/dist/esm/resources/types/ZambdaUpdateParams.d.ts +1 -1
  30. package/dist/esm/resources/types/fhir.d.ts +20 -0
  31. package/package.json +1 -1
  32. package/src/client/client.ts +22 -8
  33. package/src/resources/classes/fhir-ext.ts +257 -7
  34. package/src/resources/classes/fhir.ts +14 -3
  35. package/src/resources/types/FaxSendParams.ts +1 -1
  36. package/src/resources/types/ZambdaCreateParams.ts +1 -1
  37. package/src/resources/types/ZambdaUpdateParams.ts +1 -1
  38. package/src/resources/types/fhir.ts +22 -0
@@ -195,6 +195,21 @@ function assertRetrievedResource(config, resource) {
195
195
  }
196
196
  }
197
197
  }
198
+ /**
199
+ * Serializes an If-None-Exist value into a FHIR search query string. A raw string is
200
+ * returned unchanged; an array of SearchParam objects is encoded as a query string
201
+ * (e.g. "identifier=sys|123&active=true").
202
+ */
203
+ function ifNoneExistToString(value) {
204
+ if (typeof value === 'string') {
205
+ return value;
206
+ }
207
+ const search = new URLSearchParams();
208
+ for (const param of value) {
209
+ search.append(param.name, String(param.value));
210
+ }
211
+ return search.toString();
212
+ }
198
213
  function isAsyncRequestMode(mode) {
199
214
  return mode === 'async-bundle' || mode === 'async-bulk';
200
215
  }
@@ -231,14 +246,59 @@ async function search(params, request) {
231
246
  };
232
247
  return bundle;
233
248
  }
249
+ /**
250
+ * Performs an iterative FHIR search over initial request and following "next" urls,
251
+ * collecting all pages into a single Bundle.
252
+ *
253
+ * @param params FHIR search parameters plus optional pageSize that will overwrite _count in params
254
+ * @param request optional OystehrClientRequest object
255
+ * @returns FHIR Bundle resource that contains all entries across all pages. Bundle-level metadata
256
+ * (id, meta, total, etc.) is taken from the first page.
257
+ */
258
+ async function searchAndGetAllPages(params, request) {
259
+ const { pageSize, ...searchParams } = params;
260
+ let firstPageParams = searchParams;
261
+ if (pageSize) {
262
+ const baseParams = (searchParams.params ?? []).filter((p) => p.name !== '_count') ?? [];
263
+ firstPageParams = { ...searchParams, params: [...baseParams, { name: '_count', value: pageSize }] };
264
+ }
265
+ const allEntries = [];
266
+ const typedSearch = (search);
267
+ // search returns Bundle, and fhirRequest in the while block returns FhirBundle
268
+ let currentBundle = await typedSearch.call(this, firstPageParams, request);
269
+ const firstBundle = { ...currentBundle, link: currentBundle.link?.filter((link) => link.relation !== 'next') };
270
+ // eslint-disable-next-line no-constant-condition
271
+ while (true) {
272
+ const entries = currentBundle.entry;
273
+ if (entries) {
274
+ allEntries.push(...entries);
275
+ }
276
+ const nextLink = currentBundle.link?.find((link) => link.relation === 'next')?.url;
277
+ if (!nextLink) {
278
+ break;
279
+ }
280
+ currentBundle = await this.fhirRequest(nextLink, 'GET')({}, request);
281
+ }
282
+ return {
283
+ ...firstBundle,
284
+ entry: allEntries.length ? allEntries : undefined,
285
+ unbundle: function () {
286
+ return this.entry?.map((e) => e.resource).filter((r) => r !== undefined) ?? [];
287
+ },
288
+ };
289
+ }
234
290
  async function create(params, request) {
235
291
  const tagged = applyTagToResource(this.config, params);
236
292
  const { resourceType } = tagged;
237
293
  const requestMode = request?.mode;
294
+ const ifNoneExistRequest = {
295
+ ...request,
296
+ ifNoneExist: request?.ifNoneExist !== undefined ? ifNoneExistToString(request.ifNoneExist) : undefined,
297
+ };
238
298
  if (isAsyncRequestMode(requestMode)) {
239
- return await this.startAsyncJob(`/${resourceType}`, 'POST', tagged, requestMode, request);
299
+ return await this.startAsyncJob(`/${resourceType}`, 'POST', tagged, requestMode, ifNoneExistRequest);
240
300
  }
241
- return await this.fhirRequest(`/${resourceType}`, 'POST')(tagged, request);
301
+ return await this.fhirRequest(`/${resourceType}`, 'POST')(tagged, ifNoneExistRequest);
242
302
  }
243
303
  async function get({ resourceType, id }, request) {
244
304
  const requestMode = request?.mode;
@@ -301,9 +361,24 @@ function getRetryDelayMs(retryAfter, fallbackMs) {
301
361
  }
302
362
  return fallbackMs;
303
363
  }
364
+ /**
365
+ * Fetches the status of an async job. If the job is still in progress, returns an object with status 202. If the job is completed, returns the job result with status 200. If the job has failed, returns an object with status 500 and an OperationOutcome resource describing the failure. If the job has expired, returns an object with status 410.
366
+ * @param this The SDKResource context (this is an extension method and should be called with the SDKResource instance as the context, e.g. `sdkResource.getAsyncJob(jobId)`)
367
+ * @param jobId The ID of the async job to fetch
368
+ * @param request Optional OystehrClientRequest for authentication and headers
369
+ * @returns A Promise that resolves to the FhirAsyncJobStatus
370
+ */
304
371
  async function getAsyncJob(jobId, request) {
305
372
  return await this.fetchAsyncJobStatus(jobId, request);
306
373
  }
374
+ /**
375
+ * Waits for an async job to complete by polling its status until it reaches a terminal state (success, failure, or expiration) or the specified timeout is reached. Returns the final job status. Throws if the job fails, expires, or does not complete within the timeout.
376
+ * @param this The SDKResource context (this is an extension method and should be called with the SDKResource instance as the context, e.g. `sdkResource.waitForAsyncJob(jobId)`)
377
+ * @param jobId The ID of the async job to wait for
378
+ * @param options Optional FhirAsyncWaitOptions to configure polling behavior
379
+ * @param request Optional OystehrClientRequest for authentication and headers
380
+ * @returns A Promise that resolves to the final FhirAsyncJobStatus
381
+ */
307
382
  async function waitForAsyncJob(jobId, options, request) {
308
383
  // 5 seconds poll interval by default
309
384
  const pollIntervalMs = options?.pollIntervalMs ?? 5000;
@@ -325,6 +400,116 @@ async function waitForAsyncJob(jobId, options, request) {
325
400
  code: 408,
326
401
  });
327
402
  }
403
+ function parseNdjsonResources(ndjson, sourceUrl) {
404
+ const resources = [];
405
+ const lines = ndjson.split('\n');
406
+ for (let index$1 = 0; index$1 < lines.length; index$1++) {
407
+ const line = lines[index$1].trim();
408
+ if (line.length === 0) {
409
+ continue;
410
+ }
411
+ try {
412
+ resources.push(JSON.parse(line));
413
+ }
414
+ catch (error) {
415
+ throw new index.OystehrSdkError({
416
+ message: `Failed to parse NDJSON line ${index$1 + 1} from ${sourceUrl}`,
417
+ code: 500,
418
+ cause: error,
419
+ });
420
+ }
421
+ }
422
+ return resources;
423
+ }
424
+ /**
425
+ * Waits for an async job to complete and retrieves the bulk output manifest and files. Throws if the job fails, expires, or does not complete within the specified timeout.
426
+ * @param this The SDKResource context (this is an extension method and should be called with the SDKResource instance as the context, e.g. `sdkResource.waitForAsyncBulkOutput(jobId)`)
427
+ * @param jobId The ID of the async job to wait for
428
+ * @param options Optional FhirAsyncWaitOptions to configure polling behavior
429
+ * @param request Optional OystehrClientRequest for authentication and headers
430
+ * @returns A Promise that resolves to a FhirAsyncBulkOutputResult containing the bulk output manifest and files
431
+ */
432
+ async function waitForAsyncBulkOutput(jobId, options, request) {
433
+ const status = await waitForAsyncJob.call(this, jobId, options, request);
434
+ if (status.status === 404) {
435
+ throw new index.OystehrSdkError({
436
+ message: `Async job ${jobId} not found`,
437
+ code: 404,
438
+ });
439
+ }
440
+ if (status.status === 410) {
441
+ throw new index.OystehrSdkError({
442
+ message: `Async job ${jobId} expired`,
443
+ code: 410,
444
+ });
445
+ }
446
+ if (status.status !== 200 || !('mode' in status) || status.mode !== 'bulk') {
447
+ throw new index.OystehrSdkError({
448
+ message: `Async job ${jobId} did not complete in bulk mode`,
449
+ code: status.status,
450
+ });
451
+ }
452
+ const accessToken = request?.accessToken ?? this.config.accessToken;
453
+ const projectId = request?.projectId ?? this.config.projectId;
454
+ if (status.manifest.requiresAccessToken && !accessToken) {
455
+ throw new index.OystehrSdkError({
456
+ message: `Bulk output for async job ${jobId} requires an access token`,
457
+ code: 401,
458
+ });
459
+ }
460
+ const fetchImpl = this.config.fetch ?? fetch;
461
+ const headers = {};
462
+ if (projectId) {
463
+ headers['x-zapehr-project-id'] = projectId;
464
+ headers['x-oystehr-project-id'] = projectId;
465
+ }
466
+ if (status.manifest.requiresAccessToken && accessToken) {
467
+ headers.Authorization = `Bearer ${accessToken}`;
468
+ }
469
+ const requestHeaders = Object.keys(headers).length > 0 ? headers : undefined;
470
+ const output = await Promise.all(status.manifest.output.map(async (file) => {
471
+ const response = await fetchImpl(new Request(file.url, {
472
+ method: 'GET',
473
+ headers: requestHeaders,
474
+ }));
475
+ if (!response.ok) {
476
+ throw new index.OystehrSdkError({
477
+ message: `Failed to download bulk output (${file.type}): HTTP ${response.status}`,
478
+ code: response.status,
479
+ });
480
+ }
481
+ const ndjson = await response.text();
482
+ return {
483
+ ...file,
484
+ resources: parseNdjsonResources(ndjson, file.url),
485
+ };
486
+ }));
487
+ return {
488
+ manifest: status.manifest,
489
+ output,
490
+ };
491
+ }
492
+ /**
493
+ * Wrapper around waitForAsyncBulkOutput that transforms the retrieved bulk output files into a single Bundle resource containing all the output resources as entries. This is a convenience method for use cases where you want to work with the bulk output as a Bundle, but it may not be efficient for large outputs due to the overhead of downloading and parsing all files and constructing the Bundle in memory.
494
+ * Can be slow due to downloading and parsing potentially large NDJSON files, so use only if you need the full output as a Bundle resource. For more efficient processing of large bulk outputs, use waitForAsyncBulkOutput directly.
495
+ * @param jobId the ID of the async job to wait for
496
+ * @param options optional FhirAsyncWaitOptions to configure polling behavior
497
+ * @param request optional OystehrClientRequest for authentication and headers
498
+ * @returns a Promise that resolves to a Bundle containing all resources from the bulk output
499
+ */
500
+ async function waitForAsyncBulkBundle(jobId, options, request) {
501
+ const bulkOutput = await waitForAsyncBulkOutput.call(this, jobId, options, request);
502
+ const resources = bulkOutput.output.flatMap((file) => file.resources);
503
+ const bundle = {
504
+ resourceType: 'Bundle',
505
+ type: 'collection',
506
+ entry: resources.map((resource) => ({ resource })),
507
+ unbundle: function () {
508
+ return this.entry?.map((entry) => entry.resource).filter((value) => value !== undefined) ?? [];
509
+ },
510
+ };
511
+ return bundle;
512
+ }
328
513
  async function cancelAsyncJob(jobId, request) {
329
514
  await this.fhirRequest(`/async-job/${jobId}`, 'DELETE')({}, request);
330
515
  }
@@ -462,9 +647,13 @@ function batchInputRequestToBundleEntryItem(request, config) {
462
647
  // POST creates require a full resource
463
648
  if (method === 'POST' && 'resource' in request) {
464
649
  const resource = applyTagToResource(config, request.resource);
465
- const { fullUrl } = request;
650
+ const { fullUrl, ifNoneExist } = request;
466
651
  return {
467
- ...baseRequest,
652
+ request: {
653
+ ...baseRequest.request,
654
+ // Conditional create: only create the resource if no existing resource matches the query.
655
+ ifNoneExist: ifNoneExist !== undefined ? ifNoneExistToString(ifNoneExist) : undefined,
656
+ },
468
657
  resource: resource,
469
658
  fullUrl,
470
659
  };
@@ -622,7 +811,10 @@ exports.getAsyncJob = getAsyncJob;
622
811
  exports.history = history;
623
812
  exports.patch = patch;
624
813
  exports.search = search;
814
+ exports.searchAndGetAllPages = searchAndGetAllPages;
625
815
  exports.transaction = transaction;
626
816
  exports.update = update;
817
+ exports.waitForAsyncBulkBundle = waitForAsyncBulkBundle;
818
+ exports.waitForAsyncBulkOutput = waitForAsyncBulkOutput;
627
819
  exports.waitForAsyncJob = waitForAsyncJob;
628
820
  //# sourceMappingURL=fhir-ext.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fhir-ext.cjs","sources":["../../../../src/resources/classes/fhir-ext.ts"],"sourcesContent":["import type { Operation } from 'fast-json-patch';\nimport { Address as AddressR4B, HumanName as HumanNameR4B } from 'fhir/r4b';\nimport { Address as AddressR5, HumanName as HumanNameR5 } from 'fhir/r5';\nimport {\n BatchBundle,\n BatchInput,\n BatchInputRequest,\n Binary,\n Bundle,\n BundleEntry,\n Coding,\n FhirAsyncJobHandle,\n FhirAsyncJobStatus,\n FhirAsyncWaitOptions,\n FhirBundle,\n FhirCreateParams,\n FhirDeleteParams,\n FhirGetParams,\n FhirHistoryGetParams,\n FhirHistorySearchParams,\n FhirPatchParams,\n FhirResource,\n FhirResourceReturnValue,\n FhirResponseMode,\n FhirSearchParams,\n FhirUpdateParams,\n GenerateFriendlyPatientIdParams,\n OperationOutcome,\n Resource,\n SearchParam,\n TransactionBundle,\n} from '../..';\nimport { addParamsToSearch, FhirFetcherResponse, OystehrClientRequest, SDKResource } from '../../client/client';\nimport { OystehrConfig } from '../../config';\nimport { OystehrFHIRError, OystehrSdkError } from '../../errors';\n\n// Code adapted from https://github.com/sindresorhus/uint8array-extras\nconst MAX_BLOCK_SIZE = 65_535;\nfunction stringToBase64(input: string): string {\n const data: Uint8Array<ArrayBuffer> = new globalThis.TextEncoder().encode(input);\n let base64 = '';\n\n for (let index = 0; index < data.length; index += MAX_BLOCK_SIZE) {\n const chunk = data.subarray(index, index + MAX_BLOCK_SIZE);\n // Required as `btoa` and `atob` don't properly support Unicode: https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem\n base64 += globalThis.btoa(String.fromCodePoint.apply(undefined, chunk as unknown as number[]));\n }\n return base64;\n}\n\nfunction base64ToString(input: string): string {\n const binaryString = globalThis.atob(input);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return new globalThis.TextDecoder().decode(bytes);\n}\n\n// ─── Tag-mode helpers ────────────────────────────────────────────────────────\n\n/** Converts a Coding to the FHIR _tag parameter value format \"system|code\". */\nfunction codingToTagValue(coding: Coding): string {\n return coding.system ? `${coding.system}|${coding.code ?? ''}` : coding.code ?? '';\n}\n\n/** Returns true if two Codings match on system (treating absent as empty string) and code. */\nfunction codingMatches(a: Coding, b: Coding): boolean {\n return (a.system ?? '') === (b.system ?? '') && (a.code ?? '') === (b.code ?? '');\n}\n\n/**\n * Appends _tag (tag-workspace mode) or _tag:not (ignore-tags mode) search\n * params to an existing SearchParam array and returns the new array.\n */\nfunction applyTagSearchParams(config: OystehrConfig, params: SearchParam[] | undefined): SearchParam[] {\n const out: SearchParam[] = params ? [...params] : [];\n if (config.workspaceTag) {\n out.push({ name: '_tag', value: codingToTagValue(config.workspaceTag) });\n } else if (config.ignoreTags?.length) {\n for (const tag of config.ignoreTags) {\n out.push({ name: '_tag:not', value: codingToTagValue(tag) });\n }\n }\n return out;\n}\n\n/**\n * In ignore-tags mode: throws OystehrSdkError if the resource carries any ignored tag.\n * In tag-workspace mode: injects the workspace tag into resource.meta.tag if not already present.\n * Returns the (possibly cloned) resource.\n */\nfunction applyTagToResource<T extends FhirResource>(config: OystehrConfig, resource: T): T {\n const resourceLike = resource as unknown as Resource;\n\n if (config.ignoreTags?.length) {\n const resourceTags = (resourceLike.meta?.tag ?? []) as Coding[];\n for (const ignored of config.ignoreTags) {\n if (resourceTags.some((t) => codingMatches(t, ignored))) {\n throw new OystehrSdkError({\n message: `Resource has an ignored tag (system: \"${ignored.system ?? ''}\", code: \"${\n ignored.code ?? ''\n }\") and cannot be mutated in ignoreTags mode`,\n code: 400,\n });\n }\n }\n return resource;\n }\n\n if (config.workspaceTag) {\n const tag = config.workspaceTag;\n const existingTags = (resourceLike.meta?.tag ?? []) as Coding[];\n if (!existingTags.some((t) => codingMatches(t, tag))) {\n return {\n ...resource,\n meta: {\n ...resourceLike.meta,\n tag: [...existingTags, tag],\n },\n } as T;\n }\n }\n\n return resource;\n}\n\n/**\n * In ignore-tags mode: throws OystehrSdkError if any operation value resembles an ignored tag.\n * In tag-workspace mode: guards against removal or loss of the workspace tag:\n * - add/replace of the tag array: ensures workspace tag is present in the value\n * - add/replace of meta: ensures workspace tag is present in meta.tag\n * - remove of /meta/tag or /meta: keeps the remove and appends an operation to restore the workspace tag\n * - add of a single tag (path ends in /-): left unchanged (workspace tag already on the resource)\n */\nfunction applyTagToPatchOperations(config: OystehrConfig, operations: Operation[]): Operation[] {\n if (config.ignoreTags?.length) {\n for (const op of operations) {\n if (op.op === 'add' || op.op === 'replace' || op.op === 'test') {\n const opValue: unknown = op.value;\n if (opValue !== null && opValue !== undefined && typeof opValue === 'object') {\n const v = opValue as Coding;\n if (v.code !== undefined) {\n for (const ignored of config.ignoreTags) {\n if (codingMatches(v, ignored)) {\n throw new OystehrSdkError({\n message: `Patch operation contains an ignored tag (system: \"${ignored.system ?? ''}\", code: \"${\n ignored.code ?? ''\n }\") and cannot be applied in ignoreTags mode`,\n code: 400,\n });\n }\n }\n }\n }\n }\n }\n return operations;\n }\n\n if (config.workspaceTag) {\n const tag = config.workspaceTag;\n return operations.reduce<Operation[]>((result, op) => {\n // remove /meta/tag — restore workspace tag afterwards\n if (op.op === 'remove' && op.path === '/meta/tag') {\n result.push(op);\n result.push({ op: 'add' as const, path: '/meta/tag', value: [tag] });\n return result;\n }\n\n // remove /meta — restore workspace tag afterwards\n if (op.op === 'remove' && op.path === '/meta') {\n result.push(op);\n result.push({ op: 'add' as const, path: '/meta', value: { tag: [tag] } });\n return result;\n }\n\n // add/replace the entire tag array — ensure workspace tag is present\n if ((op.op === 'add' || op.op === 'replace') && op.path === '/meta/tag') {\n const tags: Coding[] = Array.isArray(op.value) ? (op.value as Coding[]) : [];\n if (!tags.some((t) => codingMatches(t, tag))) {\n result.push({ ...op, value: [...tags, tag] });\n } else {\n result.push(op);\n }\n return result;\n }\n\n // add/replace the entire meta object — ensure workspace tag is present in meta.tag\n if ((op.op === 'add' || op.op === 'replace') && op.path === '/meta') {\n const metaValue: { tag?: Coding[] } =\n op.value != null && typeof op.value === 'object' ? (op.value as { tag?: Coding[] }) : {};\n const tags = metaValue.tag ?? [];\n if (!tags.some((t) => codingMatches(t, tag))) {\n result.push({ ...op, value: { ...metaValue, tag: [...tags, tag] } });\n } else {\n result.push(op);\n }\n return result;\n }\n\n // All other operations (including add /meta/tag/- for individual tags) pass through unchanged.\n // Workspace tag is assumed already present on the resource from create/update.\n result.push(op);\n return result;\n }, []);\n }\n\n return operations;\n}\n\n/**\n * Throws OystehrFHIRError (404) if the retrieved resource violates the tag configuration:\n * - workspaceTag mode: resource must carry the workspace tag\n * - ignoreTags mode: resource must not carry any ignored tag\n */\nfunction assertRetrievedResource(config: OystehrConfig, resource: FhirResource): void {\n const resourceLike = resource as unknown as Resource;\n const resourceTags = (resourceLike.meta?.tag ?? []) as Coding[];\n\n if (config.workspaceTag) {\n const tag = config.workspaceTag;\n if (!resourceTags.some((t) => codingMatches(t, tag))) {\n throw new OystehrFHIRError({\n error: {\n resourceType: 'OperationOutcome',\n id: 'not-found',\n issue: [{ severity: 'error', code: 'not-found', details: { text: 'Not found' } }],\n },\n code: 404,\n });\n }\n return;\n }\n\n if (config.ignoreTags?.length) {\n for (const ignored of config.ignoreTags) {\n if (resourceTags.some((t) => codingMatches(t, ignored))) {\n throw new OystehrFHIRError({\n error: {\n resourceType: 'OperationOutcome',\n id: 'not-found',\n issue: [{ severity: 'error', code: 'not-found', details: { text: 'Not found' } }],\n },\n code: 404,\n });\n }\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Optional parameter that can be passed to the client methods. It allows\n * overriding the access token or project ID, and setting various headers,\n * such as 'Content-Type'. Also support enabling optimistic locking.\n */\nexport interface OystehrFHIRUpdateClientRequest extends OystehrClientRequest {\n /**\n * Enable optimistic locking for the request. If set to a version ID, the request will\n * include the 'If-Match' header with that value in the FHIR optimistic-locking format.\n * If the resource has been updated since the version provided, the request\n * will fail with a 412 Precondition Failed error.\n */\n optimisticLockingVersionId?: string;\n}\n\nfunction isAsyncRequestMode(mode: FhirResponseMode | undefined): mode is Exclude<FhirResponseMode, 'sync'> {\n return mode === 'async-bundle' || mode === 'async-bulk';\n}\n\n/**\n * Performs a FHIR search and returns the results as a Bundle resource\n *\n * @param options FHIR resource type and FHIR search parameters\n * @param request optional OystehrClientRequest object\n * @returns FHIR Bundle resource\n */\nexport async function search<T extends FhirResource>(\n this: SDKResource,\n params: FhirSearchParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function search<T extends FhirResource>(\n this: SDKResource,\n params: FhirSearchParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<Bundle<T>>>;\nexport async function search<T extends FhirResource>(\n this: SDKResource,\n params: FhirSearchParams<T>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<Bundle<T>> | FhirAsyncJobHandle> {\n const { resourceType } = params;\n const taggedParams = applyTagSearchParams(this.config, params.params);\n let paramMap: Record<string, (string | number)[]> | undefined;\n if (taggedParams.length) {\n paramMap = taggedParams.reduce((acc, param) => {\n if (!acc[param.name]) {\n acc[param.name] = [];\n }\n acc[param.name].push(param.value);\n return acc;\n }, {} as Record<string, (string | number)[]>);\n }\n\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(`/${resourceType}/_search`, 'POST', paramMap ?? {}, requestMode, {\n ...request,\n contentType: 'application/x-www-form-urlencoded',\n });\n }\n\n const requestBundle = await this.fhirRequest<FhirBundle<T>>(`/${resourceType}/_search`, 'POST')(paramMap, {\n ...request,\n contentType: 'application/x-www-form-urlencoded',\n });\n const bundle: Bundle<T> = {\n ...requestBundle,\n entry: requestBundle.entry as Array<BundleEntry<T>> | undefined,\n unbundle: function (this: { entry?: Array<BundleEntry<T>> | undefined }) {\n return (\n this.entry?.map((entry) => entry.resource).filter((resource): resource is T => resource !== undefined) ?? []\n );\n },\n };\n return bundle;\n}\n\nexport async function create<T extends FhirResource>(\n this: SDKResource,\n params: FhirCreateParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function create<T extends FhirResource>(\n this: SDKResource,\n params: FhirCreateParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nexport async function create<T extends FhirResource>(\n this: SDKResource,\n params: FhirCreateParams<T>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const tagged = applyTagToResource(this.config, params);\n const { resourceType } = tagged;\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(\n `/${resourceType}`,\n 'POST',\n tagged as unknown as Record<string, unknown>,\n requestMode,\n request\n );\n }\n\n return await this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}`, 'POST')(\n tagged as unknown as Record<string, unknown>,\n request\n );\n}\n\nexport async function get<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirGetParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function get<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirGetParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nexport async function get<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirGetParams<T>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(`/${resourceType}/${id}`, 'GET', {}, requestMode, request);\n }\n\n const result = await this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}/${id}`, 'GET')({}, request);\n assertRetrievedResource(this.config, result);\n return result;\n}\n\nexport async function update<T extends FhirResource>(\n this: SDKResource,\n params: FhirUpdateParams<T>,\n request: OystehrFHIRUpdateClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function update<T extends FhirResource>(\n this: SDKResource,\n params: FhirUpdateParams<T>,\n request?: OystehrFHIRUpdateClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nexport async function update<T extends FhirResource>(\n this: SDKResource,\n params: FhirUpdateParams<T>,\n request?: OystehrFHIRUpdateClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const tagged = applyTagToResource(this.config, params);\n const { id, resourceType } = tagged;\n const requestMode = request?.mode;\n const ifMatchRequest = {\n ...request,\n ifMatch: request?.optimisticLockingVersionId ? `W/\"${request.optimisticLockingVersionId}\"` : undefined,\n };\n\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(\n `/${resourceType}/${id}`,\n 'PUT',\n tagged as unknown as Record<string, unknown>,\n requestMode,\n ifMatchRequest\n );\n }\n\n return await this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}/${id}`, 'PUT')(\n tagged as unknown as Record<string, unknown>,\n ifMatchRequest\n );\n}\n\nexport async function patch<T extends FhirResource>(\n this: SDKResource,\n params: FhirPatchParams<T>,\n request: OystehrFHIRUpdateClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function patch<T extends FhirResource>(\n this: SDKResource,\n params: FhirPatchParams<T>,\n request?: OystehrFHIRUpdateClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nexport async function patch<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id, operations }: FhirPatchParams<T>,\n request?: OystehrFHIRUpdateClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const taggedOperations = applyTagToPatchOperations(this.config, operations);\n const requestMode = request?.mode;\n const ifMatchRequest = {\n ...request,\n ifMatch: request?.optimisticLockingVersionId ? `W/\"${request.optimisticLockingVersionId}\"` : undefined,\n };\n\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(\n `/${resourceType}/${id}`,\n 'PATCH',\n taggedOperations as unknown as Record<string, unknown>,\n requestMode,\n {\n ...ifMatchRequest,\n contentType: 'application/json-patch+json',\n }\n );\n }\n\n return this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}/${id}`, 'PATCH')(taggedOperations, {\n ...ifMatchRequest,\n contentType: 'application/json-patch+json',\n });\n}\n\nasync function del<T extends FhirResource>(\n this: SDKResource,\n params: FhirDeleteParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nasync function del<T extends FhirResource>(\n this: SDKResource,\n params: FhirDeleteParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nasync function del<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirDeleteParams<T>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(`/${resourceType}/${id}`, 'DELETE', {}, requestMode, request);\n }\n\n return await this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}/${id}`, 'DELETE')({}, request);\n}\nexport { del as delete };\n\nfunction getRetryDelayMs(retryAfter: string | undefined, fallbackMs: number): number {\n if (!retryAfter) {\n return fallbackMs;\n }\n\n const asSeconds = Number(retryAfter);\n if (Number.isFinite(asSeconds) && asSeconds >= 0) {\n return Math.max(0, Math.floor(asSeconds * 1000));\n }\n\n const asTimestamp = Date.parse(retryAfter);\n if (Number.isFinite(asTimestamp)) {\n return Math.max(0, asTimestamp - Date.now());\n }\n\n return fallbackMs;\n}\n\nexport async function getAsyncJob<T extends FhirResource>(\n this: SDKResource,\n jobId: string,\n request?: OystehrClientRequest\n): Promise<FhirAsyncJobStatus<T>> {\n return await this.fetchAsyncJobStatus<T>(jobId, request);\n}\n\nexport async function waitForAsyncJob<T extends FhirResource>(\n this: SDKResource,\n jobId: string,\n options?: FhirAsyncWaitOptions,\n request?: OystehrClientRequest\n): Promise<FhirAsyncJobStatus<T>> {\n // 5 seconds poll interval by default\n const pollIntervalMs = options?.pollIntervalMs ?? 5000;\n // 15 minutes timout by default\n const timeoutMs = options?.timeoutMs ?? 900000;\n const attempts = Math.max(1, Math.ceil(timeoutMs / pollIntervalMs));\n\n for (let attempt = 0; attempt < attempts; attempt++) {\n const status = await this.fetchAsyncJobStatus<T>(jobId, request);\n if (status.status !== 202) {\n return status;\n }\n\n if (attempt < attempts - 1) {\n const retryAfter = 'retryAfter' in status ? status.retryAfter : undefined;\n await new Promise((resolve) => setTimeout(resolve, getRetryDelayMs(retryAfter, pollIntervalMs)));\n }\n }\n\n throw new OystehrSdkError({\n message: `Async job ${jobId} did not complete within ${timeoutMs} ms`,\n code: 408,\n });\n}\n\nexport async function cancelAsyncJob(this: SDKResource, jobId: string, request?: OystehrClientRequest): Promise<void> {\n await this.fhirRequest(`/async-job/${jobId}`, 'DELETE')({}, request);\n}\n\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirHistorySearchParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id, versionId }: FhirHistoryGetParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id, versionId }: FhirHistoryGetParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<T>>;\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirHistorySearchParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<Bundle<T>>>;\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id, count, offset }: FhirHistorySearchParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<Bundle<T>>>;\n\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n {\n resourceType,\n id,\n versionId,\n count,\n offset,\n }: { resourceType: string; id: string; versionId?: string; count?: number; offset?: number },\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<Bundle<T>> | FhirFetcherResponse<T> | FhirAsyncJobHandle> {\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n if (versionId) {\n return await this.startAsyncJob(`/${resourceType}/${id}/_history/${versionId}`, 'GET', {}, requestMode, request);\n }\n return await this.startAsyncJob(`/${resourceType}/${id}/_history`, 'GET', {}, requestMode, request);\n }\n\n if (versionId) {\n return this.fhirRequest<T>(`/${resourceType}/${id}/_history/${versionId}`, 'GET')({}, request);\n }\n if (count) {\n return this.fhirRequest<Bundle<T>>(\n `/${resourceType}/${id}/_history?_total=accurate&_count=${count}\n ${offset ? `&_offset=${offset}` : ''}`,\n 'GET'\n )({}, request);\n }\n return this.fhirRequest<Bundle<T>>(`/${resourceType}/${id}/_history?_total=accurate`, 'GET')({}, request);\n}\n\n/**\n * Returns true when a batch GET/HEAD URL is a search (e.g. \"Patient\" or \"Patient?name=foo\")\n * rather than a direct retrieval (e.g. \"Patient/abc-123\").\n * A retrieval URL has a path segment after the resource type that is not a FHIR operation\n * (operations start with \"_\", e.g. \"_search\" or \"_history\").\n */\nfunction isBatchSearchUrl(url: string): boolean {\n const path = url.split('?')[0];\n const segments = path.split('/').filter(Boolean);\n // Only one segment → bare resource type, always a search\n if (segments.length <= 1) return true;\n // Two or more segments: second segment is an ID if it doesn't start with '_'\n return segments[1].startsWith('_');\n}\n\n/** Returns true when a batch POST URL targets a `_search` endpoint (e.g. \"Patient/_search\"). */\nfunction isBatchSearchPostUrl(url: string): boolean {\n return url.split('?')[0].endsWith('/_search');\n}\n\nfunction batchInputRequestToBundleEntryItem<T extends FhirResource>(\n request: BatchInputRequest<T>,\n config: OystehrConfig\n): BundleEntry<T | Binary<T>> {\n const { method } = request;\n let url = request.url;\n\n // Inject tag search params into search request URLs before URL encoding.\n // GET/HEAD: only for search URLs (not retrievals like Patient/<id>).\n // POST: only for _search endpoints (not creates).\n if (\n ((method === 'GET' || method === 'HEAD') && isBatchSearchUrl(url)) ||\n (method === 'POST' && isBatchSearchPostUrl(url))\n ) {\n if (config.workspaceTag) {\n url += (url.includes('?') ? '&' : '?') + `_tag=${codingToTagValue(config.workspaceTag)}`;\n }\n if (config.ignoreTags?.length) {\n for (const tag of config.ignoreTags) {\n url += (url.includes('?') ? '&' : '?') + `_tag:not=${codingToTagValue(tag)}`;\n }\n }\n }\n\n const baseRequest = {\n request: {\n method,\n url,\n },\n };\n\n // Escape query string parameters in entry.request.url\n if (url.split('?').length > 1) {\n const [resource, query] = url.split('?');\n const params = query\n .split('&')\n .map((param) => {\n const [name, value] = param.split('=');\n return { name, value };\n })\n .reduce((acc, { name, value }) => {\n if (!name) {\n return acc;\n }\n if (!acc[name]) {\n acc[name] = [];\n }\n acc[name].push(value);\n return acc;\n }, {} as Record<string, string[]>);\n const search = new URLSearchParams();\n addParamsToSearch(params, search);\n baseRequest.request.url = `${resource}?${search.toString()}`;\n }\n\n // GET, DELETE, and HEAD require no further parameters\n if (['GET', 'DELETE', 'HEAD'].includes(method)) {\n return baseRequest as BundleEntry<T>;\n }\n\n // PUT updates require a full resource\n if (method === 'PUT') {\n const resource = applyTagToResource(config, request.resource);\n return {\n request: {\n ...baseRequest.request,\n ifMatch: request.ifMatch,\n },\n resource: resource as T,\n } as BundleEntry<T>;\n }\n\n // PATCH can be Binary resource or JSON patch\n if (method === 'PATCH') {\n if ('resource' in request) {\n // Binary patch — decode operations, apply tag transforms, re-encode\n let patchResource = request.resource;\n const binaryData = patchResource.data;\n if (binaryData) {\n const operations = JSON.parse(base64ToString(binaryData)) as Operation[];\n const taggedOperations = applyTagToPatchOperations(config, operations);\n patchResource = { ...patchResource, data: stringToBase64(JSON.stringify(taggedOperations)) } as Binary<T>;\n }\n return {\n request: {\n ...baseRequest.request,\n ifMatch: request.ifMatch,\n },\n resource: patchResource,\n } as BundleEntry<Binary<T>>;\n }\n const operations = applyTagToPatchOperations(config, request.operations);\n const data = stringToBase64(JSON.stringify(operations));\n return {\n ...baseRequest,\n resource: {\n resourceType: 'Binary',\n contentType: 'application/json-patch+json',\n data,\n },\n } as BundleEntry<Binary<T>>;\n }\n\n // POST _search — no resource body; tag params were already injected into the URL above\n if (method === 'POST' && isBatchSearchPostUrl(url)) {\n return baseRequest as BundleEntry<T>;\n }\n\n // POST creates require a full resource\n if (method === 'POST' && 'resource' in request) {\n const resource = applyTagToResource(config, request.resource);\n const { fullUrl } = request;\n return {\n ...baseRequest,\n resource: resource as T,\n fullUrl,\n } as BundleEntry<T>;\n }\n\n // // Add ifMatch for the entries that support it\n // if ('ifMatch' in request) {\n // baseRequest.request = {\n // ...baseRequest.request,\n // ifMatch: request.ifMatch,\n // };\n // }\n\n throw new Error('Unrecognized method');\n}\n\nexport async function batch<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function batch<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<BatchBundle<BundleContentType>>>;\nexport async function batch<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<BatchBundle<BundleContentType>> | FhirAsyncJobHandle> {\n const requestPayload = {\n resourceType: 'Bundle',\n type: 'batch',\n entry: input.requests.map((req) => batchInputRequestToBundleEntryItem(req, this.config)),\n };\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob('/', 'POST', requestPayload, requestMode, request);\n }\n\n const resp = await this.fhirRequest<BatchBundle<BundleContentType>>('/', 'POST')(requestPayload, request);\n // Validate each GET/HEAD retrieval entry against the tag config.\n // Violations are replaced with a synthetic 404 OperationOutcome entry; batch entries are independent.\n const rawEntries = resp.entry as Array<BundleEntry<BundleContentType>> | undefined;\n const processedEntries: Array<BundleEntry<BundleContentType>> | undefined =\n this.config.workspaceTag || this.config.ignoreTags?.length\n ? rawEntries?.map((entry, i) => {\n const req = input.requests[i];\n if (!req || !entry?.resource) return entry;\n if ((req.method === 'GET' || req.method === 'HEAD') && !isBatchSearchUrl(req.url)) {\n try {\n assertRetrievedResource(this.config, entry.resource);\n } catch (err) {\n if (!(err instanceof OystehrFHIRError)) throw err;\n return {\n request: entry.request,\n response: { status: '404', outcome: err.cause },\n } as unknown as BundleEntry<BundleContentType>;\n }\n }\n return entry;\n })\n : rawEntries;\n const bundle: BatchBundle<BundleContentType> = {\n ...resp,\n entry: processedEntries,\n unbundle: function (this: { entry?: Array<BundleEntry<BundleContentType>> | undefined }) {\n return (\n this.entry\n ?.map((entry) => entry.resource)\n .filter((resource): resource is BundleContentType => resource !== undefined) ?? []\n );\n },\n errors: function (this: { entry?: Array<BundleEntry<BundleContentType>> | undefined }) {\n return this.entry\n ?.filter((entry) => entry.response?.status?.startsWith('4') || entry.response?.status?.startsWith('5'))\n .map((entry) => entry.response?.outcome)\n .filter((outcome): outcome is OperationOutcome => outcome !== undefined);\n },\n };\n return bundle;\n}\n\nexport async function transaction<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function transaction<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<TransactionBundle<BundleContentType>>>;\nexport async function transaction<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<TransactionBundle<BundleContentType>> | FhirAsyncJobHandle> {\n const requestPayload = {\n resourceType: 'Bundle',\n type: 'transaction',\n entry: input.requests.map((req) => batchInputRequestToBundleEntryItem(req, this.config)),\n };\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob('/', 'POST', requestPayload, requestMode, request);\n }\n\n const resp = await this.fhirRequest<TransactionBundle<BundleContentType>>('/', 'POST')(requestPayload, request);\n // Validate each GET/HEAD retrieval entry against the tag config.\n // A violation throws OystehrFHIRError(404) — transactions are all-or-nothing.\n if (this.config.workspaceTag || this.config.ignoreTags?.length) {\n (resp.entry as Array<BundleEntry<BundleContentType>> | undefined)?.forEach((entry, i) => {\n const req = input.requests[i];\n if (!req || !entry?.resource) return;\n if ((req.method === 'GET' || req.method === 'HEAD') && !isBatchSearchUrl(req.url)) {\n assertRetrievedResource(this.config, entry.resource);\n }\n });\n }\n const bundle: TransactionBundle<BundleContentType> = {\n ...resp,\n entry: resp.entry as Array<BundleEntry<BundleContentType>> | undefined,\n unbundle: function (this: { entry?: Array<BundleEntry<BundleContentType>> | undefined }) {\n return (\n this.entry\n ?.map((entry) => entry.resource)\n .filter((resource): resource is BundleContentType => resource !== undefined) ?? []\n );\n },\n };\n return bundle;\n}\n\nexport async function generateFriendlyPatientId(\n this: SDKResource,\n { id }: GenerateFriendlyPatientIdParams,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<FhirResource>> {\n return this.fhirRequest(`/Patient/${id}/$generate-friendly-patient-id`, 'POST')({}, request);\n}\n\nexport function formatAddress(\n address: AddressR4B | AddressR5,\n options?: { all?: boolean; use?: boolean; lineSeparator?: string }\n): string {\n const builder = [];\n\n if (address.line) {\n builder.push(...address.line);\n }\n\n if (address.city || address.state || address.postalCode) {\n const cityStateZip = [];\n if (address.city) {\n cityStateZip.push(address.city);\n }\n if (address.state) {\n cityStateZip.push(address.state);\n }\n if (address.postalCode) {\n cityStateZip.push(address.postalCode);\n }\n builder.push(cityStateZip.join(', '));\n }\n\n if (address.use && (options?.all || options?.use)) {\n builder.push('[' + address.use + ']');\n }\n\n return builder.join(options?.lineSeparator || ', ').trim();\n}\n\nexport function formatHumanName(\n name: HumanNameR4B | HumanNameR5,\n options?: {\n all?: boolean;\n prefix?: boolean;\n suffix?: boolean;\n use?: boolean;\n }\n): string {\n const builder = [];\n\n if (name.prefix && options?.prefix !== false) {\n builder.push(...name.prefix);\n }\n\n if (name.given) {\n builder.push(...name.given);\n }\n\n if (name.family) {\n builder.push(name.family);\n }\n\n if (name.suffix && options?.suffix !== false) {\n builder.push(...name.suffix);\n }\n\n if (name.use && (options?.all || options?.use)) {\n builder.push('[' + name.use + ']');\n }\n\n return builder.join(' ').trim();\n}\n"],"names":["OystehrSdkError","OystehrFHIRError","addParamsToSearch"],"mappings":";;;;;AAoCA;AACA,MAAM,cAAc,GAAG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,CAAC,IAAI,CAAC,OAAO,EAAE,aAAa,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE;AAC5D;AAEM,SAAU,eAAe,CAC7B,IAAgC,EAChC,OAKC,EAAA;IAED,MAAM,OAAO,GAAG,EAAE;IAElB,IAAI,IAAI,CAAC,MAAM,IAAI,OAAO,EAAE,MAAM,KAAK,KAAK,EAAE;QAC5C,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B;AAEA,IAAA,IAAI,IAAI,CAAC,KAAK,EAAE;QACd,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC;IAC7B;AAEA,IAAA,IAAI,IAAI,CAAC,MAAM,EAAE;AACf,QAAA,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;IAC3B;IAEA,IAAI,IAAI,CAAC,MAAM,IAAI,OAAO,EAAE,MAAM,KAAK,KAAK,EAAE;QAC5C,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B;AAEA,IAAA,IAAI,IAAI,CAAC,GAAG,KAAK,OAAO,EAAE,GAAG,IAAI,OAAO,EAAE,GAAG,CAAC,EAAE;QAC9C,OAAO,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACpC;IAEA,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE;AACjC;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"fhir-ext.cjs","sources":["../../../../src/resources/classes/fhir-ext.ts"],"sourcesContent":["import type { Operation } from 'fast-json-patch';\nimport { Address as AddressR4B, HumanName as HumanNameR4B } from 'fhir/r4b';\nimport { Address as AddressR5, HumanName as HumanNameR5 } from 'fhir/r5';\nimport {\n BatchBundle,\n BatchInput,\n BatchInputRequest,\n Binary,\n Bundle,\n BundleEntry,\n Coding,\n FhirAsyncBulkOutputResult,\n FhirAsyncJobHandle,\n FhirAsyncJobStatus,\n FhirAsyncWaitOptions,\n FhirBundle,\n FhirCreateParams,\n FhirDeleteParams,\n FhirGetParams,\n FhirHistoryGetParams,\n FhirHistorySearchParams,\n FhirPatchParams,\n FhirResource,\n FhirResourceReturnValue,\n FhirResponseMode,\n FhirSearchParams,\n FhirUpdateParams,\n GenerateFriendlyPatientIdParams,\n OperationOutcome,\n Resource,\n SearchParam,\n TransactionBundle,\n} from '../..';\nimport { addParamsToSearch, FhirFetcherResponse, OystehrClientRequest, SDKResource } from '../../client/client';\nimport { OystehrConfig } from '../../config';\nimport { OystehrFHIRError, OystehrSdkError } from '../../errors';\n\n// Code adapted from https://github.com/sindresorhus/uint8array-extras\nconst MAX_BLOCK_SIZE = 65_535;\nfunction stringToBase64(input: string): string {\n const data: Uint8Array<ArrayBuffer> = new globalThis.TextEncoder().encode(input);\n let base64 = '';\n\n for (let index = 0; index < data.length; index += MAX_BLOCK_SIZE) {\n const chunk = data.subarray(index, index + MAX_BLOCK_SIZE);\n // Required as `btoa` and `atob` don't properly support Unicode: https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem\n base64 += globalThis.btoa(String.fromCodePoint.apply(undefined, chunk as unknown as number[]));\n }\n return base64;\n}\n\nfunction base64ToString(input: string): string {\n const binaryString = globalThis.atob(input);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return new globalThis.TextDecoder().decode(bytes);\n}\n\n// ─── Tag-mode helpers ────────────────────────────────────────────────────────\n\n/** Converts a Coding to the FHIR _tag parameter value format \"system|code\". */\nfunction codingToTagValue(coding: Coding): string {\n return coding.system ? `${coding.system}|${coding.code ?? ''}` : coding.code ?? '';\n}\n\n/** Returns true if two Codings match on system (treating absent as empty string) and code. */\nfunction codingMatches(a: Coding, b: Coding): boolean {\n return (a.system ?? '') === (b.system ?? '') && (a.code ?? '') === (b.code ?? '');\n}\n\n/**\n * Appends _tag (tag-workspace mode) or _tag:not (ignore-tags mode) search\n * params to an existing SearchParam array and returns the new array.\n */\nfunction applyTagSearchParams(config: OystehrConfig, params: SearchParam[] | undefined): SearchParam[] {\n const out: SearchParam[] = params ? [...params] : [];\n if (config.workspaceTag) {\n out.push({ name: '_tag', value: codingToTagValue(config.workspaceTag) });\n } else if (config.ignoreTags?.length) {\n for (const tag of config.ignoreTags) {\n out.push({ name: '_tag:not', value: codingToTagValue(tag) });\n }\n }\n return out;\n}\n\n/**\n * In ignore-tags mode: throws OystehrSdkError if the resource carries any ignored tag.\n * In tag-workspace mode: injects the workspace tag into resource.meta.tag if not already present.\n * Returns the (possibly cloned) resource.\n */\nfunction applyTagToResource<T extends FhirResource>(config: OystehrConfig, resource: T): T {\n const resourceLike = resource as unknown as Resource;\n\n if (config.ignoreTags?.length) {\n const resourceTags = (resourceLike.meta?.tag ?? []) as Coding[];\n for (const ignored of config.ignoreTags) {\n if (resourceTags.some((t) => codingMatches(t, ignored))) {\n throw new OystehrSdkError({\n message: `Resource has an ignored tag (system: \"${ignored.system ?? ''}\", code: \"${\n ignored.code ?? ''\n }\") and cannot be mutated in ignoreTags mode`,\n code: 400,\n });\n }\n }\n return resource;\n }\n\n if (config.workspaceTag) {\n const tag = config.workspaceTag;\n const existingTags = (resourceLike.meta?.tag ?? []) as Coding[];\n if (!existingTags.some((t) => codingMatches(t, tag))) {\n return {\n ...resource,\n meta: {\n ...resourceLike.meta,\n tag: [...existingTags, tag],\n },\n } as T;\n }\n }\n\n return resource;\n}\n\n/**\n * In ignore-tags mode: throws OystehrSdkError if any operation value resembles an ignored tag.\n * In tag-workspace mode: guards against removal or loss of the workspace tag:\n * - add/replace of the tag array: ensures workspace tag is present in the value\n * - add/replace of meta: ensures workspace tag is present in meta.tag\n * - remove of /meta/tag or /meta: keeps the remove and appends an operation to restore the workspace tag\n * - add of a single tag (path ends in /-): left unchanged (workspace tag already on the resource)\n */\nfunction applyTagToPatchOperations(config: OystehrConfig, operations: Operation[]): Operation[] {\n if (config.ignoreTags?.length) {\n for (const op of operations) {\n if (op.op === 'add' || op.op === 'replace' || op.op === 'test') {\n const opValue: unknown = op.value;\n if (opValue !== null && opValue !== undefined && typeof opValue === 'object') {\n const v = opValue as Coding;\n if (v.code !== undefined) {\n for (const ignored of config.ignoreTags) {\n if (codingMatches(v, ignored)) {\n throw new OystehrSdkError({\n message: `Patch operation contains an ignored tag (system: \"${ignored.system ?? ''}\", code: \"${\n ignored.code ?? ''\n }\") and cannot be applied in ignoreTags mode`,\n code: 400,\n });\n }\n }\n }\n }\n }\n }\n return operations;\n }\n\n if (config.workspaceTag) {\n const tag = config.workspaceTag;\n return operations.reduce<Operation[]>((result, op) => {\n // remove /meta/tag — restore workspace tag afterwards\n if (op.op === 'remove' && op.path === '/meta/tag') {\n result.push(op);\n result.push({ op: 'add' as const, path: '/meta/tag', value: [tag] });\n return result;\n }\n\n // remove /meta — restore workspace tag afterwards\n if (op.op === 'remove' && op.path === '/meta') {\n result.push(op);\n result.push({ op: 'add' as const, path: '/meta', value: { tag: [tag] } });\n return result;\n }\n\n // add/replace the entire tag array — ensure workspace tag is present\n if ((op.op === 'add' || op.op === 'replace') && op.path === '/meta/tag') {\n const tags: Coding[] = Array.isArray(op.value) ? (op.value as Coding[]) : [];\n if (!tags.some((t) => codingMatches(t, tag))) {\n result.push({ ...op, value: [...tags, tag] });\n } else {\n result.push(op);\n }\n return result;\n }\n\n // add/replace the entire meta object — ensure workspace tag is present in meta.tag\n if ((op.op === 'add' || op.op === 'replace') && op.path === '/meta') {\n const metaValue: { tag?: Coding[] } =\n op.value != null && typeof op.value === 'object' ? (op.value as { tag?: Coding[] }) : {};\n const tags = metaValue.tag ?? [];\n if (!tags.some((t) => codingMatches(t, tag))) {\n result.push({ ...op, value: { ...metaValue, tag: [...tags, tag] } });\n } else {\n result.push(op);\n }\n return result;\n }\n\n // All other operations (including add /meta/tag/- for individual tags) pass through unchanged.\n // Workspace tag is assumed already present on the resource from create/update.\n result.push(op);\n return result;\n }, []);\n }\n\n return operations;\n}\n\n/**\n * Throws OystehrFHIRError (404) if the retrieved resource violates the tag configuration:\n * - workspaceTag mode: resource must carry the workspace tag\n * - ignoreTags mode: resource must not carry any ignored tag\n */\nfunction assertRetrievedResource(config: OystehrConfig, resource: FhirResource): void {\n const resourceLike = resource as unknown as Resource;\n const resourceTags = (resourceLike.meta?.tag ?? []) as Coding[];\n\n if (config.workspaceTag) {\n const tag = config.workspaceTag;\n if (!resourceTags.some((t) => codingMatches(t, tag))) {\n throw new OystehrFHIRError({\n error: {\n resourceType: 'OperationOutcome',\n id: 'not-found',\n issue: [{ severity: 'error', code: 'not-found', details: { text: 'Not found' } }],\n },\n code: 404,\n });\n }\n return;\n }\n\n if (config.ignoreTags?.length) {\n for (const ignored of config.ignoreTags) {\n if (resourceTags.some((t) => codingMatches(t, ignored))) {\n throw new OystehrFHIRError({\n error: {\n resourceType: 'OperationOutcome',\n id: 'not-found',\n issue: [{ severity: 'error', code: 'not-found', details: { text: 'Not found' } }],\n },\n code: 404,\n });\n }\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Optional parameter that can be passed to the client methods. It allows\n * overriding the access token or project ID, and setting various headers,\n * such as 'Content-Type'. Also support enabling optimistic locking.\n */\nexport interface OystehrFHIRUpdateClientRequest extends OystehrClientRequest {\n /**\n * Enable optimistic locking for the request. If set to a version ID, the request will\n * include the 'If-Match' header with that value in the FHIR optimistic-locking format.\n * If the resource has been updated since the version provided, the request\n * will fail with a 412 Precondition Failed error.\n */\n optimisticLockingVersionId?: string;\n}\n\n/**\n * Optional parameter that can be passed to the FHIR create method. In addition\n * to the standard request options, it supports FHIR conditional create via the\n * 'If-None-Exist' header.\n */\nexport interface OystehrFHIRCreateClientRequest extends OystehrClientRequest {\n /**\n * Perform a FHIR conditional create using the 'If-None-Exist' header. The value is a\n * FHIR search query that identifies whether a matching resource already exists:\n * - if no resource matches, the resource is created as normal;\n * - if exactly one resource matches, no resource is created and the existing one is returned;\n * - if more than one resource matches, the request fails with a 412 Precondition Failed error.\n *\n * Accepts either a raw search query string (e.g. `'identifier=http://acme.org|1234'`) or an\n * array of SearchParam objects (e.g. `[{ name: 'identifier', value: 'http://acme.org|1234' }]`).\n *\n * @see https://www.hl7.org/fhir/http.html#cond-update for the conditional create specification.\n */\n ifNoneExist?: string | SearchParam[];\n}\n\n/**\n * Serializes an If-None-Exist value into a FHIR search query string. A raw string is\n * returned unchanged; an array of SearchParam objects is encoded as a query string\n * (e.g. \"identifier=sys|123&active=true\").\n */\nfunction ifNoneExistToString(value: string | SearchParam[]): string {\n if (typeof value === 'string') {\n return value;\n }\n const search = new URLSearchParams();\n for (const param of value) {\n search.append(param.name, String(param.value));\n }\n return search.toString();\n}\n\nfunction isAsyncRequestMode(mode: FhirResponseMode | undefined): mode is Exclude<FhirResponseMode, 'sync'> {\n return mode === 'async-bundle' || mode === 'async-bulk';\n}\n\n/**\n * Performs a FHIR search and returns the results as a Bundle resource\n *\n * @param options FHIR resource type and FHIR search parameters\n * @param request optional OystehrClientRequest object\n * @returns FHIR Bundle resource\n */\nexport async function search<T extends FhirResource>(\n this: SDKResource,\n params: FhirSearchParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function search<T extends FhirResource>(\n this: SDKResource,\n params: FhirSearchParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<Bundle<T>>>;\nexport async function search<T extends FhirResource>(\n this: SDKResource,\n params: FhirSearchParams<T>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<Bundle<T>> | FhirAsyncJobHandle> {\n const { resourceType } = params;\n const taggedParams = applyTagSearchParams(this.config, params.params);\n let paramMap: Record<string, (string | number)[]> | undefined;\n if (taggedParams.length) {\n paramMap = taggedParams.reduce((acc, param) => {\n if (!acc[param.name]) {\n acc[param.name] = [];\n }\n acc[param.name].push(param.value);\n return acc;\n }, {} as Record<string, (string | number)[]>);\n }\n\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(`/${resourceType}/_search`, 'POST', paramMap ?? {}, requestMode, {\n ...request,\n contentType: 'application/x-www-form-urlencoded',\n });\n }\n\n const requestBundle = await this.fhirRequest<FhirBundle<T>>(`/${resourceType}/_search`, 'POST')(paramMap, {\n ...request,\n contentType: 'application/x-www-form-urlencoded',\n });\n const bundle: Bundle<T> = {\n ...requestBundle,\n entry: requestBundle.entry as Array<BundleEntry<T>> | undefined,\n unbundle: function (this: { entry?: Array<BundleEntry<T>> | undefined }) {\n return (\n this.entry?.map((entry) => entry.resource).filter((resource): resource is T => resource !== undefined) ?? []\n );\n },\n };\n return bundle;\n}\n\n/**\n * Performs an iterative FHIR search over initial request and following \"next\" urls,\n * collecting all pages into a single Bundle.\n *\n * @param params FHIR search parameters plus optional pageSize that will overwrite _count in params\n * @param request optional OystehrClientRequest object\n * @returns FHIR Bundle resource that contains all entries across all pages. Bundle-level metadata\n * (id, meta, total, etc.) is taken from the first page.\n */\nexport async function searchAndGetAllPages<T extends FhirResource>(\n this: SDKResource,\n params: FhirSearchParams<T> & { pageSize?: number },\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<Bundle<T>> {\n const { pageSize, ...searchParams } = params;\n\n let firstPageParams: FhirSearchParams<T> = searchParams;\n if (pageSize) {\n const baseParams = (searchParams.params ?? []).filter((p) => p.name !== '_count') ?? [];\n firstPageParams = { ...searchParams, params: [...baseParams, { name: '_count', value: pageSize }] };\n }\n\n const allEntries: Array<BundleEntry<T>> = [];\n\n const typedSearch = search<T>;\n // search returns Bundle, and fhirRequest in the while block returns FhirBundle\n let currentBundle: Bundle<T> | FhirBundle<T> = await typedSearch.call(this, firstPageParams, request);\n const firstBundle = { ...currentBundle, link: currentBundle.link?.filter((link) => link.relation !== 'next') };\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const entries = currentBundle.entry as Array<BundleEntry<T>> | undefined;\n if (entries) {\n allEntries.push(...entries);\n }\n\n const nextLink: string | undefined = currentBundle.link?.find((link) => link.relation === 'next')?.url;\n if (!nextLink) {\n break;\n }\n currentBundle = await this.fhirRequest<FhirBundle<T>>(nextLink, 'GET')({}, request);\n }\n\n return {\n ...firstBundle,\n entry: allEntries.length ? allEntries : undefined,\n unbundle: function (this: { entry?: Array<BundleEntry<T>> }) {\n return this.entry?.map((e) => e.resource).filter((r): r is T => r !== undefined) ?? [];\n },\n };\n}\n\nexport async function create<T extends FhirResource>(\n this: SDKResource,\n params: FhirCreateParams<T>,\n request: OystehrFHIRCreateClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function create<T extends FhirResource>(\n this: SDKResource,\n params: FhirCreateParams<T>,\n request?: OystehrFHIRCreateClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nexport async function create<T extends FhirResource>(\n this: SDKResource,\n params: FhirCreateParams<T>,\n request?: OystehrFHIRCreateClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const tagged = applyTagToResource(this.config, params);\n const { resourceType } = tagged;\n const requestMode = request?.mode;\n const ifNoneExistRequest = {\n ...request,\n ifNoneExist: request?.ifNoneExist !== undefined ? ifNoneExistToString(request.ifNoneExist) : undefined,\n };\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(\n `/${resourceType}`,\n 'POST',\n tagged as unknown as Record<string, unknown>,\n requestMode,\n ifNoneExistRequest\n );\n }\n\n return await this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}`, 'POST')(\n tagged as unknown as Record<string, unknown>,\n ifNoneExistRequest\n );\n}\n\nexport async function get<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirGetParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function get<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirGetParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nexport async function get<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirGetParams<T>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(`/${resourceType}/${id}`, 'GET', {}, requestMode, request);\n }\n\n const result = await this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}/${id}`, 'GET')({}, request);\n assertRetrievedResource(this.config, result);\n return result;\n}\n\nexport async function update<T extends FhirResource>(\n this: SDKResource,\n params: FhirUpdateParams<T>,\n request: OystehrFHIRUpdateClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function update<T extends FhirResource>(\n this: SDKResource,\n params: FhirUpdateParams<T>,\n request?: OystehrFHIRUpdateClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nexport async function update<T extends FhirResource>(\n this: SDKResource,\n params: FhirUpdateParams<T>,\n request?: OystehrFHIRUpdateClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const tagged = applyTagToResource(this.config, params);\n const { id, resourceType } = tagged;\n const requestMode = request?.mode;\n const ifMatchRequest = {\n ...request,\n ifMatch: request?.optimisticLockingVersionId ? `W/\"${request.optimisticLockingVersionId}\"` : undefined,\n };\n\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(\n `/${resourceType}/${id}`,\n 'PUT',\n tagged as unknown as Record<string, unknown>,\n requestMode,\n ifMatchRequest\n );\n }\n\n return await this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}/${id}`, 'PUT')(\n tagged as unknown as Record<string, unknown>,\n ifMatchRequest\n );\n}\n\nexport async function patch<T extends FhirResource>(\n this: SDKResource,\n params: FhirPatchParams<T>,\n request: OystehrFHIRUpdateClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function patch<T extends FhirResource>(\n this: SDKResource,\n params: FhirPatchParams<T>,\n request?: OystehrFHIRUpdateClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nexport async function patch<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id, operations }: FhirPatchParams<T>,\n request?: OystehrFHIRUpdateClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const taggedOperations = applyTagToPatchOperations(this.config, operations);\n const requestMode = request?.mode;\n const ifMatchRequest = {\n ...request,\n ifMatch: request?.optimisticLockingVersionId ? `W/\"${request.optimisticLockingVersionId}\"` : undefined,\n };\n\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(\n `/${resourceType}/${id}`,\n 'PATCH',\n taggedOperations as unknown as Record<string, unknown>,\n requestMode,\n {\n ...ifMatchRequest,\n contentType: 'application/json-patch+json',\n }\n );\n }\n\n return this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}/${id}`, 'PATCH')(taggedOperations, {\n ...ifMatchRequest,\n contentType: 'application/json-patch+json',\n });\n}\n\nasync function del<T extends FhirResource>(\n this: SDKResource,\n params: FhirDeleteParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nasync function del<T extends FhirResource>(\n this: SDKResource,\n params: FhirDeleteParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>>>;\nasync function del<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirDeleteParams<T>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<FhirResourceReturnValue<T>> | FhirAsyncJobHandle> {\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob(`/${resourceType}/${id}`, 'DELETE', {}, requestMode, request);\n }\n\n return await this.fhirRequest<FhirResourceReturnValue<T>>(`/${resourceType}/${id}`, 'DELETE')({}, request);\n}\nexport { del as delete };\n\nfunction getRetryDelayMs(retryAfter: string | undefined, fallbackMs: number): number {\n if (!retryAfter) {\n return fallbackMs;\n }\n\n const asSeconds = Number(retryAfter);\n if (Number.isFinite(asSeconds) && asSeconds >= 0) {\n return Math.max(0, Math.floor(asSeconds * 1000));\n }\n\n const asTimestamp = Date.parse(retryAfter);\n if (Number.isFinite(asTimestamp)) {\n return Math.max(0, asTimestamp - Date.now());\n }\n\n return fallbackMs;\n}\n\n/**\n * Fetches the status of an async job. If the job is still in progress, returns an object with status 202. If the job is completed, returns the job result with status 200. If the job has failed, returns an object with status 500 and an OperationOutcome resource describing the failure. If the job has expired, returns an object with status 410.\n * @param this The SDKResource context (this is an extension method and should be called with the SDKResource instance as the context, e.g. `sdkResource.getAsyncJob(jobId)`)\n * @param jobId The ID of the async job to fetch\n * @param request Optional OystehrClientRequest for authentication and headers\n * @returns A Promise that resolves to the FhirAsyncJobStatus\n */\nexport async function getAsyncJob<T extends FhirResource>(\n this: SDKResource,\n jobId: string,\n request?: OystehrClientRequest\n): Promise<FhirAsyncJobStatus<T>> {\n return await this.fetchAsyncJobStatus<T>(jobId, request);\n}\n\n/**\n * Waits for an async job to complete by polling its status until it reaches a terminal state (success, failure, or expiration) or the specified timeout is reached. Returns the final job status. Throws if the job fails, expires, or does not complete within the timeout.\n * @param this The SDKResource context (this is an extension method and should be called with the SDKResource instance as the context, e.g. `sdkResource.waitForAsyncJob(jobId)`)\n * @param jobId The ID of the async job to wait for\n * @param options Optional FhirAsyncWaitOptions to configure polling behavior\n * @param request Optional OystehrClientRequest for authentication and headers\n * @returns A Promise that resolves to the final FhirAsyncJobStatus\n */\nexport async function waitForAsyncJob<T extends FhirResource>(\n this: SDKResource,\n jobId: string,\n options?: FhirAsyncWaitOptions,\n request?: OystehrClientRequest\n): Promise<FhirAsyncJobStatus<T>> {\n // 5 seconds poll interval by default\n const pollIntervalMs = options?.pollIntervalMs ?? 5000;\n // 15 minutes timout by default\n const timeoutMs = options?.timeoutMs ?? 900000;\n const attempts = Math.max(1, Math.ceil(timeoutMs / pollIntervalMs));\n\n for (let attempt = 0; attempt < attempts; attempt++) {\n const status = await this.fetchAsyncJobStatus<T>(jobId, request);\n if (status.status !== 202) {\n return status;\n }\n\n if (attempt < attempts - 1) {\n const retryAfter = 'retryAfter' in status ? status.retryAfter : undefined;\n await new Promise((resolve) => setTimeout(resolve, getRetryDelayMs(retryAfter, pollIntervalMs)));\n }\n }\n\n throw new OystehrSdkError({\n message: `Async job ${jobId} did not complete within ${timeoutMs} ms`,\n code: 408,\n });\n}\n\nfunction parseNdjsonResources<T extends FhirResource>(ndjson: string, sourceUrl: string): T[] {\n const resources: T[] = [];\n const lines = ndjson.split('\\n');\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index].trim();\n if (line.length === 0) {\n continue;\n }\n try {\n resources.push(JSON.parse(line) as T);\n } catch (error) {\n throw new OystehrSdkError({\n message: `Failed to parse NDJSON line ${index + 1} from ${sourceUrl}`,\n code: 500,\n cause: error,\n });\n }\n }\n return resources;\n}\n\n/**\n * Waits for an async job to complete and retrieves the bulk output manifest and files. Throws if the job fails, expires, or does not complete within the specified timeout.\n * @param this The SDKResource context (this is an extension method and should be called with the SDKResource instance as the context, e.g. `sdkResource.waitForAsyncBulkOutput(jobId)`)\n * @param jobId The ID of the async job to wait for\n * @param options Optional FhirAsyncWaitOptions to configure polling behavior\n * @param request Optional OystehrClientRequest for authentication and headers\n * @returns A Promise that resolves to a FhirAsyncBulkOutputResult containing the bulk output manifest and files\n */\nexport async function waitForAsyncBulkOutput<T extends FhirResource>(\n this: SDKResource,\n jobId: string,\n options?: FhirAsyncWaitOptions,\n request?: OystehrClientRequest\n): Promise<FhirAsyncBulkOutputResult<T>> {\n const status = await waitForAsyncJob.call(this, jobId, options, request);\n\n if (status.status === 404) {\n throw new OystehrSdkError({\n message: `Async job ${jobId} not found`,\n code: 404,\n });\n }\n\n if (status.status === 410) {\n throw new OystehrSdkError({\n message: `Async job ${jobId} expired`,\n code: 410,\n });\n }\n\n if (status.status !== 200 || !('mode' in status) || status.mode !== 'bulk') {\n throw new OystehrSdkError({\n message: `Async job ${jobId} did not complete in bulk mode`,\n code: status.status,\n });\n }\n\n const accessToken = request?.accessToken ?? this.config.accessToken;\n const projectId = request?.projectId ?? this.config.projectId;\n if (status.manifest.requiresAccessToken && !accessToken) {\n throw new OystehrSdkError({\n message: `Bulk output for async job ${jobId} requires an access token`,\n code: 401,\n });\n }\n\n const fetchImpl = this.config.fetch ?? fetch;\n const headers: Record<string, string> = {};\n if (projectId) {\n headers['x-zapehr-project-id'] = projectId;\n headers['x-oystehr-project-id'] = projectId;\n }\n if (status.manifest.requiresAccessToken && accessToken) {\n headers.Authorization = `Bearer ${accessToken}`;\n }\n const requestHeaders = Object.keys(headers).length > 0 ? headers : undefined;\n\n const output = await Promise.all(\n status.manifest.output.map(async (file) => {\n const response = await fetchImpl(\n new Request(file.url, {\n method: 'GET',\n headers: requestHeaders,\n })\n );\n\n if (!response.ok) {\n throw new OystehrSdkError({\n message: `Failed to download bulk output (${file.type}): HTTP ${response.status}`,\n code: response.status,\n });\n }\n\n const ndjson = await response.text();\n return {\n ...file,\n resources: parseNdjsonResources<T>(ndjson, file.url),\n };\n })\n );\n\n return {\n manifest: status.manifest,\n output,\n };\n}\n\n/**\n * Wrapper around waitForAsyncBulkOutput that transforms the retrieved bulk output files into a single Bundle resource containing all the output resources as entries. This is a convenience method for use cases where you want to work with the bulk output as a Bundle, but it may not be efficient for large outputs due to the overhead of downloading and parsing all files and constructing the Bundle in memory.\n * Can be slow due to downloading and parsing potentially large NDJSON files, so use only if you need the full output as a Bundle resource. For more efficient processing of large bulk outputs, use waitForAsyncBulkOutput directly.\n * @param jobId the ID of the async job to wait for\n * @param options optional FhirAsyncWaitOptions to configure polling behavior\n * @param request optional OystehrClientRequest for authentication and headers\n * @returns a Promise that resolves to a Bundle containing all resources from the bulk output\n */\nexport async function waitForAsyncBulkBundle<T extends FhirResource>(\n this: SDKResource,\n jobId: string,\n options?: FhirAsyncWaitOptions,\n request?: OystehrClientRequest\n): Promise<Bundle<T>> {\n const bulkOutput = await waitForAsyncBulkOutput.call(this, jobId, options, request);\n const resources = bulkOutput.output.flatMap((file) => file.resources);\n\n const bundle = {\n resourceType: 'Bundle',\n type: 'collection',\n entry: resources.map((resource) => ({ resource } as BundleEntry<T>)),\n unbundle: function (this: { entry?: Array<BundleEntry<T>> | undefined }) {\n return this.entry?.map((entry) => entry.resource).filter((value): value is T => value !== undefined) ?? [];\n },\n } as unknown as Bundle<T>;\n\n return bundle;\n}\n\nexport async function cancelAsyncJob(this: SDKResource, jobId: string, request?: OystehrClientRequest): Promise<void> {\n await this.fhirRequest(`/async-job/${jobId}`, 'DELETE')({}, request);\n}\n\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirHistorySearchParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id, versionId }: FhirHistoryGetParams<T>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id, versionId }: FhirHistoryGetParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<T>>;\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id }: FhirHistorySearchParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<Bundle<T>>>;\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n { resourceType, id, count, offset }: FhirHistorySearchParams<T>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<Bundle<T>>>;\n\nexport async function history<T extends FhirResource>(\n this: SDKResource,\n {\n resourceType,\n id,\n versionId,\n count,\n offset,\n }: { resourceType: string; id: string; versionId?: string; count?: number; offset?: number },\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<Bundle<T>> | FhirFetcherResponse<T> | FhirAsyncJobHandle> {\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n if (versionId) {\n return await this.startAsyncJob(`/${resourceType}/${id}/_history/${versionId}`, 'GET', {}, requestMode, request);\n }\n return await this.startAsyncJob(`/${resourceType}/${id}/_history`, 'GET', {}, requestMode, request);\n }\n\n if (versionId) {\n return this.fhirRequest<T>(`/${resourceType}/${id}/_history/${versionId}`, 'GET')({}, request);\n }\n if (count) {\n return this.fhirRequest<Bundle<T>>(\n `/${resourceType}/${id}/_history?_total=accurate&_count=${count}\n ${offset ? `&_offset=${offset}` : ''}`,\n 'GET'\n )({}, request);\n }\n return this.fhirRequest<Bundle<T>>(`/${resourceType}/${id}/_history?_total=accurate`, 'GET')({}, request);\n}\n\n/**\n * Returns true when a batch GET/HEAD URL is a search (e.g. \"Patient\" or \"Patient?name=foo\")\n * rather than a direct retrieval (e.g. \"Patient/abc-123\").\n * A retrieval URL has a path segment after the resource type that is not a FHIR operation\n * (operations start with \"_\", e.g. \"_search\" or \"_history\").\n */\nfunction isBatchSearchUrl(url: string): boolean {\n const path = url.split('?')[0];\n const segments = path.split('/').filter(Boolean);\n // Only one segment → bare resource type, always a search\n if (segments.length <= 1) return true;\n // Two or more segments: second segment is an ID if it doesn't start with '_'\n return segments[1].startsWith('_');\n}\n\n/** Returns true when a batch POST URL targets a `_search` endpoint (e.g. \"Patient/_search\"). */\nfunction isBatchSearchPostUrl(url: string): boolean {\n return url.split('?')[0].endsWith('/_search');\n}\n\nfunction batchInputRequestToBundleEntryItem<T extends FhirResource>(\n request: BatchInputRequest<T>,\n config: OystehrConfig\n): BundleEntry<T | Binary<T>> {\n const { method } = request;\n let url = request.url;\n\n // Inject tag search params into search request URLs before URL encoding.\n // GET/HEAD: only for search URLs (not retrievals like Patient/<id>).\n // POST: only for _search endpoints (not creates).\n if (\n ((method === 'GET' || method === 'HEAD') && isBatchSearchUrl(url)) ||\n (method === 'POST' && isBatchSearchPostUrl(url))\n ) {\n if (config.workspaceTag) {\n url += (url.includes('?') ? '&' : '?') + `_tag=${codingToTagValue(config.workspaceTag)}`;\n }\n if (config.ignoreTags?.length) {\n for (const tag of config.ignoreTags) {\n url += (url.includes('?') ? '&' : '?') + `_tag:not=${codingToTagValue(tag)}`;\n }\n }\n }\n\n const baseRequest = {\n request: {\n method,\n url,\n },\n };\n\n // Escape query string parameters in entry.request.url\n if (url.split('?').length > 1) {\n const [resource, query] = url.split('?');\n const params = query\n .split('&')\n .map((param) => {\n const [name, value] = param.split('=');\n return { name, value };\n })\n .reduce((acc, { name, value }) => {\n if (!name) {\n return acc;\n }\n if (!acc[name]) {\n acc[name] = [];\n }\n acc[name].push(value);\n return acc;\n }, {} as Record<string, string[]>);\n const search = new URLSearchParams();\n addParamsToSearch(params, search);\n baseRequest.request.url = `${resource}?${search.toString()}`;\n }\n\n // GET, DELETE, and HEAD require no further parameters\n if (['GET', 'DELETE', 'HEAD'].includes(method)) {\n return baseRequest as BundleEntry<T>;\n }\n\n // PUT updates require a full resource\n if (method === 'PUT') {\n const resource = applyTagToResource(config, request.resource);\n return {\n request: {\n ...baseRequest.request,\n ifMatch: request.ifMatch,\n },\n resource: resource as T,\n } as BundleEntry<T>;\n }\n\n // PATCH can be Binary resource or JSON patch\n if (method === 'PATCH') {\n if ('resource' in request) {\n // Binary patch — decode operations, apply tag transforms, re-encode\n let patchResource = request.resource;\n const binaryData = patchResource.data;\n if (binaryData) {\n const operations = JSON.parse(base64ToString(binaryData)) as Operation[];\n const taggedOperations = applyTagToPatchOperations(config, operations);\n patchResource = { ...patchResource, data: stringToBase64(JSON.stringify(taggedOperations)) } as Binary<T>;\n }\n return {\n request: {\n ...baseRequest.request,\n ifMatch: request.ifMatch,\n },\n resource: patchResource,\n } as BundleEntry<Binary<T>>;\n }\n const operations = applyTagToPatchOperations(config, request.operations);\n const data = stringToBase64(JSON.stringify(operations));\n return {\n ...baseRequest,\n resource: {\n resourceType: 'Binary',\n contentType: 'application/json-patch+json',\n data,\n },\n } as BundleEntry<Binary<T>>;\n }\n\n // POST _search — no resource body; tag params were already injected into the URL above\n if (method === 'POST' && isBatchSearchPostUrl(url)) {\n return baseRequest as BundleEntry<T>;\n }\n\n // POST creates require a full resource\n if (method === 'POST' && 'resource' in request) {\n const resource = applyTagToResource(config, request.resource);\n const { fullUrl, ifNoneExist } = request;\n return {\n request: {\n ...baseRequest.request,\n // Conditional create: only create the resource if no existing resource matches the query.\n ifNoneExist: ifNoneExist !== undefined ? ifNoneExistToString(ifNoneExist) : undefined,\n },\n resource: resource as T,\n fullUrl,\n } as BundleEntry<T>;\n }\n\n // // Add ifMatch for the entries that support it\n // if ('ifMatch' in request) {\n // baseRequest.request = {\n // ...baseRequest.request,\n // ifMatch: request.ifMatch,\n // };\n // }\n\n throw new Error('Unrecognized method');\n}\n\nexport async function batch<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function batch<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<BatchBundle<BundleContentType>>>;\nexport async function batch<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<BatchBundle<BundleContentType>> | FhirAsyncJobHandle> {\n const requestPayload = {\n resourceType: 'Bundle',\n type: 'batch',\n entry: input.requests.map((req) => batchInputRequestToBundleEntryItem(req, this.config)),\n };\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob('/', 'POST', requestPayload, requestMode, request);\n }\n\n const resp = await this.fhirRequest<BatchBundle<BundleContentType>>('/', 'POST')(requestPayload, request);\n // Validate each GET/HEAD retrieval entry against the tag config.\n // Violations are replaced with a synthetic 404 OperationOutcome entry; batch entries are independent.\n const rawEntries = resp.entry as Array<BundleEntry<BundleContentType>> | undefined;\n const processedEntries: Array<BundleEntry<BundleContentType>> | undefined =\n this.config.workspaceTag || this.config.ignoreTags?.length\n ? rawEntries?.map((entry, i) => {\n const req = input.requests[i];\n if (!req || !entry?.resource) return entry;\n if ((req.method === 'GET' || req.method === 'HEAD') && !isBatchSearchUrl(req.url)) {\n try {\n assertRetrievedResource(this.config, entry.resource);\n } catch (err) {\n if (!(err instanceof OystehrFHIRError)) throw err;\n return {\n request: entry.request,\n response: { status: '404', outcome: err.cause },\n } as unknown as BundleEntry<BundleContentType>;\n }\n }\n return entry;\n })\n : rawEntries;\n const bundle: BatchBundle<BundleContentType> = {\n ...resp,\n entry: processedEntries,\n unbundle: function (this: { entry?: Array<BundleEntry<BundleContentType>> | undefined }) {\n return (\n this.entry\n ?.map((entry) => entry.resource)\n .filter((resource): resource is BundleContentType => resource !== undefined) ?? []\n );\n },\n errors: function (this: { entry?: Array<BundleEntry<BundleContentType>> | undefined }) {\n return this.entry\n ?.filter((entry) => entry.response?.status?.startsWith('4') || entry.response?.status?.startsWith('5'))\n .map((entry) => entry.response?.outcome)\n .filter((outcome): outcome is OperationOutcome => outcome !== undefined);\n },\n };\n return bundle;\n}\n\nexport async function transaction<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request: OystehrClientRequest & { mode: Exclude<FhirResponseMode, 'sync'> }\n): Promise<FhirAsyncJobHandle>;\nexport async function transaction<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request?: OystehrClientRequest & { mode?: 'sync' | undefined }\n): Promise<FhirFetcherResponse<TransactionBundle<BundleContentType>>>;\nexport async function transaction<BundleContentType extends FhirResource>(\n this: SDKResource,\n input: BatchInput<BundleContentType>,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<TransactionBundle<BundleContentType>> | FhirAsyncJobHandle> {\n const requestPayload = {\n resourceType: 'Bundle',\n type: 'transaction',\n entry: input.requests.map((req) => batchInputRequestToBundleEntryItem(req, this.config)),\n };\n const requestMode = request?.mode;\n if (isAsyncRequestMode(requestMode)) {\n return await this.startAsyncJob('/', 'POST', requestPayload, requestMode, request);\n }\n\n const resp = await this.fhirRequest<TransactionBundle<BundleContentType>>('/', 'POST')(requestPayload, request);\n // Validate each GET/HEAD retrieval entry against the tag config.\n // A violation throws OystehrFHIRError(404) — transactions are all-or-nothing.\n if (this.config.workspaceTag || this.config.ignoreTags?.length) {\n (resp.entry as Array<BundleEntry<BundleContentType>> | undefined)?.forEach((entry, i) => {\n const req = input.requests[i];\n if (!req || !entry?.resource) return;\n if ((req.method === 'GET' || req.method === 'HEAD') && !isBatchSearchUrl(req.url)) {\n assertRetrievedResource(this.config, entry.resource);\n }\n });\n }\n const bundle: TransactionBundle<BundleContentType> = {\n ...resp,\n entry: resp.entry as Array<BundleEntry<BundleContentType>> | undefined,\n unbundle: function (this: { entry?: Array<BundleEntry<BundleContentType>> | undefined }) {\n return (\n this.entry\n ?.map((entry) => entry.resource)\n .filter((resource): resource is BundleContentType => resource !== undefined) ?? []\n );\n },\n };\n return bundle;\n}\n\nexport async function generateFriendlyPatientId(\n this: SDKResource,\n { id }: GenerateFriendlyPatientIdParams,\n request?: OystehrClientRequest\n): Promise<FhirFetcherResponse<FhirResource>> {\n return this.fhirRequest(`/Patient/${id}/$generate-friendly-patient-id`, 'POST')({}, request);\n}\n\nexport function formatAddress(\n address: AddressR4B | AddressR5,\n options?: { all?: boolean; use?: boolean; lineSeparator?: string }\n): string {\n const builder = [];\n\n if (address.line) {\n builder.push(...address.line);\n }\n\n if (address.city || address.state || address.postalCode) {\n const cityStateZip = [];\n if (address.city) {\n cityStateZip.push(address.city);\n }\n if (address.state) {\n cityStateZip.push(address.state);\n }\n if (address.postalCode) {\n cityStateZip.push(address.postalCode);\n }\n builder.push(cityStateZip.join(', '));\n }\n\n if (address.use && (options?.all || options?.use)) {\n builder.push('[' + address.use + ']');\n }\n\n return builder.join(options?.lineSeparator || ', ').trim();\n}\n\nexport function formatHumanName(\n name: HumanNameR4B | HumanNameR5,\n options?: {\n all?: boolean;\n prefix?: boolean;\n suffix?: boolean;\n use?: boolean;\n }\n): string {\n const builder = [];\n\n if (name.prefix && options?.prefix !== false) {\n builder.push(...name.prefix);\n }\n\n if (name.given) {\n builder.push(...name.given);\n }\n\n if (name.family) {\n builder.push(name.family);\n }\n\n if (name.suffix && options?.suffix !== false) {\n builder.push(...name.suffix);\n }\n\n if (name.use && (options?.all || options?.use)) {\n builder.push('[' + name.use + ']');\n }\n\n return builder.join(' ').trim();\n}\n"],"names":["OystehrSdkError","OystehrFHIRError","index","addParamsToSearch"],"mappings":";;;;;AAqCA;AACA,MAAM,cAAc,GAAG,MAAM;AAC7B,SAAS,cAAc,CAAC,KAAa,EAAA;AACnC,IAAA,MAAM,IAAI,GAA4B,IAAI,UAAU,CAAC,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC;IAChF,IAAI,MAAM,GAAG,EAAE;AAEf,IAAA,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,cAAc,EAAE;AAChE,QAAA,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,cAAc,CAAC;;AAE1D,QAAA,MAAM,IAAI,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,C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