gdc-common-utils-ts 2.0.12 → 2.0.14

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 (89) hide show
  1. package/README.md +6 -2
  2. package/dist/examples/employee.d.ts +9 -1
  3. package/dist/examples/employee.js +7 -4
  4. package/dist/examples/shared.d.ts +1 -1
  5. package/dist/examples/shared.js +6 -2
  6. package/dist/utils/actor.d.ts +3 -1
  7. package/dist/utils/medication-claim-helpers.d.ts +5 -85
  8. package/dist/utils/medication-claim-helpers.js +5 -255
  9. package/package.json +1 -5
  10. package/dist/examples/communication-bundle-session.d.ts +0 -22
  11. package/dist/examples/communication-bundle-session.js +0 -79
  12. package/dist/interfaces/IWallet.d.ts +0 -55
  13. package/dist/interfaces/IWallet.js +0 -3
  14. package/dist/models/fhir-related-person.d.ts +0 -61
  15. package/dist/models/fhir-related-person.js +0 -108
  16. package/dist/models/related-profile.d.ts +0 -42
  17. package/dist/models/related-profile.js +0 -16
  18. package/dist/utils/allergy-intolerance-claim-helpers.d.ts +0 -10
  19. package/dist/utils/allergy-intolerance-claim-helpers.js +0 -47
  20. package/dist/utils/appointment-claim-helpers.d.ts +0 -10
  21. package/dist/utils/appointment-claim-helpers.js +0 -26
  22. package/dist/utils/appointment-response-claim-helpers.d.ts +0 -8
  23. package/dist/utils/appointment-response-claim-helpers.js +0 -20
  24. package/dist/utils/claim-list-helpers.d.ts +0 -21
  25. package/dist/utils/claim-list-helpers.js +0 -50
  26. package/dist/utils/clinical-impression-claim-helpers.d.ts +0 -10
  27. package/dist/utils/clinical-impression-claim-helpers.js +0 -26
  28. package/dist/utils/communication-bundle-session.d.ts +0 -175
  29. package/dist/utils/communication-bundle-session.js +0 -524
  30. package/dist/utils/composition-claim-helpers.d.ts +0 -12
  31. package/dist/utils/composition-claim-helpers.js +0 -32
  32. package/dist/utils/condition-claim-helpers.d.ts +0 -10
  33. package/dist/utils/condition-claim-helpers.js +0 -47
  34. package/dist/utils/convert-allergy-intolerance.d.ts +0 -3
  35. package/dist/utils/convert-allergy-intolerance.js +0 -34
  36. package/dist/utils/convert-appointment-response.d.ts +0 -3
  37. package/dist/utils/convert-appointment-response.js +0 -32
  38. package/dist/utils/convert-appointment.d.ts +0 -3
  39. package/dist/utils/convert-appointment.js +0 -61
  40. package/dist/utils/convert-care-plan.d.ts +0 -3
  41. package/dist/utils/convert-care-plan.js +0 -58
  42. package/dist/utils/convert-clinical-impression.d.ts +0 -3
  43. package/dist/utils/convert-clinical-impression.js +0 -42
  44. package/dist/utils/convert-composition.d.ts +0 -3
  45. package/dist/utils/convert-composition.js +0 -35
  46. package/dist/utils/convert-condition.d.ts +0 -3
  47. package/dist/utils/convert-condition.js +0 -24
  48. package/dist/utils/convert-coverage.d.ts +0 -3
  49. package/dist/utils/convert-coverage.js +0 -51
  50. package/dist/utils/convert-device-use-statement.d.ts +0 -3
  51. package/dist/utils/convert-device-use-statement.js +0 -28
  52. package/dist/utils/convert-device.d.ts +0 -3
  53. package/dist/utils/convert-device.js +0 -37
  54. package/dist/utils/convert-diagnostic-report.d.ts +0 -3
  55. package/dist/utils/convert-diagnostic-report.js +0 -55
  56. package/dist/utils/convert-document-reference.d.ts +0 -3
  57. package/dist/utils/convert-document-reference.js +0 -35
  58. package/dist/utils/convert-encounter.d.ts +0 -3
  59. package/dist/utils/convert-encounter.js +0 -68
  60. package/dist/utils/convert-flag.d.ts +0 -3
  61. package/dist/utils/convert-flag.js +0 -34
  62. package/dist/utils/convert-immunization.d.ts +0 -3
  63. package/dist/utils/convert-immunization.js +0 -56
  64. package/dist/utils/convert-medication-statement.d.ts +0 -3
  65. package/dist/utils/convert-medication-statement.js +0 -64
  66. package/dist/utils/convert-observation.d.ts +0 -3
  67. package/dist/utils/convert-observation.js +0 -57
  68. package/dist/utils/convert-procedure.d.ts +0 -3
  69. package/dist/utils/convert-procedure.js +0 -50
  70. package/dist/utils/convert-related-person.d.ts +0 -3
  71. package/dist/utils/convert-related-person.js +0 -31
  72. package/dist/utils/convert-shared.d.ts +0 -34
  73. package/dist/utils/convert-shared.js +0 -179
  74. package/dist/utils/coverage-claim-helpers.d.ts +0 -10
  75. package/dist/utils/coverage-claim-helpers.js +0 -26
  76. package/dist/utils/diagnostic-report-claim-helpers.d.ts +0 -12
  77. package/dist/utils/diagnostic-report-claim-helpers.js +0 -32
  78. package/dist/utils/employee-editor.d.ts +0 -24
  79. package/dist/utils/employee-editor.js +0 -41
  80. package/dist/utils/encounter-claim-helpers.d.ts +0 -10
  81. package/dist/utils/encounter-claim-helpers.js +0 -26
  82. package/dist/utils/gateway-index-params.d.ts +0 -44
  83. package/dist/utils/gateway-index-params.js +0 -80
  84. package/dist/utils/normalize-subject-uuid.d.ts +0 -1
  85. package/dist/utils/normalize-subject-uuid.js +0 -24
  86. package/dist/utils/related-person-claim-helpers.d.ts +0 -8
  87. package/dist/utils/related-person-claim-helpers.js +0 -20
  88. package/dist/utils/search-parameter-catalog.d.ts +0 -31
  89. package/dist/utils/search-parameter-catalog.js +0 -81
