@claudebernard/web-component-fhir-utils
Shared FHIR Bundle helpers for Claude Bernard medication web components (bcb-medication-request-editor, bcb-therapeutic-alternative) and the applications that embed them.
These components take a small FHIR collection Bundle as input and emit a FHIR transaction Bundle describing exactly what changed — standard Bundle.entry.request.method semantics, no custom DTOs. This package gives you the two sides of that contract so you never write bespoke reconciliation code:
- Integrating an app? Build the input Bundle, then apply the output Bundle back onto your own state.
- Building a component? Use the same helpers to produce standards-compliant transaction diffs.
See the full guide on the Claude Bernard Developer Portal for the wider FHIR model
Status: this package defines the target Bundle-in/Bundle-out contract. Check each component's own changelog for the version that adopts it — until then, refer to that component's
integrationdoc for its current API.
Installation
npm install @claudebernard/web-component-fhir-utils
Integrating an app
Build the input Bundle, pushing whatever resources the component needs:
import { createCollectionBundle } from "@claudebernard/web-component-fhir-utils";
const bundle = createCollectionBundle();
bundle.entry.push({ resource: medication });
bundle.entry.push({ resource: medicationRequest });
The Bundle gets a random id (UUID) by default; pass your own with createCollectionBundle(resources, { id }). Components that list several prescriptions (e.g. bcb-shared-medication-review) identify each one by its Bundle.id, so keep it stable if you rebuild the Bundle. Entries built from the resources you pass get a fullUrl (<resourceType>/<id>).
To build a whole prescription (with its date, patient and prescriber, which bcb-shared-medication-review uses to sort prescriptions by date), use createDocumentBundle:
const prescription = createDocumentBundle([medication, medicationRequest], {
date: "2026-10-21",
patientId: patient.id,
practitionerName: "Dr Martin",
});
It returns a document Bundle whose first entry is a Composition (date, title, patient, author), followed by the Practitioner.
<bcb-medication-request-editor .medication="${bundle}"></bcb-medication-request-editor>
Apply the transaction Bundle the component emits back onto your own Bundle — this is the only integration code you need, and it never changes per component or per feature:
import { applyTransactionBundle } from "@claudebernard/web-component-fhir-utils";
editor.addEventListener("fhir-changes", ({ detail }) => {
myPrescriptionBundle = applyTransactionBundle(myPrescriptionBundle, detail.bundle);
});
applyTransactionBundle understands POST (append), PUT (replace by resourceType + id), and DELETE (remove by resourceType + id). Options:
| Option | Default | Effect |
|---|---|---|
onMissingTarget | "append" | "throw" fails loudly instead of silently inserting a missing PUT / ignoring a missing DELETE |
fullUrlFormat | "urn:uuid" | fullUrl given to the entries the call adds (POST, or a PUT appended for a missing target): "urn:uuid" → urn:uuid:<id>, "resource-type" → <resourceType>/<id> (what createCollectionBundle uses), or a function (resource) => string. Existing entries keep their fullUrl |
To apply several transaction Bundles in a row, use applyTransactionBundles. They apply in array order, each one seeing the result of the previous one; the options are the same:
import { applyTransactionBundles } from "@claudebernard/web-component-fhir-utils";
myPrescriptionBundle = applyTransactionBundles(myPrescriptionBundle, [firstTransaction, secondTransaction], {
fullUrlFormat: "resource-type",
});
Working with a prescription Bundle
Removing medications
removeMedications returns the transaction entries that delete medications from a prescription: each Medication, every MedicationRequest pointing at it (on-hold history included) and the matching references in Composition.section.entry (a PUT of the updated Composition). Apply them like any other diff, then use isPrescriptionEmpty to decide whether the whole prescription should go — deleting it stays your call, since you own its persistence:
import {
applyTransactionBundle, createTransactionBundle, isPrescriptionEmpty, removeMedications,
} from "@claudebernard/web-component-fhir-utils";
const entries = removeMedications(myPrescriptionBundle, [medicationId]);
myPrescriptionBundle = applyTransactionBundle(myPrescriptionBundle, createTransactionBundle(entries));
if (isPrescriptionEmpty(myPrescriptionBundle)) {
// no active MedicationRequest left: delete the prescription on your side
}
Only MedicationRequests that reference the removed Medication directly are deleted. A request of another medication that merely has a removed one as priorPrescription (a therapeutic-alternative swap) is the live replacement and is kept. Unknown ids are ignored.
Cleaning a Bundle
cleanBundle returns a copy of a Bundle without its orphan resources (no link to, and no link from, any other resource of the Bundle) and without dangling Composition.section.entry references (sections left empty by that are dropped). It is pure and idempotent.
import { cleanBundle, getCleanupEntries } from "@claudebernard/web-component-fhir-utils";
myPrescriptionBundle = cleanBundle(myPrescriptionBundle);
// or, to emit the cleanup as part of a transaction diff (DELETE per orphan, PUT per updated Composition):
const entries = getCleanupEntries(myPrescriptionBundle);
Composition,PatientandPractitionerare never deleted, even when nothing links to them. Override with{ keep: ["Composition", ...] }.- Inactive resources (
on-holdhistory linked throughpriorPrescription) are not orphans and are kept. - Resources without an
idare left alone, as a transaction cannot target them.
Finding linked resources
findResourceReferences lists the resources a Bundle resource references (references) and the ones referencing it (referencedBy), through every Reference.reference (medication, priorPrescription, subject, Composition.section.entry, ...). target is an id, a Type/id reference, or the resource itself.
import { findResourceReferences } from "@claudebernard/web-component-fhir-utils";
const { referencedBy } = findResourceReferences<MedicationRequest>(bundle, medication, {
direction: "incoming",
resourceType: "MedicationRequest",
});
| Option | Default | Effect |
|---|---|---|
direction | "both" | "outgoing" (what target references), "incoming" (what references it) or "both" |
transitive | false | Follow links of links until the chain ends |
includeInactive | false | Also return, and walk through, resources no longer active (on-hold, stopped, cancelled, completed, entered-in-error, inactive, revoked, deprecated, or active: false) |
resourceType | all | Only return resources of this type |
References are matched whatever their spelling (Type/id, urn:uuid:<id>, an entry's fullUrl, absolute URL); references to resources absent from the Bundle, contained (#id) and canonical references are ignored.
Building a component
Produce diff entries with createBundleEntry / createTransactionBundle:
import { createBundleEntry, createTransactionBundle } from "@claudebernard/web-component-fhir-utils";
const bundle = createTransactionBundle([
createBundleEntry(updatedResource, "PUT"),
createBundleEntry(newResource, "POST"),
]);
For the common "this MedicationRequest replaces that one" case (dosage override, therapeutic alternative, ...), use supersedeMedicationRequest — it produces the on-hold PUT + linked, tagged POST pair as house convention dictates, so every component represents supersession the same way:
import { PriorPrescriptionReason, supersedeMedicationRequest } from "@claudebernard/web-component-fhir-utils";
const entries = supersedeMedicationRequest(
originalMedicationRequest,
{ dosageInstruction: newDosage },
PriorPrescriptionReason.DOSAGE_OVERRIDE,
{ bundle: inputBundle }, // optional, see below
);
Pass the Bundle the original lives in as options.bundle and every Composition listing the original in section.entry also gets a PUT swapping that reference for the new request, so the document stops pointing at the on-hold one. Without bundle, only the two entries below are returned.
The two main entries are shaped like this a diff shaped like this — the original request goes on-hold via PUT, the new one is created active via POST and linked back through priorPrescription:
{
"resourceType": "Bundle",
"type": "transaction",
"entry": [
{
"resource": { "resourceType": "MedicationRequest", "id": "mr-123", "status": "on-hold", "...": "..." },
"request": { "method": "PUT", "url": "MedicationRequest/mr-123" }
},
{
"resource": {
"resourceType": "MedicationRequest",
"id": "mr-456",
"status": "active",
"dosageInstruction": ["..."],
"priorPrescription": {
"reference": "MedicationRequest/mr-123",
"extension": [{ "url": "https://platform.claudebernard.fr/fhir/StructureDefinition/prior-prescription-reason", "valueCode": "dosage-override" }]
}
},
"request": { "method": "POST", "url": "MedicationRequest" }
}
]
}
Supersession reasons
PriorPrescriptionReason carries why the new request replaces the old one, as a valueCode on the
priorPrescription extension. Pick the one that matches the user's intent — consumers filter on it
with hasPriorPrescriptionReason:
| Value | Code | When |
|---|---|---|
PriorPrescriptionReason.DOSAGE_OVERRIDE | dosage-override | Same medication, dosage changed |
PriorPrescriptionReason.MEDICATION_OVERRIDE | medication-override | Different medication, same therapeutic intent |
PriorPrescriptionReason.THERAPEUTIC_ALTERNATIVE | therapeutic-alternative | Substitution proposed by bcb-therapeutic-alternative |
More worked examples (including the therapeutic-alternative case) are in the Developer Portal guide.
API
| Export | Purpose |
|---|---|
createCollectionBundle(resources?, options?) | Build the input collection Bundle (options.id, random UUID by default) |
createDocumentBundle(resources?, { date, patientId, practitionerName?, id? }) | Build a prescription document Bundle (Composition + Practitioner first) |
createBundleEntry(resource, method, url?) | Build one transaction entry (POST/PUT/DELETE) |
createTransactionBundle(entries) | Wrap entries into the output transaction Bundle |
applyTransactionBundle(target, transaction, options?) | Apply a transaction Bundle onto a Bundle you hold (options.onMissingTarget, options.fullUrlFormat) |
applyTransactionBundles(target, transactions, options?) | Apply several transaction Bundles, in order, onto a Bundle you hold |
findResourceInBundle(bundle, resourceType, id) | Look up a resource by type + id |
supersedeMedicationRequest(original, changes, reason, { bundle? }) | Build the on-hold/priorPrescription/extension pair for a supersession; with bundle, also a PUT swapping the reference in Composition.section.entry |
removeMedications(bundle, medicationIds) | Entries deleting medications, their MedicationRequests, and their Composition.section.entry references |
isPrescriptionEmpty(bundle) | True when no active MedicationRequest is left |
cleanBundle(bundle, options?) / getCleanupEntries(bundle, options?) | Drop orphan resources and dangling Composition.section.entry references (as a Bundle / as transaction entries) |
findResourceReferences(bundle, target, options?) | Active resources a resource references and is referenced by (direction, transitive, includeInactive, resourceType) |
hasPriorPrescriptionReason(medicationRequest, reason) | Check why a MedicationRequest supersedes another |
PriorPrescriptionReason, PRIOR_PRESCRIPTION_REASON_URL, BCB_CODE_SYSTEM | Shared constants |
Versioning
This package carries the version of the fhir-monorepo repository — one version, tag and changelog
for the whole repo. Published versions are therefore sparse: a release only reaches npm when this
package actually changed.
License
Copyright of Cegedim. See LICENSE for details.