npm package: @healthcare-interoperability/fhir-tools
Description: Helper tools for FHIR processing
Author: quicore
Latest version: 1.2.0

# @healthcare-interoperability/fhir-tools

A lightweight but powerful toolkit for **FHIR reference normalization**, **deterministic ID generation**, and **schema-aware traversal** of FHIR resources in JavaScript / Node.js.

Designed for **healthcare interoperability pipelines**, **HL7 → FHIR transforms**, and **US Core–aligned processing**.

---

## ✨ What This Package Solves

FHIR resources contain many `Reference` fields that:

* appear at different depths
* can be single or arrays
* vary by resource type
* need consistent internal identifiers

This package provides:

* 🔗 **Safe FHIR reference extraction**
* 🧭 **Config-driven reference traversal**
* 🆔 **Deterministic, integration-scoped ID generation**
* 🏗️ **Automatic object & array creation**
* 🇺🇸 **Built-in US Core reference rules**

---

## 📦 Installation

```bash
npm install @healthcare-interoperability/fhir-tools
```

---

## 🔧 Peer Dependency

This package relies on deterministic ID generation:

```ts
@quicore/resource-id
```

---

## 🧠 Core Components

### 1️⃣ `FHIRReferenceAssigner`

Low-level utility that **assigns a normalized FHIR reference** to a declared object path.

* Creates missing objects and arrays
* Enforces correct types
* Preserves original FHIR reference
* Generates deterministic IDs

📌 Use this when you need **manual or custom reference placement**.

---

### 2️⃣ `FHIRReferenceEngine`

A **config-driven processor** that:

* Scans a FHIR resource
* Finds reference fields based on rules
* Normalizes all references into a single `_reference` tree

📌 Use this for **automated pipeline processing**.

---

### 3️⃣ `USCoreFHIRReferenceEngine`

A ready-to-use engine with **US Core–aligned reference rules** for common resources like:

* Encounter
* Observation
* Condition
* Procedure
* MedicationRequest
* Claim / Coverage

📌 Use this if you process **US Core FHIR R4 data**.

---

## 🚀 Quick Start (US Core)

```ts
import { USCoreFHIRReferenceEngine } from "@healthcare-interoperability/fhir-tools";

const engine = new USCoreFHIRReferenceEngine("my-integration-id");

engine.process(fhirResource);

console.log(fhirResource._reference);
```

---

## 🧾 What Gets Generated

All normalized references are stored under:

```ts
resource._reference
```

Each reference has the shape:

```ts
{
  id: string;                 // Deterministic internal ID
  type: string;               // FHIR resource type
  originalReference: string;  // Original FHIR reference (ResourceType/ID)
}
```

This allows:

* consistent internal linking
* traceability back to source FHIR
* safe downstream joins and indexing

---

## 🧩 How the Engine Works

### Step 1: Match Rules

Each rule declares:

* `resourceType` (or `"*"`)
* one or more reference paths

Example:

```ts
{
  resourceType: "Encounter",
  references: [
    { path: ["serviceProvider"] },
    { path: ["participant"], array: true, nested: "individual" }
  ]
}
```

---

### Step 2: Traverse Resource

For each rule:

* the engine checks if the path exists
* supports arrays automatically
* supports nested reference fields

---

### Step 3: Normalize References

References like:

```json
{
  "reference": "Patient/123"
}
```

Are transformed into:

```json
_reference: {
  subject: {
    id: "...",
    type: "Patient",
    originalReference: "Patient/123"
  }
}
```

---

## 📐 Rule Definition Reference

Each reference rule supports:

| Field    | Type       | Description                  |
| -------- | ---------- | ---------------------------- |
| `path`   | `string[]` | Path to the reference field  |
| `array`  | `boolean`  | Whether the path is an array |
| `nested` | `string`   | Nested reference key         |

### Example (Array + Nested)

```ts
{
  path: ["participant"],
  array: true,
  nested: "individual"
}
```

Targets:

```ts
participant[].individual.reference
```

---

## 🇺🇸 US Core Coverage

The built-in `US_CORE_REFERENCE_CONFIG` covers:

### Common (All Resources)

* subject
* patient
* beneficiary
* encounter
* author
* custodian
* recorder
* requester
* organization
* provider

### Encounter

* serviceProvider
* partOf
* location[].location
* participant[].individual
* diagnosis[].condition
* reasonReference[]

### Observation

* specimen
* device
* focus[]
* hasMember[]
* derivedFrom[]
* performer[]

### Condition

* asserter
* recorder
* evidence[].detail

### Procedure

* location
* usedReference[]
* reasonReference[]
* report[]
* performer[].actor

### MedicationRequest

* medicationReference
* recorder
* performer
* reasonReference[]
* basedOn[]

### DiagnosticReport

* specimen[]
* result[]
* imagingStudy[]

### Claim / Coverage

* insurer
* insurance[].coverage
* careTeam[].provider
* diagnosis[].diagnosisReference
* procedure[].procedureReference
* beneficiary
* payor[]

---

## 🔐 Error Handling Philosophy

* Invalid references are **ignored safely**
* Structural conflicts are prevented
* Failures are **logged, not fatal**

```ts
console.warn(
  `Reference assign failed Encounter/123 at ["participant",0,"individual"]`
);
```

This makes the engine safe for:

* batch processing
* partial data
* real-world EHR payloads

---

## 🏥 Typical Use Cases

* HL7v2 → FHIR pipelines
* US Core ingestion
* Appointment & encounter consolidation
* Claim normalization
* AI-ready FHIR preprocessing
* Cross-resource reference indexing

---

## 📄 API Summary

### `FHIRReferenceAssigner`

```ts
new FHIRReferenceAssigner(integrationId)
assign(baseObject, pathSegments, sourceReference)
```

---

### `FHIRReferenceEngine`

```ts
new FHIRReferenceEngine(integrationId, config)
process(resource)
```

---

### `USCoreFHIRReferenceEngine`

```ts
new USCoreFHIRReferenceEngine(integrationId)
```

---

## 🧪 Design Goals

* Deterministic
* Schema-aware
* Safe-by-default
* Interop-friendly
* AI-readable output

---

## 📜 License

MIT

---

## 🤝 Contributing

Contributions are welcome—especially for:

* Additional FHIR profiles
* R5 support
* Custom profile generators
* Reference validation helpers