@@ -1,175 +0,0 @@
1
- import { BundleEntry, BundleJsonApi, BundleRequest } from '../models/bundle';
2
- import { type BundleResourceIdFilters } from './bundle-query';
3
- import { type MedicationStatementClaimsFlat } from '../models/interoperable-claims/medication-statement-claims';
4
- export type CommunicationBundleSessionMode = 'strict' | 'normalize';
5
- export type CommunicationBundleSessionOptions = Readonly<{
6
- communicationClaims?: Record<string, unknown>;
7
- initialBundle?: BundleJsonApi<BundleEntry>;
8
- mode?: CommunicationBundleSessionMode;
9
- }>;
10
- export type ActiveEntrySelection = Readonly<{
11
- index?: number;
12
- fullUrl?: string;
13
- }>;
14
- export type UpsertEntryInput = Readonly<{
15
- resourceType: string;
16
- claims: Record<string, unknown>;
17
- type?: string;
18
- fullUrl?: string;
19
- request?: BundleRequest;
20
- }>;
21
- export type AddContainedDocumentToActiveEntryInput = Readonly<{
22
- identifier?: string;
23
- fullUrl?: string;
24
- claims?: Record<string, unknown>;
25
- attachmentContentType?: string;
26
- attachmentDataBase64?: string;
27
- attachmentUrl?: string;
28
- description?: string;
29
- date?: string;
30
- language?: string;
31
- }>;
32
- /**
33
- * Communication editing session with bundle-in-memory as source of truth.
34
- *
35
- * Design contract:
36
- * - `activeEntry` is the real editing unit (not only `activeResource`), because
37
- * it can include `fullUrl`, `request`, and entry-level context.
38
- * - `Communication.content-attachment-data` is always derived from the
39
- * in-memory bundle after each committed update.
40
- * - saving can release active entry memory via `saveAndReleaseActiveEntry()`.
41
- */
42
- export declare class CommunicationBundleSession {
43
- private communicationClaims;
44
- private bundleInMemory;
45
- private activeEntryIndex;
46
- private mode;
47
- constructor(options?: CommunicationBundleSessionOptions);
48
- /** Returns a deep copy of communication claims. */
49
- getCommunicationClaims(): Record<string, unknown>;
50
- /** Returns a deep copy of the current in-memory bundle. */
51
- getBundleInMemory(): BundleJsonApi<BundleEntry>;
52
- /** Returns the active entry index, or null when no entry is selected. */
53
- getActiveEntryIndex(): number | null;
54
- /** Returns a deep copy of the active entry when selected. */
55
- getActiveEntry(): BundleEntry | null;
56
- /** Selects an active entry by index or fullUrl. */
57
- selectActiveEntry(selection: ActiveEntrySelection): this;
58
- /** Clears active entry selection from memory. */
59
- clearActiveEntry(): this;
60
- /**
61
- * Upserts an entry in bundle memory and marks it as active.
62
- * Matching priority: `fullUrl` if present, then resource claim identifier.
63
- */
64
- upsertActiveEntry(input: UpsertEntryInput): this;
65
- /**
66
- * Consent-first helper for developer onboarding.
67
- *
68
- * Expected keys should come from `ClaimConsent` in caller code.
69
- */
70
- upsertActiveConsentEntry(input: Readonly<{
71
- claims: Record<string, unknown>;
72
- fullUrl?: string;
73
- type?: string;
74
- request?: BundleRequest;
75
- }>): this;
76
- /**
77
- * MedicationStatement helper for IPS-in-Communication use cases.
78
- *
79
- * Expected keys should come from MedicationStatement claims constants.
80
- */
81
- upsertActiveMedicationStatementEntry(input: Readonly<{
82
- claims: MedicationStatementClaimsFlat | Record<string, unknown>;
83
- fullUrl?: string;
84
- type?: string;
85
- request?: BundleRequest;
86
- }>): this;
87
- /**
88
- * DocumentReference helper for bundle-contained attachments linked from
89
- * other clinical resources through `*.contained-documents`.
90
- */
91
- upsertActiveDocumentReferenceEntry(input: Readonly<{
92
- claims: Record<string, unknown>;
93
- fullUrl?: string;
94
- type?: string;
95
- request?: BundleRequest;
96
- }>): this;
97
- /**
98
- * Condition helper for IPS-in-Communication use cases.
99
- *
100
- * Expected keys should come from Condition claims constants.
101
- */
102
- upsertActiveConditionEntry(input: Readonly<{
103
- claims: Record<string, unknown>;
104
- fullUrl?: string;
105
- type?: string;
106
- request?: BundleRequest;
107
- }>): this;
108
- /**
109
- * AllergyIntolerance helper for IPS-in-Communication use cases.
110
- *
111
- * Expected keys should come from AllergyIntolerance claims constants.
112
- */
113
- upsertActiveAllergyIntoleranceEntry(input: Readonly<{
114
- claims: Record<string, unknown>;
115
- fullUrl?: string;
116
- type?: string;
117
- request?: BundleRequest;
118
- }>): this;
119
- /**
120
- * TODO(ips-next):
121
- * Add `upsertActiveDiagnosticReportEntry(...)` once the shared claim helpers
122
- * for `DiagnosticReport` are in place.
123
- *
124
- * Expected shape should mirror the existing resource helpers:
125
- * - `claims` authored with `@context = org.hl7.fhir.api`
126
- * - matching priority by `DiagnosticReport.identifier`
127
- * - support for linked `DocumentReference` ids through
128
- * `DiagnosticReport.contained-documents`
129
- *
130
- * Intentionally not implemented in this pass:
131
- * - IPS authoring already works for the currently documented resources
132
- * - GW Core can already consume bundle-contained `DocumentReference` rows
133
- * - adding the DiagnosticReport editing surface now would expand the IPS
134
- * contract further than intended for this release slice
135
- */
136
- /**
137
- * Creates or updates a linked `DocumentReference` entry and stores its
138
- * identifier under the active resource `*.contained-documents` claim.
139
- */
140
- addContainedDocumentToActiveEntry(input: AddContainedDocumentToActiveEntryInput): this;
141
- /**
142
- * Patches active entry `resource.meta.claims` and synchronizes attachment data.
143
- */
144
- patchActiveEntryClaims(claimPatch: Record<string, unknown>): this;
145
- /**
146
- * Persists current memory state into communication claims attachment.
147
- * No-op for active entry pointer.
148
- */
149
- saveActiveEntry(): this;
150
- /**
151
- * Persists and releases active entry memory pointer.
152
- * This is the recommended step after a successful save operation.
153
- */
154
- saveAndReleaseActiveEntry(): this;
155
- /**
156
- * Returns stable resource IDs from bundle entries with optional filters.
157
- */
158
- getResourceIds(filters?: BundleResourceIdFilters): string[];
159
- /**
160
- * Returns bundle entries matching resource IDs produced by `getResourceIds`.
161
- */
162
- getResourceEntriesByIds(resourceIds: readonly string[]): BundleEntry[];
163
- /**
164
- * Resolves the entry URL (`fullUrl`) for a given entry/resource identifier.
165
- */
166
- getEntryUrl(entryId: string): string | undefined;
167
- private decodeBundleFromClaims;
168
- private syncAttachmentFromBundle;
169
- private resolveCurrentSubject;
170
- private findUpsertIndex;
171
- private resolveEntryIdentifier;
172
- private createBundleEntry;
173
- private resolveEntryCanonicalIdValue;
174
- private assertEntryIndex;
175
- }
@@ -1,524 +0,0 @@
1
- // Copyright 2026 Conectate Soluciones y Aplicaciones SL under the Apache License, Version 2.0.
2
- // Always create JSDoc, do not use strings inline in keys nor values, use types instead, and reuse the data test examples.
3
- import { ResourceTypesFhirR4 } from '../constants/fhir-resource-types.js';
4
- import { ClaimConsent } from '../models/consent-rule.js';
5
- import { AllergyIntoleranceClaim } from '../models/interoperable-claims/allergy-intolerance-claims.js';
6
- import { CommunicationClaim } from '../models/interoperable-claims/communication-claims.js';
7
- import { ConditionClaim } from '../models/interoperable-claims/condition-claims.js';
8
- import { DocumentReferenceClaim } from '../models/interoperable-claims/document-reference-claims.js';
9
- import { BundleQuery } from './bundle-query.js';
10
- import { addClaimValues } from '../claims/claim-list-helpers.js';
11
- import { MedicationStatementClaim, } from '../models/interoperable-claims/medication-statement-claims.js';
12
- /**
13
- * Communication editing session with bundle-in-memory as source of truth.
14
- *
15
- * Design contract:
16
- * - `activeEntry` is the real editing unit (not only `activeResource`), because
17
- * it can include `fullUrl`, `request`, and entry-level context.
18
- * - `Communication.content-attachment-data` is always derived from the
19
- * in-memory bundle after each committed update.
20
- * - saving can release active entry memory via `saveAndReleaseActiveEntry()`.
21
- */
22
- export class CommunicationBundleSession {
23
- communicationClaims;
24
- bundleInMemory;
25
- activeEntryIndex;
26
- mode;
27
- constructor(options = {}) {
28
- this.mode = options.mode || 'strict';
29
- this.communicationClaims = {
30
- ...options.communicationClaims,
31
- };
32
- this.activeEntryIndex = null;
33
- const providedBundle = options.initialBundle ? cloneBundle(options.initialBundle) : undefined;
34
- this.bundleInMemory = providedBundle || this.decodeBundleFromClaims(this.communicationClaims);
35
- this.syncAttachmentFromBundle();
36
- }
37
- /** Returns a deep copy of communication claims. */
38
- getCommunicationClaims() {
39
- return {
40
- ...this.communicationClaims,
41
- };
42
- }
43
- /** Returns a deep copy of the current in-memory bundle. */
44
- getBundleInMemory() {
45
- return cloneBundle(this.bundleInMemory);
46
- }
47
- /** Returns the active entry index, or null when no entry is selected. */
48
- getActiveEntryIndex() {
49
- return this.activeEntryIndex;
50
- }
51
- /** Returns a deep copy of the active entry when selected. */
52
- getActiveEntry() {
53
- if (this.activeEntryIndex === null) {
54
- return null;
55
- }
56
- return cloneEntry(this.bundleInMemory.data[this.activeEntryIndex]);
57
- }
58
- /** Selects an active entry by index or fullUrl. */
59
- selectActiveEntry(selection) {
60
- if (typeof selection.index === 'number') {
61
- this.assertEntryIndex(selection.index);
62
- this.activeEntryIndex = selection.index;
63
- return this;
64
- }
65
- if (selection.fullUrl) {
66
- const foundIndex = this.bundleInMemory.data.findIndex((entry) => String(entry?.fullUrl || '').trim() === selection.fullUrl);
67
- if (foundIndex < 0) {
68
- throw new Error(`Active entry not found for fullUrl: ${selection.fullUrl}`);
69
- }
70
- this.activeEntryIndex = foundIndex;
71
- return this;
72
- }
73
- throw new Error('selectActiveEntry requires either index or fullUrl.');
74
- }
75
- /** Clears active entry selection from memory. */
76
- clearActiveEntry() {
77
- this.activeEntryIndex = null;
78
- return this;
79
- }
80
- /**
81
- * Upserts an entry in bundle memory and marks it as active.
82
- * Matching priority: `fullUrl` if present, then resource claim identifier.
83
- */
84
- upsertActiveEntry(input) {
85
- const entry = this.createBundleEntry(input);
86
- const nextIndex = this.findUpsertIndex(entry, input.fullUrl);
87
- if (nextIndex >= 0) {
88
- this.bundleInMemory.data[nextIndex] = entry;
89
- this.activeEntryIndex = nextIndex;
90
- }
91
- else {
92
- this.bundleInMemory.data.push(entry);
93
- this.activeEntryIndex = this.bundleInMemory.data.length - 1;
94
- }
95
- this.syncAttachmentFromBundle();
96
- return this;
97
- }
98
- /**
99
- * Consent-first helper for developer onboarding.
100
- *
101
- * Expected keys should come from `ClaimConsent` in caller code.
102
- */
103
- upsertActiveConsentEntry(input) {
104
- return this.upsertActiveEntry({
105
- resourceType: ResourceTypesFhirR4.Consent,
106
- claims: input.claims,
107
- fullUrl: input.fullUrl,
108
- type: input.type,
109
- request: input.request,
110
- });
111
- }
112
- /**
113
- * MedicationStatement helper for IPS-in-Communication use cases.
114
- *
115
- * Expected keys should come from MedicationStatement claims constants.
116
- */
117
- upsertActiveMedicationStatementEntry(input) {
118
- return this.upsertActiveEntry({
119
- resourceType: ResourceTypesFhirR4.MedicationStatement,
120
- claims: {
121
- ...input.claims,
122
- },
123
- fullUrl: input.fullUrl,
124
- type: input.type,
125
- request: input.request,
126
- });
127
- }
128
- /**
129
- * DocumentReference helper for bundle-contained attachments linked from
130
- * other clinical resources through `*.contained-documents`.
131
- */
132
- upsertActiveDocumentReferenceEntry(input) {
133
- return this.upsertActiveEntry({
134
- resourceType: ResourceTypesFhirR4.DocumentReference,
135
- claims: {
136
- ...input.claims,
137
- },
138
- fullUrl: input.fullUrl,
139
- type: input.type,
140
- request: input.request,
141
- });
142
- }
143
- /**
144
- * Condition helper for IPS-in-Communication use cases.
145
- *
146
- * Expected keys should come from Condition claims constants.
147
- */
148
- upsertActiveConditionEntry(input) {
149
- return this.upsertActiveEntry({
150
- resourceType: ResourceTypesFhirR4.Condition,
151
- claims: {
152
- ...input.claims,
153
- },
154
- fullUrl: input.fullUrl,
155
- type: input.type,
156
- request: input.request,
157
- });
158
- }
159
- /**
160
- * AllergyIntolerance helper for IPS-in-Communication use cases.
161
- *
162
- * Expected keys should come from AllergyIntolerance claims constants.
163
- */
164
- upsertActiveAllergyIntoleranceEntry(input) {
165
- return this.upsertActiveEntry({
166
- resourceType: ResourceTypesFhirR4.AllergyIntolerance,
167
- claims: {
168
- ...input.claims,
169
- },
170
- fullUrl: input.fullUrl,
171
- type: input.type,
172
- request: input.request,
173
- });
174
- }
175
- /**
176
- * TODO(ips-next):
177
- * Add `upsertActiveDiagnosticReportEntry(...)` once the shared claim helpers
178
- * for `DiagnosticReport` are in place.
179
- *
180
- * Expected shape should mirror the existing resource helpers:
181
- * - `claims` authored with `@context = org.hl7.fhir.api`
182
- * - matching priority by `DiagnosticReport.identifier`
183
- * - support for linked `DocumentReference` ids through
184
- * `DiagnosticReport.contained-documents`
185
- *
186
- * Intentionally not implemented in this pass:
187
- * - IPS authoring already works for the currently documented resources
188
- * - GW Core can already consume bundle-contained `DocumentReference` rows
189
- * - adding the DiagnosticReport editing surface now would expand the IPS
190
- * contract further than intended for this release slice
191
- */
192
- /**
193
- * Creates or updates a linked `DocumentReference` entry and stores its
194
- * identifier under the active resource `*.contained-documents` claim.
195
- */
196
- addContainedDocumentToActiveEntry(input) {
197
- if (this.activeEntryIndex === null) {
198
- throw new Error('No active entry selected.');
199
- }
200
- const parentIndex = this.activeEntryIndex;
201
- const parentEntry = cloneEntry(this.bundleInMemory.data[parentIndex]);
202
- const parentResource = ensureEntryResource(parentEntry, this.mode);
203
- const parentClaims = {
204
- ...(parentResource.meta?.claims || {}),
205
- };
206
- const parentResourceType = asTrimmedString(parentResource.resourceType);
207
- const containedDocumentsClaimKey = resolveContainedDocumentsClaimKey(parentResourceType);
208
- if (!containedDocumentsClaimKey) {
209
- throw new Error(`Contained documents are not supported for resourceType: ${parentResourceType || 'unknown'}`);
210
- }
211
- const documentIdentifier = asTrimmedString(input.identifier)
212
- || asTrimmedString(input.claims?.[DocumentReferenceClaim.Identifier])
213
- || runtimeUuid('docref');
214
- const documentSubject = asTrimmedString(input.claims?.[DocumentReferenceClaim.Subject])
215
- || resolveSubjectFromClaims(parentClaims)
216
- || asTrimmedString(this.communicationClaims[CommunicationClaim.Subject]);
217
- const documentClaims = {
218
- '@context': 'org.hl7.fhir.api',
219
- ...(input.claims || {}),
220
- [DocumentReferenceClaim.Identifier]: documentIdentifier,
221
- };
222
- if (documentSubject) {
223
- documentClaims[DocumentReferenceClaim.Subject] = documentSubject;
224
- }
225
- setIfMissing(documentClaims, DocumentReferenceClaim.ContentType, input.attachmentContentType);
226
- setIfMissing(documentClaims, DocumentReferenceClaim.ContentData, input.attachmentDataBase64);
227
- setIfMissing(documentClaims, DocumentReferenceClaim.Location, input.attachmentUrl);
228
- setIfMissing(documentClaims, DocumentReferenceClaim.Description, input.description);
229
- setIfMissing(documentClaims, DocumentReferenceClaim.Date, input.date);
230
- setIfMissing(documentClaims, DocumentReferenceClaim.Language, input.language);
231
- this.upsertActiveDocumentReferenceEntry({
232
- claims: documentClaims,
233
- fullUrl: input.fullUrl || `urn:uuid:${documentIdentifier}`,
234
- });
235
- parentResource.meta = parentResource.meta || {};
236
- parentResource.meta.claims = addClaimValues(parentClaims, containedDocumentsClaimKey, [documentIdentifier]);
237
- parentEntry.resource = parentResource;
238
- this.bundleInMemory.data[parentIndex] = parentEntry;
239
- this.activeEntryIndex = parentIndex;
240
- this.syncAttachmentFromBundle();
241
- return this;
242
- }
243
- /**
244
- * Patches active entry `resource.meta.claims` and synchronizes attachment data.
245
- */
246
- patchActiveEntryClaims(claimPatch) {
247
- if (this.activeEntryIndex === null) {
248
- throw new Error('No active entry selected.');
249
- }
250
- const current = cloneEntry(this.bundleInMemory.data[this.activeEntryIndex]);
251
- const resource = ensureEntryResource(current, this.mode);
252
- resource.meta = resource.meta || {};
253
- resource.meta.claims = {
254
- ...(resource.meta.claims || {}),
255
- ...claimPatch,
256
- };
257
- current.resource = resource;
258
- this.bundleInMemory.data[this.activeEntryIndex] = current;
259
- this.syncAttachmentFromBundle();
260
- return this;
261
- }
262
- /**
263
- * Persists current memory state into communication claims attachment.
264
- * No-op for active entry pointer.
265
- */
266
- saveActiveEntry() {
267
- this.syncAttachmentFromBundle();
268
- return this;
269
- }
270
- /**
271
- * Persists and releases active entry memory pointer.
272
- * This is the recommended step after a successful save operation.
273
- */
274
- saveAndReleaseActiveEntry() {
275
- this.syncAttachmentFromBundle();
276
- this.clearActiveEntry();
277
- return this;
278
- }
279
- /**
280
- * Returns stable resource IDs from bundle entries with optional filters.
281
- */
282
- getResourceIds(filters = {}) {
283
- const query = new BundleQuery(this.bundleInMemory);
284
- return query.getResourceIds(filters);
285
- }
286
- /**
287
- * Returns bundle entries matching resource IDs produced by `getResourceIds`.
288
- */
289
- getResourceEntriesByIds(resourceIds) {
290
- const query = new BundleQuery(this.bundleInMemory);
291
- return query.getResourceEntriesByIds(resourceIds);
292
- }
293
- /**
294
- * Resolves the entry URL (`fullUrl`) for a given entry/resource identifier.
295
- */
296
- getEntryUrl(entryId) {
297
- const query = new BundleQuery(this.bundleInMemory);
298
- return query.getEntryUrl(entryId);
299
- }
300
- decodeBundleFromClaims(claims) {
301
- const encoded = asTrimmedString(claims[CommunicationClaim.ContentAttachmentData]);
302
- if (!encoded) {
303
- return createEmptyBundle();
304
- }
305
- try {
306
- const text = Buffer.from(encoded, 'base64').toString('utf8');
307
- const parsed = JSON.parse(text);
308
- validateBundleLike(parsed, this.mode);
309
- return cloneBundle(parsed);
310
- }
311
- catch (error) {
312
- if (this.mode === 'normalize') {
313
- return createEmptyBundle();
314
- }
315
- throw new Error(`Invalid ${CommunicationClaim.ContentAttachmentData}: ${error.message}`);
316
- }
317
- }
318
- syncAttachmentFromBundle() {
319
- this.communicationClaims[CommunicationClaim.ContentAttachmentType] = 'application/fhir+json';
320
- this.communicationClaims[CommunicationClaim.ContentAttachmentData] = encodeBundleToBase64(this.bundleInMemory);
321
- const activeSubject = this.resolveCurrentSubject();
322
- if (activeSubject) {
323
- this.communicationClaims[CommunicationClaim.Subject] = activeSubject;
324
- }
325
- }
326
- resolveCurrentSubject() {
327
- if (this.activeEntryIndex !== null) {
328
- const claims = this.bundleInMemory.data[this.activeEntryIndex]?.resource?.meta?.claims || {};
329
- const consentSubject = asTrimmedString(claims[ClaimConsent.subject]);
330
- if (consentSubject) {
331
- return consentSubject;
332
- }
333
- const medicationSubject = asTrimmedString(claims[MedicationStatementClaim.Subject]);
334
- if (medicationSubject) {
335
- return medicationSubject;
336
- }
337
- const conditionSubject = asTrimmedString(claims[ConditionClaim.Subject]);
338
- if (conditionSubject) {
339
- return conditionSubject;
340
- }
341
- const allergySubject = asTrimmedString(claims[AllergyIntoleranceClaim.Subject] || claims[AllergyIntoleranceClaim.Patient]);
342
- if (allergySubject) {
343
- return allergySubject;
344
- }
345
- const documentReferenceSubject = asTrimmedString(claims[DocumentReferenceClaim.Subject]);
346
- if (documentReferenceSubject) {
347
- return documentReferenceSubject;
348
- }
349
- }
350
- const fromClaims = asTrimmedString(this.communicationClaims[CommunicationClaim.Subject]);
351
- return fromClaims || undefined;
352
- }
353
- findUpsertIndex(entry, fullUrl) {
354
- if (fullUrl) {
355
- const byFullUrl = this.bundleInMemory.data.findIndex((item) => String(item?.fullUrl || '').trim() === fullUrl);
356
- if (byFullUrl >= 0) {
357
- return byFullUrl;
358
- }
359
- }
360
- const incomingClaims = entry.resource?.meta?.claims || {};
361
- const incomingIdentifier = this.resolveEntryIdentifier(incomingClaims);
362
- if (!incomingIdentifier) {
363
- return -1;
364
- }
365
- return this.bundleInMemory.data.findIndex((item) => {
366
- const itemClaims = item?.resource?.meta?.claims || {};
367
- return this.resolveEntryIdentifier(itemClaims) === incomingIdentifier;
368
- });
369
- }
370
- resolveEntryIdentifier(claims) {
371
- const consentIdentifier = asTrimmedString(claims[ClaimConsent.identifier]);
372
- if (consentIdentifier) {
373
- return `${ResourceTypesFhirR4.Consent}:${consentIdentifier}`;
374
- }
375
- const medicationIdentifier = asTrimmedString(claims[MedicationStatementClaim.Identifier]);
376
- if (medicationIdentifier) {
377
- return `${ResourceTypesFhirR4.MedicationStatement}:${medicationIdentifier}`;
378
- }
379
- const conditionIdentifier = asTrimmedString(claims[ConditionClaim.Identifier]);
380
- if (conditionIdentifier) {
381
- return `${ResourceTypesFhirR4.Condition}:${conditionIdentifier}`;
382
- }
383
- const allergyIdentifier = asTrimmedString(claims[AllergyIntoleranceClaim.Identifier]);
384
- if (allergyIdentifier) {
385
- return `${ResourceTypesFhirR4.AllergyIntolerance}:${allergyIdentifier}`;
386
- }
387
- const documentReferenceIdentifier = asTrimmedString(claims[DocumentReferenceClaim.Identifier]);
388
- if (documentReferenceIdentifier) {
389
- return `${ResourceTypesFhirR4.DocumentReference}:${documentReferenceIdentifier}`;
390
- }
391
- return '';
392
- }
393
- createBundleEntry(input) {
394
- const resourceClaims = {
395
- ...input.claims,
396
- };
397
- const canonicalEntryIdentifier = this.resolveEntryCanonicalIdValue(resourceClaims);
398
- return {
399
- id: canonicalEntryIdentifier || undefined,
400
- type: input.type || `${input.resourceType}-edit-request-v1.0`,
401
- fullUrl: input.fullUrl,
402
- request: input.request,
403
- resource: {
404
- resourceType: input.resourceType,
405
- meta: {
406
- claims: resourceClaims,
407
- },
408
- },
409
- };
410
- }
411
- resolveEntryCanonicalIdValue(claims) {
412
- const consentIdentifier = asTrimmedString(claims[ClaimConsent.identifier]);
413
- if (consentIdentifier) {
414
- return consentIdentifier;
415
- }
416
- const medicationIdentifier = asTrimmedString(claims[MedicationStatementClaim.Identifier]);
417
- if (medicationIdentifier) {
418
- return medicationIdentifier;
419
- }
420
- const conditionIdentifier = asTrimmedString(claims[ConditionClaim.Identifier]);
421
- if (conditionIdentifier) {
422
- return conditionIdentifier;
423
- }
424
- const allergyIdentifier = asTrimmedString(claims[AllergyIntoleranceClaim.Identifier]);
425
- if (allergyIdentifier) {
426
- return allergyIdentifier;
427
- }
428
- const documentReferenceIdentifier = asTrimmedString(claims[DocumentReferenceClaim.Identifier]);
429
- if (documentReferenceIdentifier) {
430
- return documentReferenceIdentifier;
431
- }
432
- const communicationIdentifier = asTrimmedString(claims[CommunicationClaim.Identifier]);
433
- if (communicationIdentifier) {
434
- return communicationIdentifier;
435
- }
436
- return '';
437
- }
438
- assertEntryIndex(index) {
439
- if (!Number.isInteger(index) || index < 0 || index >= this.bundleInMemory.data.length) {
440
- throw new Error(`Entry index out of range: ${index}`);
441
- }
442
- }
443
- }
444
- function ensureEntryResource(entry, mode) {
445
- const resource = entry.resource;
446
- if (resource && typeof resource === 'object') {
447
- return resource;
448
- }
449
- if (mode === 'normalize') {
450
- return { meta: { claims: {} } };
451
- }
452
- throw new Error('Active entry does not contain a valid resource object.');
453
- }
454
- function validateBundleLike(bundle, mode) {
455
- const looksLikeBundle = bundle && bundle.resourceType === ResourceTypesFhirR4.Bundle && Array.isArray(bundle.data);
456
- if (looksLikeBundle) {
457
- return;
458
- }
459
- if (mode === 'normalize') {
460
- return;
461
- }
462
- throw new Error('Decoded attachment is not a valid BundleJsonApi payload.');
463
- }
464
- function createEmptyBundle() {
465
- return {
466
- resourceType: ResourceTypesFhirR4.Bundle,
467
- type: 'batch',
468
- data: [],
469
- };
470
- }
471
- function encodeBundleToBase64(bundle) {
472
- return Buffer.from(JSON.stringify(bundle), 'utf8').toString('base64');
473
- }
474
- function cloneBundle(bundle) {
475
- return JSON.parse(JSON.stringify(bundle));
476
- }
477
- function cloneEntry(entry) {
478
- return JSON.parse(JSON.stringify(entry));
479
- }
480
- function asTrimmedString(value) {
481
- if (value === undefined || value === null) {
482
- return '';
483
- }
484
- return String(value).trim();
485
- }
486
- function resolveContainedDocumentsClaimKey(resourceType) {
487
- if (resourceType === ResourceTypesFhirR4.Consent) {
488
- return ClaimConsent.containedDocuments;
489
- }
490
- if (resourceType === ResourceTypesFhirR4.MedicationStatement) {
491
- return MedicationStatementClaim.ContainedDocuments;
492
- }
493
- if (resourceType === ResourceTypesFhirR4.Condition) {
494
- return ConditionClaim.ContainedDocuments;
495
- }
496
- if (resourceType === ResourceTypesFhirR4.AllergyIntolerance) {
497
- return AllergyIntoleranceClaim.ContainedDocuments;
498
- }
499
- return '';
500
- }
501
- function resolveSubjectFromClaims(claims) {
502
- return asTrimmedString(claims[ClaimConsent.subject]
503
- || claims[MedicationStatementClaim.Subject]
504
- || claims[ConditionClaim.Subject]
505
- || claims[AllergyIntoleranceClaim.Subject]
506
- || claims[AllergyIntoleranceClaim.Patient]
507
- || claims[DocumentReferenceClaim.Subject]);
508
- }
509
- function setIfMissing(target, key, value) {
510
- if (target[key] !== undefined) {
511
- return;
512
- }
513
- if (value === undefined || value === null || String(value).trim() === '') {
514
- return;
515
- }
516
- target[key] = value;
517
- }
518
- function runtimeUuid(prefix) {
519
- const cryptoLike = globalThis;
520
- if (typeof cryptoLike.crypto?.randomUUID === 'function') {
521
- return cryptoLike.crypto.randomUUID();
522
- }
523
- return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
524
- }